Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Bake patterned, textured and emissive parts, and skip hair hosts

Nguyen Xuan Ance12da6654e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e8a0b06..d716793c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Bake patterned, textured and emissive parts, and skip hair hosts (part of issue #128). A recipe `bake` used to skip every part with a pattern, a map or emission (31 parts, the floor and every wall, in the demo room) and failed `scene_create` with "Textured geometry requires UV channel 0" on a node that hosts hair. Those parts now keep `uvs` and their look and take the bounced light through a new `lightMap` material slot on a second UV set (`geometry.lightUvs`); the fragment shader adds `color * (1 - metallic) * lightMap * lightMapScale`, so a brick pattern tints its own bounced light. Hair and particle host nodes are skipped and listed in `report.skipped`. The shader branch compiles out of scenes with no light map; the renderer carries about 650 bytes of gzip for it in `entry:core` (see `docs/light-bake.md` for the measured sizes). GLB export writes `TEXCOORD_1` and the light map as the emissive texture (an approximation: glTF has no light map slot). The path tracer ignores baked maps by design. New reference scene `brick-room` (a recipe-built closed brick room).
+
- A path trace job keeps its own `maxSeconds` below the job deadline: the deadline of an image job with `settings.renderer` now reaches `maxSeconds` plus 60 s (it was 60 s plus 2 s per frame, so a 1920x1080 trace of 120 s was cancelled at about 67 s), and the traced PNG may be as large as any job frame (12 MiB, not 1 MiB).
- Add `67js/addons/path-tracer` (part of issue #57; the Cycles comparison is partial). `renderPathTracedImage({ parts, environment, camera }, options)` draws a still by CPU path tracing against the triangle BVH of the light bake, with next-event estimation for the sun, point, spot and area lights, an importance-sampled environment map, GGX metal, clear coat, glass, maps and cutouts, and a wavelet denoiser, on up to eight module workers. An `image` render job selects it with `settings.renderer: { type: "pathTracer", samples, bounces, denoise, seed, maxSeconds }`; the same recipe and seed give the same PNG, a job past `maxSeconds` fails with no image, and samples, size and ray work are bounded. It loads on demand: the core bundle and the agent scene do not carry it (the limits live in `src/path-tracer-capabilities.js`, listed under `jobs.pathTracer` in `scene_capabilities`; the tool schemas gain one `renderer` field inside the total budget). `npm run reference -- --path-tracer` scores it against Cycles: better than the rasterizer on 7 of the 11 reference scenes (`lit-interior` 0.5055 to 0.1993, `spot-area` 0.1242 to 0.0639), worse on `outdoor-hdri`, `character` and `fog`, mean 0.171 against 0.189. Not drawn: volume fog, normal maps, translucent leaves, caustics, lights seen in mirrors. `src/ray-query.js` now holds the ray query and light falloff that `light-bake` used to carry. `npm run smoke:path-tracer` checks it through MCP.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 7d672835..fcfda3d8 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -31,6 +31,8 @@ Rows are the baseline taken before shadows for point lights. The `lit-interior`
Light bake (issue #55): `npm run reference -- --bake lit-interior` bakes bounced light into the room with `addons/light-bake` (defaults: 128 samples, 2 bounces, 25,648 texels, about 6 s on this machine) and leaves the scene itself unchanged; Blender still gets the plain scene. Measured 2026-10-31 on the RTX 3060: `lit-interior` against Cycles goes from 0.5055 to 0.1444 (SwiftShader 0.5051 to 0.1439), and against EEVEE from 0.0923 to 0.4739, because EEVEE has no indirect light here and the bake adds it. No other scene moved by more than 0.002 (the largest change was 0.0001, `car-paint` against EEVEE). The committed baseline rows and images are not rewritten. The remaining gap shows in the FLIP image as faint blotches on the walls, which is bake noise at 128 samples; at 48 samples the blotches were plain to see and the score was 0.1688.
+`brick-room` (issue #128) is a closed room built from a recipe (`createAgentScene`) with three brick pattern walls, two point lights and a table with a vase. Blender gets the box projection as UVs (`boxProjectedGeometry`) and the baked brick map, but not the bump or the roughness map. Measured 2026-11-01 on the RTX 3060: against Cycles 0.5102 without the bake and 0.1515 with it (`npm run reference -- --bake brick-room`; SwiftShader 0.5096 and 0.1503; EEVEE against Cycles 0.5020); the bake took 14.4 s for 28,576 texels while another session loaded the machine. `lit-interior` stayed at 0.1444 with the bake, and every scene without a bake kept its earlier score to four digits (largest change 0.0000).
+
`brick-graph` (issue #50) is a wall of bricks written as one material graph (triangle waves for the joints, half a brick of shift on every second course, noise through a colour ramp, height as bump) on a quad with UVs, so it uses `mapping: "uv"`. `render-blender.py` translates the same graph JSON into Blender nodes (Math, Map Range, Noise Texture, Color Ramp, Mix and Bump), so each side evaluates its own nodes. It measured 0.2269 against Cycles and 0.1440 for EEVEE on 2026-10-31. A first run scored 0.4027 and showed a black wall in 67js: the `min` and `max` nodes returned NaN. The scene found that bug. The other rows were re-measured in the same run; `glass` against Cycles moved from 0.1450 to 0.1326 and `lit-interior` to the with-shadows numbers described above, and no other score moved by more than 0.002.
The mean against Cycles is 0.198 for 67js and 0.160 for EEVEE. The mean difference between the RTX 3060 and SwiftShader is 0.007.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index dfa58394..c05be319 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -1,144 +1,156 @@
{
- "metric": "FLIP (LDR), mean error, lower is better",
- "blenderVersion": "5.2.2 LTS",
- "seconds": {
- "brick-graph": {
- "cycles": 8.9,
- "eevee": 15.2
- },
- "car-paint": {
- "cycles": 35.4,
- "eevee": 82.5
- },
- "character": {
- "cycles": 19.2,
- "eevee": 4.5
- },
- "fog": {
- "cycles": 63.5,
- "eevee": 36.3
- },
- "foliage": {
- "cycles": 39.5,
- "eevee": 27.4
- },
- "glass": {
- "cycles": 29.5,
- "eevee": 13.7
- },
- "lit-interior": {
- "cycles": 77.4,
- "eevee": 2.6
- },
- "material-spheres": {
- "cycles": 25,
- "eevee": 60.5
- },
- "metal": {
- "cycles": 42.2,
- "eevee": 30.4
- },
- "outdoor-hdri": {
- "cycles": 42.9,
- "eevee": 12.9
- },
- "spot-area": {
- "cycles": 28.5,
- "eevee": 10.1
- }
- },
- "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": {
- "brick-graph": {
- "gpu-vs-cycles": 0.2269,
- "gpu-vs-eevee": 0.148,
- "cpu-vs-cycles": 0.2268,
- "cpu-vs-eevee": 0.1479,
- "eevee-vs-cycles": 0.144,
- "gpu-vs-cpu": 0.0074
- },
- "car-paint": {
- "gpu-vs-cycles": 0.1521,
- "gpu-vs-eevee": 0.1323,
- "cpu-vs-cycles": 0.152,
- "cpu-vs-eevee": 0.1323,
- "eevee-vs-cycles": 0.0819,
- "gpu-vs-cpu": 0.0055
- },
- "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.1326,
- "gpu-vs-eevee": 0.1471,
- "cpu-vs-cycles": 0.1323,
- "cpu-vs-eevee": 0.1474,
- "eevee-vs-cycles": 0.115,
- "gpu-vs-cpu": 0.0075
- },
- "lit-interior": {
- "gpu-vs-cycles": 0.5055,
- "gpu-vs-eevee": 0.0923,
- "cpu-vs-cycles": 0.5051,
- "cpu-vs-eevee": 0.0928,
- "eevee-vs-cycles": 0.5159,
- "gpu-vs-cpu": 0.0062
- },
- "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.0384,
- "gpu-vs-cpu": 0.0058
- },
- "spot-area": {
- "gpu-vs-cycles": 0.1242,
- "gpu-vs-eevee": 0.1707,
- "cpu-vs-cycles": 0.1242,
- "cpu-vs-eevee": 0.1709,
- "eevee-vs-cycles": 0.1935,
- "gpu-vs-cpu": 0.0032
- }
+ "metric": "FLIP (LDR), mean error, lower is better",
+ "blenderVersion": "5.2.2 LTS",
+ "seconds": {
+ "brick-graph": {
+ "cycles": 53.1,
+ "eevee": 66.2
+ },
+ "brick-room": {
+ "cycles": 56.7,
+ "eevee": 7.1
+ },
+ "car-paint": {
+ "cycles": 28.1,
+ "eevee": 13.7
+ },
+ "character": {
+ "cycles": 38.8,
+ "eevee": 12.0
+ },
+ "fog": {
+ "cycles": 146.4,
+ "eevee": 95.8
+ },
+ "foliage": {
+ "cycles": 47.6,
+ "eevee": 173.8
+ },
+ "glass": {
+ "cycles": 127.1,
+ "eevee": 64.6
+ },
+ "lit-interior": {
+ "cycles": 206.9,
+ "eevee": 233.9
+ },
+ "material-spheres": {
+ "cycles": 40.8,
+ "eevee": 229.1
+ },
+ "metal": {
+ "cycles": 225.1,
+ "eevee": 14.1
+ },
+ "outdoor-hdri": {
+ "cycles": 11.3,
+ "eevee": 11.0
+ },
+ "spot-area": {
+ "cycles": 12.7,
+ "eevee": 21.2
+ }
+ },
+ "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": {
+ "brick-graph": {
+ "gpu-vs-cycles": 0.2269,
+ "gpu-vs-eevee": 0.148,
+ "cpu-vs-cycles": 0.2268,
+ "cpu-vs-eevee": 0.1479,
+ "eevee-vs-cycles": 0.144,
+ "gpu-vs-cpu": 0.0074
+ },
+ "brick-room": {
+ "gpu-vs-cycles": 0.5102,
+ "gpu-vs-eevee": 0.071,
+ "cpu-vs-cycles": 0.5096,
+ "cpu-vs-eevee": 0.0713,
+ "eevee-vs-cycles": 0.502,
+ "gpu-vs-cpu": 0.0071
+ },
+ "car-paint": {
+ "gpu-vs-cycles": 0.1521,
+ "gpu-vs-eevee": 0.1323,
+ "cpu-vs-cycles": 0.152,
+ "cpu-vs-eevee": 0.1323,
+ "eevee-vs-cycles": 0.0819,
+ "gpu-vs-cpu": 0.0055
+ },
+ "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.1387,
+ "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.1326,
+ "gpu-vs-eevee": 0.1472,
+ "cpu-vs-cycles": 0.1323,
+ "cpu-vs-eevee": 0.1474,
+ "eevee-vs-cycles": 0.115,
+ "gpu-vs-cpu": 0.0075
+ },
+ "lit-interior": {
+ "gpu-vs-cycles": 0.5055,
+ "gpu-vs-eevee": 0.0923,
+ "cpu-vs-cycles": 0.5051,
+ "cpu-vs-eevee": 0.0928,
+ "eevee-vs-cycles": 0.5159,
+ "gpu-vs-cpu": 0.0062
+ },
+ "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.0384,
+ "gpu-vs-cpu": 0.0058
+ },
+ "spot-area": {
+ "gpu-vs-cycles": 0.1242,
+ "gpu-vs-eevee": 0.1707,
+ "cpu-vs-cycles": 0.1242,
+ "cpu-vs-eevee": 0.1709,
+ "eevee-vs-cycles": 0.1935,
+ "gpu-vs-cpu": 0.0032
}
+ }
}
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index a74a7dd1..a89cacf6 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -2,6 +2,7 @@
import { Renderer67 } from '/src/renderer.js';
import { REFERENCE_SCENES } from './scenes.js';
import { skinnedGeometry } from '/src/path-tracer-scene.js';
+import { boxProjectedGeometry } from '/src/export-box-uv.js';
function encodeBytes(typedArray) {
const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
@@ -27,13 +28,28 @@ function plainData(value) {
return value;
}
+// A pattern material is box projected in the shader and has no UVs. Blender gets the same projection written as UVs,
+// per part, because the projection depends on the part's scale.
+function boxProjectedFor(part, cache) {
+ const boxMapScale = part.material.boxMapScale;
+ if (!(boxMapScale > 0) || part.geometry.uvs) return part.geometry;
+ const { matrix } = part;
+ const scale = [0, 1, 2].map(column => Math.hypot(matrix[column * 4], matrix[column * 4 + 1], matrix[column * 4 + 2]));
+ const key = `${scale.join(',')}|${boxMapScale}|${part.material.boxMapAxis ?? 1}`;
+ if (!cache.has(part.geometry)) cache.set(part.geometry, new Map());
+ const byScale = cache.get(part.geometry);
+ if (!byScale.has(key)) byScale.set(key, boxProjectedGeometry(part.geometry, scale, boxMapScale, part.material.boxMapAxis ?? 1));
+ return byScale.get(key);
+}
+
// Blender's glTF importer cannot reproduce this rig's pose (three.js and 67js agree on it), so Blender gets the
// skinned result as plain geometry. A score then measures shading, and not an importer's pose.
function describeScene(id, scene) {
const { map: _map, ...environment } = scene.environment;
const geometries = new Map();
+ const boxProjected = new Map();
const describedParts = scene.parts.map(part => {
- const geometry = part.skin ? skinnedGeometry(part) : part.geometry;
+ const geometry = part.skin ? skinnedGeometry(part) : boxProjectedFor(part, boxProjected);
if (!geometries.has(geometry)) geometries.set(geometry, geometries.size);
return { name: part.name, geometry: geometries.get(geometry), matrix: [...part.matrix], material: plainData(part.material) };
});
diff --git a/bench/reference/images/brick-room.jpg b/bench/reference/images/brick-room.jpg
new file mode 100644
index 00000000..506e0b37
Binary files /dev/null and b/bench/reference/images/brick-room.jpg differ
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 26cca8c1..26fab950 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -4,6 +4,7 @@ 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';
+import { createAgentScene, loadAgentSceneModules } from '/src/agent-scene.js';
import { materialPatternTextures, normalizeMaterialPattern } from '/src/material-patterns.js';
const HDRI_FILE = 'public/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr';
@@ -135,6 +136,44 @@ export const REFERENCE_SCENES = {
};
},
+ // A closed room built from a recipe, with brick walls: the bake has to give a patterned wall bounced light and keep its bricks.
+ async 'brick-room'() {
+ const lighting = constantLighting(0.02);
+ const pointLights = [
+ { position: [0, 2.6, -0.5], color: [1, 0.9, 0.75], intensity: 8, radius: 0.05, castShadow: true },
+ { position: [-2.5, 1.5, 1.5], color: [1, 0.6, 0.4], intensity: 2, radius: 0.05, castShadow: true },
+ ];
+ const placedBox = (id, translation, scale, material) => ({ id, geometry: 'box', material, translation, scale });
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'ball', type: 'sphere', segments: 48, rings: 32 }],
+ materials: [
+ { id: 'bricks', color: [1, 1, 1], roughness: 0.9, pattern: { type: 'bricks', size: 0.5 } },
+ { id: 'plaster', color: [0.7, 0.68, 0.62], roughness: 0.9 },
+ { id: 'boards', color: [0.45, 0.32, 0.22], roughness: 0.6 },
+ { id: 'teal', color: [0.2, 0.5, 0.45], roughness: 0.2 },
+ ],
+ nodes: [
+ placedBox('room-floor', [0, -0.05, 0], [8, 0.1, 8], 'boards'),
+ placedBox('room-ceiling', [0, 3.05, 0], [8, 0.1, 8], 'plaster'),
+ placedBox('room-back', [0, 1.5, -4.05], [8, 3.2, 0.1], 'bricks'),
+ placedBox('room-left', [-4.05, 1.5, 0], [0.1, 3.2, 8], 'bricks'),
+ placedBox('room-right', [4.05, 1.5, 0], [0.1, 3.2, 8], 'bricks'),
+ placedBox('room-front', [0, 1.5, 4.05], [8, 3.2, 0.1], 'plaster'),
+ placedBox('table', [0, 0.7, -1], [2.4, 0.1, 1.2], 'plaster'),
+ { id: 'vase', geometry: 'ball', material: 'teal', translation: [-0.5, 1.05, -1], scale: [0.3, 0.3, 0.3] },
+ ],
+ camera: { eye: [0, 1.5, 3.6], target: [0, 1.1, -1], fov: 60, near: 0.05, far: 50 },
+ };
+ await loadAgentSceneModules(recipe);
+ const scene = createAgentScene(recipe);
+ return {
+ parts: scene.parts, blenderWorld: lighting.blenderWorld,
+ environment: environment(lighting, { pointLights }),
+ camera: { eye: [0, 1.5, 3.6], target: [0, 1.1, -1], up: [0, 1, 0], fov: 60, near: 0.05, far: 50 },
+ };
+ },
+
// A shadowing spot light with a soft cone edge and a rectangular panel, over objects that block the spot.
async 'spot-area'() {
const lighting = constantLighting(0.01);
diff --git a/docs/light-bake.md b/docs/light-bake.md
index b2c1a4e7..edbf3250 100644
--- a/docs/light-bake.md
+++ b/docs/light-bake.md
@@ -38,9 +38,13 @@ Not baked: spot lights, area lights, the environment map (it already lights ever
## How a part draws it
-A baked part is a copy with new geometry and a new material. The geometry gets lightmap UVs from the `uv_unwrap` unwrap in channel 0. The material gets `emissiveMap` (the lightmap, `srgb`, linear filter, clamped), `emissiveColor [1, 1, 1]` and `emission` set to the brightest texel, so the renderer, its shaders and every scene without a bake stay as they are. The input parts are not changed.
+A baked part is a copy with new geometry and a new material. A plain part (no maps, pattern, layers or emission) gets lightmap UVs from the `uv_unwrap` unwrap in channel 0, and its material gets `emissiveMap` (the lightmap, `srgb`, linear filter, clamped), `emissiveColor [1, 1, 1]` and `emission` set to the brightest texel, so the renderer, its shaders and every scene without a bake stay as they are. The input parts are not changed.
-The renderer reads one UV channel, so a part that already has texture maps, a pattern, layers, its own emission or transparency is left as it was and listed in `report.skipped` with the reason. Skipped parts still block and reflect light. A skinned or morphing part is skipped too.
+A part with texture maps, a pattern, layers or its own emission cannot lend its emissive map or its UV channel 0, so it takes the light through the renderer's `lightMap` slot instead. Its geometry keeps `uvs` (the unwrap splits vertices along its seams, and each new vertex copies the `uvs` and `colors` of the vertex it came from) and gains `lightUvs`, the second UV set. The material keeps every field and gains `lightMap` (`srgb`, linear filter, clamped) and `lightMapScale` (the brightest texel). The texture holds the light that arrives, not the light times an albedo, and the fragment shader adds `color * (1 - metallic) * lightMap * lightMapScale` under the existing shading, so the pattern or texture (box projected or UV mapped) tints it at run time. The renderer uploads the two UV sets as one four-wide attribute; the shader branch, the sampler and the uniforms compile out of any scene with no `lightMap`. The bake traces such a part with its colour times the mean colour of its base map, so a brick wall reflects brick coloured light and not white light.
+
+Skipped, with the reason in `report.skipped`: transparent parts, a material tag that draws its own look (water, fire, foliage), skinned or morphing parts, and a node that hosts a hair or particle system (its geometry is rebuilt every frame and has no UVs; the recipe bake marks these, which fixed `scene_create` failing with "Textured geometry requires UV channel 0"). Skipped parts still block and reflect light.
+
+GLB export writes `lightUvs` as `TEXCOORD_1` and the light map as the emissive texture on `texCoord` 1, with the base colour factor as `emissiveFactor`. glTF has no light map slot, so a base colour texture does not tint it there: the export is an approximation for viewers, not for reference renders. The path tracer ignores `lightMap` and `emissiveMap` on purpose: it traces indirect light itself, so reading a baked map would count the same light twice.
## Limits
diff --git a/docs/parity.md b/docs/parity.md
index c0327aed..01e491b2 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -187,7 +187,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, 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), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |
-| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It does not trace volume fog, normal maps or translucent leaves, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets; scene_inspect reports bake seconds and skipped parts), but there is no GLB export, no reflection probes, no spot or area lights, no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57 |
+| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It does not trace volume fog, normal maps or translucent leaves, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets; scene_inspect reports bake seconds and skipped parts), patterned, textured and emissive parts bake through a second UV set and a `lightMap` slot, GLB export writes the map approximately as `TEXCOORD_1` emissive, but there are no reflection probes, no spot or area lights, no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57, #128 |
| Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | |
| Rendering > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 71ff593e..a426e5dc 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -15,7 +15,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- An object studio uses `src/model.js` and `src/main.js`.
- An outdoor world uses `src/nature.js` and `src/nature-viewer.js`. Real trees, bushes, grass and forest scattering use optional `src/vegetation.js` and `docs/vegetation.md` (`leaves: 'mesh'` needs no alpha support).
- A grass field, meadow, lawn or savanna over terrain uses optional `src/grass.js` and the checkout's `docs/grass.md`: clumped curved blades, tile level of detail, `mask` for paths. Darken every ground layer under the grass toward `grass.groundColor` (a bright floor between blades looks fake); prefer it over scattered `grass` clumps for anything wider than a few metres. Pebbles, rocks, twigs and fallen leaves on paths, riverbanks or forest floor use optional `src/clutter.js` and the checkout's `docs/clutter.md` (`riverbed`, `forest`, `scree`, `meadow` presets).
-- Light that bounces inside a closed room (colour bleed, shadows that are not black) comes from optional `src/light-bake.js` and the checkout's `docs/light-bake.md`: `bakeLightmaps(parts, { pointLights, keyColor, lightDirection }, options)` returns new parts with a lightmap in the emissive map; direct light stays live. It is code only: recipes and the MCP tools cannot ask for it yet, and parts with their own texture maps, pattern or emission are skipped.
+- Light that bounces inside a closed room (colour bleed, shadows that are not black) comes from optional `src/light-bake.js` and the checkout's `docs/light-bake.md`: `bakeLightmaps(parts, { pointLights, keyColor, lightDirection }, options)` returns new parts with a lightmap (plain parts through the emissive map, patterned, textured and emissive parts through the `lightMap` slot on a second UV set); direct light stays live. Recipes reach it through `bake`.
- A deterministic film uses `src/film.js` and `src/film-player.js`.
- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.
- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.
@@ -50,7 +50,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; bodies bound to bones for ragdolls are not supported. See "Recipe physics" in the checkout's `docs/physics.md`.
- Flags, curtains, capes and cloths draped over props use the recipe `cloth` section: a `grid` geometry node (flat sheet in XY, `segments` up to 64) listed in `sheets` with `pin` edges (`top`, `left`, a corner...), `wind` in m/s, and fixed `colliders` (`ball` or `box` fitted to their node). Seek with `motionTime`; a flag needs wind along its length (+x for a left pin), not across it. No peer needed, no self collision, no soft bodies. Units, defaults and limits are in `scene_capabilities` under `cloth`; see "Recipe cloth" in `docs/physics.md`.
- Sparks, dust, embers, confetti and fur use the recipe `particles` section: a root node whose small low-poly geometry (a box) is the particle, in an emitter system with `seed`, `count` (at most 2000), `rate` (omit for one burst), `lifetime`, `speed`, `spread`, `drag`, `floor` and an `emitter` shape; a system with `type: "hair"` grows strands from a `surface` node. Seek with `motionTime`; the same seed and time give the same particles. The node transform does not move particles, and there is no collision beyond the floor, bounce or per-particle colour. Fields and limits are in `scene_capabilities` under `particles`; see "Recipe particles and hair" in `docs/physics.md`. Smoke, fire and browser liquid are not supported.
-- A closed room, or any scene lit by point lights, is dark where the light does not reach. Add the recipe `bake` section (`{ "preset": "standard" }`, or `draft` to try fast, `fine` to finish) or the `set-bake` operation: it writes bounced light into lightmaps when the scene builds and reruns only when parts, lights, materials or the bake change. `scene_inspect` shows `bake.seconds` and `bake.skipped` (parts with maps, patterns, emission, alpha, skins or morphs are left as they were). It bakes the rest pose and no spot or area lights. Read `docs/light-bake.md`.
+- A closed room, or any scene lit by point lights, is dark where the light does not reach. Add the recipe `bake` section (`{ "preset": "standard" }`, or `draft` to try fast, `fine` to finish) or the `set-bake` operation: it writes bounced light into lightmaps when the scene builds and reruns only when parts, lights, materials or the bake change. `scene_inspect` shows `bake.seconds` and `bake.skipped` (alpha, skins, morphs, procedural tags and hair or particle hosts are left as they were; patterned, textured and emissive parts are baked and keep their pattern). It bakes the rest pose and no spot or area lights. Read `docs/light-bake.md`.
- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.
- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.
- To pick between variants, fork each with `scene_apply` and a `branch` name (the scene and revision stay put), compare them in one `scene_review` with a `branch` per shot, then keep the winner with `scene_restore` and its `branch`. Add `labels: true` to `scene_look` or `scene_review` to match node names and lint problems to what the image shows. Docs: `docs/agent-review.md`.
diff --git a/src/agent-bake.js b/src/agent-bake.js
index a2bffd5f..c95b3d5f 100644
--- a/src/agent-bake.js
+++ b/src/agent-bake.js
@@ -6,7 +6,7 @@ import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS } from './agent-scene-c
// without a bake never download the ray tracer.
const BAKE_FIELDS = ['preset', 'samples', 'bounces', 'texelsPerUnit'];
-const BAKED_MATERIAL_FIELDS = ['emission', 'emissiveColor', 'emissiveMap'];
+const BAKED_MATERIAL_FIELDS = ['emission', 'emissiveColor', 'emissiveMap', 'lightMap', 'lightMapScale'];
/** Validates a recipe bake section and returns the plain, resolved form stored in the recipe (null clears it). */
export function normalizeAgentBake(input) {
@@ -47,14 +47,20 @@ function liveBakedMaterial(liveMaterial, bakedMaterial) {
* Returns the new parts, which share the originals' matrices so poses still move them, and a report: texels,
* rayWork, seconds, skipped parts with reasons.
*/
-export function bakeAgentParts(parts, worldMatrices, environment, settings) {
+export function bakeAgentParts(parts, worldMatrices, environment, settings, generatedGeometryNames = new Set()) {
const sunScale = environment.keyIntensity ?? 1;
const lighting = {
pointLights: environment.pointLights,
keyColor: Array.from(environment.keyColor, channel => channel * sunScale),
lightDirection: environment.lightDirection,
};
- const snapshots = parts.map(part => ({ ...part, matrix: worldMatrices.get(part.name), material: { ...part.material } }));
+ // A hair or particle host is drawn from geometry built every frame, which has no lightmap UVs.
+ const snapshots = parts.map(part => ({
+ ...part,
+ matrix: worldMatrices.get(part.name),
+ material: { ...part.material },
+ generatesGeometry: generatedGeometryNames.has(part.name),
+ }));
const { parts: bakedSnapshots, report } = bakeLightmaps(snapshots, lighting, { ...settings, maxSeconds: BAKE_MAXIMUM_SECONDS });
const bakedParts = parts.map((part, index) => {
if (bakedSnapshots[index] === snapshots[index]) {
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 2aabbafc..2191b3fc 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -192,7 +192,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
bake: Object.freeze({
fields: 'preset, or samples (1-256), bounces (1-3), texelsPerUnit (1-12) over it. Same recipe, same bytes.',
presets: BAKE_PRESETS,
- notes: 'Bounced light from point lights and the key light, for closed rooms. Reruns only when parts, lights, materials or bake change, never on seek or camera. Skips parts with maps, pattern, emission, alpha, skin or morph (scene_inspect bake.skipped, bake.seconds). Spot and area lights, environment map and specular are not baked. Over 20 s fails the edit.',
+ notes: 'Bounced light from point lights and the key light, for closed rooms. Reruns only when parts, lights, materials or bake change. Patterns and textures keep their look. Skips alpha, skin, morph, hair hosts (bake.skipped, bake.seconds). Spot and area lights, environment map and specular are not baked. Over 20 s fails the edit.',
limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, maxPointLights: 8 }),
}),
motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 3778e654..ef0f4c3a 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1020,12 +1020,13 @@ export function createAgentScene(input, inputLimits = {}) {
}
const worldMatrices = new Map(sourceRestParts.map(part => [part.name, new Float32Array(graph.getNode(part.name).worldMatrix)]));
const { pointLights, keyColor, keyIntensity, lightDirection } = recipe.environment;
- const key = JSON.stringify([recipe.bake, pointLights, keyColor, keyIntensity, lightDirection, recipe.materials,
+ const generatedGeometryNames = new Set((recipe.particles?.systems ?? []).map(system => system.node));
+ const key = JSON.stringify([recipe.bake, [...generatedGeometryNames], pointLights, keyColor, keyIntensity, lightDirection, recipe.materials,
[...worldMatrices].map(([name, matrix]) => [name, Array.from(matrix)])]);
if (lightBake?.key === key && lightBake.sourceRestParts === sourceRestParts) {
return { ...lightBake, reused: true };
}
- const baked = agentSceneModule('bake').bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake);
+ const baked = agentSceneModule('bake').bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake, generatedGeometryNames);
lightBake = { key, sourceRestParts, parts: baked.parts, report: baked.report };
return { ...lightBake, reused: false };
}
diff --git a/src/export-box-uv.js b/src/export-box-uv.js
index 070caebb..f26a2993 100644
--- a/src/export-box-uv.js
+++ b/src/export-box-uv.js
@@ -62,7 +62,7 @@ export function boxProjectedGeometry(geometry, scale, boxMapScale, boxMapAxis) {
const projected = { ...geometry, indices: newIndices };
projected.positions = remapped(positions, 3, sourceOf);
projected.normals = remapped(geometry.normals, 3, sourceOf);
- for (const [field, perVertex] of [['colors', 3], ['skinIndices', 4], ['skinWeights', 4]]) {
+ for (const [field, perVertex] of [['colors', 3], ['lightUvs', 2], ['skinIndices', 4], ['skinWeights', 4]]) {
if (geometry[field]) projected[field] = remapped(geometry[field], perVertex, sourceOf);
}
if (geometry.morphTargets) {
diff --git a/src/export.js b/src/export.js
index 3e3c32d4..6719bb3c 100644
--- a/src/export.js
+++ b/src/export.js
@@ -138,12 +138,28 @@ function createIdentityTracker() {
}
function materialKeyOf(material, identify) {
- const textures = TEXTURE_CHANNELS.map(channel => material[channel] ? identify(material[channel]) : null);
+ const textures = [...TEXTURE_CHANNELS, 'lightMap'].map(channel => material[channel] ? identify(material[channel]) : null);
const fields = { ...material };
- for (const channel of [...TEXTURE_CHANNELS, 'pattern', 'boxMapScale', 'boxMapAxis']) delete fields[channel];
+ for (const channel of [...TEXTURE_CHANNELS, 'lightMap', 'pattern', 'boxMapScale', 'boxMapAxis']) delete fields[channel];
return JSON.stringify([fields, textures, material.boxMapScale ?? 0, material.boxMapAxis ?? 1]);
}
+/**
+ * glTF has no light map slot, so a baked light map goes out as the emissive texture on TEXCOORD_1: the light that
+ * arrives, tinted by the base colour factor and not by a base color texture. Parts with their own emission keep it.
+ */
+function writeLightMap(writer, textureWriter, material, gltfMaterial) {
+ if (!material.lightMap || material.emissiveMap || (material.emission ?? 0) !== 0) return;
+ const tint = material.color.map(channel => channel * (1 - material.metallic));
+ gltfMaterial.emissiveFactor = tint;
+ gltfMaterial.emissiveTexture = { index: textureWriter.textureIndex(material.lightMap, 'lightMap'), texCoord: 1 };
+ const strength = material.lightMapScale ?? 1;
+ if (strength !== 1) {
+ gltfMaterial.extensions = { ...gltfMaterial.extensions, [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
+ writer.addExtension(EMISSIVE_STRENGTH, { required: true });
+ }
+}
+
function writeMaterial(writer, textureWriter, material) {
const pbr = { baseColorFactor: [...material.color, 1], metallicFactor: material.metallic, roughnessFactor: material.roughness };
const gltfMaterial = {
@@ -167,6 +183,7 @@ function writeMaterial(writer, textureWriter, material) {
if (material.normalMap) gltfMaterial.normalTexture = { ...textureOf('normalMap'), scale: material.normalScale?.[0] ?? 1 };
if (material.occlusionMap) gltfMaterial.occlusionTexture = { ...textureOf('occlusionMap'), strength: material.occlusionStrength ?? 1 };
if (material.emissiveMap) gltfMaterial.emissiveTexture = textureOf('emissiveMap');
+ writeLightMap(writer, textureWriter, material, gltfMaterial);
return gltfMaterial;
}
@@ -176,6 +193,7 @@ function writeGeometry(writer, geometry) {
const primitive = { attributes, indices: writer.addAccessor(geometry.indices, 'SCALAR', 34963) };
if (geometry.colors) attributes.COLOR_0 = writer.addAccessor(geometry.colors, 'VEC3', ARRAY_BUFFER);
if (geometry.uvs) attributes.TEXCOORD_0 = writer.addAccessor(geometry.uvs, 'VEC2', ARRAY_BUFFER);
+ if (geometry.lightUvs) attributes.TEXCOORD_1 = writer.addAccessor(geometry.lightUvs, 'VEC2', ARRAY_BUFFER);
if (geometry.skinIndices) {
attributes.JOINTS_0 = writer.addAccessor(Uint16Array.from(geometry.skinIndices), 'VEC4', ARRAY_BUFFER, { bounds: false });
attributes.WEIGHTS_0 = writer.addAccessor(normalizedWeights(geometry.skinWeights), 'VEC4', ARRAY_BUFFER, { bounds: false });
diff --git a/src/light-bake.js b/src/light-bake.js
index 94333e17..5c6712c5 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -28,6 +28,7 @@ export const MAX_BAKE_POINT_LIGHTS = 8;
const MAP_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const SURFACE_UTILIZATION_FLOOR = 0.05;
const DILATION_PASSES = 2;
+const AVERAGE_GRID = 16;
const LIGHT_MAP_CLAMP_TO_EDGE = 33071;
const LIGHT_MAP_LINEAR = 9729;
@@ -93,18 +94,45 @@ function validatePart(part, index) {
function skipReason(part) {
const material = part.material;
+ if (part.generatesGeometry) return 'a hair or particle system rebuilds its geometry every frame, so it has no fixed surface to bake';
if (part.skin || part.morph || part.geometry.skinIndices || part.geometry.morphTargets) return 'skinned or morphing parts move, so a fixed lightmap would not follow';
if ((material.tag ?? 'surface') !== 'surface') return `the ${material.tag} material draws its own look`;
- if (MAP_FIELDS.some(field => material[field])) return 'it already has texture maps, which use the only UV channel the renderer reads';
- if (material.pattern || material.layers) return 'it has a procedural pattern or layers';
- if ((material.emission ?? 0) > 0) return 'it emits light itself';
if (material.opacity !== undefined && material.opacity < 1 || material.alphaMode && material.alphaMode !== 'opaque') return 'it is transparent';
return null;
}
+/**
+ * A plain part shows the light through its emissive map on UV channel 0. A part with texture maps, a pattern, layers or
+ * its own emission keeps channel 0 and its look, and receives the light through the lightMap slot on a second UV set.
+ */
+function usesLightMapSlot(material) {
+ return MAP_FIELDS.some(field => material[field]) || Boolean(material.pattern || material.layers) || (material.emission ?? 0) > 0;
+}
+
+function srgbToLinear(byte) {
+ const unit = byte / 255;
+ return unit <= 0.04045 ? unit / 12.92 : ((unit + 0.055) / 1.055) ** 2.4;
+}
+
+/** Mean linear colour of a base color map on a fixed grid of samples, or white when the image bytes are not readable. */
+function averageMapColor(map) {
+ const image = map?.image;
+ if (!image?.data || !(image.width > 0) || !(image.height > 0)) return [1, 1, 1];
+ const sum = [0, 0, 0];
+ for (let row = 0; row < AVERAGE_GRID; row++) {
+ for (let column = 0; column < AVERAGE_GRID; column++) {
+ const x = Math.floor((column + 0.5) / AVERAGE_GRID * image.width);
+ const y = Math.floor((row + 0.5) / AVERAGE_GRID * image.height);
+ for (let channel = 0; channel < 3; channel++) sum[channel] += srgbToLinear(image.data[(y * image.width + x) * 4 + channel]);
+ }
+ }
+ return sum.map(total => total / (AVERAGE_GRID * AVERAGE_GRID));
+}
+
function diffuseAlbedo(material) {
const keep = 1 - (material.metallic ?? 0);
- return material.color.map(channel => Math.max(channel, 0) * keep);
+ const mapAverage = averageMapColor(material.map);
+ return material.color.map((channel, index) => Math.max(channel, 0) * keep * mapAverage[index]);
}
function emittedRadiance(material) {
@@ -345,6 +373,37 @@ function unwrapForLightmap(geometry) {
return { geometry: unwrappedGeometry, utilization: Math.max(unwrapped.utilization, SURFACE_UTILIZATION_FLOOR) };
}
+/**
+ * Gives a geometry lightmap UVs in `lightUvs` and keeps its own `uvs` and `colors`. The unwrap splits vertices along its
+ * seams, so each source vertex index rides through it as a corner colour and the attributes are gathered back from it.
+ */
+function unwrapIntoSecondUvSet(geometry) {
+ const { positions, normals, indices } = geometry;
+ const vertexCount = positions.length / 3;
+ const sourceIndices = new Float32Array(vertexCount * 3);
+ for (let vertex = 0; vertex < vertexCount; vertex++) sourceIndices[vertex * 3] = vertex;
+ const mesh = meshFromGeometry({ positions, normals, indices, colors: sourceIndices }, { quads: false, tags: 'none' });
+ const unwrapped = unwrapUv(mesh);
+ const { geometry: extracted } = extractRender(unwrapped.mesh);
+ const newCount = extracted.positions.length / 3;
+ const result = { positions: extracted.positions, normals: extracted.normals, indices: extracted.indices, lightUvs: extracted.uvs };
+ const uvs = geometry.uvs ? new Float32Array(newCount * 2) : null;
+ const colors = geometry.colors ? new Float32Array(newCount * 3) : null;
+ for (let vertex = 0; vertex < newCount; vertex++) {
+ const source = Math.round(extracted.colors[vertex * 3]);
+ if (uvs) {
+ uvs[vertex * 2] = geometry.uvs[source * 2];
+ uvs[vertex * 2 + 1] = geometry.uvs[source * 2 + 1];
+ }
+ if (colors) {
+ for (let channel = 0; channel < 3; channel++) colors[vertex * 3 + channel] = geometry.colors[source * 3 + channel];
+ }
+ }
+ if (uvs) result.uvs = uvs;
+ if (colors) result.colors = colors;
+ return { geometry: result, utilization: Math.max(unwrapped.utilization, SURFACE_UTILIZATION_FLOOR) };
+}
+
function lightmapResolution(area, utilization, options) {
const wanted = Math.sqrt(area / utilization) * options.texelsPerUnit;
const rounded = Math.ceil(wanted / 4) * 4;
@@ -357,7 +416,8 @@ function rasterizeTexels(geometry, matrix, resolution) {
const positions = new Float64Array(texelCount * 3);
const normals = new Float64Array(texelCount * 3);
const covered = new Uint8Array(texelCount);
- const { positions: vertexPositions, normals: vertexNormals, uvs, indices } = geometry;
+ const { positions: vertexPositions, normals: vertexNormals, indices } = geometry;
+ const uvs = geometry.lightUvs ?? geometry.uvs;
const worldCorner = [0, 0, 0, 0, 0, 0, 0, 0, 0];
for (let triangle = 0; triangle < indices.length / 3; triangle++) {
const corners = [indices[triangle * 3], indices[triangle * 3 + 1], indices[triangle * 3 + 2]];
@@ -461,6 +521,10 @@ function bakedPart(part, geometry, texture, peak) {
return { ...part, geometry, material: { ...part.material, emission: peak, emissiveColor: [1, 1, 1], emissiveMap: texture } };
}
+function lightMappedPart(part, geometry, texture, peak) {
+ return { ...part, geometry, material: { ...part.material, lightMap: texture, lightMapScale: peak } };
+}
+
/**
* Bakes bounced light into the parts and returns new parts (the input is not changed) plus a report.
* lighting: { pointLights: [{ position, color, intensity, radius, range }], keyColor, lightDirection }, the same shapes
@@ -483,6 +547,7 @@ export function bakeLightmaps(parts, lighting, options = {}) {
const emissionOfPart = parts.map(part => emittedRadiance(part.material));
const gather = createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples: settings.samples, bounces: settings.bounces });
const unwrapCache = new Map();
+ const secondSetCache = new Map();
const plans = [];
const skipped = [];
let texelTotal = 0;
@@ -492,11 +557,13 @@ export function bakeLightmaps(parts, lighting, options = {}) {
skipped.push({ name: part.name, reason });
return;
}
- if (!unwrapCache.has(part.geometry)) unwrapCache.set(part.geometry, unwrapForLightmap(part.geometry));
- const unwrapped = unwrapCache.get(part.geometry);
+ const slot = usesLightMapSlot(part.material);
+ const cache = slot ? secondSetCache : unwrapCache;
+ if (!cache.has(part.geometry)) cache.set(part.geometry, slot ? unwrapIntoSecondUvSet(part.geometry) : unwrapForLightmap(part.geometry));
+ const unwrapped = cache.get(part.geometry);
const resolution = lightmapResolution(worldTriangleArea(part), unwrapped.utilization, settings);
texelTotal += resolution * resolution;
- plans.push({ part, index, unwrapped, resolution });
+ plans.push({ part, index, unwrapped, resolution, slot });
});
const rayWork = texelTotal * settings.samples * settings.bounces * (1 + lights.pointLights.length + (lights.sun ? 1 : 0));
if (texelTotal > MAX_BAKE_TEXELS) throw new RangeError(`Light bake would use ${texelTotal} texels; the limit is ${MAX_BAKE_TEXELS}. Lower maxResolution or texelsPerUnit.`);
@@ -504,7 +571,7 @@ export function bakeLightmaps(parts, lighting, options = {}) {
const baked = parts.slice();
const partReports = [];
const sum = [0, 0, 0];
- for (const { part, index, unwrapped, resolution } of plans) {
+ for (const { part, index, unwrapped, resolution, slot } of plans) {
const { positions, normals, covered } = rasterizeTexels(unwrapped.geometry, part.matrix, resolution);
const radiance = new Float32Array(resolution * resolution * 3);
const albedo = albedoOfPart[index];
@@ -520,14 +587,16 @@ export function bakeLightmaps(parts, lighting, options = {}) {
}
gather(point, normal, index * 1_000_003 + texel, sum);
for (let channel = 0; channel < 3; channel++) {
- radiance[texel * 3 + channel] = sum[channel] * albedo[channel];
+ // The lightMap slot stores the light that arrives; the shader multiplies it by the live surface colour.
+ radiance[texel * 3 + channel] = slot ? sum[channel] : sum[channel] * albedo[channel];
peak = Math.max(peak, radiance[texel * 3 + channel]);
}
}
partReports.push({ name: part.name, resolution, peak });
if (peak <= 0) continue;
dilate(radiance, covered, resolution);
- baked[index] = bakedPart(part, unwrapped.geometry, lightmapTexture(radiance, resolution, peak), peak);
+ const texture = lightmapTexture(radiance, resolution, peak);
+ baked[index] = (slot ? lightMappedPart : bakedPart)(part, unwrapped.geometry, texture, peak);
}
const report = { parts: partReports, skipped, texels: texelTotal, rayWork, seconds: (performance.now() - started) / 1000 };
return { parts: baked, report };
diff --git a/src/renderer.js b/src/renderer.js
index 7ae59a68..f3db97fe 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -54,6 +54,7 @@ function shaderFeaturesOfParts(parts) {
MATERIAL_MAPS.forEach((field, index) => {
if (material[field]) features.add(MAP_SHADER_FEATURES[index]);
});
+ if (material.lightMap) features.add('lightMap');
if (material.layers) features.add('splat');
if (material.moss > 0) features.add('moss');
if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');
@@ -89,6 +90,8 @@ const DEPTH_ALPHA_UNIFORMS = ['alphaMasked', 'alphaCutoff', 'materialOpacity', '
const MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];
const ENVIRONMENT_LOOKUP_UNIFORMS = ['environmentSpecular', 'environmentEnabled', 'environmentIntensity', 'environmentRotation', 'environmentLevelMax'];
const ENVIRONMENT_UNIFORMS = [...ENVIRONMENT_LOOKUP_UNIFORMS, 'environmentBrdf', 'environmentIrradiance[0]'];
+// Shares a unit with the skin influence texture, which no light-mapped (rigid) batch binds.
+const LIGHT_MAP_UNIT = 6;
const ENVIRONMENT_SPECULAR_UNIT = 9;
const ENVIRONMENT_BRDF_UNIT = 10;
const SPLAT_COLOR_UNIT = 11;
@@ -141,7 +144,16 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
validateSplatMaterial(material);
if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...splatBatchState(material)];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material)];
+}
+
+// A baked light map reads the second UV set, so it is only drawn for parts that cannot be skinned or morphed.
+function lightMapState(material) {
+ if (!material.lightMap) return [null, 0];
+ const scale = material.lightMapScale ?? 1;
+ if (!Number.isFinite(scale) || scale < 0) throw new RangeError('lightMapScale must be a nonnegative number.');
+ if ((material.lightMap.colorSpace ?? 'srgb') !== 'srgb') throw new Error('lightMap requires an srgb texture descriptor.');
+ return [material.lightMap, scale];
}
function validateAlphaMaterial(material) {
@@ -296,8 +308,26 @@ function sampleCount(context, format, requested) {
return Math.max(0, ...colorCounts.filter(count => count <= requested && depthCounts.includes(count)));
}
+// Light-mapped geometry uploads its two UV sets as one four-wide attribute (zeros where channel 0 is absent).
+function uvBufferBytes(geometry) {
+ if (!geometry.lightUvs) return geometry.uvs?.byteLength ?? 0;
+ return geometry.lightUvs.byteLength * 2;
+}
+
+function interleaveUvSets(geometry) {
+ const vertexCount = geometry.lightUvs.length / 2;
+ const combined = new Float32Array(vertexCount * 4);
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ combined[vertex * 4] = geometry.uvs?.[vertex * 2] ?? 0;
+ combined[vertex * 4 + 1] = geometry.uvs?.[vertex * 2 + 1] ?? 0;
+ combined[vertex * 4 + 2] = geometry.lightUvs[vertex * 2];
+ combined[vertex * 4 + 3] = geometry.lightUvs[vertex * 2 + 1];
+ }
+ return combined;
+}
+
function geometryBufferBytes(geometry) {
- return ['positions', 'normals', 'uvs', 'colors', 'indices'].reduce((total, field) => total + (geometry[field]?.byteLength ?? 0), 0);
+ return ['positions', 'normals', 'colors', 'indices'].reduce((total, field) => total + (geometry[field]?.byteLength ?? 0), uvBufferBytes(geometry));
}
function validateReplacementGeometry(geometry) {
@@ -410,7 +440,7 @@ export class Renderer67 {
}
const maps = new Set();
for (const group of groups) {
- for (const field of MATERIAL_MAPS) {
+ for (const field of [...MATERIAL_MAPS, 'lightMap']) {
const map = group[0].material[field];
if (!map) continue;
const info = textureDescriptorInfo(map, textureLimit);
@@ -443,7 +473,7 @@ export class Renderer67 {
}
if (geometry.colors && geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');
}
- const expectedGeometryBytes = groups.reduce((total, group) => total + ['positions', 'normals', 'indices', 'uvs', 'colors'].reduce((bytes, field) => bytes + (group[0].geometry[field]?.byteLength ?? 0), 0) + group.length * INSTANCE_STRIDE * 4, 0);
+ const expectedGeometryBytes = groups.reduce((total, group) => total + geometryBufferBytes(group[0].geometry) + group.length * INSTANCE_STRIDE * 4, 0);
planRenderSize({ width: Math.max(1, canvas.clientWidth), height: Math.max(1, canvas.clientHeight), pixelRatio, samples: this.samples, memoryBudgetMiB, geometryBytes: expectedGeometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !benchmark, depth: this.depth, maximumSize: textureLimit });
this.view = mat4.create();
this.projection = mat4.create();
@@ -520,7 +550,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -712,9 +742,11 @@ export class Renderer67 {
for (const field of ['positions', 'normals', 'uvs', 'colors', 'indices']) {
if (geometry[field]) {
const target = field === 'indices' ? context.ELEMENT_ARRAY_BUFFER : context.ARRAY_BUFFER;
- geometryBuffers.set(field, this.uploadBuffer(target, geometry[field]));
+ const values = field === 'uvs' && geometry.lightUvs ? interleaveUvSets(geometry) : geometry[field];
+ geometryBuffers.set(field, this.uploadBuffer(target, values));
}
}
+ if (geometry.lightUvs && !geometry.uvs) geometryBuffers.set('uvs', this.uploadBuffer(context.ARRAY_BUFFER, interleaveUvSets(geometry)));
this.geometryBuffers.set(geometry, geometryBuffers);
}
for (const [location, field] of [[0, 'positions'], [1, 'normals']]) {
@@ -722,11 +754,12 @@ export class Renderer67 {
context.enableVertexAttribArray(location);
context.vertexAttribPointer(location, 3, context.FLOAT, false, 0, 0);
}
- if (geometry.uvs) {
- if (geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');
+ if (geometry.lightUvs && geometry.lightUvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry lightUvs count must match the vertex count.');
+ if (geometry.uvs || geometry.lightUvs) {
+ if (geometry.uvs && geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');
context.bindBuffer(context.ARRAY_BUFFER, geometryBuffers.get('uvs'));
context.enableVertexAttribArray(13);
- context.vertexAttribPointer(13, 2, context.FLOAT, false, 0, 0);
+ context.vertexAttribPointer(13, geometry.lightUvs ? 4 : 2, context.FLOAT, false, 0, 0);
} else {
if (hasMaterialMap(material) && !material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');
context.disableVertexAttribArray(13);
@@ -846,6 +879,8 @@ export class Renderer67 {
const mapState = materialMapState(parts[0].material);
const textures = mapState.slice(0, 5).map(descriptor => this.createTexture(descriptor));
const splat = parts[0].material.layers ? this.createSplatResources(parts[0].material) : null;
+ const lightMapTexture = mapState[14] ? this.createTexture(mapState[14]) : null;
+ if (lightMapTexture && (parts[0].skin || parts[0].morph || !geometry.lightUvs)) throw new Error('A light map needs lightUvs on rigid geometry, with no skin or morph.');
const skin = parts[0].skin ?? null;
const skinTexture = skin ? this.createSkinTexture(this.skinTextures, skin, skin.jointMatrices, 4) : null;
const influenceTexture = skin ? this.createSkinTexture(this.influenceTextures, geometry, null, 2) : null;
@@ -855,7 +890,7 @@ export class Renderer67 {
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
return batch;
@@ -1054,6 +1089,8 @@ export class Renderer67 {
for (let index = 0; index < MATERIAL_MAPS.length; index++) {
if ((part.material[MATERIAL_MAPS[index]] ?? null) !== mapState[index]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
}
+ const [lightMapDescriptor, lightMapScale] = lightMapState(part.material);
+ if (lightMapDescriptor !== (mapState[14] ?? null) || lightMapScale !== (mapState[15] ?? 0)) throw new Error(`Light map changes require a new renderer: ${part.name}`);
if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7] || mossState(part.material).some((value, index) => value !== mapState[8 + index]) || materialLayerState(part.material).some((value, index) => value !== location.layerState[index])) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
validateTransform(part, location.normalMatrix);
}
@@ -1760,6 +1797,13 @@ export class Renderer67 {
this.context.uniform1f(this.uniforms.boxMapScale, batch.mapState[12]);
this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);
this.bindSplat(batch.splat);
+ this.context.uniform1f(this.uniforms.hasLightMap, batch.lightMapTexture ? 1 : 0);
+ if (batch.lightMapTexture) {
+ this.context.activeTexture(this.context.TEXTURE0 + LIGHT_MAP_UNIT);
+ this.context.bindTexture(this.context.TEXTURE_2D, batch.lightMapTexture);
+ this.context.uniform1i(this.uniforms.lightMap, LIGHT_MAP_UNIT);
+ this.context.uniform1f(this.uniforms.lightMapScale, batch.mapState[15]);
+ }
}
if (selection && !selection.isEverything) {
this.drawSelectedLevels(batch, selection);
diff --git a/src/shaders.js b/src/shaders.js
index 55c99cce..cc5b5b42 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -99,7 +99,7 @@ layout(location=9) in vec3 instanceColor;
layout(location=10) in vec4 instanceSurface;
layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
-layout(location=13) in vec2 uv;
+layout(location=13) in vec4 uvSets;
layout(location=14) in vec3 vertexColor;
layout(location=15) in vec3 instanceEmissive;
uniform mat4 viewProjection;
@@ -115,6 +115,7 @@ flat out vec3 baseColor;
flat out vec4 surface;
out vec4 shadowPosition;
out vec2 textureUV;
+out vec2 lightmapUV;
out vec3 vertexTint;
flat out vec3 emissionColor;
flat out float instanceOrdinal;
@@ -125,6 +126,7 @@ ${skinningShader}
${morphingShader}
${windShader}
void main() {
+ vec2 uv = uvSets.xy;
mat4 deformation = skinTransform();
vec4 world = instanceMatrix * deformation * vec4(morphedPosition(position), 1.0);
world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);
@@ -145,6 +147,7 @@ void main() {
boxNormalMatrix = instanceNormal;
baseColor = instanceColor;
textureUV = uv;
+ lightmapUV = uvSets.zw;
vertexTint = vertexColor;
emissionColor = instanceEmissive;
instanceOrdinal = float(gl_InstanceID);
@@ -355,9 +358,13 @@ flat in vec3 baseColor;
flat in vec4 surface;
in vec4 shadowPosition;
in vec2 textureUV;
+in vec2 lightmapUV;
in vec3 vertexTint;
flat in vec3 emissionColor;
flat in float instanceOrdinal;
+uniform sampler2D lightMap;
+uniform float lightMapScale;
+uniform float hasLightMap;
uniform vec3 eye;
uniform float renderPassMode;
uniform float renderPassDepthRange;
@@ -862,6 +869,8 @@ void main() {
radiance += surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;
radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;
}
+ // Baked bounced light arrives as irradiance, so the surface colour (pattern and texture included) tints it here.
+ if (USES_LIGHT_MAP) radiance += color * (1.0 - metallic) * texture(lightMap, lightmapUV).rgb * lightMapScale;
vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);
keyResponse *= mix(daylight, 1.0, worldMode);
if (CANOPY_TAG) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;
@@ -923,6 +932,7 @@ const SHADER_FEATURE_CONDITIONS = {
metallicRoughnessMap: ['USES_METALLIC_ROUGHNESS_MAP', 'hasMetallicRoughnessMap > 0.5'],
occlusionMap: ['USES_OCCLUSION_MAP', 'hasOcclusionMap > 0.5'],
emissiveMap: ['USES_EMISSIVE_MAP', 'hasEmissiveMap > 0.5'],
+ lightMap: ['USES_LIGHT_MAP', 'hasLightMap > 0.5'],
splat: ['USES_SPLAT', 'splatEnabled > 0.5'],
moss: ['USES_MOSS', 'materialMoss.x > 0.0'],
alphaMode: ['USES_ALPHA_MODE', 'alphaMode > 0.5'],
diff --git a/tests/agent-bake.test.js b/tests/agent-bake.test.js
index 2b7c9a1a..8053a7ca 100644
--- a/tests/agent-bake.test.js
+++ b/tests/agent-bake.test.js
@@ -63,12 +63,14 @@ test('a recipe bake lights the room with lightmaps and reports its time and skip
assert.equal(bake.reused, false);
assert.ok(bake.seconds > 0);
assert.ok(bake.texels > 0);
- assert.deepEqual(bake.skipped.map(entry => entry.name), ['bulb']);
+ assert.deepEqual(bake.skipped, []);
const floor = scene.parts.find(part => part.name === 'floor');
assert.ok(floor.material.emissiveMap);
assert.equal(floor.material.color[0], 0.8);
const bulb = scene.parts.find(part => part.name === 'bulb');
assert.equal(bulb.material.emissiveMap, undefined);
+ assert.ok(bulb.material.lightMap);
+ assert.equal(bulb.material.emission, 2);
assert.equal(createAgentScene(closedRoomWithoutBake()).parts.some(part => part.material.emissiveMap), false);
});
@@ -117,3 +119,33 @@ test('a failed bake leaves the scene as it was', () => {
assert.equal(scene.revision, 0);
assert.equal(scene.inspect().bake.samples, BAKE_PRESETS.draft.samples);
});
+
+test('a brick wall keeps its pattern and receives bounced light through a light map', () => {
+ const recipe = closedRoom();
+ recipe.materials.push({ id: 'bricks', color: [1, 1, 1], roughness: 0.9, pattern: { type: 'bricks', size: 1 } });
+ recipe.nodes.find(node => node.id === 'back').material = 'bricks';
+ const scene = createAgentScene(recipe);
+ assert.deepEqual(scene.inspect().bake.skipped, []);
+ const wall = scene.parts.find(part => part.name === 'back');
+ assert.ok(wall.material.lightMap);
+ assert.ok(wall.material.map);
+ assert.ok(wall.material.boxMapScale > 0);
+ assert.equal(wall.geometry.lightUvs.length, wall.geometry.positions.length / 3 * 2);
+ const again = createAgentScene(recipe).parts.find(part => part.name === 'back');
+ assert.deepEqual(Array.from(again.material.lightMap.image.data), Array.from(wall.material.lightMap.image.data));
+});
+
+test('a node that hosts a hair system bakes without an error and is reported as skipped', () => {
+ const recipe = closedRoom({
+ geometries: [{ id: 'box', type: 'box' }, { id: 'head', type: 'sphere', segments: 12, rings: 8 }],
+ particles: { systems: [{ type: 'hair', node: 'fur', surface: 'head', seed: 5, count: 40, length: [0.1, 0.2], segments: 3 }] },
+ });
+ recipe.nodes.push({ id: 'head', geometry: 'head', material: 'white', translation: [0.5, 0.5, 0.5], scale: [0.3, 0.3, 0.3] });
+ recipe.nodes.push({ id: 'fur', geometry: 'box', material: 'white' });
+ const scene = createAgentScene(recipe);
+ const skipped = scene.inspect().bake.skipped.find(entry => entry.name === 'fur');
+ assert.ok(skipped);
+ assert.match(skipped.reason, /hair|particle/);
+ assert.ok(scene.parts.find(part => part.name === 'head').material.emissiveMap);
+ assert.equal(scene.parts.find(part => part.name === 'fur').material.emissiveMap, undefined);
+});
diff --git a/tests/light-bake.test.js b/tests/light-bake.test.js
index 622d1066..eb5b05a0 100644
--- a/tests/light-bake.test.js
+++ b/tests/light-bake.test.js
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { box } from '../src/geometry.js';
+import { exportGlb } from '../src/export.js';
import { BAKE_LIMITS, MAX_BAKE_POINT_LIGHTS, bakeLightmaps, normalizeBakeOptions } from '../src/light-bake.js';
const cube = box(0, 1);
@@ -69,14 +70,60 @@ test('light reaches a surface the lamp cannot see, and a dark scene bakes nothin
test('parts that cannot take a lightmap are skipped with a reason and still block light', () => {
const parts = smallRoom();
- parts.push(placed('painted', [1, 0.5, 1], [0.5, 1, 0.5], { map: { image: { width: 1, height: 1, data: new Uint8ClampedArray(4) }, colorSpace: 'srgb' } }));
- parts.push(placed('lamp-shade', [0, 2, 1], [0.2, 0.2, 0.2], { emission: 2 }));
+ parts.push(placed('glass', [1, 0.5, 1], [0.5, 1, 0.5], { alphaMode: 'blend', opacity: 0.4 }));
+ parts.push(placed('lava', [0, 2, 1], [0.2, 0.2, 0.2], { tag: 'fire' }));
const { parts: baked, report } = bakeLightmaps(parts, lamp, fastOptions);
- assert.deepEqual(report.skipped.map(entry => entry.name), ['painted', 'lamp-shade']);
+ assert.deepEqual(report.skipped.map(entry => entry.name), ['glass', 'lava']);
assert.equal(baked[7], parts[7]);
assert.equal(baked[8], parts[8]);
});
+test('a textured part keeps its map and UV channel 0 and receives light through a second UV set', () => {
+ const mapImage = { width: 2, height: 2, data: new Uint8ClampedArray([200, 60, 40, 255, 220, 90, 60, 255, 190, 70, 50, 255, 210, 80, 50, 255]) };
+ const brickMap = { image: mapImage, colorSpace: 'srgb' };
+ const parts = smallRoom();
+ const cubeUvs = new Float32Array(cube.positions.length / 3 * 2);
+ for (let vertex = 0; vertex < cube.positions.length / 3; vertex++) {
+ cubeUvs[vertex * 2] = cube.positions[vertex * 3] + 0.5;
+ cubeUvs[vertex * 2 + 1] = cube.positions[vertex * 3 + 1] + 0.5;
+ }
+ const texturedCube = { ...cube, uvs: cubeUvs };
+ parts.push({ ...placed('wall', [1.5, 1, 1.5], [1, 2, 1], { map: brickMap }), geometry: texturedCube });
+ const { parts: baked, report } = bakeLightmaps(parts, lamp, { ...fastOptions, samples: 16 });
+ const wall = baked[7];
+ assert.equal(report.skipped.length, 0);
+ assert.equal(wall.material.map, brickMap);
+ assert.equal(wall.material.emissiveMap, undefined);
+ assert.equal(wall.material.emission, 0);
+ assert.equal(wall.material.lightMap.colorSpace, 'srgb');
+ assert.ok(wall.material.lightMapScale > 0);
+ const vertexCount = wall.geometry.positions.length / 3;
+ assert.equal(wall.geometry.lightUvs.length, vertexCount * 2);
+ assert.equal(wall.geometry.uvs.length, vertexCount * 2);
+ const sourceUvs = new Set();
+ for (let index = 0; index < cubeUvs.length; index += 2) sourceUvs.add(`${cubeUvs[index]},${cubeUvs[index + 1]}`);
+ for (let index = 0; index < wall.geometry.uvs.length; index += 2) assert.ok(sourceUvs.has(`${wall.geometry.uvs[index]},${wall.geometry.uvs[index + 1]}`));
+ const again = bakeLightmaps(parts, lamp, { ...fastOptions, samples: 16 }).parts[7];
+ assert.deepEqual(Array.from(again.material.lightMap.image.data), Array.from(wall.material.lightMap.image.data));
+});
+
+test('an emitting part is baked through the light map slot and still lights the others', () => {
+ const parts = smallRoom();
+ parts.push(placed('lamp-shade', [-1.5, 2, 1], [0.2, 0.2, 0.2], { emission: 2 }));
+ const { parts: baked, report } = bakeLightmaps(parts, lamp, fastOptions);
+ assert.equal(report.skipped.length, 0);
+ assert.equal(baked[7].material.emission, 2);
+ assert.ok(baked[7].material.lightMap);
+});
+
+test('a part marked as generating its own geometry is skipped', () => {
+ const parts = smallRoom();
+ parts[0] = { ...parts[0], generatesGeometry: true };
+ const { parts: baked, report } = bakeLightmaps(parts, lamp, fastOptions);
+ assert.deepEqual(report.skipped.map(entry => entry.name), ['floor']);
+ assert.equal(baked[0], parts[0]);
+});
+
test('options are validated with their bounds', () => {
assert.deepEqual(normalizeBakeOptions({}), Object.fromEntries(Object.entries(BAKE_LIMITS).map(([name, limit]) => [name, limit.fallback])));
for (const [name, bad] of [['samples', 0], ['samples', 513], ['samples', Number.NaN], ['bounces', 5], ['maxResolution', 3], ['maxResolution', 1e9], ['texelsPerUnit', 0], ['texelsPerUnit', Infinity], ['maxSeconds', 0], ['maxSeconds', '60']]) {
@@ -123,6 +170,22 @@ test('a bake that would trace too many rays is refused up front', () => {
assert.throws(() => bakeLightmaps(smallRoom(), lamp, heavy), /limit is/);
});
+test('a light mapped part exports its second UV set as TEXCOORD_1 and its light map as the emissive texture', () => {
+ const parts = smallRoom();
+ const mapImage = { width: 2, height: 2, data: new Uint8ClampedArray(16).fill(180) };
+ const withMap = placed('wall', [1.5, 1, 1.5], [1, 2, 1], { map: { image: mapImage, colorSpace: 'srgb' } });
+ parts.push({ ...withMap, geometry: { ...cube, uvs: new Float32Array(cube.positions.length / 3 * 2) } });
+ const baked = bakeLightmaps(parts, lamp, fastOptions).parts;
+ const view = new DataView(exportGlb(baked));
+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(view.buffer, 20, view.getUint32(12, true))));
+ const lightMapped = json.meshes.find((mesh, index) => json.nodes.some(node => node.mesh === index && node.name === 'wall'));
+ assert.ok(lightMapped.primitives[0].attributes.TEXCOORD_1 !== undefined);
+ assert.ok(lightMapped.primitives[0].attributes.TEXCOORD_0 !== undefined);
+ const material = json.materials[lightMapped.primitives[0].material];
+ assert.equal(material.emissiveTexture.texCoord, 1);
+ assert.ok(material.pbrMetallicRoughness.baseColorTexture);
+});
+
test('a bake that runs out of time throws instead of returning a partial result', () => {
const slow = { samples: 256, bounces: 4, texelsPerUnit: 8, maxResolution: 128, maxSeconds: 1 };
assert.throws(() => bakeLightmaps(smallRoom(), lamp, slow), /maxSeconds/);
diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.js
index 9ae33c9d..2d044d55 100644
--- a/tests/reference-baseline.test.js
+++ b/tests/reference-baseline.test.js
@@ -4,7 +4,7 @@ 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 = ['brick-graph', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
+const EXPECTED_SCENES = ['brick-graph', 'brick-room', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
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', () => {