3D engine that AI agents drive
Tell an agent when its scene is a closed room with no bake
Nguyen Xuan An12b20ae4251a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7ad26c8..e003c23d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Tell an agent when its scene is a closed room with no bake (issue #163). `scene_inspect` now returns a `closed-room-without-bake` diagnostic when 90 percent or more of 48 rays from the middle of the scene hit a front face, and names `bake`; measured against Cycles a closed room goes from 0.1430 and 0.1436 (`dark-shaft`, `temple-hall`) to 0.0609 and 0.0560 once baked. No frame cost and no schema change; agent scene entry grows 884 bytes gzip. `bakeSkyVisibility` in `light-bake` writes only the occlusion map (0.1021 and 0.0856 in under a second) and is not applied automatically. **A closed room without a bake now shows a warning in `scene_inspect`.**- The GitHub repository is `anxuanng/67.js`, public since 2026-11-02. Links and `repository.url` point there, which npm provenance needs to match.- Follow 3 bounces by default in a light bake, up from 2 (part of issue #159, which stays open). Baked rooms scored worse after the sky visibility change (`lit-interior` 0.1444 to 0.1915, `brick-room` 0.1515 to 0.2048 against Cycles) because the occlusion map removed the world light that had been filling the light a 2 bounce path cuts off. With 3 bounces they score 0.1341 and 0.1412, `dark-shaft` 0.0609 and `temple-hall` 0.0560. A bake takes about 1.3 to 1.9 times as long (`temple-hall` 39 to 75 s); pass `bounces: 2` for the old light and time. Recipe presets are unchanged.- Remove the streaks in baked dark scenes and the speckle in the fog's glow (part of issue #159, which stays open). A bake unwrapped each shared geometry once at unit size, so a 2 x 32 x 180 m wall got texels 90 times longer than wide (carpet 2,867 times), which drew as streaks fanning from the vanishing point; it now unwraps each part at its world size and smooths the gathered light and sky visibility over neighbouring texels of the same surface. The glow reads the frame's mip chain instead of 24 jittered single pixels. `bench/reference/noise.py` measures what FLIP misses (high frequency energy in dark regions and around the door): `temple-hall` baked 0.448 to 0.182 and its glow ring 1.826 to 0.990 (Cycles 0.158 and 1.053), `dark-shaft` baked 0.318 to 0.150; whole frame scores against Cycles stay within 0.006 and `temple-hall` baked goes from 0.0716 to 0.0578. A baked part's report `skyVisibility` now weighs texels by area, and baked thin parts get more texels (`brick-room` 28,576 to 98,848). Core grows 92 bytes gzip and a frame with fog costs about 0.5 ms more on a shared machine. **Baked scenes with long or thin parts look smoother and lightmaps are larger.**diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 9a810115..a8324ecc 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -158,6 +158,26 @@ Baked scores against Cycles, whole frame (shaft region), before and after:Cost: the bake takes more path steps. `temple-hall` 38.9 to 74.9 s, `dark-shaft` 9.0 to 17.5 s, `lit-interior` 4.0 to 5.8 s, `brick-room` 4.3 to 5.2 s, `metal-room` 5.6 to 7.1 s (one run each, shared machine). The frame is unchanged: no shader or bundle code moved. A bake that passes `bounces: 2` keeps the old time and the old light.+## Closed rooms without a bake (2026-11-02, issue #163)++Without a bake, `dark-shaft` scores 0.1430 against Cycles and `temple-hall` 0.1436; with the default bake 0.0609 and 0.0560. An agent that never asks for a bake gets the first pair. Three ways to close the gap were weighed.++| Option | `dark-shaft` | `temple-hall` | Cost | Verdict |+| --- | --- | --- | --- | --- |+| No bake | 0.1430 | 0.1436 | none | the gap |+| Sky visibility alone, no light written, 0.5 texels per unit, 16 samples | 0.1021 | 0.0856 | bake 0.1 s and 0.9 s (1,168 and 102,048 texels) | measured, not shipped |+| Sky visibility alone, 1.5 texels per unit, 16 samples | 0.1026 | 0.0859 | bake 0.2 s and 3.2 s (7,904 and 340,752 texels) | density does not matter |+| Default bake (3 bounces) | 0.0609 | 0.0560 | 17.5 s and 75 s | the target |+| `scene_inspect` names the bake | 0.0609 once the agent adds it | 0.0560 | no frame cost, no schema | shipped |++Sky visibility alone gets about half of the bake's gain (`dark-shaft` 0.1430 to 0.1021 of 0.0821, `temple-hall` 0.1436 to 0.0856 of 0.0876) in a second. It does not shoot light, so the room keeps no bounced light and the sun shaft region gets worse (0.3066 and 0.2660, against 0.1763 and 0.2529 with the bake). `node bench/reference/run.mjs --skip-blender --bake dark-shaft,temple-hall --sky-only 0.5,16` draws these rows; `bakeSkyVisibility` in `src/light-bake.js` is the function. A density of 3 texels per unit with 32 samples was started and stopped on a loaded machine, so it has no number.++Why it is not applied on its own. The agent scene loads its bake code on demand, picked by a text marker (`"bake":{`) in the recipe, and `createAgentScene` is synchronous. A scene that asks for nothing has no marker, so an automatic bake would make every recipe load the ray tracer or add a second detection path before the scene exists. The lifted look would also become a half-fix (0.10, not 0.06) that hides the cheaper full answer from the agent. A new recipe field was not added: an agent that does not know a closed room needs one would not set it.++What ships: a `closed-room-without-bake` diagnostic in `scene_inspect` (`src/closed-room.js`). It shoots 48 fixed rays from the middle of the scene's bounds and counts a hit only on a triangle whose front face looks at the ray, so a solid object around the centre is never a room. At 90 percent or more (the share the automatic reflection probe already uses) and with no `bake` in the recipe, the result carries a warning that names `"bake": { "preset": "standard" }` and `scene_apply set-bake`. Nothing runs per frame: the test runs in `scene_inspect`, is kept until the scene's revision changes, and skips scenes of more than 150,000 triangles. Measured worst case, with no ray hitting anything, is 30 ms at 20,000 triangles and 140 ms at 150,000. A six-slab test room is detected (the reference scenes are drawn in the harness page, so `dark-shaft` itself was not run through it); the same room with its roof removed, a lone box and a recipe with a bake are not (`tests/closed-room.test.js`).++The no-bake scores of every scene are unchanged: no shader, renderer or scene build code moved, and the full rescore after this change matches the committed `baseline.json`. Size: the agent scene entry grows by 884 bytes gzip and `light-bake` by 158; every budget still holds, so none changed. Whether a cold agent follows the existing rule in the skill without the diagnostic was not measured: the suite's tasks each need a reference recipe and checks, which cost more than the $1 the issue allowed.+## BaselineMeasured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metric is [FLIP](https://github.com/NVlabs/flip) for LDR images: 0 means identical, and a higher score means a larger visible difference.diff --git a/bench/reference/run.mjs b/bench/reference/run.mjsindex d351a44d..a3d335cd 100644--- a/bench/reference/run.mjs+++ b/bench/reference/run.mjs@@ -46,7 +46,11 @@ const ambientOcclusionRadius = radiusFlag >= 0 ? Number(argumentsGiven[radiusFlaconst bakeFlag = argumentsGiven.indexOf('--bake');const bakeValue = bakeFlag >= 0 ? argumentsGiven[bakeFlag + 1] : undefined;const bakedSceneIds = bakeFlag >= 0 && bakeValue && !bakeValue.startsWith('--') ? bakeValue.split(',') : null;-const probesFlag = argumentsGiven.indexOf('--probes');+// --sky-only <texelsPerUnit>,<samples> makes the --bake rows sky visibility alone (no light written) at that density.+const skyOnlyFlag = argumentsGiven.indexOf('--sky-only');+const [skyTexelsPerUnit, skySamples] = skyOnlyFlag >= 0 ? argumentsGiven[skyOnlyFlag + 1].split(',').map(Number) : [];+const skyOnlyOptions = skyOnlyFlag >= 0 ? { skyOnly: true, texelsPerUnit: skyTexelsPerUnit, samples: skySamples } : {};+const probesFlag =argumentsGiven.indexOf('--probes');const probesValue = probesFlag >= 0 ? argumentsGiven[probesFlag + 1] : undefined;const probedSceneIds = probesFlag >= 0 && probesValue && !probesValue.startsWith('--') ? probesValue.split(',') : null;const cascadesFlag = argumentsGiven.indexOf('--cascades');@@ -80,7 +84,8 @@ async function renderBackend(backend, serverUrl, graphics) {const started = performance.now();const describe = backend === 'gpu';const probes = probesFlag >= 0 && (probedSceneIds === null || probedSceneIds.includes(id));- const bake = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id)) ? {} : null;+ const bakesThisScene = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id));+ const bake = bakesThisScene ? { ...skyOnlyOptions } : null;const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount, withProbes, ambientScale]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount, probes: withProbes, ambient: ambientScale }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades, probes, ambient]);if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);graphics[backend] = result.graphics;diff --git a/docs/light-bake.md b/docs/light-bake.mdindex e5c44db4..d867c5ed 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -57,6 +57,10 @@ Skipped, with the reason in `report.skipped`: transparent parts, a material tagGLB 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.+## Sky visibility alone++`bakeSkyVisibility(parts, lighting, options)` (or `bakeLightmaps` with `skyOnly: true`) shoots one cosine ray per sample from each texel and writes only the occlusion map of the parts that see under 98 percent of the sky. It writes no light and shades nothing, so it takes a second where a bake takes seconds to a minute, and density barely matters (0.5 and 1.5 texels per unit scored the same). On `dark-shaft` and `temple-hall` it gives about half of the improvement a full bake gives (see "Closed rooms without a bake" in `bench/reference/README.md`). The recipe does not use it: a recipe asks for a closed room's bake because `scene_inspect` reports `closed-room-without-bake`.+## Reflection probesA probe is the room around a point, traced once and prefiltered like an environment map (`createEnvironmentResources`), so a glossy part reflects the room and not only the sky. `src/reflection-probes.js` holds placement and the renderer link; `src/probe-trace.js` traces on the CPU with the bake's ray tracer (direct light, bounced light, emission; a ray that leaves the scene reads the environment map or the sky colours), 64 by 32 texels, 32 samples and 2 bounces, deterministic, about 0.2 to 0.3 s per probe. A part takes the nearest probe whose `radius` reaches the middle of its bounds, else the environment. A probe lights the specular term only: diffuse stays with the environment and the bake. No parallax correction (not built: a probe at the centre of a room is wrong near the walls).diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 3a95a6d5..1e68e4df 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 (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`.+- 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 closed room with no `bake` renders lifted and grey; `scene_inspect` reports it as the `closed-room-without-bake` diagnostic, so add `bake` then.- 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/agent-diagnostics.js b/src/agent-diagnostics.jsindex 4883055a..2bb2796e 100644--- a/src/agent-diagnostics.js+++ b/src/agent-diagnostics.js@@ -75,6 +75,16 @@ export function recipeDiagnostics(recipe) {return problems;}+/**+ * The scene looks like a closed room and asks for no bake, so the world's light reaches it through the walls and the room+ * renders lifted and flat. `share` is the share of rays from the middle of the scene that hit an inner face.+ */+export function closedRoomDiagnostic(share) {+ return diagnostic('closed-room-without-bake', 'warning', 'bake',+ `${Math.round(share * 100)} percent of rays from the middle of the scene hit a wall, so this is a closed room, and without a bake the world's light still reaches it: the room renders lifted and grey, with weak contact shadows.`,+ 'Add "bake": { "preset": "standard" } (scene_apply set-bake). It darkens what the sky cannot see and adds bounced light; measured against Cycles it halves the error of a closed room.');+}+/*** Rig and asset diagnostics. `warnings` are the decoder's notes about features it accepted but does not draw.*/diff --git a/src/agent-scene.js b/src/agent-scene.jsindex fc432737..bce8a8de 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -6,7 +6,8 @@ import { normalizeAgentLook, environmentPatchWithSetup, environmentLinksLights }import { agentSceneModule } from './agent-scene-modules.js';import { MESH_SMOOTH_ANGLE_DEFAULT, CURVE_TEXT_LIMITS, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';import { ALL_LIGHTS_MASK, MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';-import { recipeDiagnostics } from './agent-diagnostics.js';+import { recipeDiagnostics, closedRoomDiagnostic } from './agent-diagnostics.js';+import { closedRoomShare, CLOSED_ROOM_SHARE } from './closed-room.js';import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';@@ -1128,6 +1129,21 @@ export function createAgentScene(input, inputLimits = {}) {return { ...lightBake, reused: false };}+ // A scene that asks for no bake and looks like a closed room gets one diagnostic naming the bake. The ray test costs a+ // few milliseconds, so it runs for scene_inspect only and is kept until the scene changes.+ let closedRoomCache = null;+ function closedRoomProblems() {+ if (state.recipe.bake) {+ return [];+ }+ if (closedRoomCache?.revision !== revision) {+ const worldMatrices = new Map(state.parts.map(part => [part.name, state.graph.getNode(part.name).worldMatrix]));+ closedRoomCache = { revision, share: closedRoomShare(state.parts, worldMatrices) };+ }+ const { share } = closedRoomCache;+ return share !== null && share >= CLOSED_ROOM_SHARE ? [closedRoomDiagnostic(share)] : [];+ }+// A bake costs a solver run, so an unchanged section on unchanged geometry reuses the last one.function stagePhysics(recipe, geometryRecords) {if (!recipe.physics) {@@ -1465,7 +1481,7 @@ export function createAgentScene(input, inputLimits = {}) {return result;});const resident = geometryStats(ownedGeometryRecords());- const diagnostics = recipeDiagnostics(state.recipe);+ const diagnostics = [...recipeDiagnostics(state.recipe), ...closedRoomProblems()];return {revision, topologyRevision,...(state.recipe.motion?.ik?.length ? { motionIk: agentSceneModule('motion').compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),diff --git a/src/closed-room.js b/src/closed-room.jsnew file mode 100644index 00000000..9d5dbb0f--- /dev/null+++ b/src/closed-room.js@@ -0,0 +1,101 @@+// A cheap test for a closed room: shoot a fixed set of rays from the middle of the scene's bounds and count how many hit+// the inner face of a part. A solid object has only back faces facing a ray that starts inside it, so it never counts as a+// room. It reads no clock and uses no random numbers, so the same scene gives the same share.++export const CLOSED_ROOM_RAYS = 48;+// The same share the automatic reflection probe uses to call a scene a room (probe-trace.js).+export const CLOSED_ROOM_SHARE = 0.9;+// Brute force over every triangle: 48 rays over this many triangles stays near 10 ms, and a larger scene is not tested.+export const CLOSED_ROOM_MAXIMUM_TRIANGLES = 150_000;+const PARALLEL_EPSILON = 1e-9;++function worldTriangles(parts, worldMatrices) {+ let triangleCount = 0;+ for (const part of parts) {+ triangleCount += part.geometry.indices.length / 3;+ }+ if (triangleCount === 0 || triangleCount > CLOSED_ROOM_MAXIMUM_TRIANGLES) {+ return null;+ }+ const corners = new Float64Array(triangleCount * 9);+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ let write = 0;+ for (const part of parts) {+ const matrix = worldMatrices.get(part.name);+ const { positions, indices } = part.geometry;+ for (const index of indices) {+ for (let axis = 0; axis < 3; axis++) {+ const value = matrix[axis] * positions[index * 3] + matrix[4 + axis] * positions[index * 3 + 1] + matrix[8 + axis] * positions[index * 3 + 2] + matrix[12 + axis];+ corners[write++] = value;+ minimum[axis] = Math.min(minimum[axis], value);+ maximum[axis] = Math.max(maximum[axis], value);+ }+ }+ }+ return { corners, triangleCount, centre: minimum.map((value, axis) => (value + maximum[axis]) / 2) };+}++function fibonacciDirection(index, count, out) {+ const height = 1 - (index + 0.5) * 2 / count;+ const ring = Math.sqrt(1 - height * height);+ const angle = index * Math.PI * (3 - Math.sqrt(5));+ out[0] = Math.cos(angle) * ring;+ out[1] = height;+ out[2] = Math.sin(angle) * ring;+}++// Moller-Trumbore, counting only a triangle whose front face looks at the ray (det > 0).+function hitsFrontFace(corners, offset, origin, direction) {+ const edgeOneX = corners[offset + 3] - corners[offset];+ const edgeOneY = corners[offset + 4] - corners[offset + 1];+ const edgeOneZ = corners[offset + 5] - corners[offset + 2];+ const edgeTwoX = corners[offset + 6] - corners[offset];+ const edgeTwoY = corners[offset + 7] - corners[offset + 1];+ const edgeTwoZ = corners[offset + 8] - corners[offset + 2];+ const pX = direction[1] * edgeTwoZ - direction[2] * edgeTwoY;+ const pY = direction[2] * edgeTwoX - direction[0] * edgeTwoZ;+ const pZ = direction[0] * edgeTwoY - direction[1] * edgeTwoX;+ const determinant = edgeOneX * pX + edgeOneY * pY + edgeOneZ * pZ;+ if (determinant < PARALLEL_EPSILON) {+ return false;+ }+ const toOriginX = origin[0] - corners[offset];+ const toOriginY = origin[1] - corners[offset + 1];+ const toOriginZ = origin[2] - corners[offset + 2];+ const u = toOriginX * pX + toOriginY * pY + toOriginZ * pZ;+ if (u < 0 || u > determinant) {+ return false;+ }+ const qX = toOriginY * edgeOneZ - toOriginZ * edgeOneY;+ const qY = toOriginZ * edgeOneX - toOriginX * edgeOneZ;+ const qZ = toOriginX * edgeOneY - toOriginY * edgeOneX;+ const v = direction[0] * qX + direction[1] * qY + direction[2] * qZ;+ if (v < 0 || u + v > determinant) {+ return false;+ }+ return edgeTwoX * qX + edgeTwoY * qY + edgeTwoZ * qZ > 0;+}++/**+ * The share of rays from the middle of the parts' bounds that hit a part's inner face, or null when the scene is empty or+ * has more than CLOSED_ROOM_MAXIMUM_TRIANGLES triangles. `worldMatrices` maps a part's name to its world matrix.+ */+export function closedRoomShare(parts, worldMatrices) {+ const triangles = worldTriangles(parts.filter(part => part.material?.alphaMode !== 'blend'), worldMatrices);+ if (!triangles) {+ return null;+ }+ const direction = [0, 0, 0];+ let hits = 0;+ for (let ray = 0; ray < CLOSED_ROOM_RAYS; ray++) {+ fibonacciDirection(ray, CLOSED_ROOM_RAYS, direction);+ for (let triangle = 0; triangle < triangles.triangleCount; triangle++) {+ if (hitsFrontFace(triangles.corners, triangle * 9, triangles.centre, direction)) {+ hits++;+ break;+ }+ }+ }+ return hits / CLOSED_ROOM_RAYS;+}diff --git a/src/light-bake.js b/src/light-bake.jsindex 47d36aac..2bb81b22 100644--- a/src/light-bake.js+++ b/src/light-bake.js@@ -791,7 +791,37 @@ function skyVisibilityPart(part, geometry, texture, slot) {*/export function bakeLightmaps(parts, lighting, options = {}) {const plan = planLightmaps(parts, lighting, options);- return traceLightmaps(plan, plan.settings);+ return traceLightmaps(plan, { ...plan.settings, skyOnly: options.skyOnly === true });+}++/**+ * Sky visibility alone, with no light written: the parts that see little of the sky get the occlusion map the full bake+ * would give them, and every other part is returned as it was. One ray per sample and no light leaves it much cheaper+ * than a bake, so it can run at a low density on a scene that never asked for one.+ */+export function bakeSkyVisibility(parts, lighting, options = {}) {+ return bakeLightmaps(parts, lighting, { ...options, skyOnly: true });+}++// The gatherer of a sky-only bake: the same first-leg cosine rays, and nothing is shaded when one hits a part.+function createSkyVisibilityGatherer({ tracer, offset, samples }) {+ const direction = [0, 0, 0];+ return function gatherSkyVisibility(point, surfaceNormal, texelIndex, sum) {+ sum[0] = 0;+ sum[1] = 0;+ sum[2] = 0;+ const rotation = hashUnit(texelIndex, 1, 7);+ let escaped = 0;+ for (let sample = 0; sample < samples; sample++) {+ cosineDirection(surfaceNormal, (sample + 0.5) / samples, (radicalInverse(sample) + rotation) % 1, direction);+ const hit = tracer.trace(+ point[0] + surfaceNormal[0] * offset, point[1] + surfaceNormal[1] * offset, point[2] + surfaceNormal[2] * offset,+ direction[0], direction[1], direction[2], Infinity, false,+ );+ if (hit.nearestTriangle < 0) escaped++;+ }+ return escaped / samples;+ };}/**@@ -855,7 +885,9 @@ export function traceLightmaps(plan, tracedSettings) {const directIrradiance = createDirectIrradiance(tracer, withReach(lights, parts), 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 gather = settings.skyOnly+ ? createSkyVisibilityGatherer({ tracer, offset, samples: settings.samples })+ : createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples: settings.samples, bounces: settings.bounces });const baked = parts.slice();const partReports = [];const sum = [0, 0, 0];diff --git a/tests/closed-room.test.js b/tests/closed-room.test.jsnew file mode 100644index 00000000..71f33507--- /dev/null+++ b/tests/closed-room.test.js@@ -0,0 +1,73 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene } from '../src/agent-scene.js';+import { loadAgentSceneModules } from '../src/agent-scene-modules.js';+import { closedRoomShare, CLOSED_ROOM_SHARE } from '../src/closed-room.js';++const WALL = 0.2;++function wall(id, translation, scale) {+ return { id, geometry: 'box', material: 'stone', translation, scale };+}++// A 10 x 6 x 10 room built from six slabs, or the same room with the roof left out.+function roomRecipe({ roof = true, bake } = {}) {+ const slabs = [+ wall('floor', [0, -3, 0], [10, WALL, 10]),+ wall('north', [0, 0, -5], [10, 6, WALL]),+ wall('south', [0, 0, 5], [10, 6, WALL]),+ wall('west', [-5, 0, 0], [WALL, 6, 10]),+ wall('east', [5, 0, 0], [WALL, 6, 10]),+ ];+ if (roof) slabs.push(wall('roof', [0, 3, 0], [10, WALL, 10]));+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],+ materials: [{ id: 'stone', color: [0.5, 0.5, 0.5] }],+ nodes: slabs,+ ...(bake ? { bake } : {}),+ };+}++function diagnosticKinds(recipe) {+ const inspection = createAgentScene(recipe).inspect();+ return (inspection.diagnostics ?? []).map(entry => entry.kind);+}++test('a closed room without a bake gets a diagnostic that names the bake', () => {+ const inspection = createAgentScene(roomRecipe()).inspect();+ const found = inspection.diagnostics.find(entry => entry.kind === 'closed-room-without-bake');+ assert.ok(found, 'expected closed-room-without-bake');+ assert.equal(found.severity, 'warning');+ assert.match(found.fix, /"bake"/);+});++test('a room with a bake, a room with its roof off and a lone solid get no closed room diagnostic', () => {+ assert.ok(!diagnosticKinds(roomRecipe({ roof: false })).includes('closed-room-without-bake'));+ const solid = { ...roomRecipe(), nodes: [wall('block', [0, 0, 0], [4, 4, 4])] };+ assert.ok(!diagnosticKinds(solid).includes('closed-room-without-bake'));+});++test('the ray test counts only inner faces: a room is closed, a solid around the centre is not', () => {+ const matrices = parts => new Map(parts.map(part => [part.name, new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])]));+ const triangle = (a, b, c) => ({ positions: new Float32Array([...a, ...b, ...c]), indices: new Uint32Array([0, 1, 2]) });+ // Two large triangles on opposite sides of the centre, wound to face it or to face away from it.+ const facingCentre = [+ { name: 'near', geometry: triangle([-9, -9, -5], [9, -9, -5], [0, 9, -5]) },+ { name: 'far', geometry: triangle([-9, -9, 5], [0, 9, 5], [9, -9, 5]) },+ ];+ const facingAway = [+ { name: 'near', geometry: triangle([-9, -9, -5], [0, 9, -5], [9, -9, -5]) },+ { name: 'far', geometry: triangle([-9, -9, 5], [9, -9, 5], [0, 9, 5]) },+ ];+ assert.ok(closedRoomShare(facingCentre, matrices(facingCentre)) > 0);+ assert.equal(closedRoomShare(facingAway, matrices(facingAway)), 0);+ assert.equal(closedRoomShare([], new Map()), null);+ assert.ok(CLOSED_ROOM_SHARE <= 1);+});++test('the closed room diagnostic disappears once the recipe asks for a bake', async () => {+ const recipe = roomRecipe({ bake: { preset: 'draft' } });+ await loadAgentSceneModules(recipe);+ assert.ok(!diagnosticKinds(recipe).includes('closed-room-without-bake'));+});