3D engine that AI agents drive
Add three options for each grand reference scene (part of issue #168)
Nguyen Xuan An284b122f3423
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7733d585..eb3efcd7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add three options for each grand reference scene, to pick from (part of issue #168, which stays open until An picks). `bench/reference/grand-scenes.js` holds `mountain-valley`, `temple-hall` and `megacity-dusk` as `-a`, `-b` and `-c`, each with its own composition, light and time of day, drawn by `npm run reference -- --grand` into `grand.json` and `images/grand-<id>.jpg` (`baseline.json` and the existing images are unchanged). The Blender side gained a `gradient` world, written as the same equirectangular image 67js draws. `bench/reference/grand-sheets.py` makes one comparison sheet per scene.+- Show the floor and the other parts in smooth metal (part of issue #167, which stays open). `traceObjectProbes` in `src/probe-trace.js` gives each part with `metallic` of at least 0.5 and `roughness` of at most 0.6 a reflection probe of its own, traced from the middle of the part without it (up to 8 parts, lit by direct light and the environment's diffuse light), and `placeProbes` assigns it. `metal` scores 0.1294 to 0.1036 against Cycles (EEVEE 0.0916), `brushed-film` 0.1149 to 0.1029, `car-paint` 0.1059 to 0.1038, `material-spheres` 0.1312 to 0.1293; every scene without a reflective part is unchanged to four digits and draws the same frame (`metal` 1.51 ms plain, 1.58 ms with four probes). `npm run reference -- --object-probes` places them (opt in; the committed baseline is unchanged); recipes do not yet.- Make every test file pass on its own, and check it in CI (issue #172). `node --test tests/agent-bake.test.js` failed 16 of 19 because `npm test` preloaded every on-demand module into each test process, so 28 files only passed through that preload. The loading path agents use was fine (`tests/agent-scene-on-demand.test.js` runs it in clean processes). Each of those files now imports `tests/support/load-agent-scene-modules.mjs` itself, `npm test` no longer preloads, and `npm run test:isolated` (`scripts/test-each-file.mjs`) runs each file in its own process, 4 at a time at below-normal priority, rerunning a failure alone once so a busy machine does not count. It runs in the `Test` workflow.diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 2a5c028a..f5e00285 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -52,6 +52,24 @@ With the shadow floor `temple-hall` scored 0.5841, `mountain-valley` 0.3658 and`temple-hall` sets its own `bakeOptions`. The defaults need 1.4 million texels, and the bake allows 1 million. With the options the bake scores 0.2239, against 0.2126 without it.+### Options for the grand scenes (2026-11-02, part of issue #168)++The three scenes measure well and look plain, so `grand-scenes.js` holds three options of each, `-a`, `-b` and `-c`, each a different composition, light and time of day. `npm run reference -- --grand` draws them on both sides into `grand.json` and `images/grand-<id>.jpg`; `baseline.json` and the other images are unchanged. `python bench/reference/grand-sheets.py <directory>` (command in its header) writes one comparison sheet per scene. An picks by letter, and a later change moves the pick into `REFERENCE_SCENES`. Blender draws the same geometry; the sky is the same equirectangular gradient on both sides (`gradient` world type), and every window, lamp and sky panel is Emission.++| Option | What it is | 67js against Cycles | Cycles seconds |+| --- | --- | --- | --- |+| `mountain-valley-a` | Golden hour at a lake, sun from the left, rocky shore in the foreground | 0.3530 | 26.3 |+| `mountain-valley-b` | Midday from a high slope, a river winding down a flat valley floor | 0.1839 | 24.5 |+| `mountain-valley-c` | Alpenglow on one tall peak, forest edge close to the camera | 0.2282 | 52.7 |+| `temple-hall-a` | Four clerestory windows throw slanted sun shafts across the nave, people in the light | 0.2530 | 21.7 |+| `temple-hall-b` | Square oculus hall: ring of columns, one beam on a gilded seated figure | 0.3642 | 25.4 |+| `temple-hall-c` | Setting sun down the nave axis through a tall opening, columns as silhouettes in glowing fog | 0.2746 | 23.4 |+| `megacity-dusk-a` | Blue hour on a river with lit bridges and quays | 0.1978 | 28.9 |+| `megacity-dusk-b` | Sunrise across a bay from a pier, skyline and its reflection | 0.1575 | 33.2 |+| `megacity-dusk-c` | Night, high view over an avenue grid of car lights and dense lit towers | 0.1149 | 35.9 |++Known gaps in the 67js side: a lake or bay shows the sky only, where Cycles also mirrors the shore, the trees and the towers; the dark halls have no bounced light.+## Dark spaces (2026-11-01, part of issue #159)`dark-shaft` is a closed stone room, 11 m by 15 m and 6.5 m high, with one 2.2 m opening in the roof. The sun comes through it as a shaft in `volumeFog` (density 0.07) and lands on the floor and on a plinth with an urn. There is no HDRI, and the world is a constant 0.03, as in `temple-hall`.diff --git a/bench/reference/grand-scenes.js b/bench/reference/grand-scenes.jsnew file mode 100644index 00000000..54ace992--- /dev/null+++ b/bench/reference/grand-scenes.js@@ -0,0 +1,486 @@+// Options for the three grand scenes (issue #168). Each option is a different composition, light and time of day, not a tweak:+// a letter names it, `-a`, `-b` and `-c`, and a later change promotes the pick into REFERENCE_SCENES. They are drawn with+// `npm run reference -- --grand` (?set=grand), so baseline.json and the default images stay as they are.+// The rules of scenes.js hold: only what Blender draws too (terrain vertex colours, Emission, volume fog, plain geometry).+import { box, cylinder, sphere } from '/src/geometry.js';+import { createEnvironmentMap } from '/src/hdri.js';+import { createNoiseHeight, createTerrain } from '/src/terrain.js';+import { scatterVegetation, selectLevels } from '/src/vegetation.js';+import {+ HALL, HALL_BLOCK, VALLEY_TERRAIN, cityTowerParts, clamp01, constantLighting, environment, hallColumnParts, mixColors,+ normalized, part, seededRandom, smoothBetween, sunShadow,+} from './scenes.js';++const UNIT_BOX = box(0, 1);+const UNIT_CYLINDER = cylinder(32, 0, 1);+const UNIT_SPHERE = sphere(20, 14);++// A part with a turn about Y (yaw) and then about X (pitch), which `part` does not have.+function turnedPart(name, geometry, translation, scale, material, yaw = 0, pitch = 0) {+ const [cosYaw, sinYaw] = [Math.cos(yaw), Math.sin(yaw)];+ const [cosPitch, sinPitch] = [Math.cos(pitch), Math.sin(pitch)];+ const turn = ([x, y, z]) => [cosYaw * x + sinYaw * z, y, -sinYaw * x + cosYaw * z];+ const [xAxis, yAxis, zAxis] = [turn([scale[0], 0, 0]), turn([0, cosPitch * scale[1], sinPitch * scale[1]]), turn([0, -sinPitch * scale[2], cosPitch * scale[2]])];+ const built = part(name, geometry, translation, scale, material);+ built.matrix = new Float32Array([...xAxis, 0, ...yAxis, 0, ...zAxis, 0, ...translation, 1]);+ return built;+}++// Sky colour by elevation: horizon to zenith above the horizon (raised to `power`), horizon to ground below it.+// render-blender.py (gradient_sky_image) uses the same formula, and `intensity` scales all three colours.+function skyGradient({ zenith, horizon, ground = horizon, power = 0.5, intensity = 1 }) {+ const [width, height] = [256, 128];+ const scaled = colors => colors.map(color => color.map(channel => channel * intensity));+ const [zenithColor, horizonColor, groundColor] = scaled([zenith, horizon, ground]);+ const data = new Float32Array(width * height * 3);+ for (let row = 0; row < height; row++) {+ const sine = Math.sin((0.5 - (row + 0.5) / height) * Math.PI);+ const above = clamp01(sine) ** power;+ const below = clamp01(-sine * 4);+ const color = mixColors(mixColors(horizonColor, zenithColor, above), groundColor, below);+ for (let column = 0; column < width; column++) data.set(color, (row * width + column) * 3);+ }+ const map = createEnvironmentMap({ width, height, data, showBackground: true });+ return { map, blenderWorld: { type: 'gradient', zenith: zenithColor, horizon: horizonColor, ground: groundColor, power } };+}++const WATER = { color: [0.02, 0.05, 0.08], roughness: 0.04 };++// ---------------------------------------------------------------------------------------------------------------------+// Mountain valley++// The reference valley (floor hills, a rim of ridged peaks, a far wall) with options: a flatter floor, a hero peak, and+// `carve(x, z, height)` for a lake or a river.+function valleyHeight({ floorScale = 1, floorOffset = 0, rimScale = 1, hero = null, carve = (x, z, height) => height }) {+ const floorHills = createNoiseHeight({ amplitude: 14, featureSize: 260, mountainMask: () => 0 }, 3);+ const peaks = createNoiseHeight({ amplitude: 0, mountainAmplitude: 1100, featureSize: 800, octaves: 7, warp: 260, warpFeatureSize: 700, mountainMask: () => 1 }, 11);+ return (x, z) => {+ const radius = Math.hypot(x, z * 0.75);+ const rise = smoothBetween(520, 1500, radius);+ const farWall = smoothBetween(2000, 2600, radius) * 600;+ const peakHeight = peaks(x, z);+ let height = floorHills(x, z) * floorScale + floorOffset + rise * (peakHeight * 1.5 * rimScale + 90) + farWall;+ if (hero) {+ const distance = Math.hypot(x - hero.x, z - hero.z) / hero.radius;+ height += hero.height * Math.exp(-distance * distance) * (0.75 + 0.5 * peakHeight / 1000);+ }+ return carve(x, z, height, rise);+ };+}++function paintGrandTerrain(terrain, { grass, alpine, rock, snow, shore, treeLine, snowLine, waterLevel = -Infinity }) {+ for (const terrainPart of terrain.parts) {+ const { positions, normals } = terrainPart.geometry;+ const colors = new Float32Array(positions.length);+ for (let vertex = 0; vertex < positions.length; vertex += 3) {+ const height = positions[vertex + 1];+ const flatness = normals[vertex + 1];+ let color = mixColors(grass, alpine, smoothBetween(treeLine * 0.7, treeLine * 1.5, height));+ color = mixColors(color, rock, smoothBetween(0.9, 0.7, flatness));+ color = mixColors(color, snow, smoothBetween(snowLine, snowLine + 120, height) * smoothBetween(0.55, 0.8, flatness));+ if (Number.isFinite(waterLevel)) color = mixColors(color, shore, 1 - smoothBetween(waterLevel + 0.5, waterLevel + 3.5, height));+ colors.set(color, vertex);+ }+ terrainPart.geometry.colors = colors;+ }+}++// Boulders around a point: squashed spheres and tilted blocks, so the near ground reads as rock and not as a bare slope.+function boulderParts({ terrain, center, innerRadius, outerRadius, count, size, seed, facing = 0 }) {+ const random = seededRandom(seed);+ const parts = [];+ const tones = [[0.3, 0.27, 0.24], [0.24, 0.23, 0.22], [0.36, 0.32, 0.27], [0.2, 0.22, 0.17]];+ for (let index = 0; index < count; index++) {+ const angle = facing + (random() - 0.5) * 2.4;+ const distance = innerRadius + (outerRadius - innerRadius) * random() ** 1.5;+ const x = center[0] + Math.sin(angle) * distance;+ const z = center[1] - Math.cos(angle) * distance;+ const radius = size[0] + (size[1] - size[0]) * random() ** 2;+ const material = { color: tones[Math.floor(random() * tones.length)], roughness: 0.9 };+ const sunk = radius * 0.25;+ if (random() < 0.2) {+ parts.push(turnedPart(`boulder-${index}`, UNIT_SPHERE, [x, terrain.heightAt(x, z) + radius * 0.3 - sunk, z], [radius * 1.3, radius * 0.8, radius], material, random() * 6.28, (random() - 0.5) * 0.4));+ } else {+ parts.push(turnedPart(`boulder-${index}`, UNIT_BOX, [x, terrain.heightAt(x, z) + radius * 0.35 - sunk, z], [radius * 1.5, radius * 0.9, radius * 1.1], material, random() * 6.28, (random() - 0.5) * 0.5));+ }+ }+ return parts;+}++async function grandValleyScene({ lighting, key, sunDirection, height, palette, waterLevel, water, eyeGround, eyeLift, target, fov = 50, boulders, forestDensity = 0.0016, treeExclusion, seed = 5 }) {+ const eyeXZ = eyeGround;+ const terrain = createTerrain({ ...VALLEY_TERRAIN, height, eye: [eyeXZ[0], 100, eyeXZ[1]], material: { color: [1, 1, 1], metallic: 0, roughness: 0.95, emission: 0 } });+ paintGrandTerrain(terrain, { ...palette, waterLevel: water ? waterLevel : -Infinity });+ const eye = [eyeXZ[0], terrain.heightAt(eyeXZ[0], eyeXZ[1]) + eyeLift, eyeXZ[1]];+ const forest = scatterVegetation({+ area: { minX: -1500, maxX: 1500, minZ: -1700, maxZ: 1100 }, density: forestDensity, terrainHeight: terrain.heightAt, slopeLimit: 26,+ exclusion: (x, z) => terrain.heightAt(x, z) > palette.treeLine || (water && terrain.heightAt(x, z) < waterLevel + 2.5) || (treeExclusion ?? (() => false))(x, z, eye),+ mix: { conifer: 1 }, variants: 3, scale: [0.8, 1.3], seed,+ });+ const visibleForest = selectLevels(forest.instances, eye, { cullDistance: 1800, distanceScale: 3 });+ const parts = [...terrain.parts, ...visibleForest.parts];+ if (water) parts.push(part('water', UNIT_BOX, [water.center[0], waterLevel - 0.5, water.center[1]], [water.size[0], 1, water.size[1]], WATER));+ if (boulders) parts.push(...boulderParts({ terrain, center: [eye[0], eye[2]], ...boulders }));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: key, lightDirection: normalized(sunDirection) }),+ camera: { eye, target, up: [0, 1, 0], fov, near: 0.5, far: 8000 },+ shadow: sunShadow(sunDirection, [0, 150, -400], 2300, 3500),+ };+}++const MEADOW = { grass: [0.14, 0.22, 0.07], alpine: [0.2, 0.19, 0.12], rock: [0.27, 0.25, 0.23], snow: [0.85, 0.87, 0.9], shore: [0.3, 0.28, 0.22], treeLine: 420, snowLine: 520 };++// A: golden hour at a lake. A low warm sun behind the peaks, a lake on the floor that mirrors the sky, rock in the near foreground.+const LAKE = { x: -20, z: -150 };+function lakeCarve(x, z, height) {+ const distance = Math.hypot((x - LAKE.x) / 330, (z - LAKE.z) / 220);+ const basin = 1 - smoothBetween(0.45, 1, distance);+ return height * (1 - basin) + -16 * basin;+}+async function mountainValleyA() {+ return grandValleyScene({+ lighting: skyGradient({ zenith: [0.12, 0.2, 0.5], horizon: [1, 0.55, 0.3], ground: [0.25, 0.15, 0.1], power: 0.45, intensity: 0.7 }),+ key: [7, 3.8, 1.8], sunDirection: [-0.75, 0.42, 0.3],+ height: valleyHeight({ floorScale: 1, carve: lakeCarve }), palette: MEADOW, waterLevel: -1.5,+ water: { center: [LAKE.x, -150], size: [900, 900] },+ eyeGround: [-150, 230], eyeLift: 12, target: [60, 220, -1500],+ boulders: { innerRadius: 10, outerRadius: 120, count: 120, size: [0.6, 4], seed: 21 },+ treeExclusion: (x, z, eye) => Math.hypot(x - eye[0], z - eye[2]) < 45,+ });+}++// B: midday from a high slope. A river winds down a flat valley floor from the camera to the far peaks.+function riverCentre(z) {+ return 150 * Math.sin(z / 300) + 40 * Math.sin(z / 97);+}+function riverCarve(x, z, height, rise) {+ const channel = (1 - smoothBetween(16, 55, Math.abs(x - riverCentre(z)))) * (1 - smoothBetween(0.05, 0.3, rise));+ return height * (1 - channel) + -6 * channel;+}+async function mountainValleyB() {+ return grandValleyScene({+ lighting: skyGradient({ zenith: [0.1, 0.3, 0.75], horizon: [0.65, 0.78, 0.95], ground: [0.2, 0.22, 0.2], power: 0.5, intensity: 1 }),+ key: [4.6, 4.2, 3.6], sunDirection: [0.35, 0.78, 0.25],+ height: valleyHeight({ floorScale: 0.5, floorOffset: 3, carve: riverCarve }), palette: { ...MEADOW, treeLine: 650, snowLine: 720 }, waterLevel: -1,+ water: { center: [0, -400], size: [3000, 3000] },+ eyeGround: [-700, 420], eyeLift: 30, target: [120, 60, -800], fov: 55, forestDensity: 0.0014,+ treeExclusion: (x, z, eye) => Math.hypot(x - eye[0], z - eye[2]) < 60,+ });+}++// C: cool morning with alpenglow. One tall peak rim lit by the low sun, a forest edge close to the camera.+async function mountainValleyC() {+ return grandValleyScene({+ lighting: skyGradient({ zenith: [0.1, 0.2, 0.55], horizon: [1, 0.62, 0.5], ground: [0.2, 0.17, 0.2], power: 0.4, intensity: 0.75 }),+ key: [6.5, 3.4, 1.9], sunDirection: [0.7, 0.5, 0.35],+ height: valleyHeight({ hero: { x: 60, z: -1150, radius: 360, height: 900 } }),+ palette: { ...MEADOW, snowLine: 380, treeLine: 460, snow: [0.95, 0.88, 0.88] }, waterLevel: -Infinity,+ eyeGround: [-420, 480], eyeLift: 7, target: [60, 480, -1150], fov: 46, forestDensity: 0.0022,+ boulders: { innerRadius: 6, outerRadius: 50, count: 30, size: [0.5, 2.4], seed: 3, facing: 0.4 },+ treeExclusion: (x, z, eye) => Math.hypot(x - eye[0], z - eye[2]) < 22,+ });+}++// ---------------------------------------------------------------------------------------------------------------------+// Temple hall++const ROBES = [[0.5, 0.1, 0.08], [0.1, 0.2, 0.45], [0.55, 0.45, 0.15], [0.15, 0.3, 0.18], [0.4, 0.4, 0.42], [0.6, 0.3, 0.1]];++// People at the given [x, z] spots: a robe and a head, 1.5 to 1.8 m tall, for scale.+function peopleParts(spots, prefix = 'person') {+ const parts = [];+ spots.forEach(([x, z, yaw = 0], index) => {+ const height = 1.55 + (index % 4) * 0.08;+ parts.push(turnedPart(`${prefix}-body-${index}`, UNIT_CYLINDER, [x, height / 2, z], [0.22, height, 0.22], { color: ROBES[index % ROBES.length], roughness: 0.8 }, yaw));+ parts.push(part(`${prefix}-head-${index}`, UNIT_SPHERE, [x, height + 0.14, z], [0.14, 0.14, 0.14], { color: [0.75, 0.55, 0.42], roughness: 0.7 }));+ });+ return parts;+}++function fogBox(density, minimum, maximum, maxDistance, anisotropy = 0.6) {+ return { density, minimum, maximum, color: [1, 0.95, 0.85], ambient: [0.02, 0.02, 0.02], anisotropy, noiseAmount: 0, steps: 48, maxDistance };+}++const NAVE_LENGTH = HALL.front - HALL.back;+const NAVE_MIDDLE = (HALL.front + HALL.back) / 2;+const STONE = { color: [0.52, 0.45, 0.36], roughness: 0.85 };+const FLOOR_STONE = { color: [0.36, 0.32, 0.27], roughness: 0.6 };++// The reference nave without the roof openings: floor, carpet, solid roof, the far wall and the columns.+function closedNaveParts() {+ const roofY = HALL.roofHeight;+ const parts = [+ part('hall-floor', HALL_BLOCK, [0, -0.5, NAVE_MIDDLE], [HALL.halfWidth * 2, 1, NAVE_LENGTH], FLOOR_STONE),+ part('hall-carpet', HALL_BLOCK, [0, 0.03, NAVE_MIDDLE], [5, 0.06, NAVE_LENGTH - 8], { color: [0.45, 0.06, 0.05], roughness: 0.9 }),+ part('wall-right', HALL_BLOCK, [HALL.halfWidth + 1, roofY / 2, NAVE_MIDDLE], [2, roofY + 1, NAVE_LENGTH], STONE),+ part('wall-front', HALL_BLOCK, [0, roofY / 2, HALL.front + 1], [HALL.halfWidth * 2 + 4, roofY + 1, 2], STONE),+ part('roof', HALL_BLOCK, [0, roofY, NAVE_MIDDLE], [HALL.halfWidth * 2 + 4, 2, NAVE_LENGTH], STONE),+ ];+ hallColumnParts(parts, STONE);+ return parts;+}++// A: a strong sun shaft across the nave. Four clerestory windows in the left wall throw slanted beams through fog onto the+// columns and the floor, and people stand in the light for scale.+const CLERESTORY_CENTRES = [-12, -42, -72, -102];+async function templeHallA() {+ const lighting = constantLighting(0.08);+ const sunDirection = [-0.78, 0.62, 0.1];+ const parts = closedNaveParts();+ const [windowBottom, windowTop, windowWidth] = [11, 26, 10];+ parts.push(part('wall-far', HALL_BLOCK, [0, HALL.roofHeight / 2, HALL.back - 1], [HALL.halfWidth * 2 + 4, HALL.roofHeight + 1, 2], STONE));+ parts.push(part('wall-left-low', HALL_BLOCK, [-HALL.halfWidth - 1, windowBottom / 2, NAVE_MIDDLE], [2, windowBottom, NAVE_LENGTH], STONE));+ parts.push(part('wall-left-high', HALL_BLOCK, [-HALL.halfWidth - 1, (windowTop + HALL.roofHeight + 1) / 2, NAVE_MIDDLE], [2, HALL.roofHeight + 1 - windowTop, NAVE_LENGTH], STONE));+ let pierStart = HALL.front;+ for (const [index, centre] of [...CLERESTORY_CENTRES, HALL.back - windowWidth].entries()) {+ const pierEnd = centre + windowWidth / 2;+ if (pierStart - pierEnd > 0.5) {+ parts.push(part(`wall-left-pier-${index}`, HALL_BLOCK, [-HALL.halfWidth - 1, (windowBottom + windowTop) / 2, (pierStart + pierEnd) / 2], [2, windowTop - windowBottom, pierStart - pierEnd], STONE));+ }+ pierStart = centre - windowWidth / 2;+ }+ parts.push(+ part('altar-steps-low', HALL_BLOCK, [0, 0.4, HALL.back + 9], [26, 0.8, 18], STONE),+ part('altar-steps-high', HALL_BLOCK, [0, 1.2, HALL.back + 6], [16, 0.8, 11], STONE),+ part('altar', HALL_BLOCK, [0, 2.8, HALL.back + 6], [4, 2.4, 3], FLOOR_STONE),+ );+ parts.push(...peopleParts([[-8, -13], [-5, -15, 1], [-13, -17, 2], [-4, -44], [-9, -41, 1], [-7, -71], [-2, -75, 3], [-9, 0, 1], [-6, 3, 2], [-14, -4, 4]]));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: [14, 12, 9], lightDirection: normalized(sunDirection), volumeFog: fogBox(0.04, [-HALL.halfWidth, 0, HALL.back], [HALL.halfWidth, HALL.roofHeight - 1, HALL.front + 2], 190) }),+ camera: { eye: [12, 1.7, 16], target: [-10, 8, -45], up: [0, 1, 0], fov: 64, near: 0.1, far: 300 },+ shadow: sunShadow(sunDirection, [0, 15, NAVE_MIDDLE], 105, 200),+ };+}++// B: an oculus hall. A square chamber 64 m across and 36 m high with a ring of columns, one square opening in the middle of the+// roof, and a gilded seated figure on a stepped plinth where the beam lands.+async function templeHallB() {+ const lighting = constantLighting(0.08);+ const sunDirection = [0.35, 0.88, 0.3];+ const [half, height, roofThickness, opening] = [32, 36, 2, 8];+ const gold = { color: [0.85, 0.62, 0.2], metallic: 0.9, roughness: 0.3 };+ const parts = [+ part('floor', HALL_BLOCK, [0, -0.5, 0], [half * 2 + 4, 1, half * 2 + 4], FLOOR_STONE),+ part('floor-ring', UNIT_CYLINDER, [0, 0.02, 0], [34, 0.04, 34], { color: [0.55, 0.5, 0.42], roughness: 0.5 }),+ part('wall-left', HALL_BLOCK, [-half - 1, height / 2, 0], [2, height, half * 2 + 4], STONE),+ part('wall-right', HALL_BLOCK, [half + 1, height / 2, 0], [2, height, half * 2 + 4], STONE),+ part('wall-back', HALL_BLOCK, [0, height / 2, -half - 1], [half * 2 + 4, height, 2], STONE),+ part('wall-front', HALL_BLOCK, [0, height / 2, half + 1], [half * 2 + 4, height, 2], STONE),+ part('roof-near', HALL_BLOCK, [0, height + roofThickness / 2, (half + opening) / 2 + 1], [half * 2 + 4, roofThickness, half - opening + 2], STONE),+ part('roof-far', HALL_BLOCK, [0, height + roofThickness / 2, -(half + opening) / 2 - 1], [half * 2 + 4, roofThickness, half - opening + 2], STONE),+ part('roof-left', HALL_BLOCK, [-(half + opening) / 2 - 1, height + roofThickness / 2, 0], [half - opening + 2, roofThickness, opening * 2], STONE),+ part('roof-right', HALL_BLOCK, [(half + opening) / 2 + 1, height + roofThickness / 2, 0], [half - opening + 2, roofThickness, opening * 2], STONE),+ ];+ const ringCount = 16;+ for (let index = 0; index < ringCount; index++) {+ const angle = (index / ringCount) * Math.PI * 2;+ const [x, z] = [Math.cos(angle) * 24, Math.sin(angle) * 24];+ parts.push(part(`ring-column-${index}`, UNIT_CYLINDER, [x, 14, z], [1.5, 28, 1.5], STONE));+ parts.push(part(`ring-base-${index}`, HALL_BLOCK, [x, 0.7, z], [3.6, 1.4, 3.6], STONE));+ parts.push(part(`ring-capital-${index}`, HALL_BLOCK, [x, 28.7, z], [3.6, 1.4, 3.6], STONE));+ }+ // The beam lands about 14 m toward -x and -z of the opening.+ const [statueX, statueZ] = [-14, -12];+ parts.push(+ part('plinth-low', HALL_BLOCK, [statueX, 0.4, statueZ], [13, 0.8, 13], FLOOR_STONE),+ part('plinth-mid', HALL_BLOCK, [statueX, 1.2, statueZ], [10, 0.8, 10], STONE),+ part('plinth-high', HALL_BLOCK, [statueX, 2, statueZ], [7, 0.8, 7], FLOOR_STONE),+ part('statue-legs', HALL_BLOCK, [statueX, 3.4, statueZ], [5.2, 2, 3.4], gold),+ part('statue-torso', UNIT_CYLINDER, [statueX, 6.6, statueZ], [1.9, 4.4, 1.5], gold),+ part('statue-arms', HALL_BLOCK, [statueX, 6, statueZ + 1.4], [4.2, 1.2, 1.6], gold),+ part('statue-head', UNIT_SPHERE, [statueX, 9.6, statueZ], [1.15, 1.35, 1.15], gold),+ part('statue-crown', UNIT_CYLINDER, [statueX, 11, statueZ], [0.35, 1.2, 0.35], gold),+ );+ parts.push(...peopleParts([[-8, -2], [-12, 1, 1], [-3, -8, 2], [4, -5], [-19, -4, 4], [-2, 6, 5], [8, 14, 2], [11, 17, 1]]));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: [10, 8.8, 6.8], lightDirection: normalized(sunDirection), volumeFog: fogBox(0.016, [-half, 0, -half], [half, height - 0.5, half], 120) }),+ camera: { eye: [22, 1.8, 29], target: [-12, 7, -10], up: [0, 1, 0], fov: 62, near: 0.1, far: 200 },+ shadow: sunShadow(sunDirection, [0, 18, 0], 60, 120),+ };+}++// C: the setting sun down the axis of the nave. The far wall has a tall opening onto a glowing sky, so the columns stand as+// silhouettes in a glowing fog, their shadows run toward the camera, and a few people walk the carpet.+async function templeHallC() {+ const lighting = constantLighting(0.06);+ const sunDirection = [0.06, 0.2, -0.98];+ const [openingHalf, openingTop] = [10, 27];+ const parts = closedNaveParts();+ parts.push(+ part('wall-left', HALL_BLOCK, [-HALL.halfWidth - 1, HALL.roofHeight / 2, NAVE_MIDDLE], [2, HALL.roofHeight + 1, NAVE_LENGTH], STONE),+ part('wall-far-left', HALL_BLOCK, [-(HALL.halfWidth + openingHalf + 2) / 2, HALL.roofHeight / 2, HALL.back - 1], [HALL.halfWidth - openingHalf + 2, HALL.roofHeight + 1, 2], STONE),+ part('wall-far-right', HALL_BLOCK, [(HALL.halfWidth + openingHalf + 2) / 2, HALL.roofHeight / 2, HALL.back - 1], [HALL.halfWidth - openingHalf + 2, HALL.roofHeight + 1, 2], STONE),+ part('wall-far-top', HALL_BLOCK, [0, (openingTop + HALL.roofHeight + 1) / 2, HALL.back - 1], [openingHalf * 2, HALL.roofHeight + 1 - openingTop, 2], STONE),+ part('sky-glow', HALL_BLOCK, [0, 20, HALL.back - 40], [150, 90, 0.1], { color: [1, 0.62, 0.28], roughness: 1, emission: 7 }),+ part('sill', HALL_BLOCK, [0, 0.4, HALL.back - 5], [openingHalf * 2, 0.8, 8], FLOOR_STONE),+ );+ parts.push(...peopleParts([[0.8, 30], [-1.2, 22, 3], [1, 8], [-0.9, -6, 1], [1.2, -26, 2], [-1, -50], [0.5, -70, 4], [-10, 20], [12, 14, 1], [-16, -20, 2]]));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: [11, 8.4, 5.2], lightDirection: normalized(sunDirection), volumeFog: fogBox(0.011, [-HALL.halfWidth, 0, HALL.back], [HALL.halfWidth, HALL.roofHeight - 1, HALL.front + 2], 190, 0.65) }),+ camera: { eye: [0, 1.7, HALL.front - 3], target: [0, 10, -130], up: [0, 1, 0], fov: 58, near: 0.1, far: 400 },+ shadow: sunShadow(sunDirection, [0, 15, NAVE_MIDDLE], 105, 200),+ };+}++// ---------------------------------------------------------------------------------------------------------------------+// Megacity++const GROUND = { color: [0.1, 0.1, 0.11], roughness: 0.95 };+const ROAD = { color: [0.14, 0.14, 0.15], roughness: 0.6 };++function lampParts(prefix, positions, { height = 10, emission = 14, color = [1, 0.75, 0.4] } = {}) {+ const parts = [];+ positions.forEach(([x, z], index) => {+ parts.push(part(`${prefix}-post-${index}`, UNIT_BOX, [x, height / 2, z], [0.5, height, 0.5], { color: [0.15, 0.15, 0.16], roughness: 0.5, metallic: 0.8 }));+ parts.push(part(`${prefix}-head-${index}`, UNIT_BOX, [x, height + 0.2, z], [1.8, 0.5, 1.2], { color, roughness: 1, emission }));+ });+ return parts;+}++// Towers from a list of [x, z, height] sites, with the reference city's facades, windows and spires.+function towerParts(sites, seed) {+ const parts = [];+ const random = seededRandom(seed);+ sites.forEach(([x, z, towerHeight], index) => cityTowerParts(parts, UNIT_BOX, x, z, random, index, towerHeight));+ return parts;+}++// Sites on a grid with jitter. `heightAt(x, z, random)` gives the height, `skip(x, z)` leaves a gap.+function gridSites({ xs, zs, jitter = 6, heightAt, skip = () => false, seed }) {+ const random = seededRandom(seed);+ const sites = [];+ for (const z of zs) {+ for (const x of xs) {+ const [siteX, siteZ] = [x + (random() - 0.5) * jitter, z + (random() - 0.5) * jitter];+ if (random() < 0.12 || skip(siteX, siteZ)) continue;+ sites.push([siteX, siteZ, heightAt(siteX, siteZ, random)]);+ }+ }+ return sites;+}++// Values from `from` to `to` inclusive, in either direction.+const range = (from, to, step) => Array.from({ length: Math.floor(Math.abs(to - from) / step) + 1 }, (_, index) => from + Math.sign(to - from) * index * step);+const downtown = (x, z, centreZ, spreadX, spreadZ) => Math.exp(-(((z - centreZ) / spreadZ) ** 2)) * Math.exp(-((x / spreadX) ** 2));++// A: blue hour on a river. The sun is down, the sky goes from deep blue to a warm band on the horizon, and every bridge and+// quay is a line of light. Towers stand on both banks.+async function megacityDuskA() {+ const lighting = skyGradient({ zenith: [0.02, 0.06, 0.28], horizon: [0.7, 0.4, 0.35], ground: [0.05, 0.06, 0.1], power: 0.35, intensity: 0.6 });+ const riverHalf = 70;+ const parts = [+ part('city-ground', UNIT_BOX, [0, -1.5, -500], [9000, 2, 9000], GROUND),+ part('river', UNIT_BOX, [0, -1.2, -500], [riverHalf * 2, 1.4, 3200], WATER),+ ];+ for (const side of [-1, 1]) {+ parts.push(part(`quay-${side}`, UNIT_BOX, [side * (riverHalf + 18), 0.1, -500], [36, 0.3, 3200], ROAD));+ parts.push(part(`quay-edge-${side}`, UNIT_BOX, [side * (riverHalf + 0.6), 0.5, -500], [1.2, 1, 3200], { color: [0.2, 0.2, 0.21], roughness: 0.7 }));+ }+ parts.push(...lampParts('quay-lamp', range(260, -1040, 34).flatMap(z => [[-riverHalf - 4, z], [riverHalf + 4, z]]), { height: 9, emission: 16 }));+ const bridgeCentres = [60, -150, -380, -640];+ bridgeCentres.forEach((z, index) => {+ parts.push(part(`bridge-deck-${index}`, UNIT_BOX, [0, 6, z], [riverHalf * 2 + 30, 2.4, 22], { color: [0.12, 0.12, 0.13], roughness: 0.5 }));+ for (const edge of [-1, 1]) {+ parts.push(part(`bridge-light-${index}-${edge}`, UNIT_BOX, [0, 7.6, z + edge * 10.5], [riverHalf * 2 + 30, 0.5, 0.5], { color: [1, 0.8, 0.5], roughness: 1, emission: 9 }));+ parts.push(part(`bridge-rail-${index}-${edge}`, UNIT_BOX, [0, 7, z + edge * 11], [riverHalf * 2 + 30, 1.2, 0.3], { color: [0.15, 0.15, 0.16], roughness: 0.5, metallic: 0.7 }));+ }+ for (const pier of [-45, -15, 15, 45]) {+ parts.push(part(`bridge-pier-${index}-${pier}`, UNIT_BOX, [pier, 1.5, z], [4, 8, 14], { color: [0.2, 0.2, 0.21], roughness: 0.8 }));+ }+ parts.push(...lampParts(`bridge-lamp-${index}`, range(-60, 60, 30).flatMap(x => [[x, z - 9], [x, z + 9]]), { height: 7, emission: 12 }));+ });+ const xs = [...range(riverHalf + 60, riverHalf + 60 + 5 * 58, 58)].flatMap(x => [x, -x]);+ const sites = gridSites({+ xs, zs: range(280, -1100, 44), seed: 41,+ heightAt: (x, z, random) => 30 + downtown(x, z, -460, 380, 320) * 360 * (0.3 + random() * 0.95) * (random() < 0.05 ? 1.4 : 1),+ });+ parts.push(...towerParts(sites, 42));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: [0, 0, 0], lightDirection: normalized([0, 1, 0]) }),+ camera: { eye: [15, 28, 250], target: [0, 70, -600], up: [0, 1, 0], fov: 55, near: 1, far: 4000 },+ shadow: sunShadow([0, 1, 0], [0, 0, -420], 900, 2500),+ };+}++// B: sunrise across a bay. The camera stands at the end of a pier, the water between it and a skyline carries the glow, and+// the sun rises behind the towers.+async function megacityDuskB() {+ const lighting = skyGradient({ zenith: [0.1, 0.25, 0.65], horizon: [1, 0.55, 0.32], ground: [0.3, 0.2, 0.15], power: 0.4, intensity: 0.7 });+ const sunDirection = [0.18, 0.1, -0.98];+ const parts = [+ part('land', UNIT_BOX, [0, -1.5, -1600], [6000, 2, 2400], GROUND),+ part('bay', UNIT_BOX, [0, -1.2, 150], [6000, 1.4, 1100], WATER),+ part('harbour-quay', UNIT_BOX, [0, 0.1, -400], [6000, 0.5, 40], ROAD),+ ];+ parts.push(part('pier', UNIT_BOX, [0, 1.6, 300], [6, 0.5, 420], { color: [0.4, 0.3, 0.22], roughness: 0.7 }));+ for (let beam = 0; beam < 26; beam++) {+ parts.push(part(`pier-pile-${beam}`, UNIT_BOX, [beam % 2 ? 2.8 : -2.8, 0, 500 - beam * 16], [0.6, 3.2, 0.6], { color: [0.2, 0.15, 0.1], roughness: 0.9 }));+ }+ parts.push(...lampParts('pier-lamp', range(330, 60, 30).flatMap(z => [[-2.8, z], [2.8, z]]), { height: 5, emission: 6, color: [1, 0.7, 0.4] }));+ const boats = [[-22, 330, 0.2], [-34, 250, -0.15], [26, 280, 0.1], [24, 100, -0.3], [-14, 40, 0.4]];+ boats.forEach(([x, z, yaw], index) => {+ parts.push(turnedPart(`boat-hull-${index}`, UNIT_BOX, [x, 0.6, z], [4.4, 1.4, 12], { color: [0.9, 0.9, 0.88], roughness: 0.4 }, yaw));+ parts.push(turnedPart(`boat-cabin-${index}`, UNIT_BOX, [x, 2.2, z - 1], [3.2, 1.8, 5], { color: [0.2, 0.3, 0.45], roughness: 0.3 }, yaw));+ });+ const sites = gridSites({+ xs: range(-900, 900, 56), zs: range(-440, -1300, 42), seed: 61,+ heightAt: (x, z, random) => 26 + downtown(x, z, -900, 520, 360) * 420 * (0.3 + random() * 0.95) * (random() < 0.05 ? 1.4 : 1),+ });+ parts.push(...towerParts(sites, 62));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: [6.5, 3.6, 1.9], lightDirection: normalized(sunDirection) }),+ camera: { eye: [0.6, 8, 440], target: [0, 90, -700], up: [0, 1, 0], fov: 46, near: 1, far: 5000 },+ shadow: sunShadow(sunDirection, [0, 0, -500], 1400, 3000),+ };+}++// C: a night view from a tower top. Avenues are lines of car lights between dense, lit towers.+async function megacityDuskC() {+ const lighting = skyGradient({ zenith: [0.004, 0.007, 0.025], horizon: [0.06, 0.045, 0.08], power: 0.4, intensity: 1 });+ const parts = [part('city-ground', UNIT_BOX, [0, -1.5, -400], [9000, 2, 9000], GROUND)];+ const avenueXs = range(-500, 500, 125);+ const avenueZs = range(300, -1000, 130);+ for (const x of avenueXs) {+ parts.push(part(`avenue-x-${x}`, UNIT_BOX, [x, 0.05, -350], [26, 0.1, 1700], ROAD));+ parts.push(part(`cars-white-${x}`, UNIT_BOX, [x - 4, 0.3, -350], [1, 0.4, 1700], { color: [1, 0.9, 0.7], roughness: 1, emission: 3 }));+ parts.push(part(`cars-red-${x}`, UNIT_BOX, [x + 4, 0.3, -350], [1, 0.4, 1700], { color: [1, 0.12, 0.08], roughness: 1, emission: 3 }));+ }+ for (const z of avenueZs) {+ parts.push(part(`avenue-z-${z}`, UNIT_BOX, [0, 0.06, z], [1300, 0.1, 26], ROAD));+ parts.push(part(`cars-z-white-${z}`, UNIT_BOX, [0, 0.3, z - 4], [1300, 0.4, 1], { color: [1, 0.9, 0.7], roughness: 1, emission: 3 }));+ parts.push(part(`cars-z-red-${z}`, UNIT_BOX, [0, 0.3, z + 4], [1300, 0.4, 1], { color: [1, 0.12, 0.08], roughness: 1, emission: 3 }));+ }+ const sites = gridSites({+ xs: range(-560, 560, 125).map(value => value + 62), zs: range(240, -1000, 130).map(value => value - 65), jitter: 8, seed: 81,+ skip: () => false,+ heightAt: (siteX, siteZ, random) => 40 + downtown(siteX, siteZ, -380, 420, 520) * 470 * (0.3 + random() * 0.95) * (random() < 0.05 ? 1.4 : 1),+ });+ // Four towers fill each block, so the grid reads as city and not as a few stems.+ const blockSites = sites.flatMap(([siteX, siteZ, towerHeight]) => [[siteX - 22, siteZ - 22, towerHeight], [siteX + 22, siteZ + 22, towerHeight * 0.7], [siteX + 22, siteZ - 22, towerHeight * 0.45], [siteX - 22, siteZ + 22, towerHeight * 0.6]]);+ parts.push(...towerParts(blockSites, 82));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: [0, 0, 0], lightDirection: normalized([0, 1, 0]) }),+ camera: { eye: [300, 470, 760], target: [0, 20, -250], up: [0, 1, 0], fov: 54, near: 1, far: 5000 },+ shadow: sunShadow([0, 1, 0], [0, 0, -400], 900, 2500),+ };+}++export const GRAND_SCENES = {+ 'mountain-valley-a': mountainValleyA,+ 'mountain-valley-b': mountainValleyB,+ 'mountain-valley-c': mountainValleyC,+ 'temple-hall-a': templeHallA,+ 'temple-hall-b': templeHallB,+ 'temple-hall-c': templeHallC,+ 'megacity-dusk-a': megacityDuskA,+ 'megacity-dusk-b': megacityDuskB,+ 'megacity-dusk-c': megacityDuskC,+};+diff --git a/bench/reference/grand-sheets.py b/bench/reference/grand-sheets.pynew file mode 100644index 00000000..6f61db89--- /dev/null+++ b/bench/reference/grand-sheets.py@@ -0,0 +1,69 @@+"""Comparison sheets for the grand scene options (issue #168): one sheet per scene, one row per option.++Each row has the Cycles render and the 67js render side by side, labelled with the option letter, the FLIP score of 67js+against Cycles and the Cycles time. Run after `npm run reference -- --grand`:++ uv run --no-project --python 3.12 --with pillow --with numpy --with flip-evaluator python -I bench/reference/grand-sheets.py <output directory>+"""+import json+import sys+from pathlib import Path++import numpy as np+from PIL import Image, ImageDraw, ImageFont++WORK_DIRECTORY = Path("artifacts/reference-grand")+REPORT = Path("bench/reference/grand.json")+SCENES = ["mountain-valley", "temple-hall", "megacity-dusk"]+PANEL_SIZE = (800, 450)+LABEL_HEIGHT = 44+++def load_tone_map():+ # score.py runs main() when it is imported, so take its functions without the last call.+ source = Path("bench/reference/score.py").read_text(encoding="utf-8").rstrip()+ assert source.endswith("main()")+ namespace = {"__name__": "score_functions"}+ exec(compile(source[: -len("main()")], "score.py", "exec"), namespace)+ return namespace["tone_map_like_67js"]+++def to_image(display_array):+ return Image.fromarray(np.clip(np.asarray(display_array) * 255 + 0.5, 0, 255).astype(np.uint8)).resize(PANEL_SIZE, Image.LANCZOS)+++def font(size):+ for name in ("arialbd.ttf", "arial.ttf"):+ try:+ return ImageFont.truetype(name, size)+ except OSError:+ continue+ return ImageFont.load_default()+++def main():+ output_directory = Path(sys.argv[1])+ output_directory.mkdir(parents=True, exist_ok=True)+ report = json.loads(REPORT.read_text(encoding="utf-8"))+ tone_map = load_tone_map()+ for scene_id in SCENES:+ sheet = Image.new("RGB", (PANEL_SIZE[0] * 2 + 12, (PANEL_SIZE[1] + LABEL_HEIGHT) * 3), (18, 18, 20))+ draw = ImageDraw.Draw(sheet)+ for row, letter in enumerate("abc"):+ option_id = f"{scene_id}-{letter}"+ top = row * (PANEL_SIZE[1] + LABEL_HEIGHT)+ cycles = to_image(tone_map(np.load(WORK_DIRECTORY / f"{option_id}-cycles.npy")))+ gpu = Image.open(WORK_DIRECTORY / f"{option_id}-gpu.png").convert("RGB").resize(PANEL_SIZE, Image.LANCZOS)+ sheet.paste(cycles, (0, top + LABEL_HEIGHT))+ sheet.paste(gpu, (PANEL_SIZE[0] + 12, top + LABEL_HEIGHT))+ flip = report["scores"][option_id]["gpu-vs-cycles"]+ seconds = report["seconds"][option_id]["cycles"]+ draw.text((12, top + 6), letter.upper(), font=font(30), fill=(255, 214, 90))+ draw.text((60, top + 12), f"Cycles ({seconds:.0f} s)", font=font(22), fill=(230, 230, 230))+ draw.text((PANEL_SIZE[0] + 24, top + 12), f"67js FLIP {flip:.4f}", font=font(22), fill=(230, 230, 230))+ path = output_directory / f"{scene_id}.png"+ sheet.save(path)+ print(path)+++main()diff --git a/bench/reference/grand.json b/bench/reference/grand.jsonnew file mode 100644index 00000000..e2c4b597--- /dev/null+++ b/bench/reference/grand.json@@ -0,0 +1,120 @@+{+ "metric": "FLIP (LDR), mean error, lower is better",+ "blenderVersion": "5.2.2 LTS",+ "seconds": {+ "megacity-dusk-a": {+ "cycles": 28.9,+ "eevee": 42.4+ },+ "megacity-dusk-b": {+ "cycles": 33.2,+ "eevee": 27.7+ },+ "megacity-dusk-c": {+ "cycles": 35.9,+ "eevee": 26.7+ },+ "mountain-valley-b": {+ "cycles": 24.5,+ "eevee": 5.8+ },+ "mountain-valley-c": {+ "cycles": 52.7,+ "eevee": 24.7+ },+ "temple-hall-a": {+ "cycles": 21.7,+ "eevee": 2.7+ },+ "temple-hall-b": {+ "cycles": 25.4,+ "eevee": 1.6+ },+ "temple-hall-c": {+ "cycles": 23.4,+ "eevee": 2.2+ },+ "mountain-valley-a": {+ "cycles": 26.3,+ "eevee": 20.0+ }+ },+ "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": {+ "megacity-dusk-a": {+ "gpu-vs-cycles": 0.1978,+ "gpu-vs-eevee": 0.1556,+ "cpu-vs-cycles": 0.1972,+ "cpu-vs-eevee": 0.1571,+ "eevee-vs-cycles": 0.1404,+ "gpu-vs-cpu": 0.0154+ },+ "megacity-dusk-b": {+ "gpu-vs-cycles": 0.1575,+ "gpu-vs-eevee": 0.1476,+ "cpu-vs-cycles": 0.1584,+ "cpu-vs-eevee": 0.1487,+ "eevee-vs-cycles": 0.1041,+ "gpu-vs-cpu": 0.0252+ },+ "megacity-dusk-c": {+ "gpu-vs-cycles": 0.1149,+ "gpu-vs-eevee": 0.0647,+ "cpu-vs-cycles": 0.1087,+ "cpu-vs-eevee": 0.0657,+ "eevee-vs-cycles": 0.098,+ "gpu-vs-cpu": 0.0419+ },+ "mountain-valley-a": {+ "gpu-vs-cycles": 0.353,+ "gpu-vs-eevee": 0.2928,+ "cpu-vs-cycles": 0.3539,+ "cpu-vs-eevee": 0.2933,+ "eevee-vs-cycles": 0.1756,+ "gpu-vs-cpu": 0.0106+ },+ "mountain-valley-b": {+ "gpu-vs-cycles": 0.1839,+ "gpu-vs-eevee": 0.1472,+ "cpu-vs-cycles": 0.184,+ "cpu-vs-eevee": 0.1467,+ "eevee-vs-cycles": 0.13,+ "gpu-vs-cpu": 0.0157+ },+ "mountain-valley-c": {+ "gpu-vs-cycles": 0.2282,+ "gpu-vs-eevee": 0.163,+ "cpu-vs-cycles": 0.2273,+ "cpu-vs-eevee": 0.1619,+ "eevee-vs-cycles": 0.1504,+ "gpu-vs-cpu": 0.017+ },+ "temple-hall-a": {+ "gpu-vs-cycles": 0.253,+ "gpu-vs-eevee": 0.4215,+ "cpu-vs-cycles": 0.2533,+ "cpu-vs-eevee": 0.4211,+ "eevee-vs-cycles": 0.4986,+ "gpu-vs-cpu": 0.0064+ },+ "temple-hall-b": {+ "gpu-vs-cycles": 0.3642,+ "gpu-vs-eevee": 0.234,+ "cpu-vs-cycles": 0.3644,+ "cpu-vs-eevee": 0.2335,+ "eevee-vs-cycles": 0.4743,+ "gpu-vs-cpu": 0.0054+ },+ "temple-hall-c": {+ "gpu-vs-cycles": 0.2746,+ "gpu-vs-eevee": 0.2216,+ "cpu-vs-cycles": 0.2749,+ "cpu-vs-eevee": 0.2213,+ "eevee-vs-cycles": 0.3989,+ "gpu-vs-cpu": 0.0028+ }+ }+}diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex fb4194ed..bc07684e 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -1,6 +1,7 @@// 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, KHRONOS_SCENES, CLOTH_SCENES } from './scenes.js';+import { GRAND_SCENES } from './grand-scenes.js';import { skinnedGeometry } from '/src/path-tracer-scene.js';import { boxProjectedGeometry } from '/src/export-box-uv.js';import '/src/material-layer-shaders.js';@@ -9,7 +10,7 @@ import { applyLightLinks } from '/src/light-linking.js';// ?set=khronos draws the Khronos sample assets (npm run reference -- --khronos) and ?set=cloth the cloth scenes// (npm run reference -- --cloth) instead of the fixed scenes.-const SCENE_SETS = { khronos: KHRONOS_SCENES, cloth: CLOTH_SCENES };+const SCENE_SETS = { khronos: KHRONOS_SCENES, cloth: CLOTH_SCENES, grand: GRAND_SCENES };const SCENES = SCENE_SETS[new URLSearchParams(location.search).get('set')] ?? REFERENCE_SCENES;function encodeBytes(typedArray) {diff --git a/bench/reference/images/grand-megacity-dusk-a.jpg b/bench/reference/images/grand-megacity-dusk-a.jpgnew file mode 100644index 00000000..2799cd90Binary files /dev/null and b/bench/reference/images/grand-megacity-dusk-a.jpg differdiff --git a/bench/reference/images/grand-megacity-dusk-b.jpg b/bench/reference/images/grand-megacity-dusk-b.jpgnew file mode 100644index 00000000..f4d03666Binary files /dev/null and b/bench/reference/images/grand-megacity-dusk-b.jpg differdiff --git a/bench/reference/images/grand-megacity-dusk-c.jpg b/bench/reference/images/grand-megacity-dusk-c.jpgnew file mode 100644index 00000000..35054e10Binary files /dev/null and b/bench/reference/images/grand-megacity-dusk-c.jpg differdiff --git a/bench/reference/images/grand-mountain-valley-a.jpg b/bench/reference/images/grand-mountain-valley-a.jpgnew file mode 100644index 00000000..abaeb1c5Binary files /dev/null and b/bench/reference/images/grand-mountain-valley-a.jpg differdiff --git a/bench/reference/images/grand-mountain-valley-b.jpg b/bench/reference/images/grand-mountain-valley-b.jpgnew file mode 100644index 00000000..5d3f2d8bBinary files /dev/null and b/bench/reference/images/grand-mountain-valley-b.jpg differdiff --git a/bench/reference/images/grand-mountain-valley-c.jpg b/bench/reference/images/grand-mountain-valley-c.jpgnew file mode 100644index 00000000..1e143cb6Binary files /dev/null and b/bench/reference/images/grand-mountain-valley-c.jpg differdiff --git a/bench/reference/images/grand-temple-hall-a.jpg b/bench/reference/images/grand-temple-hall-a.jpgnew file mode 100644index 00000000..09ebf42dBinary files /dev/null and b/bench/reference/images/grand-temple-hall-a.jpg differdiff --git a/bench/reference/images/grand-temple-hall-b.jpg b/bench/reference/images/grand-temple-hall-b.jpgnew file mode 100644index 00000000..77eef63cBinary files /dev/null and b/bench/reference/images/grand-temple-hall-b.jpg differdiff --git a/bench/reference/images/grand-temple-hall-c.jpg b/bench/reference/images/grand-temple-hall-c.jpgnew file mode 100644index 00000000..aaa8f64bBinary files /dev/null and b/bench/reference/images/grand-temple-hall-c.jpg differdiff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.pyindex d84df33c..49826789 100644--- a/bench/reference/render-blender.py+++ b/bench/reference/render-blender.py@@ -492,6 +492,27 @@ def build_cloth(scene, description):scene.collection.objects.link(bpy.data.objects.new("cloth", baked_mesh))+def gradient_sky_image(sky):+ """Sky colour by elevation: horizon to zenith above the horizon (raised to `power`), horizon to ground below it.++ grand-scenes.js (skyGradient) uses the same formula; its first row is the zenith, and Blender images start at the bottom."""+ import numpy+ width, height = 256, 128+ elevation = (numpy.arange(height) + 0.5) / height * math.pi - math.pi / 2+ sine = numpy.sin(elevation)+ above = numpy.clip(sine, 0, 1) ** sky["power"]+ below = numpy.clip(-sine * 4, 0, 1)+ horizon, zenith, ground = (numpy.array(sky[name]) for name in ("horizon", "zenith", "ground"))+ colors = horizon + (zenith - horizon) * above[:, None]+ colors = colors + (ground - colors) * below[:, None]+ pixels = numpy.ones((height, width, 4), dtype=numpy.float32)+ pixels[:, :, :3] = colors[:, None, :]+ image = bpy.data.images.new("gradient-sky", width, height, float_buffer=True)+ image.colorspace_settings.name = "Linear Rec.709"+ image.pixels.foreach_set(pixels.ravel())+ return image++def build_world(scene, world_description, root):world = bpy.data.worlds.new("World")world.use_nodes = True@@ -508,6 +529,14 @@ def build_world(scene, world_description, root):mapping = nodes.new("ShaderNodeMapping")mapping.inputs["Rotation"].default_value = (0, 0, ENVIRONMENT_ROTATION_Z)texture = nodes.new("ShaderNodeTexEnvironment")+ if world_description["type"] == "gradient":+ # The same equirectangular gradient that grand-scenes.js hands to 67js, written as an image.+ texture.image = gradient_sky_image(world_description)+ 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 = 1+ returntexture.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"])@@ -736,7 +765,12 @@ def main():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:+ timings_path = os.path.join(work_directory, "blender-timings.json")+ if only and os.path.exists(timings_path):+ # A run of some scenes keeps the times of the others, so the scores of the whole directory still have them.+ with open(timings_path, encoding="utf-8") as file:+ timings = {**json.load(file)["seconds"], **timings}+ with open(timings_path, "w", encoding="utf-8") as file:json.dump({"blenderVersion": bpy.app.version_string, "seconds": timings}, file, indent=1)diff --git a/bench/reference/run.mjs b/bench/reference/run.mjsindex 11e72922..b2be10b2 100644--- a/bench/reference/run.mjs+++ b/bench/reference/run.mjs@@ -20,7 +20,9 @@ import { createServer } from 'vite';// cloth bake, and scores them into cloth.json the same way (the pixels the scene covers, with the sky left out).const khronos = process.argv.includes('--khronos');const cloth = process.argv.includes('--cloth');-const sceneSet = khronos ? 'khronos' : cloth ? 'cloth' : null;+// --grand draws the options for the grand scenes (grand-scenes.js, issue #168) and scores them into grand.json.+const grand = process.argv.includes('--grand');+const sceneSet = khronos ? 'khronos' : cloth ? 'cloth' : grand ? 'grand' : null;const WORK_DIRECTORY = resolve(sceneSet ? `artifacts/reference-${sceneSet}` : 'artifacts/reference');const OUTPUT_DIRECTORY = resolve('bench/reference');const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';@@ -98,7 +100,7 @@ async function renderBackend(backend, serverUrl, graphics) {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));- if (sceneSet && describe) {+ if ((khronos || cloth) && describe) {const background = await page.evaluate(sceneId => window.renderReferenceScene(sceneId, { describe: false, backgroundOnly: true }), id);await writeFile(`${WORK_DIRECTORY}/${id}-background.png`, Buffer.from(background.image, 'base64'));}diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsindex 7b453473..f3b7bc05 100644--- a/bench/reference/scenes.js+++ b/bench/reference/scenes.js@@ -27,7 +27,7 @@ function placedMatrix(translation, scale) {]);}-function part(name, geometry, translation, scale, material) {+export 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 } };}@@ -35,7 +35,7 @@ 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) {+export async function skyLighting(intensity = 1) {const response = await fetch(HDRI_URL);const parsed = parseRadianceHdr(await response.arrayBuffer());const data = parsed.data.map((radiance) => Math.min(radiance, HDRI_RADIANCE_LIMIT));@@ -43,20 +43,20 @@ async function skyLighting(intensity = 1) {return { map, blenderWorld: { type: 'hdri', file: HDRI_FILE, intensity, radianceLimit: HDRI_RADIANCE_LIMIT } };}-function constantLighting(value) {+export 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 = [], spotLights = [], areaLights = [], volumeFog } = {}) {+export function environment(lighting, { lightDirection = [-3, 6, 4], keyColor = [0, 0, 0], pointLights = [], spotLights = [], areaLights = [], volumeFog } = {}) {return {world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0, lightDirection, keyColor, pointLights, spotLights, areaLights,map: lighting.map, ...(volumeFog ? { volumeFog } : {}),};}-const SUN_COLOR = [3, 2.8, 2.5];+export const SUN_COLOR = [3, 2.8, 2.5];// A wall of bricks written as a material graph: a triangle wave across each course for the mortar joints, half a brick of// shift on every second course, noise through a colour ramp for the brick tone. Blender gets the same graph as nodes.@@ -170,7 +170,7 @@ export const KHRONOS_SCENES = Object.fromEntries(KHRONOS_ASSET_NAMES.map(name =>// Grand scenes: the scale people actually want to draw, built from the engine's terrain, vegetation and plain boxes.// Only what Blender can draw too is used: the terrain colours are vertex colours, the emissive windows are Emission, the// fog is a volume box. The built-in leaf translucency of 67js has no Blender counterpart (see the README).-function seededRandom(seed) {+export function seededRandom(seed) {let state = seed >>> 0;return () => {state = (state + 0x6d2b79f5) >>> 0;@@ -180,32 +180,32 @@ function seededRandom(seed) {};}-function clamp01(value) {+export function clamp01(value) {return Math.min(1, Math.max(0, value));}-function smoothBetween(low, high, value) {+export function smoothBetween(low, high, value) {const fraction = clamp01((value - low) / (high - low));return fraction * fraction * (3 - 2 * fraction);}-function mixColors(first, second, amount) {+export function mixColors(first, second, amount) {return first.map((channel, index) => channel + (second[index] - channel) * amount);}-function normalized(vector) {+export function normalized(vector) {const length = Math.hypot(...vector);return vector.map(component => component / length);}// A shadow map that looks along the sun from `depth` metres away and covers a square of half-width `extent`.-function sunShadow(towardLight, target, extent, depth) {+export function sunShadow(towardLight, target, extent, depth) {const direction = normalized(towardLight);return { eye: target.map((value, axis) => value + direction[axis] * depth), target, up: [0, 1, 0], extent, near: 1, far: depth * 2 };}// Mountain valley: a bowl about 2 km across whose rim rises into ridged peaks, a conifer forest on the lower slopes.-const VALLEY_TERRAIN = { size: 5120, chunks: 20, resolution: 64, levels: 4 };+export const VALLEY_TERRAIN = { size: 5120, chunks: 20, resolution: 64, levels: 4 };const VALLEY_FLOOR_RADIUS = 520;const VALLEY_RIM_RADIUS = 1500;const VALLEY_SNOW_LINE = 520;@@ -266,8 +266,8 @@ async function mountainValleyScene() {// Temple hall: a nave 140 m long between four rows of columns 30 m tall, a roof with square openings that let the sun// fall through fog, a bright window at the far end and a few small figures near the camera for scale.-const HALL_BLOCK = box(0, 1);-const HALL = { halfWidth: 33, front: 50, back: -130, columnHeight: 30, columnRadius: 1.6, roofHeight: 31.5 };+export const HALL_BLOCK = box(0, 1);+export const HALL = { halfWidth: 33, front: 50, back: -130, columnHeight: 30, columnRadius: 1.6, roofHeight: 31.5 };const HALL_COLUMN_ROWS = [-22, -11, 11, 22];const HALL_COLUMN_PITCH = 12;const HALL_COLUMN_COUNT = 11;@@ -277,7 +277,7 @@ const HALL_OPENING_COUNT = 6;const HALL_OPENING_FIRST_Z = -5;const HALL_OPENING_SIZE = [10, 7];-function hallRoofParts(parts, stone) {+export function hallRoofParts(parts, stone) {const roofThickness = 2;const length = HALL.front - HALL.back;const middleZ = (HALL.front + HALL.back) / 2;@@ -294,7 +294,7 @@ function hallRoofParts(parts, stone) {}}-function hallColumnParts(parts, stone) {+export function hallColumnParts(parts, stone) {const column = cylinder(48, 0, 1);for (const [rowIndex, x] of HALL_COLUMN_ROWS.entries()) {for (let index = 0; index < HALL_COLUMN_COUNT; index++) {@@ -308,7 +308,7 @@ function hallColumnParts(parts, stone) {}}-function hallFigureParts(parts) {+export function hallFigureParts(parts) {const body = cylinder(16, 0, 1);const head = sphere(16, 10);const robes = [[0.5, 0.1, 0.08], [0.1, 0.2, 0.45], [0.55, 0.45, 0.15], [0.15, 0.3, 0.18], [0.4, 0.4, 0.42]];@@ -429,13 +429,13 @@ const CITY_ROW_COUNT = 29;const CITY_CENTER_Z = -430;const CITY_SUN_DIRECTION = [-0.7, 0.14, -0.35];const WINDOW_PITCH = 6.5;-const FACADE_STYLES = [+export const FACADE_STYLES = [{ color: [0.07, 0.09, 0.13], metallic: 0.3, roughness: 0.25 },{ color: [0.3, 0.3, 0.32], metallic: 0, roughness: 0.8 },{ color: [0.38, 0.31, 0.25], metallic: 0, roughness: 0.75 },{ color: [0.14, 0.16, 0.2], metallic: 0.5, roughness: 0.3 },];-const WINDOW_STYLES = [+export const WINDOW_STYLES = [{ color: [1, 0.7, 0.35], emission: 1.1 },{ color: [1, 0.8, 0.55], emission: 1 },{ color: [0.6, 0.78, 1], emission: 0.9 },@@ -447,12 +447,12 @@ function towerHeight(x, z, random) {return random() < 0.04 ? ridge * 1.5 : ridge;}-function cityTowerParts(parts, towerBox, x, z, random, towerIndex) {+export function cityTowerParts(parts, towerBox, x, z, random, towerIndex, heightOverride) {const width = 24 + random() * 16;const depth = 24 + random() * 16;const facade = FACADE_STYLES[Math.floor(random() * FACADE_STYLES.length)];const windows = WINDOW_STYLES[Math.floor(random() * WINDOW_STYLES.length)];- const totalHeight = towerHeight(x, z, random);+ const totalHeight = heightOverride ?? towerHeight(x, z, random);const tierCount = totalHeight > 90 ? 1 + Math.floor(random() * 3) : 1;let baseY = 0;for (let tier = 0; tier < tierCount; tier++) {diff --git a/bench/reference/score.py b/bench/reference/score.pyindex 4a0148c7..d5f4e3e5 100644--- a/bench/reference/score.py+++ b/bench/reference/score.py@@ -105,8 +105,8 @@ def main():return# Khronos assets and cloth sheets sit in front of a sky that both sides draw alike, so they also get a score over the# pixels the scene covers.- set_name = "khronos" if "--khronos" in sys.argv else "cloth" if "--cloth" in sys.argv else None- khronos = set_name is not None+ set_name = "khronos" if "--khronos" in sys.argv else "cloth" if "--cloth" in sys.argv else "grand" if "--grand" in sys.argv else None+ khronos = set_name in ("khronos", "cloth")work_directory = Path(sys.argv[1])output_directory = Path(sys.argv[2])images_directory = output_directory / "images"