3D engine that AI agents drive
Add a light bake addon for bounced light
Nguyen Xuan An52ca4c2f82b5
diff --git a/.gitignore b/.gitignoreindex 5153be0b..d537b834 100644--- a/.gitignore+++ b/.gitignore@@ -26,6 +26,7 @@ public/vegetation.mdpublic/terrain.mdpublic/grass.mdpublic/clutter.md+public/light-bake.mdpublic/scene-graph.mdpublic/modeling.mdpublic/animation-curves.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a353fe8..339eb88d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add `67js/addons/light-bake` (part of issue #55; recipes, MCP, GLB export and reflection probes are not done). `bakeLightmaps(parts, lights, options)` traces cosine-weighted paths on the CPU against a triangle BVH and returns new parts that carry the light that bounces between surfaces (point lights and the sun, shadowed) as a lightmap texture drawn through the emissive map, with lightmap UVs from the `uv_unwrap` unwrap. The renderer and its shaders are untouched, so a scene without a bake renders as before and core size is unchanged. Bounded and deterministic: `samples`, `bounces`, `texelsPerUnit`, `maxResolution` and `maxSeconds` are range checked, texel, triangle, light and ray-work totals are checked before any ray is traced, and the same input gives the same bytes. Parts with their own maps, pattern, emission, skin or transparency are skipped and listed in the report. `npm run reference -- --bake lit-interior` takes `lit-interior` from 0.5055 to 0.1444 against Cycles (6 s bake); no other scene moved by more than 0.002. The package archive grows by 3,525 bytes (717,978 to 721,503). See `docs/light-bake.md`.+- Edit the topology of imported GLB parts (part of issue #48, no new tool). `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` of an imported asset: the part becomes a welded polygon mesh with axis tags and a `material-<n>` tag, the edit log is kept in the asset recipe as `meshEdits` (checkpoints, export and replay work), and every result passes `validateTopology`. New vertices take skin weights, morph deltas and vertex colours from the nearest original surface point and faces left without UVs read the nearest UV island; on a skinned or morphed part an edit more than a quarter of the part's bounds diagonal from the original surface is rejected with the next action. `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`. Measured on RobotExpressive through MCP (`npm run smoke:imported-topology`): a through hole in the closed left leg (98 to 210 triangles, still one closed part), a cut in the skinned right hand (124 to 109) and the morphed head (154 to 134), a 3 m extrude on the head rejected, GLB export and checkpoint restore intact. Suite task `robot-leg-hole`.- Make room in the npm package (part of issue #36). The MCP preview page, `build/mcp/preview.js`, is now an entry of the library build and imports the engine chunks that the package entries already ship, instead of bundling its own copy of the engine. The archive drops from 904,975 to 666,214 bytes. `build/mcp/manifest.json` lists those chunks under `previewChunks` with their hashes, the MCP runtime serves them next to `preview.js`, and `bench/size/budgets.json` gains `archiveBytes`, which `npm run smoke:package` checks.- Add six whole-mesh modifiers as edits and stack nodes (part of issue #42): `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform` (twist, bend, taper, stretch) and `cast` (sphere). Each has Blender cases in `tests/fixtures/blender/` that match with no listed difference, `triangulate` and `edge_split` check their output size before building it, and their fields are described in `scene_capabilities` `meshModifiers` so the tool schemas grow by one compact entry. Left for later slices: screw, skin, wireframe, lattice, curve, hook, wave, shrinkwrap, weighted normal, smooth by angle and the other cast shapes. `npm run parity` now prints the modifier coverage.diff --git a/README.md b/README.mdindex 2bfb408b..f48ec3a7 100644--- a/README.md+++ b/README.md@@ -120,6 +120,7 @@ Each addon is a separate import, so a page loads only what it uses.| Terrain | `67js/addons/terrain`, `67js/addons/texture-set` | [Chunked terrain](https://67js.codepawl.com/terrain.md) with level of detail and a four-layer splat material from scanned textures. || Grass | `67js/addons/grass` | [Grass fields](https://67js.codepawl.com/grass.md) of clumped, curved blades with rolling wind gusts, paths and level of detail. || Clutter | `67js/addons/clutter` | [Pebbles, rocks, twigs and fallen leaves](https://67js.codepawl.com/clutter.md) scattered over terrain in streamed tiles. |+| Light bake | `67js/addons/light-bake` | [Bounced light baked into one lightmap per part](https://67js.codepawl.com/light-bake.md), drawn through the emissive map. || Vegetation | `67js/addons/vegetation` | [Seeded trees, bushes and grass](https://67js.codepawl.com/vegetation.md) with scanned leaves and bark, wind and level of detail. || Liquid | `67js/addons/spume` | [Baked liquid playback](https://67js.codepawl.com/spume.md) with refraction and spray from the Spume solver. || Vehicles | `67js/addons/vehicle` | [Wheeled vehicles on a path](https://67js.codepawl.com/vehicle.md): wheel spin, steering, roll, pitch and ground following. |diff --git a/bench/reference/README.md b/bench/reference/README.mdindex d49264b9..5813d903 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -29,6 +29,8 @@ Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metrRows are the baseline taken before shadows for point lights. The `lit-interior` scene now sets `castShadow` on its three point lights. With shadows, 67.js scores 0.5055 against Cycles (0.4997 before, so 0.0058 worse) and 0.0923 against EEVEE (0.1204 before, better): the shadow shape now matches, but Cycles fills its shadows with indirect light and 67.js leaves them dark. The committed `lit-interior` row stays at the earlier numbers. `spot-area` is new with shadows, a spot light and an area light.+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-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 67.js: 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 67.js and 0.160 for EEVEE. The mean difference between the RTX 3060 and SwiftShader is 0.007.diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 61b9a5d4..df3e150b 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -70,10 +70,20 @@ function describeScene(id, scene) {};}-async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5 }) {+// Blender always gets the original parts: the bake is 67.js's approximation of what Cycles computes.+async function bakeScene(scene, bakeOptions) {+ const { bakeLightmaps } = await import('/src/light-bake.js');+ const { pointLights, keyColor, lightDirection } = scene.environment;+ const started = performance.now();+ const baked = bakeLightmaps(scene.parts, { pointLights, keyColor, lightDirection }, bakeOptions);+ return { parts: baked.parts, report: baked.report, seconds: (performance.now() - started) / 1000 };+}++async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null }) {const scene = await REFERENCE_SCENES[id]();+ const baked = bake ? await bakeScene(scene, bake) : null;const canvas = document.querySelector('canvas');- const renderer = new Renderer67(canvas, scene.parts, {+ const renderer = new Renderer67(canvas, baked ? baked.parts : scene.parts, {ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,environment: scene.environment, shadowBounds: scene.shadow,});@@ -87,6 +97,7 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambienglError: renderer.context.getError(),graphics: renderer.context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : renderer.context.RENDERER),description: describe ? describeScene(id, scene) : null,+ bake: baked ? { seconds: baked.seconds, report: baked.report } : null,};renderer.dispose();return result;diff --git a/bench/reference/run.mjs b/bench/reference/run.mjsindex a825387e..0bbd3419 100644--- a/bench/reference/run.mjs+++ b/bench/reference/run.mjs@@ -1,5 +1,7 @@// Renders the reference scenes in 67.js and Blender, then scores them: npm run reference// --ambient-occlusion <strength> [--ambient-occlusion-radius <units>] turns occlusion on (off by default).+// --bake [<id>,<id>] bakes bounced light into the named scenes (every scene when no ids follow) before 67.js draws them;+// Blender still gets the plain scene.// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.import { spawnSync } from 'node:child_process';import { mkdir, writeFile } from 'node:fs/promises';@@ -30,6 +32,9 @@ const occlusionFlag = argumentsGiven.indexOf('--ambient-occlusion');const ambientOcclusion = occlusionFlag >= 0 ? Number(argumentsGiven[occlusionFlag + 1]) : 0;const radiusFlag = argumentsGiven.indexOf('--ambient-occlusion-radius');const ambientOcclusionRadius = radiusFlag >= 0 ? Number(argumentsGiven[radiusFlag + 1]) : 0.5;+const bakeFlag = argumentsGiven.indexOf('--bake');+const bakeValue = bakeFlag >= 0 ? argumentsGiven[bakeFlag + 1] : undefined;+const bakedSceneIds = bakeFlag >= 0 && bakeValue && !bakeValue.startsWith('--') ? bakeValue.split(',') : null;const onlyScene = sceneFlag >= 0 ? argumentsGiven[sceneFlag + 1] : null;async function renderBackend(backend, serverUrl, graphics) {@@ -45,12 +50,14 @@ async function renderBackend(backend, serverUrl, graphics) {if (onlyScene && id !== onlyScene) continue;const started = performance.now();const describe = backend === 'gpu';- const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius }), [id, describe, ambientOcclusion, ambientOcclusionRadius]);+ const bake = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id)) ? {} : null;+ const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake]);if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);graphics[backend] = result.graphics;await writeFile(`${WORK_DIRECTORY}/${id}-${backend}.png`, Buffer.from(result.image, 'base64'));if (describe) await writeFile(`${WORK_DIRECTORY}/scenes/${id}.json`, JSON.stringify(result.description));- console.log(`${id} on ${backend}: ${Math.round(performance.now() - started)} ms`);+ const bakeNote = result.bake ? `, bake ${result.bake.seconds.toFixed(1)} s, ${result.bake.report.texels} texels` : '';+ console.log(`${id} on ${backend}: ${Math.round(performance.now() - started)} ms${bakeNote}`);}if (errors.length) throw new Error(errors.join('\n'));} finally {diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex 200aeec1..10e95cb7 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 283167,- "gzip": 80916,- "brotli": 68973+ "min": 283213,+ "gzip": 80927,+ "brotli": 69079},"entry:model": {"min": 40093,@@ -123,6 +123,11 @@"gzip": 5185,"brotli": 4675},+ "entry:light-bake": {+ "min": 67640,+ "gzip": 24805,+ "brotli": 21989+ },"entry:texture-set": {"min": 1837,"gzip": 874,diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 195a732c..e309daa3 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -1,5 +1,5 @@{- "archiveBytes": 717978,+ "archiveBytes": 721503,"goals": {"lit-box": 50000,"gltf-box": 80000,@@ -28,6 +28,7 @@"entry:terrain": 3100,"entry:grass": 4400,"entry:clutter": 5300,+ "entry:light-bake": 25400,"entry:texture-set": 900,"entry:agent-scene": 61800,"entry:agent-scene+lazy": 191900,diff --git a/docs/guide.md b/docs/guide.mdindex 048e6d9e..cb4eef89 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -223,6 +223,8 @@ Tint the ground under the grass with `grass.groundColor`. The [Grass contract](/`67js/addons/clutter` is in the current source and not yet published. It scatters pebbles, rocks, twigs and fallen leaves over terrain in the same streamed tiles. Pick a `preset` (`meadow`, `forest`, `riverbed`, `scree`), pass `terrainHeight`, and add `clutter.parts` next to the grass. The [Clutter contract](/clutter.md) lists options and budgets.+`67js/addons/light-bake` is in the current source and not yet published. `bakeLightmaps(parts, lights, options)` ray traces the light that bounces between surfaces into a lightmap texture for each part and returns new parts that draw it through the emissive map; direct light stays live. The [Light bake contract](/light-bake.md) lists the limits.+## Terrain and ground textures`67js/addons/terrain` and `67js/addons/texture-set` are available from version `0.10.0`. They build a chunked, seeded heightfield with distance level of detail and a four-layer ground material (slope, height and mask rules, height-based edge blending, triplanar cliffs, anti-tiling) from CC0 scans.diff --git a/docs/light-bake.md b/docs/light-bake.mdnew file mode 100644index 00000000..1f2b5af6--- /dev/null+++ b/docs/light-bake.md@@ -0,0 +1,45 @@+# Light bake++`67js/addons/light-bake` writes the light that bounces between surfaces into one lightmap texture per part. It is in the current source and not yet published. It is code only: recipes and the MCP tools cannot ask for a bake yet (issue #55).++```js+import { bakeLightmaps } from '67js/addons/light-bake';++const { parts: bakedParts, report } = bakeLightmaps(parts, {+ pointLights: environment.pointLights,+ keyColor: environment.keyColor,+ lightDirection: environment.lightDirection,+}, { samples: 128, bounces: 2 });++const renderer = new Renderer67(canvas, bakedParts, rendererOptions);+```++## What it bakes++The bake traces cosine-weighted paths from each texel through up to `bounces` reflections. Each hit adds its own emission and the direct light it receives from the point lights and the sun, with shadow rays. A texel stores that light times its own albedo. Direct light is not baked: it stays live, so shadows and moving lights keep working. The stored light is only what has bounced at least once, so a scene needs the same lights at run time that it gave the bake.++Not baked: spot lights, area lights, the environment map (it already lights every surface at run time), and specular reflection. A metal part reflects no baked light. Fresnel and sheen are ignored.++## 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.++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.++## Limits++| Option | Default | Range | Meaning |+| --- | --- | --- | --- |+| `samples` | 128 | 1 to 512 | Paths per texel. |+| `bounces` | 2 | 1 to 4 | Reflections followed by each path. |+| `texelsPerUnit` | 6 | 0.5 to 64 | Lightmap density in world units. |+| `maxResolution` | 128 | 4 to 256 | Largest lightmap side for one part. |+| `maxSeconds` | 60 | 1 to 600 | Wall-clock limit. Passing it throws; a bake never returns a partial result. |++Also checked before any ray is traced: at most 256 parts, 200,000 triangles in total, 8 point lights, 1,000,000 texels and 400 million units of ray work (texels, samples, bounces and lights multiplied). Positions, indices, matrices, colours and lights must be finite and in range, and an error names the field.++The result is deterministic: the same parts, lights and options give the same bytes, with no `Math.random` and no clock in the output. `report.seconds` is the only value that varies from run to run.++## Measured++The `lit-interior` reference scene (25,648 texels at the defaults) bakes in about 6 s in the page on an RTX 3060 machine, running at below-normal priority. Its score against Cycles goes from 0.5055 to 0.1444 with the bake (`npm run reference -- --bake lit-interior`; details in `bench/reference/README.md`). Frame time with and without the bake has not been measured.diff --git a/docs/parity.md b/docs/parity.mdindex 77a1de48..9bf972ec 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 | missing | No path tracer and no render baking. | | #55, #57 |+| Rendering > Render Engines > Cycles | partial | No path tracer. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; it is code only (no recipe field, 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), [lit-interior scene](../bench/reference/scenes.js) | #55, #57 || 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/package.json b/package.jsonindex 394c1ddf..7fe58797 100644--- a/package.json+++ b/package.json@@ -70,6 +70,7 @@"./addons/terrain": "./build/terrain.js","./addons/grass": "./build/grass.js","./addons/clutter": "./build/clutter.js",+ "./addons/light-bake": "./build/light-bake.js","./addons/texture-set": "./build/texture-set.js","./addons/agent-scene": "./build/agent-scene.js","./addons/agent-asset": "./build/agent-asset.js",diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 9ac00b24..e116f161 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -43,7 +43,7 @@ const sourceDocuments = ['retarget.md','skeleton-pose.md','vehicle.md',- 'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md',+ 'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md','camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md','surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',];diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex d576856a..607de25f 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -15,6 +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.- 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`.diff --git a/src/light-bake.js b/src/light-bake.jsnew file mode 100644index 00000000..71c72ee2--- /dev/null+++ b/src/light-bake.js@@ -0,0 +1,575 @@+import { buildTriangleBvh, rayBoxDistance, traverseTriangleBvh } from './triangle-bvh.js';+import { intersectRayTriangle, readTriangle } from './triangle-math.js';+import { extractRender } from './mesh-render.js';+import { meshFromGeometry } from './mesh-convert.js';+import { unwrapUv } from './mesh-uv.js';+import { createImage, linearToSrgbByte } from './material-texture-kit.js';++// Light bake: the light that bounces between surfaces, written into one lightmap texture per part. A part draws it+// through its emissive map, so the renderer, its shaders and every scene without a bake stay exactly as they were.+// The bake gathers light that reaches each texel after reflecting off other surfaces (point lights and the sun, shadowed+// by ray tracing). Direct light stays live, so shadows and moving lights keep working. Same input, same bytes.++export const BAKE_LIMITS = Object.freeze({+ maxResolution: { minimum: 4, maximum: 256, fallback: 128 },+ texelsPerUnit: { minimum: 0.5, maximum: 64, fallback: 6 },+ samples: { minimum: 1, maximum: 512, fallback: 128 },+ bounces: { minimum: 1, maximum: 4, fallback: 2 },+ maxSeconds: { minimum: 1, maximum: 600, fallback: 60 },+});+// Total ray work (texels x samples x bounces x rays per hit) a bake may ask for, checked before any ray is traced.+export const MAX_BAKE_RAY_WORK = 400_000_000;+export const MAX_BAKE_TEXELS = 1_000_000;+export const MAX_BAKE_TRIANGLES = 200_000;+export const MAX_BAKE_PARTS = 256;+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 LIGHT_MAP_CLAMP_TO_EDGE = 33071;+const LIGHT_MAP_LINEAR = 9729;++function boundedNumber(options, name) {+ const limit = BAKE_LIMITS[name];+ const value = options[name] ?? limit.fallback;+ if (!Number.isFinite(value) || value < limit.minimum || value > limit.maximum) {+ throw new RangeError(`Light bake ${name} must be a number from ${limit.minimum} to ${limit.maximum}.`);+ }+ return name === 'samples' || name === 'bounces' || name === 'maxResolution' ? Math.floor(value) : value;+}++/** Validates the bake options and fills in defaults. Throws a RangeError that names the field and its bounds. */+export function normalizeBakeOptions(options = {}) {+ if (options === null || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Light bake options must be an object.');+ const normalized = {};+ for (const name of Object.keys(BAKE_LIMITS)) normalized[name] = boundedNumber(options, name);+ return normalized;+}++function finiteVector(value, length) {+ return (Array.isArray(value) || ArrayBuffer.isView(value)) && value.length === length && Array.from(value).every(Number.isFinite);+}++function normalizeLights(lighting) {+ if (lighting === null || typeof lighting !== 'object') throw new TypeError('Light bake needs a lighting object.');+ const pointLights = lighting.pointLights ?? [];+ if (!Array.isArray(pointLights) || pointLights.length > MAX_BAKE_POINT_LIGHTS) throw new RangeError(`Light bake takes at most ${MAX_BAKE_POINT_LIGHTS} point lights.`);+ const normalizedPoints = pointLights.map((light, index) => {+ const range = light.range ?? 0;+ const radius = light.radius ?? 0.05;+ if (!finiteVector(light.position, 3) || !finiteVector(light.color ?? [1, 1, 1], 3) || !Number.isFinite(light.intensity) || light.intensity < 0) {+ throw new RangeError(`Light bake point light ${index} needs a position, a color and a nonnegative intensity.`);+ }+ if (!Number.isFinite(range) || range < 0 || !Number.isFinite(radius) || radius < 0) throw new RangeError(`Light bake point light ${index} has an invalid range or radius.`);+ return { position: Array.from(light.position), color: Array.from(light.color ?? [1, 1, 1]), intensity: light.intensity, range, radius };+ });+ const keyColor = lighting.keyColor ?? [0, 0, 0];+ const lightDirection = lighting.lightDirection ?? [0, 1, 0];+ if (!finiteVector(keyColor, 3) || keyColor.some(channel => channel < 0) || !finiteVector(lightDirection, 3)) throw new RangeError('Light bake keyColor and lightDirection must be finite vectors.');+ const directionLength = Math.hypot(...lightDirection);+ const hasSun = keyColor.some(channel => channel > 0) && directionLength > 0;+ const sunDirection = hasSun ? lightDirection.map(component => component / directionLength) : [0, 1, 0];+ return { pointLights: normalizedPoints, sun: hasSun ? { color: Array.from(keyColor), direction: sunDirection } : null };+}++function validatePart(part, index) {+ const { geometry, matrix } = part ?? {};+ const label = `Light bake part ${index}`;+ if (!geometry || !(geometry.positions instanceof Float32Array) || geometry.positions.length === 0 || geometry.positions.length % 3 !== 0) throw new TypeError(`${label} needs Float32 positions.`);+ if (!(geometry.indices instanceof Uint32Array) || geometry.indices.length === 0 || geometry.indices.length % 3 !== 0) throw new TypeError(`${label} needs Uint32 triangle indices.`);+ if (!finiteVector(matrix, 16)) throw new RangeError(`${label} needs a finite 4x4 matrix.`);+ const vertexCount = geometry.positions.length / 3;+ for (let position = 0; position < geometry.positions.length; position++) {+ if (!Number.isFinite(geometry.positions[position])) throw new RangeError(`${label} has a non-finite position.`);+ }+ for (let slot = 0; slot < geometry.indices.length; slot++) {+ if (geometry.indices[slot] >= vertexCount) throw new RangeError(`${label} has an index past its last vertex.`);+ }+ const color = part.material?.color;+ if (!finiteVector(color, 3)) throw new RangeError(`${label} needs a material color.`);+}++function skipReason(part) {+ const material = part.material;+ 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;+}++function diffuseAlbedo(material) {+ const keep = 1 - (material.metallic ?? 0);+ return material.color.map(channel => Math.max(channel, 0) * keep);+}++function emittedRadiance(material) {+ const strength = material.emission ?? 0;+ if (strength <= 0) return [0, 0, 0];+ return (material.emissiveColor ?? material.color).map(channel => channel * strength);+}++/** All parts in world space as one triangle soup: positions, indices, and the part each triangle belongs to. */+function buildWorld(parts) {+ let vertexTotal = 0;+ let indexTotal = 0;+ for (const part of parts) {+ vertexTotal += part.geometry.positions.length / 3;+ indexTotal += part.geometry.indices.length;+ }+ if (indexTotal / 3 > MAX_BAKE_TRIANGLES) throw new RangeError(`Light bake takes at most ${MAX_BAKE_TRIANGLES} triangles in total.`);+ const positions = new Float32Array(vertexTotal * 3);+ const indices = new Uint32Array(indexTotal);+ const triangleOwner = new Uint32Array(indexTotal / 3);+ let vertexOffset = 0;+ let triangleOffset = 0;+ parts.forEach((part, partIndex) => {+ const { matrix } = part;+ const source = part.geometry.positions;+ for (let vertex = 0; vertex < source.length / 3; vertex++) {+ const x = source[vertex * 3];+ const y = source[vertex * 3 + 1];+ const z = source[vertex * 3 + 2];+ const target = (vertexOffset + vertex) * 3;+ positions[target] = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];+ positions[target + 1] = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];+ positions[target + 2] = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];+ }+ for (let slot = 0; slot < part.geometry.indices.length; slot++) indices[triangleOffset * 3 + slot] = part.geometry.indices[slot] + vertexOffset;+ triangleOwner.fill(partIndex, triangleOffset, triangleOffset + part.geometry.indices.length / 3);+ vertexOffset += source.length / 3;+ triangleOffset += part.geometry.indices.length / 3;+ });+ return { positions, indices, triangleOwner, bvh: buildTriangleBvh(positions, indices) };+}++function sceneScale(positions) {+ let largest = 0;+ for (let index = 0; index < positions.length; index++) largest = Math.max(largest, Math.abs(positions[index]));+ return Math.max(largest, 1e-3);+}++/** Ray queries with preallocated state: the traversal callbacks are built once, not once per ray. */+function createTracer(world) {+ const origin = new Float64Array(3);+ const direction = new Float64Array(3);+ const triangle = new Float64Array(9);+ const state = { nearestDistance: Infinity, nearestTriangle: -1, stopAtAnyHit: false };+ const scoreBounds = (bounds, offset) => rayBoxDistance(origin, direction, bounds, offset);+ const shouldVisit = score => score < state.nearestDistance;+ const visitTriangle = triangleId => {+ readTriangle(world.positions, world.indices, triangleId, triangle);+ const distance = intersectRayTriangle(origin, direction, triangle);+ if (distance < 0 || distance >= state.nearestDistance) return false;+ state.nearestDistance = distance;+ state.nearestTriangle = triangleId;+ return state.stopAtAnyHit;+ };+ function trace(ox, oy, oz, dx, dy, dz, limit, stopAtAnyHit) {+ origin[0] = ox;+ origin[1] = oy;+ origin[2] = oz;+ direction[0] = dx;+ direction[1] = dy;+ direction[2] = dz;+ state.nearestDistance = limit;+ state.nearestTriangle = -1;+ state.stopAtAnyHit = stopAtAnyHit;+ traverseTriangleBvh(world.bvh, scoreBounds, shouldVisit, visitTriangle);+ return state;+ }+ return { trace };+}++/** Integer hash to [0, 1): the only source of randomness, so a bake repeats exactly. */+function hashUnit(first, second, third) {+ let value = Math.imul(first ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(second + 0x7f4a7c15, 0xc2b2ae35) ^ Math.imul(third + 0x165667b1, 0x27d4eb2f);+ value = Math.imul(value ^ (value >>> 15), 0x2c1b3c6d);+ value = Math.imul(value ^ (value >>> 12), 0x297a2d39);+ value ^= value >>> 15;+ return (value >>> 0) / 4294967296;+}++function radicalInverse(index) {+ let bits = index;+ let result = 0;+ let scale = 0.5;+ while (bits > 0) {+ if (bits & 1) result += scale;+ bits >>>= 1;+ scale *= 0.5;+ }+ return result;+}++/** A cosine-weighted direction about `normal`, written into `out`. */+function cosineDirection(normal, firstUnit, secondUnit, out) {+ const radius = Math.sqrt(firstUnit);+ const angle = 2 * Math.PI * secondUnit;+ const localX = radius * Math.cos(angle);+ const localY = radius * Math.sin(angle);+ const localZ = Math.sqrt(Math.max(0, 1 - firstUnit));+ const helper = Math.abs(normal[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];+ let tangentX = normal[1] * helper[2] - normal[2] * helper[1];+ let tangentY = normal[2] * helper[0] - normal[0] * helper[2];+ let tangentZ = normal[0] * helper[1] - normal[1] * helper[0];+ const tangentLength = Math.hypot(tangentX, tangentY, tangentZ);+ tangentX /= tangentLength;+ tangentY /= tangentLength;+ tangentZ /= tangentLength;+ const bitangentX = normal[1] * tangentZ - normal[2] * tangentY;+ const bitangentY = normal[2] * tangentX - normal[0] * tangentZ;+ const bitangentZ = normal[0] * tangentY - normal[1] * tangentX;+ out[0] = tangentX * localX + bitangentX * localY + normal[0] * localZ;+ out[1] = tangentY * localX + bitangentY * localY + normal[1] * localZ;+ out[2] = tangentZ * localX + bitangentZ * localY + normal[2] * localZ;+}++function pointLightFalloff(distanceSquared, light) {+ let cutoff = 1;+ if (light.range > 0) {+ const ratio = distanceSquared / (light.range * light.range);+ const fade = Math.max(1 - ratio * ratio, 0);+ cutoff = fade * fade;+ }+ return cutoff / Math.max(distanceSquared, light.radius * light.radius);+}++/**+ * Builds the function that returns the irradiance (light power per area, before the albedo and 1/pi of a diffuse+ * surface) of the direct lights at a point, with shadow rays against the world.+ */+function createDirectIrradiance(tracer, lights, offset, scale) {+ const result = [0, 0, 0];+ const shadowReach = scale * 1e6;+ function addLight(point, normal, toLight, distance, power) {+ const cosine = normal[0] * toLight[0] + normal[1] * toLight[1] + normal[2] * toLight[2];+ if (cosine <= 0) return;+ const blocked = tracer.trace(+ point[0] + normal[0] * offset, point[1] + normal[1] * offset, point[2] + normal[2] * offset,+ toLight[0], toLight[1], toLight[2], distance, true,+ ).nearestTriangle >= 0;+ if (blocked) return;+ for (let channel = 0; channel < 3; channel++) result[channel] += power[channel] * cosine;+ }+ const toLight = [0, 0, 0];+ const power = [0, 0, 0];+ return function directIrradiance(point, normal) {+ result[0] = 0;+ result[1] = 0;+ result[2] = 0;+ for (const light of lights.pointLights) {+ const deltaX = light.position[0] - point[0];+ const deltaY = light.position[1] - point[1];+ const deltaZ = light.position[2] - point[2];+ const distanceSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;+ if (distanceSquared < 1e-12) continue;+ const distance = Math.sqrt(distanceSquared);+ toLight[0] = deltaX / distance;+ toLight[1] = deltaY / distance;+ toLight[2] = deltaZ / distance;+ const strength = light.intensity * pointLightFalloff(distanceSquared, light);+ for (let channel = 0; channel < 3; channel++) power[channel] = light.color[channel] * strength;+ addLight(point, normal, toLight, distance - offset, power);+ }+ if (lights.sun) addLight(point, normal, lights.sun.direction, shadowReach, lights.sun.color);+ return result;+ };+}++function hitNormal(world, triangleId, direction, out) {+ readTriangle(world.positions, world.indices, triangleId, SCRATCH_TRIANGLE);+ const firstX = SCRATCH_TRIANGLE[3] - SCRATCH_TRIANGLE[0];+ const firstY = SCRATCH_TRIANGLE[4] - SCRATCH_TRIANGLE[1];+ const firstZ = SCRATCH_TRIANGLE[5] - SCRATCH_TRIANGLE[2];+ const secondX = SCRATCH_TRIANGLE[6] - SCRATCH_TRIANGLE[0];+ const secondY = SCRATCH_TRIANGLE[7] - SCRATCH_TRIANGLE[1];+ const secondZ = SCRATCH_TRIANGLE[8] - SCRATCH_TRIANGLE[2];+ let normalX = firstY * secondZ - firstZ * secondY;+ let normalY = firstZ * secondX - firstX * secondZ;+ let normalZ = firstX * secondY - firstY * secondX;+ const length = Math.hypot(normalX, normalY, normalZ) || 1;+ normalX /= length;+ normalY /= length;+ normalZ /= length;+ const facing = normalX * direction[0] + normalY * direction[1] + normalZ * direction[2] > 0 ? -1 : 1;+ out[0] = normalX * facing;+ out[1] = normalY * facing;+ out[2] = normalZ * facing;+}+const SCRATCH_TRIANGLE = new Float64Array(9);++/**+ * The mean radiance arriving at one texel from other surfaces: cosine-weighted paths of up to `bounces` reflections,+ * each hit adding its own emission and its direct light. The caller multiplies by the texel's albedo.+ */+function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples, bounces }) {+ const direction = [0, 0, 0];+ const origin = [0, 0, 0];+ const normal = [0, 0, 0];+ const hitPoint = [0, 0, 0];+ const throughput = [1, 1, 1];+ return function gather(point, surfaceNormal, texelIndex, sum) {+ sum[0] = 0;+ sum[1] = 0;+ sum[2] = 0;+ const rotation = hashUnit(texelIndex, 1, 7);+ for (let sample = 0; sample < samples; sample++) {+ const firstUnit = (sample + 0.5) / samples;+ const secondUnit = (radicalInverse(sample) + rotation) % 1;+ cosineDirection(surfaceNormal, firstUnit, secondUnit, direction);+ origin[0] = point[0] + surfaceNormal[0] * offset;+ origin[1] = point[1] + surfaceNormal[1] * offset;+ origin[2] = point[2] + surfaceNormal[2] * offset;+ throughput[0] = 1;+ throughput[1] = 1;+ throughput[2] = 1;+ for (let bounce = 0; bounce < bounces; bounce++) {+ const hit = tracer.trace(origin[0], origin[1], origin[2], direction[0], direction[1], direction[2], Infinity, false);+ if (hit.nearestTriangle < 0) break;+ for (let axis = 0; axis < 3; axis++) hitPoint[axis] = origin[axis] + direction[axis] * hit.nearestDistance;+ hitNormal(world, hit.nearestTriangle, direction, normal);+ const owner = world.triangleOwner[hit.nearestTriangle];+ const albedo = albedoOfPart[owner];+ const emission = emissionOfPart[owner];+ const irradiance = directIrradiance(hitPoint, normal);+ for (let channel = 0; channel < 3; channel++) {+ sum[channel] += throughput[channel] * (emission[channel] + albedo[channel] * irradiance[channel] / Math.PI);+ throughput[channel] *= albedo[channel];+ }+ if (throughput[0] + throughput[1] + throughput[2] < 1e-4) break;+ origin[0] = hitPoint[0] + normal[0] * offset;+ origin[1] = hitPoint[1] + normal[1] * offset;+ origin[2] = hitPoint[2] + normal[2] * offset;+ cosineDirection(normal, hashUnit(texelIndex, sample, bounce * 2 + 11), hashUnit(texelIndex, sample, bounce * 2 + 12), direction);+ }+ }+ for (let channel = 0; channel < 3; channel++) sum[channel] /= samples;+ };+}++function worldTriangleArea(part) {+ const { positions, indices } = part.geometry;+ const { matrix } = part;+ const world = new Float64Array(9);+ let area = 0;+ for (let triangle = 0; triangle < indices.length / 3; triangle++) {+ for (let corner = 0; corner < 3; corner++) {+ const source = indices[triangle * 3 + corner] * 3;+ const x = positions[source];+ const y = positions[source + 1];+ const z = positions[source + 2];+ world[corner * 3] = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];+ world[corner * 3 + 1] = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];+ world[corner * 3 + 2] = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];+ }+ const firstX = world[3] - world[0];+ const firstY = world[4] - world[1];+ const firstZ = world[5] - world[2];+ const secondX = world[6] - world[0];+ const secondY = world[7] - world[1];+ const secondZ = world[8] - world[2];+ area += Math.hypot(firstY * secondZ - firstZ * secondY, firstZ * secondX - firstX * secondZ, firstX * secondY - firstY * secondX) / 2;+ }+ return area;+}++/** Gives a geometry its lightmap UVs in channel 0, from the unwrap that `uv_unwrap` uses. */+function unwrapForLightmap(geometry) {+ const { positions, normals, indices } = geometry;+ const mesh = meshFromGeometry({ positions, normals, indices }, { quads: false, tags: 'none' });+ const unwrapped = unwrapUv(mesh);+ const { geometry: unwrappedGeometry } = extractRender(unwrapped.mesh);+ return { geometry: unwrappedGeometry, 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;+ return Math.min(Math.max(rounded, BAKE_LIMITS.maxResolution.minimum), options.maxResolution);+}++/** The world position and facing of every texel a triangle of the geometry covers, or null where nothing covers it. */+function rasterizeTexels(geometry, matrix, resolution) {+ const texelCount = resolution * 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 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]];+ for (let corner = 0; corner < 3; corner++) {+ const x = vertexPositions[corners[corner] * 3];+ const y = vertexPositions[corners[corner] * 3 + 1];+ const z = vertexPositions[corners[corner] * 3 + 2];+ worldCorner[corner * 3] = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];+ worldCorner[corner * 3 + 1] = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];+ worldCorner[corner * 3 + 2] = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];+ }+ const faceNormal = worldFaceNormal(worldCorner, vertexNormals, corners[0], matrix);+ const texels = corners.map(corner => [uvs[corner * 2] * resolution, uvs[corner * 2 + 1] * resolution]);+ const [firstTexel, secondTexel, thirdTexel] = texels;+ const determinant = (secondTexel[1] - thirdTexel[1]) * (firstTexel[0] - thirdTexel[0]) + (thirdTexel[0] - secondTexel[0]) * (firstTexel[1] - thirdTexel[1]);+ if (Math.abs(determinant) < 1e-12) continue;+ const minimumColumn = Math.max(Math.floor(Math.min(firstTexel[0], secondTexel[0], thirdTexel[0])), 0);+ const maximumColumn = Math.min(Math.ceil(Math.max(firstTexel[0], secondTexel[0], thirdTexel[0])), resolution - 1);+ const minimumRow = Math.max(Math.floor(Math.min(firstTexel[1], secondTexel[1], thirdTexel[1])), 0);+ const maximumRow = Math.min(Math.ceil(Math.max(firstTexel[1], secondTexel[1], thirdTexel[1])), resolution - 1);+ for (let row = minimumRow; row <= maximumRow; row++) {+ for (let column = minimumColumn; column <= maximumColumn; column++) {+ const index = row * resolution + column;+ if (covered[index]) continue;+ const centerX = column + 0.5;+ const centerY = row + 0.5;+ const firstWeight = ((secondTexel[1] - thirdTexel[1]) * (centerX - thirdTexel[0]) + (thirdTexel[0] - secondTexel[0]) * (centerY - thirdTexel[1])) / determinant;+ const secondWeight = ((thirdTexel[1] - firstTexel[1]) * (centerX - thirdTexel[0]) + (firstTexel[0] - thirdTexel[0]) * (centerY - thirdTexel[1])) / determinant;+ const thirdWeight = 1 - firstWeight - secondWeight;+ if (firstWeight < -1e-9 || secondWeight < -1e-9 || thirdWeight < -1e-9) continue;+ for (let axis = 0; axis < 3; axis++) {+ positions[index * 3 + axis] = firstWeight * worldCorner[axis] + secondWeight * worldCorner[3 + axis] + thirdWeight * worldCorner[6 + axis];+ normals[index * 3 + axis] = faceNormal[axis];+ }+ covered[index] = 1;+ }+ }+ }+ return { positions, normals, covered };+}++function worldFaceNormal(worldCorner, vertexNormals, firstVertex, matrix) {+ const firstX = worldCorner[3] - worldCorner[0];+ const firstY = worldCorner[4] - worldCorner[1];+ const firstZ = worldCorner[5] - worldCorner[2];+ const secondX = worldCorner[6] - worldCorner[0];+ const secondY = worldCorner[7] - worldCorner[1];+ const secondZ = worldCorner[8] - worldCorner[2];+ const crossX = firstY * secondZ - firstZ * secondY;+ const crossY = firstZ * secondX - firstX * secondZ;+ const crossZ = firstX * secondY - firstY * secondX;+ const length = Math.hypot(crossX, crossY, crossZ) || 1;+ const authored = [vertexNormals[firstVertex * 3], vertexNormals[firstVertex * 3 + 1], vertexNormals[firstVertex * 3 + 2]];+ const transformedX = matrix[0] * authored[0] + matrix[4] * authored[1] + matrix[8] * authored[2];+ const transformedY = matrix[1] * authored[0] + matrix[5] * authored[1] + matrix[9] * authored[2];+ const transformedZ = matrix[2] * authored[0] + matrix[6] * authored[1] + matrix[10] * authored[2];+ const facing = crossX * transformedX + crossY * transformedY + crossZ * transformedZ < 0 ? -1 : 1;+ return [crossX / length * facing, crossY / length * facing, crossZ / length * facing];+}++/** Fills texels outside every chart from covered neighbours, so bilinear sampling at a chart edge reads real light. */+function dilate(radiance, covered, resolution) {+ for (let pass = 0; pass < DILATION_PASSES; pass++) {+ const additions = [];+ for (let row = 0; row < resolution; row++) {+ for (let column = 0; column < resolution; column++) {+ if (covered[row * resolution + column]) continue;+ const sum = [0, 0, 0];+ let neighbours = 0;+ for (let rowShift = -1; rowShift <= 1; rowShift++) {+ for (let columnShift = -1; columnShift <= 1; columnShift++) {+ const neighbourRow = row + rowShift;+ const neighbourColumn = column + columnShift;+ if (neighbourRow < 0 || neighbourColumn < 0 || neighbourRow >= resolution || neighbourColumn >= resolution) continue;+ const neighbour = neighbourRow * resolution + neighbourColumn;+ if (!covered[neighbour]) continue;+ for (let channel = 0; channel < 3; channel++) sum[channel] += radiance[neighbour * 3 + channel];+ neighbours++;+ }+ }+ if (neighbours > 0) additions.push([row * resolution + column, sum.map(value => value / neighbours)]);+ }+ }+ for (const [index, value] of additions) {+ radiance.set(value, index * 3);+ covered[index] = 1;+ }+ }+}++function lightmapTexture(radiance, resolution, peak) {+ const bytes = new Uint8ClampedArray(resolution * resolution * 4);+ for (let texel = 0; texel < resolution * resolution; texel++) {+ for (let channel = 0; channel < 3; channel++) bytes[texel * 4 + channel] = linearToSrgbByte(radiance[texel * 3 + channel] / peak);+ bytes[texel * 4 + 3] = 255;+ }+ return { image: createImage(bytes, resolution, resolution), colorSpace: 'srgb', wrapS: LIGHT_MAP_CLAMP_TO_EDGE, wrapT: LIGHT_MAP_CLAMP_TO_EDGE, minFilter: LIGHT_MAP_LINEAR, magFilter: LIGHT_MAP_LINEAR };+}++function bakedPart(part, geometry, texture, peak) {+ return { ...part, geometry, material: { ...part.material, emission: peak, emissiveColor: [1, 1, 1], emissiveMap: texture } };+}++/**+ * 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+ * the renderer takes. Spot and area lights are not baked.+ * options: maxResolution, texelsPerUnit, samples, bounces, maxSeconds (see BAKE_LIMITS). The time limit throws and+ * never truncates, so a bake that finishes always has the same bytes.+ */+export function bakeLightmaps(parts, lighting, options = {}) {+ const settings = normalizeBakeOptions(options);+ const lights = normalizeLights(lighting);+ if (!Array.isArray(parts) || parts.length === 0 || parts.length > MAX_BAKE_PARTS) throw new RangeError(`Light bake takes from 1 to ${MAX_BAKE_PARTS} parts.`);+ parts.forEach(validatePart);+ const started = performance.now();+ const world = buildWorld(parts);+ const scale = sceneScale(world.positions);+ const offset = scale * 1e-4;+ const tracer = createTracer(world);+ const directIrradiance = createDirectIrradiance(tracer, lights, offset, scale);+ const albedoOfPart = parts.map(part => diffuseAlbedo(part.material));+ 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 plans = [];+ const skipped = [];+ let texelTotal = 0;+ parts.forEach((part, index) => {+ const reason = skipReason(part);+ if (reason) {+ 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 resolution = lightmapResolution(worldTriangleArea(part), unwrapped.utilization, settings);+ texelTotal += resolution * resolution;+ plans.push({ part, index, unwrapped, resolution });+ });+ 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.`);+ if (rayWork > MAX_BAKE_RAY_WORK) throw new RangeError(`Light bake would trace about ${rayWork} rays; the limit is ${MAX_BAKE_RAY_WORK}. Lower samples, bounces or texelsPerUnit.`);+ const baked = parts.slice();+ const partReports = [];+ const sum = [0, 0, 0];+ for (const { part, index, unwrapped, resolution } of plans) {+ const { positions, normals, covered } = rasterizeTexels(unwrapped.geometry, part.matrix, resolution);+ const radiance = new Float32Array(resolution * resolution * 3);+ const albedo = albedoOfPart[index];+ const point = [0, 0, 0];+ const normal = [0, 0, 0];+ let peak = 0;+ for (let texel = 0; texel < resolution * resolution; texel++) {+ if (!covered[texel]) continue;+ if (performance.now() - started > settings.maxSeconds * 1000) throw new Error(`Light bake passed maxSeconds (${settings.maxSeconds}).`);+ for (let axis = 0; axis < 3; axis++) {+ point[axis] = positions[texel * 3 + axis];+ normal[axis] = normals[texel * 3 + axis];+ }+ gather(point, normal, index * 1_000_003 + texel, sum);+ for (let channel = 0; channel < 3; channel++) {+ radiance[texel * 3 + 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 report = { parts: partReports, skipped, texels: texelTotal, rayWork, seconds: (performance.now() - started) / 1000 };+ return { parts: baked, report };+}diff --git a/tests/light-bake.test.js b/tests/light-bake.test.jsnew file mode 100644index 00000000..622d1066--- /dev/null+++ b/tests/light-bake.test.js@@ -0,0 +1,129 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { box } from '../src/geometry.js';+import { BAKE_LIMITS, MAX_BAKE_POINT_LIGHTS, bakeLightmaps, normalizeBakeOptions } from '../src/light-bake.js';++const cube = box(0, 1);++function placed(name, translation, scale, material = {}) {+ const matrix = new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, translation[0], translation[1], translation[2], 1]);+ return { name, geometry: cube, matrix, material: { tag: 'surface', color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.8, emission: 0, ...material } };+}++// A small closed room with a wall that hides the floor behind it from the lamp.+function smallRoom() {+ return [+ placed('floor', [0, -0.05, 0], [6, 0.1, 6]),+ placed('ceiling', [0, 3.05, 0], [6, 0.1, 6]),+ placed('back', [0, 1.5, -3.05], [6, 3.2, 0.1]),+ placed('left', [-3.05, 1.5, 0], [0.1, 3.2, 6]),+ placed('right', [3.05, 1.5, 0], [0.1, 3.2, 6]),+ placed('front', [0, 1.5, 3.05], [6, 3.2, 0.1]),+ placed('divider', [0, 1.5, 0], [0.1, 3, 3]),+ ];+}++const lamp = { pointLights: [{ position: [-1.5, 2.5, 0], color: [1, 1, 1], intensity: 8, radius: 0.05 }], keyColor: [0, 0, 0] };+const fastOptions = { samples: 8, bounces: 2, texelsPerUnit: 2, maxResolution: 32 };++function lightmapBytes(part) {+ return part.material.emissiveMap.image.data;+}++test('the same input bakes the same bytes', () => {+ const first = bakeLightmaps(smallRoom(), lamp, fastOptions);+ const second = bakeLightmaps(smallRoom(), lamp, fastOptions);+ assert.equal(first.parts.length, second.parts.length);+ first.parts.forEach((part, index) => {+ assert.deepEqual(Array.from(lightmapBytes(part)), Array.from(lightmapBytes(second.parts[index])));+ assert.equal(part.material.emission, second.parts[index].material.emission);+ assert.deepEqual(Array.from(part.geometry.uvs), Array.from(second.parts[index].geometry.uvs));+ });+});++test('a bake gives each part lightmap UVs and an srgb emissive map, and leaves its input alone', () => {+ const parts = smallRoom();+ const originalGeometry = parts[0].geometry;+ const { parts: baked } = bakeLightmaps(parts, lamp, fastOptions);+ const floor = baked[0];+ assert.equal(parts[0].geometry, originalGeometry);+ assert.equal(parts[0].material.emissiveMap, undefined);+ assert.equal(floor.material.emissiveMap.colorSpace, 'srgb');+ assert.deepEqual(floor.material.emissiveColor, [1, 1, 1]);+ assert.ok(floor.material.emission > 0);+ assert.equal(floor.geometry.uvs.length, floor.geometry.positions.length / 3 * 2);+ const { width, height, data } = floor.material.emissiveMap.image;+ assert.equal(data.length, width * height * 4);+});++test('light reaches a surface the lamp cannot see, and a dark scene bakes nothing', () => {+ const { parts: baked } = bakeLightmaps(smallRoom(), lamp, { ...fastOptions, samples: 32 });+ // The right half of the floor sits behind the divider, so it gets only bounced light, but not none.+ const floor = baked[0];+ const bytes = lightmapBytes(floor);+ const brightestChannel = Math.max(...bytes.filter((value, index) => index % 4 !== 3));+ assert.ok(brightestChannel > 0);+ const dark = bakeLightmaps(smallRoom(), { pointLights: [], keyColor: [0, 0, 0] }, fastOptions);+ dark.parts.forEach(part => assert.equal(part.material.emissiveMap, undefined));+});++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 }));+ const { parts: baked, report } = bakeLightmaps(parts, lamp, fastOptions);+ assert.deepEqual(report.skipped.map(entry => entry.name), ['painted', 'lamp-shade']);+ assert.equal(baked[7], parts[7]);+ assert.equal(baked[8], parts[8]);+});++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']]) {+ assert.throws(() => normalizeBakeOptions({ [name]: bad }), { name: 'RangeError', message: new RegExp(name) }, `${name} ${bad}`);+ }+ for (const bad of [null, [], 'fast', 3]) assert.throws(() => normalizeBakeOptions(bad), TypeError);+});++test('hostile parts and lights are refused before any ray is traced', () => {+ const withPosition = value => {+ const parts = smallRoom();+ const geometry = { ...cube, positions: Float32Array.from(cube.positions) };+ geometry.positions[4] = value;+ parts[0] = { ...parts[0], geometry };+ return parts;+ };+ assert.throws(() => bakeLightmaps(withPosition(Number.NaN), lamp, fastOptions), /non-finite position/);+ assert.throws(() => bakeLightmaps(withPosition(Infinity), lamp, fastOptions), /non-finite position/);+ const badIndex = smallRoom();+ badIndex[0] = { ...badIndex[0], geometry: { ...cube, indices: Uint32Array.from([0, 1, 9999]) } };+ assert.throws(() => bakeLightmaps(badIndex, lamp, fastOptions), /index past its last vertex/);+ const badMatrix = smallRoom();+ badMatrix[1] = { ...badMatrix[1], matrix: new Float32Array(15) };+ assert.throws(() => bakeLightmaps(badMatrix, lamp, fastOptions), /4x4 matrix/);+ const nanMatrix = smallRoom();+ nanMatrix[1].matrix[0] = Number.NaN;+ assert.throws(() => bakeLightmaps(nanMatrix, lamp, fastOptions), /4x4 matrix/);+ const noColor = smallRoom();+ noColor[1] = { ...noColor[1], material: { tag: 'surface' } };+ assert.throws(() => bakeLightmaps(noColor, lamp, fastOptions), /material color/);+ assert.throws(() => bakeLightmaps([], lamp, fastOptions), /from 1 to/);+ assert.throws(() => bakeLightmaps(null, lamp, fastOptions), /from 1 to/);+ const tooManyLights = { pointLights: Array.from({ length: MAX_BAKE_POINT_LIGHTS + 1 }, () => lamp.pointLights[0]) };+ assert.throws(() => bakeLightmaps(smallRoom(), tooManyLights, fastOptions), /at most 8 point lights/);+ for (const light of [{ position: [Number.NaN, 0, 0], intensity: 1 }, { position: [0, 0, 0], intensity: -1 }, { position: [0, 0, 0], intensity: Infinity }, { position: [0, 0], intensity: 1 }, { position: [0, 0, 0], intensity: 1, range: -2 }]) {+ assert.throws(() => bakeLightmaps(smallRoom(), { pointLights: [light] }, fastOptions), RangeError);+ }+ assert.throws(() => bakeLightmaps(smallRoom(), { keyColor: [1, 1, Number.NaN], lightDirection: [0, 1, 0] }, fastOptions), /keyColor/);+ assert.throws(() => bakeLightmaps(smallRoom(), null, fastOptions), TypeError);+});++test('a bake that would trace too many rays is refused up front', () => {+ const heavy = { samples: BAKE_LIMITS.samples.maximum, bounces: BAKE_LIMITS.bounces.maximum, texelsPerUnit: BAKE_LIMITS.texelsPerUnit.maximum, maxResolution: BAKE_LIMITS.maxResolution.maximum };+ assert.throws(() => bakeLightmaps(smallRoom(), lamp, heavy), /limit is/);+});++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/vite.lib.config.js b/vite.lib.config.jsindex 60b3a0c6..f347aaa9 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -34,6 +34,7 @@ export default defineConfig({terrain: 'src/terrain.js',grass: 'src/grass.js',clutter: 'src/clutter.js',+ 'light-bake': 'src/light-bake.js','texture-set': 'src/texture-set.js','agent-scene': 'src/agent-scene.js','agent-asset': 'src/agent-asset.js',