Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

chore(render-lab): GI scenes against Cycles measure how much bounce light SSGI, Voxel GI and the bake give, off screen and from emissive surfaces included

yhh76907368fe1e
diff --git a/tools/render-lab/README.md b/tools/render-lab/README.md
index 1e519cad3..b8f3deb29 100644
--- a/tools/render-lab/README.md
+++ b/tools/render-lab/README.md
@@ -19,3 +19,48 @@ Blender renders with the Standard view transform and the engine with no output t
strength S lights a white diffuse surface to S / pi; the engine's sun of intensity I to I, so the lab gives Blender pi times the engine's intensity.
`sourceAngle` is in degrees in the engine and radians in Blender. Spheres stand three metres apart so one does not light another (the engine has
no bounce light by default; Blender has twelve bounces).
+
+## Global illumination
+
+`gi_specs.py` holds four rooms of boxes, built the same way on both sides: Blender draws the boxes in metres, and the engine draws them as `builtin:cube` in centimetres. There is no sky, so every pixel the sun does not reach directly shows only what the GI method gives it. Cycles (12 bounces) is the truth here, not another engine's approximation.
+
+| Scene | What it asks |
+| --- | --- |
+| `gi_room` | A Cornell-like room lit through a skylight: bounce brightness, colour bleed off the red and green walls, the block's shaded face |
+| `gi_away` | The same light with the camera turned so the lit patch is off screen: light the picture does not show |
+| `gi_leak` | The room closed with the sun outside: anything inside is leak |
+| `gi_emissive` | Closed and dark but for an emissive panel |
+
+```bash
+B="/c/Program Files/Blender Foundation/Blender 5.2/blender.exe"; O=D:/estella/output/render-lab/gi
+"$B" --background --python tools/render-lab/gi_ref.py -- gi_room $O/ref_gi_room.png
+EFFECTS='[{"type":"voxelGI","enabled":true,"uniforms":{}}]' bash tools/render-lab/gi-run.sh gi_room vgi # BAKE=1 bakes lightmaps first
+python tools/render-lab/gi_compare.py gi_room $O/ref_gi_room.png vgi=$O/engine_vgi.png
+node tools/render-lab/gi_cost.mjs $O/web_vgi # frame ms, GPU ms per pass
+```
+
+### 2026-11-05 results
+
+Each figure is a region's linear value in the engine as a share of Cycles' value there; 1.00 matches. WebGL2 numbers come from headless Chromium. The WebGPU column is the compute path, rendered in the MCP's hidden editor.
+
+| Region | Cycles | no GI | SSGI (radius 400) | Voxel GI default, WebGL2 | Voxel GI default, WebGPU |
+| --- | --- | --- | --- | --- | --- |
+| `gi_room` ceiling | 0.030 | 0 | 0 | 0.30 | 0.23 |
+| `gi_room` back wall | 0.021 | 0 | 0.02 | 0.17 | 0.09 |
+| `gi_room` floor in shade | 0.018 | 0 | 0 | 0.02 | 0.01 |
+| `gi_room` block, shaded face | 0.004 | 0 | 0 | 0 | 0 |
+| `gi_away`, every region | 0.010–0.014 | 0 | 0 | 0 | — |
+| `gi_emissive` ceiling | 0.16 | 0 | 0.07 | 0.12 | — |
+| `gi_emissive` floor | 0.14 | 0 | 0.04 | 0.08 | — |
+
+- **Too little light.** Where the engine's GI reaches at all, it gives a tenth to a third of the bounce Cycles does. Faces that only a second bounce reaches (the block's shaded side, the floor away from the patch) get nothing.
+- **Nothing off screen.** Both methods seed from the frame's own picture, so `gi_away` is black under every method. A surface cache lit independently of the view is what changes this.
+- **No colour bleed.** On the red wall the engine's red channel is 0.10–0.32 of Cycles, but green and blue are 1–5×. The bounce arrives grey, and the wall's albedo does not tint it the way Cycles does. The green wall shows the same.
+- **No leak in `gi_leak`.** That is only because the lit outside is never on screen, so there is nothing to leak.
+- **Banding.** The WebGL2 voxel fallback and SSGI both band visibly in the emissive room.
+- **The bake shows nothing on built-in meshes.** `BAKE=1` renders pixel-identical to no GI. `bake-scene` unwraps a built-in mesh for the bake (`pipeline/src/assets/lightmapBake.ts`), but the runtime's `builtin:cube` has no `TexCoord1`, so `MESH_LIGHTMAP` is never on and the atlas is never read. `examples/physics-3d` bakes `builtin:cube` too.
+- **Direct light is 19% bright.** The sun patch is 1.19 of Cycles on both backends. This is separate from GI and not explained yet.
+
+GPU cost at 1280×720, WebGL2, on this desktop:
+- SSGI: gather 0.8–0.9 ms + apply 0.4 ms. Frame 1.25 → 2.8 ms.
+- Voxel GI: voxels 0.6 ms + gather 1.9 ms + apply 0.1 ms. Frame → 4.3 ms.
diff --git a/tools/render-lab/gi-run.sh b/tools/render-lab/gi-run.sh
new file mode 100644
index 000000000..7f8d14209
--- /dev/null
+++ b/tools/render-lab/gi-run.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# The engine's picture of a GI lab scene: <out>/engine_<name>.png.
+# usage: gi-run.sh <lab> [name] env: BACKEND (webgl2|webgpu) EFFECTS (json list) Q BAKE=1 OUT WAIT (ms, default 12000)
+set -e
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -W)"
+ROOT="$(cd "$HERE/../.." && pwd -W)"
+OUT="${OUT:-$ROOT/output/render-lab/gi}"
+mkdir -p "$OUT"
+LAB=$1; NAME=${2:-$LAB}
+P="$OUT/proj_$NAME"
+rm -rf "$P" "$OUT/web_$NAME"
+python "$HERE/gi_project.py" "$P" "$LAB" > /dev/null
+cd "$ROOT"
+node tools/asset-meta.js "$P/assets" > /dev/null 2>&1
+if [ "$BAKE" = "1" ]; then
+ node pipeline/bin/estella.mjs bake-scene "$P/assets/scenes/lab.esscene" 2>&1 | tail -3
+ node tools/asset-meta.js "$P/assets" > /dev/null 2>&1
+ node pipeline/bin/estella.mjs bake-scene "$P/assets/scenes/lab.esscene" 2>&1 | tail -3
+ node tools/asset-meta.js "$P/assets" > /dev/null 2>&1
+fi
+node pipeline/bin/estella.mjs export "$P" --out "$OUT/web_$NAME" 2>&1 | grep -E '"ok"|error' | head -2
+node "$HERE/shot.mjs" "$OUT" "$OUT/web_$NAME" "$NAME" 2>&1 | grep -E "error|ERROR|warn|context" | head -8 | cut -c1-240 || true
+mv "$OUT/lab-$NAME.png" "$OUT/engine_$NAME.png"
+echo "engine_$NAME.png written to $OUT"
diff --git a/tools/render-lab/gi_compare.py b/tools/render-lab/gi_compare.py
new file mode 100644
index 000000000..86777603b
--- /dev/null
+++ b/tools/render-lab/gi_compare.py
@@ -0,0 +1,50 @@
+"""Reads a GI lab scene's regions in the Cycles picture and in one or more engine pictures, in linear light.
+python gi_compare.py <lab> <ref.png> <name=engine.png> [...] prints, per region, Cycles' linear value and each engine picture's share of it.
+The share is of the indirect light alone where the region is not lit directly, which is every region but the sun's patch.
+"""
+import os
+import sys
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import gi_specs as S # noqa: E402
+
+
+def lin(img):
+ c = img / 255.0
+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
+
+
+lab, ref_path = sys.argv[1:3]
+engines = [a.split('=', 1) for a in sys.argv[3:]]
+ref = lin(np.array(Image.open(ref_path).convert('RGB')).astype(float))
+eng = {n: lin(np.array(Image.open(p).convert('RGB')).astype(float)) for n, p in engines}
+spec = S.GI[lab]
+R = 10
+
+
+def patch(img, px, py):
+ return img[int(py) - R:int(py) + R, int(px) - R:int(px) + R].reshape(-1, 3).mean(0)
+
+
+rows = []
+for name, pt in S.REGIONS[lab]:
+ if pt is None:
+ pt = S.sun_patch_centre(lab)
+ px, py, z = S.project(pt, spec['cam'])
+ if z <= 0 or not (R <= px < S.SIZE[0] - R and R <= py < S.SIZE[1] - R):
+ print('%-22s off screen' % name)
+ continue
+ r = patch(ref, px, py)
+ cells = []
+ for n, im in eng.items():
+ e = patch(im, px, py)
+ cells.append('%s %s' % (n, ' '.join('%4.2f' % (e[k] / r[k]) if r[k] > 1e-3 else ' -- ' for k in range(3))))
+ rows.append(name)
+ print('%-22s cycles %.3f %.3f %.3f | %s' % (name, r[0], r[1], r[2], ' | '.join(cells)))
+
+# The whole picture: the share of Cycles' light (linear luminance summed over the frame) each engine picture holds, and the mean error.
+Y = lambda im: im @ np.array([0.2126, 0.7152, 0.0722])
+print('frame light share: ' + ' '.join('%s %.2f (mean |d| %.4f)' % (n, Y(im).sum() / Y(ref).sum(), np.abs(Y(im) - Y(ref)).mean()) for n, im in eng.items()))
diff --git a/tools/render-lab/gi_cost.mjs b/tools/render-lab/gi_cost.mjs
new file mode 100644
index 000000000..eae1afc7e
--- /dev/null
+++ b/tools/render-lab/gi_cost.mjs
@@ -0,0 +1,46 @@
+// What a GI variant of a lab scene costs a frame and how many frames its light takes to arrive, in headless Chromium (WebGL2).
+// usage: node gi_cost.mjs <web_dir> [...] prints frame ms (median of 20 x 8 frames), GPU ms per pass, and the frame's mean
+// luminance after 1, 4, 16, 64 and 240 frames, as a share of the last.
+import { pathToFileURL } from 'node:url';
+import path from 'node:path';
+const { chromium } = await import(pathToFileURL(path.resolve(import.meta.dirname, '../../node_modules/playwright/index.mjs')).href);
+const { serveHost } = await import(pathToFileURL(path.resolve(import.meta.dirname, '../lib/staticServer.mjs')).href);
+
+const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };
+const browser = await chromium.launch({ headless: true, args: ['--use-angle=d3d11', '--enable-webgl', '--ignore-gpu-blocklist'] });
+try {
+ for (const dir of process.argv.slice(2)) {
+ const server = await serveHost(path.resolve(dir));
+ const page = await browser.newPage({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 });
+ try {
+ await page.goto(`http://127.0.0.1:${server.address().port}/?headless`, { waitUntil: 'load', timeout: 120000 });
+ await page.waitForFunction(() => window.__estellaCooked?.facts, null, { timeout: 120000 });
+ await page.evaluate(() => window.__estellaCooked.setPaused(true));
+ const r = await page.evaluate(async () => {
+ const c = window.__estellaCooked;
+ const lum = () => { const { rgba } = c.capture(); let s = 0; for (let i = 0; i < rgba.length; i += 4) s += rgba[i] * 0.2126 + rgba[i + 1] * 0.7152 + rgba[i + 2] * 0.0722; return s / (rgba.length / 4); };
+ // Shaders compile on first use: a few frames, then the light is counted from frame 1.
+ for (let i = 0; i < 40; i++) { await c.step(1, 1 / 60); if (!(c.render()['render.draws.waitingForProgram'] > 0) && i > 4) break; await new Promise((res) => setTimeout(res, 30)); }
+ const curve = [];
+ let done = 0;
+ for (const n of [1, 4, 16, 64, 240]) { await c.step(n - done, 1 / 60); done = n; curve.push([n, lum()]); }
+ c.render(); c.costs();
+ const ms = [];
+ for (let s = 0; s < 20; s++) { const t0 = performance.now(); await c.step(8, 1 / 60); c.capture(); ms.push((performance.now() - t0) / 8); }
+ const gpu = [];
+ for (let s = 0; s < 12; s++) { await c.step(4, 1 / 60); c.capture(); await new Promise((res) => setTimeout(res, 40)); gpu.push(c.gpu?.() ?? {}); }
+ return { curve, ms, gpu };
+ });
+ const keys = new Set(r.gpu.flatMap((g) => Object.keys(g)));
+ const passes = [...keys].map((k) => [k, median(r.gpu.map((g) => g[k]).filter((v) => typeof v === 'number' && v >= 0))]).filter(([, v]) => v !== undefined && v > 0.02).sort((a, b) => b[1] - a[1]);
+ const last = r.curve.at(-1)[1] || 1;
+ console.log(`${path.basename(dir)}: frame ${median(r.ms).toFixed(2)} ms | light by frame ${r.curve.map(([n, l]) => `${n}:${(l / last).toFixed(2)}`).join(' ')}`);
+ console.log(' gpu ' + passes.slice(0, 10).map(([k, v]) => `${k} ${v.toFixed(2)}`).join(', '));
+ } finally {
+ await page.close();
+ server.close();
+ }
+ }
+} finally {
+ await browser.close();
+}
diff --git a/tools/render-lab/gi_project.py b/tools/render-lab/gi_project.py
new file mode 100644
index 000000000..a236f35d5
--- /dev/null
+++ b/tools/render-lab/gi_project.py
@@ -0,0 +1,65 @@
+"""The engine's side of a GI lab scene: a project whose scene is the boxes of gi_specs as built-in cubes, the camera and the sun.
+python gi_project.py <projectDir> <lab> (env BACKEND, EFFECTS (json list), Q (json quality), BAKE=1 adds a BakedLighting entity)
+"""
+import json
+import os
+import sys
+import uuid
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import gi_specs as S # noqa: E402
+import lab_specs as L # noqa: E402
+
+proj, lab = sys.argv[1:3]
+spec = S.GI[lab]
+os.makedirs(proj + '/assets/scenes', exist_ok=True)
+os.makedirs(proj + '/assets/materials', exist_ok=True)
+json.dump({'formatVersion': '1', 'name': 'GiLab', 'version': '0.1.0', 'tag': '3D', 'defaultScene': 'assets/scenes/lab.esscene',
+ 'designResolution': {'width': S.SIZE[0], 'height': S.SIZE[1]}, 'spineVersion': 'none',
+ 'features': {'rendering': {'backend': os.environ.get('BACKEND', 'webgl2'), 'colorSpace': 'linear', 'outputTransform': 'none',
+ 'quality': dict({'mode': 'high'}, **json.loads(os.environ.get('Q', '{}')))}}},
+ open(proj + '/project.esproject', 'w'), indent=2)
+
+pos, target, fov = spec['cam']
+qw, qx, qy, qz = L.cam_quaternion(spec['cam'])
+entities = [{'id': 0, 'name': 'Camera', 'parent': None, 'children': [], 'visible': True, 'components': [
+ {'type': 'Transform', 'data': {'position': {'x': pos[0], 'y': pos[1], 'z': pos[2]}, 'rotation': {'w': qw, 'x': qx, 'y': qy, 'z': qz}}},
+ {'type': 'Camera', 'data': {'projectionType': 0, 'fov': fov, 'nearPlane': 5.0, 'farPlane': 5000.0, 'isActive': True, 'priority': 0, 'clearFlags': 3}}]}]
+
+panel_material = None
+if 'emission' in spec:
+ e = spec['emission']
+ mid = str(uuid.uuid4())
+ json.dump({'version': '1.0', 'type': 'material', 'shader': 'builtin:model', 'blendMode': 0, 'depthTest': True, 'depthWrite': True,
+ 'properties': {'u_emissive': {'r': e, 'g': e, 'b': e, 'a': 1}, 'u_roughness': 1}},
+ open(proj + '/assets/materials/panel.esmaterial', 'w'), indent=2)
+ json.dump({'uuid': mid, 'version': '2.0', 'type': 'material', 'importer': {}}, open(proj + '/assets/materials/panel.esmaterial.meta', 'w'), indent=2)
+ panel_material = '@uuid:' + mid
+
+for i, (name, centre, size, colour) in enumerate(spec['boxes']):
+ mr = {'mesh': 'builtin:cube', 'lit': True, 'opaque': True, 'cullBackfaces': True,
+ 'color': {'r': colour[0], 'g': colour[1], 'b': colour[2], 'a': 1}}
+ if name == 'panel' and panel_material:
+ mr['material'] = panel_material
+ entities.append({'id': 10 + i, 'name': name, 'parent': None, 'children': [], 'visible': True, 'components': [
+ {'type': 'Transform', 'data': {'position': {'x': centre[0], 'y': centre[1], 'z': centre[2]},
+ 'scale': {'x': size[0] / 100.0, 'y': size[1] / 100.0, 'z': size[2] / 100.0}}},
+ {'type': 'MeshRenderer', 'data': mr}]})
+
+if spec['sun']:
+ sw, sx, sy, sz = L.sun_quaternion(spec['sun']['dir'])
+ entities.append({'id': 5, 'name': 'Sun', 'parent': None, 'children': [], 'visible': True, 'components': [
+ {'type': 'Transform', 'data': {'rotation': {'w': sw, 'x': sx, 'y': sy, 'z': sz}}},
+ {'type': 'Light', 'data': {'type': 1, 'color': {'r': 1, 'g': 1, 'b': 1, 'a': 1}, 'intensity': spec['sun']['intensity'], 'enabled': True,
+ 'meshShadows': True, 'shadowExtent': 0.0, 'shadowStrength': 1.0, 'sourceAngle': 0.0}}]})
+
+if os.environ.get('BAKE') == '1':
+ entities.append({'id': 6, 'name': 'Lighting', 'parent': None, 'children': [], 'visible': True, 'components': [
+ {'type': 'BakedLighting', 'data': {'atlasSize': 1024, 'texelsPerUnit': float(os.environ.get('TPU', '0.2')), 'bounces': 4,
+ 'samples': int(os.environ.get('BAKE_SAMPLES', '256')), 'probeSamples': 128}}]})
+
+effects = json.loads(os.environ.get('EFFECTS', '[]'))
+if effects:
+ entities[0]['components'].append({'type': 'PostProcessVolume', 'data': {'isGlobal': True, 'weight': 1, 'priority': 0, 'effects': effects}})
+json.dump({'version': 4, 'name': 'Lab', 'entities': entities}, open(proj + '/assets/scenes/lab.esscene', 'w'), indent=1)
+print('project ready')
diff --git a/tools/render-lab/gi_ref.py b/tools/render-lab/gi_ref.py
new file mode 100644
index 000000000..b0e3243f0
--- /dev/null
+++ b/tools/render-lab/gi_ref.py
@@ -0,0 +1,74 @@
+"""The Cycles picture of a GI lab scene: the boxes of gi_specs, the camera and the sun, no sky.
+blender --background --python gi_ref.py -- <lab> <out.png> (env SAMPLES, default 512)
+"""
+import math
+import os
+import sys
+
+import bpy
+from mathutils import Vector
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import gi_specs as S # noqa: E402
+import lab_specs as L # noqa: E402
+
+lab, out = sys.argv[sys.argv.index('--') + 1:][:2]
+spec = S.GI[lab]
+bpy.ops.wm.read_factory_settings(use_empty=True)
+scene = bpy.context.scene
+scene.render.engine = 'CYCLES'
+scene.cycles.samples = int(os.environ.get('SAMPLES', '512'))
+scene.cycles.use_denoising = True
+scene.cycles.device = 'CPU'
+scene.cycles.max_bounces = 12
+scene.cycles.diffuse_bounces = 12
+scene.render.resolution_x, scene.render.resolution_y = S.SIZE
+scene.view_settings.view_transform = 'Standard'
+scene.view_settings.look = 'None'
+
+to_b = lambda v: Vector((v[0] / 100.0, -v[2] / 100.0, v[1] / 100.0))
+world = bpy.data.worlds.new('W')
+world.use_nodes = True
+world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.0
+scene.world = world
+
+for name, centre, size, colour in spec['boxes']:
+ bpy.ops.mesh.primitive_cube_add(size=1.0, location=to_b(centre))
+ ob = bpy.context.active_object
+ ob.name = name
+ ob.scale = (size[0] / 100.0, size[2] / 100.0, size[1] / 100.0)
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ bsdf = m.node_tree.nodes['Principled BSDF']
+ lin = tuple(S.srgb_to_linear(c) for c in colour)
+ bsdf.inputs['Base Color'].default_value = (*lin, 1.0)
+ bsdf.inputs['Roughness'].default_value = 1.0
+ bsdf.inputs['Metallic'].default_value = 0.0
+ if name == 'panel':
+ bsdf.inputs['Emission Color'].default_value = (1, 1, 1, 1)
+ bsdf.inputs['Emission Strength'].default_value = spec['emission']
+ ob.data.materials.append(m)
+
+pos, target, fov = spec['cam']
+cam_data = bpy.data.cameras.new('C')
+cam_data.sensor_fit = 'VERTICAL'
+cam_data.angle_y = math.radians(fov)
+cam_data.clip_start, cam_data.clip_end = 0.05, 100
+cam = bpy.data.objects.new('C', cam_data)
+scene.collection.objects.link(cam)
+cam.location = to_b(pos)
+cam.rotation_euler = (to_b(target) - cam.location).to_track_quat('-Z', 'Y').to_euler()
+scene.camera = cam
+
+if spec['sun']:
+ sun = bpy.data.lights.new('S', 'SUN')
+ sun.energy = spec['sun']['intensity'] * L.SUN_STRENGTH_PER_INTENSITY
+ sun.angle = 0.0
+ ob = bpy.data.objects.new('S', sun)
+ scene.collection.objects.link(ob)
+ d = spec['sun']['dir']
+ ob.rotation_euler = Vector((d[0], -d[2], d[1])).to_track_quat('-Z', 'Y').to_euler()
+
+scene.render.filepath = out
+bpy.ops.render.render(write_still=True)
+print('rendered', out)
diff --git a/tools/render-lab/gi_specs.py b/tools/render-lab/gi_specs.py
new file mode 100644
index 000000000..abb9cc3b8
--- /dev/null
+++ b/tools/render-lab/gi_specs.py
@@ -0,0 +1,124 @@
+"""Global-illumination scenes of the render lab: rooms whose light, past the patch the sun lands on, is all bounce.
+
+Every scene is boxes, written once here and built from this list on both sides: Blender (Cycles, 12 bounces) draws the reference, the engine
+draws the same boxes as built-in cubes. With no sky, a pixel the sun does not reach directly is exactly what a GI method gives it, so the
+ratio engine / Cycles over a region is that method's answer for that region.
+
+Units: the engine's world is centimetres (the built-in cube is 100 across), Blender's is metres. Coordinates here are the engine's
+(+Y up), Blender's are (x, -z, y) / 100 of them.
+
+Colours are written as the editor shows them (sRGB); the engine linearizes them in a linear project and Blender is handed the linear value.
+"""
+import math
+
+SIZE = (1280, 720)
+
+W, H, D, T = 400.0, 300.0, 500.0, 10.0 # room inner width, height, depth, wall thickness
+WHITE, RED, GREEN = (0.85, 0.85, 0.85), (0.80, 0.18, 0.15), (0.18, 0.70, 0.22)
+SKY = (120.0, 120.0) # skylight opening, x by z, in the ceiling
+
+
+def room(skylight_z=None, emissive=None):
+ """The six walls (inner faces at x = +-W/2, y = 0 and H, z = +-D/2), the ceiling with a hole at `skylight_z` when given."""
+ hw, hd = W / 2, D / 2
+ b = [
+ ('floor', (0, -T / 2, 0), (W + 2 * T, T, D + 2 * T), WHITE),
+ ('left', (hw + T / 2, H / 2, 0), (T, H, D), RED), # +X: seen on the camera's left when it looks along +Z
+ ('right', (-hw - T / 2, H / 2, 0), (T, H, D), GREEN),
+ ('back', (0, H / 2, hd + T / 2), (W + 2 * T, H, T), WHITE),
+ ('front', (0, H / 2, -hd - T / 2), (W + 2 * T, H, T), WHITE),
+ ]
+ if skylight_z is None:
+ b.append(('ceiling', (0, H + T / 2, 0), (W + 2 * T, T, D + 2 * T), WHITE))
+ else:
+ sx, sz = SKY
+ z0, z1 = skylight_z - sz / 2, skylight_z + sz / 2
+ zlo, zhi = -hd - T, hd + T
+ b += [
+ ('ceil_n', (0, H + T / 2, (zlo + z0) / 2), (W + 2 * T, T, z0 - zlo), WHITE),
+ ('ceil_s', (0, H + T / 2, (z1 + zhi) / 2), (W + 2 * T, T, zhi - z1), WHITE),
+ ('ceil_l', ((hw + T + sx / 2) / 2, H + T / 2, skylight_z), (hw + T - sx / 2, T, sz), WHITE),
+ ('ceil_r', (-(hw + T + sx / 2) / 2, H + T / 2, skylight_z), (hw + T - sx / 2, T, sz), WHITE),
+ ]
+ # A block in the room, so there is a contact shadow and a face that sees only bounce.
+ b.append(('block', (-90, 50, 80), (100, 100, 100), WHITE))
+ if emissive:
+ b.append(('panel', emissive['centre'], emissive['size'], (1, 1, 1)))
+ return b
+
+
+def sun_dir(elev_deg, azim_deg):
+ """Direction the light travels: down at `elev_deg` below the horizon, heading `azim_deg` from +Z toward +X."""
+ e, a = math.radians(elev_deg), math.radians(azim_deg)
+ return (math.cos(e) * math.sin(a), -math.sin(e), math.cos(e) * math.cos(a))
+
+
+CAM_IN = ((0.0, 160.0, -235.0), (0.0, 110.0, 250.0), 62.0)
+# Facing the front wall from the back: the sun's patch is on the floor behind and under the camera, off the picture.
+CAM_AWAY = ((0.0, 170.0, 235.0), (0.0, 175.0, -250.0), 50.0)
+
+SUN = dict(dir=sun_dir(68.0, 20.0), intensity=1.0)
+
+GI = {
+ # A Cornell-like room lit through a skylight: the floor patch is direct, the rest is bounce; the red and green walls tint what faces them.
+ 'gi_room': dict(cam=CAM_IN, boxes=room(skylight_z=60.0), sun=SUN),
+ # The same light, the camera turned so the lit patch is off screen: a method that only knows what the picture shows has nothing to bounce.
+ 'gi_away': dict(cam=CAM_AWAY, boxes=room(skylight_z=60.0), sun=SUN),
+ # The room closed, the sun on its roof and walls outside: every pixel inside is 0 in Cycles, so whatever the engine shows is leak.
+ 'gi_leak': dict(cam=CAM_IN, boxes=room(), sun=dict(dir=sun_dir(40.0, 60.0), intensity=1.0)),
+ # The room closed and dark but for an emissive panel on the back wall: the light of an emissive surface, which a lamp list does not have.
+ 'gi_emissive': dict(cam=CAM_IN, boxes=room(emissive=dict(centre=(0.0, 150.0, 248.0), size=(120.0, 70.0, 4.0))), sun=None, emission=4.0),
+}
+
+
+# Regions read by the comparison: a world point on a surface and the pixel radius of the patch read around where it lands.
+REGIONS = {
+ 'gi_room': [
+ ('sun patch (direct)', None), ('ceiling', (0.0, 299.0, 150.0)), ('red wall', (199.0, 120.0, 120.0)),
+ ('green wall', (-199.0, 120.0, 120.0)), ('back wall', (60.0, 200.0, 249.0)), ('floor in shade', (120.0, 1.0, 200.0)),
+ ('block, shaded face', (-90.0, 50.0, 29.0)),
+ ],
+ 'gi_away': [
+ ('front wall', (0.0, 170.0, -249.0)), ('ceiling', (0.0, 299.0, -100.0)), ('red wall', (199.0, 150.0, -100.0)),
+ ('green wall', (-199.0, 150.0, -100.0)),
+ ],
+ 'gi_leak': [
+ ('ceiling', (0.0, 299.0, 150.0)), ('red wall', (199.0, 120.0, 120.0)), ('green wall', (-199.0, 120.0, 120.0)),
+ ('back wall', (60.0, 200.0, 249.0)), ('floor', (100.0, 1.0, 150.0)),
+ ],
+ 'gi_emissive': [
+ ('panel (emitter)', (0.0, 150.0, 246.0)), ('ceiling', (0.0, 299.0, 150.0)), ('red wall', (199.0, 120.0, 150.0)),
+ ('green wall', (-199.0, 120.0, 150.0)), ('floor', (60.0, 1.0, 150.0)), ('block, top', (-90.0, 100.5, 80.0)),
+ ],
+}
+
+
+def srgb_to_linear(c):
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
+
+
+def project(point, cam, size=SIZE):
+ """Where a world point lands, in pixels, for a camera (position, target, vertical fov degrees)."""
+ pos, target, fov = cam
+ f = [target[i] - pos[i] for i in range(3)]
+ n = math.sqrt(sum(c * c for c in f))
+ f = [c / n for c in f]
+ right = [-f[2], 0.0, f[0]]
+ rn = math.sqrt(sum(c * c for c in right))
+ right = [c / rn for c in right]
+ up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]]
+ d = [point[i] - pos[i] for i in range(3)]
+ z = sum(d[i] * f[i] for i in range(3))
+ x = sum(d[i] * right[i] for i in range(3))
+ y = sum(d[i] * up[i] for i in range(3))
+ t = math.tan(math.radians(fov) / 2)
+ aspect = size[0] / size[1]
+ return (x / (z * t * aspect) * 0.5 + 0.5) * size[0], (0.5 - y / (z * t) * 0.5) * size[1], z
+
+
+def sun_patch_centre(lab):
+ """Where the sun through the skylight lands on the floor (the skylight's centre carried down along the light)."""
+ d = GI[lab]['sun']['dir']
+ sz = 60.0
+ t = H / -d[1]
+ return (0.0 + d[0] * t, 0.0, sz + d[2] * t)