Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Let recipes reach cascaded sun shadows and light linking

Nguyen Xuan Anbf412fb7a117
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 34fc3d9f..6f4db382 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Let recipes reach cascaded sun shadows and light linking (part of issue #52; the lit-interior score goal is still open). `environment.shadowCascades` (0 to 4) and `affects` on point, spot and area lights plus `environment.keyAffects` name nodes; both addons load on demand through `src/agent-scene-modules.js`, `scene_capabilities` now reports `lightLinking` and `shadowCascades`, unknown node IDs are refused with the next action, and `set-environment` and `scene_export_recipe` carry the fields. The light bake honours `affects` (a linked light adds nothing at a part it skips, even as a bounce) and the path tracer lists linking in `report.ignored`. Default: a scene without `shadowCascades` whose `shadow.extent` is above 40 gets three cascades (the single map is then 4 cm per texel or coarser; `long-street` scores 0.1555 with one map and 0.1398 with three, for about 0.2 ms on an RTX 3060); every scene at or below 40 draws as before, and `shadowCascades: 0` keeps one map. `node scripts/smoke-mcp-linking.mjs` proves one recipe with both through the MCP server, with a seek giving identical PNG bytes. The MCP schema total stays at its budget by shortening environment descriptions.
+
- Add an automatic floor with a contact shadow to the MCP preview, and measure the default look on cold runs (part of issue #53; its done condition is not shown, see below). Breaking look change: a recipe with no floor of its own now draws a light grey disc under its lowest geometry at that height, so the key light's shadow falls on something; before, objects floated on a flat grey backdrop. It is not a recipe node: `src/agent-ground.js` builds it from world bounds on every draw (`agentGroundPlacement`), so the exported recipe, `scene.parts`, silhouettes and the suite's checks do not hold it, and it reaches the renderer through the `ground` option, which now also accepts a part (about 20 bytes in `entry:core`). It is left out when a part already forms a floor: one that spans at least 90 percent of the scene's width and depth, is thinner than a quarter of its width, and is the lowest geometry. `environment.ground: false` switches it off (the field is absent from recipes that do not set it). Nothing else about the default look changed: `effects.exposure` stays 1 (an exposure of 0.8 was tried and dropped: on the six cold recipes no pixel of the subject reached 250 at either value, and mean luma was 157 to 199 at 1 and 142 to 187 at 0.8), setup `daylight`, occlusion 0. The suite's look harness drew without the setup's environment map, so its images were darker than the preview shows; it now draws with the map and the floor, and `regrade.mjs` finds files of runs made with `--runs`. Measured on six cold Haiku recipes with a reference-free Sonnet vision question ("does the object sit on a surface, with a believable contact shadow", 0 to 3): 0, 0, 0, 0, 0, 0 before and 1, 1, 2, 1, 1, 0 after. The judge named the front and side cameras as the gap: they are orthographic at floor height, so a floor is edge-on and a shadow falls behind the object, and only the three-quarter view shows it. The reference-based judge (shape, proportions, features, surface) tied at 66 of 72 across the dropped exposure change, because it cannot see lighting defaults. Tool schema text was shortened to pay for the `ground` field.
- Measure what an equal feature set costs against three.js (part of issue #74; no engine change, no speed-up). `bench/runtime` gets the engines `67js-ldr`, `67js-one-sample`, `67js-ldr-one-sample` and `three-one-sample` (run with `--engine`) and a `--cpu-only` flag. Measured: with no MSAA and no HDR target 67js is still 5.2 to 5.7 times three.js on SwiftShader in `large-mesh`, `many-materials` and `instanced-objects` (7.8, 5.3 and 7.8 with the defaults), so the gap is the lit shader and not those two features. On the RTX 3060 `large-mesh` costs 3.6 ms against 0.6 ms and is not explained by HDR, MSAA, the vertex shader or the vertex attributes; on ANGLE Vulkan the ratio is 2.3 instead of 5.8. Skipping zero-intensity fill lights was tried and reverted (inside the noise). The profile is in `bench/runtime/PROFILE.md`.
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index eb061dbe..3de373e2 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -33,9 +33,9 @@
"entry:path-tracer": 13800,
"entry:texture-set": 900,
"entry:agent-scene": 67100,
- "entry:agent-scene+lazy": 231800,
+ "entry:agent-scene+lazy": 232600,
"entry:agent-asset": 99400,
- "entry:agent-asset+lazy": 243800,
+ "entry:agent-asset+lazy": 244300,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
@@ -46,6 +46,6 @@
"scene:gltf-box": 81700,
"scene:gltf-box+lazy": 83700,
"scene:agent-scene": 98600,
- "scene:agent-scene+lazy": 263300
+ "scene:agent-scene+lazy": 263500
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 52575ce8..2d2c73d9 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,5 +1,5 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades",
"schemaTotalBytes": 190830,
"schemaToolBytes": {
"scene_create": 62930,
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 13370,
+ "scene_capabilities": 13870,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/lighting.md b/docs/lighting.md
index b2952617..b9ca3595 100644
--- a/docs/lighting.md
+++ b/docs/lighting.md
@@ -108,7 +108,9 @@ const renderer = new Renderer67(canvas, parts, {
});
```
-Options: `count` (1 to 4, default 3), `resolution` (256 to 4096, default 2048), `maximumDistance` (default 150 m; farther surfaces are lit), `splitLambda` (0 uniform to 1 logarithmic, default 0.7) and `casterReach` (how far toward the light a caster may stand, default 200 m). Each slice is a bounding sphere, so turning the camera does not change its size, and its centre snaps to whole texels, so edges do not crawl. The last tenth of a slice blends into the next. The slice maps are drawn again when the camera, the light or a caster moves, so a still camera pays the depth passes once and a moving one pays `count` passes per frame; the measured cost is in `bench/reference/README.md`. Three slices of 2048 x 2048 are a 48 MiB depth array. The single map is still drawn for volume fog and water, which do not read the cascades. A scene without cascades compiles none of this code, and recipes do not reach it yet.
+Options: `count` (1 to 4, default 3), `resolution` (256 to 4096, default 2048), `maximumDistance` (default 150 m; farther surfaces are lit), `splitLambda` (0 uniform to 1 logarithmic, default 0.7) and `casterReach` (how far toward the light a caster may stand, default 200 m). Each slice is a bounding sphere, so turning the camera does not change its size, and its centre snaps to whole texels, so edges do not crawl. The last tenth of a slice blends into the next. The slice maps are drawn again when the camera, the light or a caster moves, so a still camera pays the depth passes once and a moving one pays `count` passes per frame; the measured cost is in `bench/reference/README.md`. Three slices of 2048 x 2048 are a 48 MiB depth array. The single map is still drawn for volume fog and water, which do not read the cascades. A scene without cascades compiles none of this code.
+
+Recipes reach it through `environment.shadowCascades` (an integer from 1 to 4, or 0 for the single map). Without the field a scene gets three cascades when `shadow.extent` is above 40, because the single map then covers more than 80 m and a texel is 4 cm or wider (`extent / 1024` metres); a scene with the default extent of 3.5 and any scene at or below 40 draws exactly as before. The rule reads only recipe numbers, so a recipe always resolves the same way; set `shadowCascades: 0` to keep the single map on a wide scene. The preview loads the cascade code only for a scene that gets cascades, and rebuilds its renderer when the count changes.
## Light linking
@@ -121,7 +123,9 @@ const environment = { pointLights: [{ position: [-1.8, 2.4, 1.2], intensity: 14,
const renderer = new Renderer67(canvas, applyLightLinks(parts, environment), { environment });
```
-A part gets a bit mask in `material.lightMask` (bit 0 the sun, bits 1 to 8 the point lights, 9 to 16 the spot lights, 17 to 20 the area lights, in list order); the shader skips a light whose bit is clear. Linking changes what a light adds, not what it shadows: a part a light does not reach still blocks that light for the others, and in Blender too. Parts with different masks are different batches. The path tracer and the light bake ignore linking, and recipes do not reach it yet (`lightLinking: false` in `scene_capabilities`). A scene without links compiles none of this code. The reference scene `light-linking` is the measured case.
+A part gets a bit mask in `material.lightMask` (bit 0 the sun, bits 1 to 8 the point lights, 9 to 16 the spot lights, 17 to 20 the area lights, in list order); the shader skips a light whose bit is clear. Linking changes what a light adds, not what it shadows: a part a light does not reach still blocks that light for the others, and in Blender too. Parts with different masks are different batches. The path tracer ignores linking and says so in `report.ignored`; the light bake honours it, so a lamp linked to some parts bakes no light onto the others, not even as a bounce off a part it lights.
+
+Recipes reach it through `affects` (a list of node IDs) on a point, spot or area light and `environment.keyAffects` for the sun; a light without the list lights every node. A name that is not a node of the recipe is refused with the list of names to check (`scene_inspect`), and removing a node that a list names is refused until the list changes. `set-environment` carries the lists, `scene_export_recipe` keeps them, and the code loads on demand only for a recipe that names them. A scene without links compiles none of this code. The reference scene `light-linking` is the measured case.
## Animation and resources
diff --git a/docs/parity.md b/docs/parity.md
index 1904a849..c160e4f5 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -190,7 +190,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| 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 draws normal and metallic-roughness maps on UV-mapped materials (issue #129) and runs about 2.8 times faster per thread than at that table, so its scores and seconds there predate both; it does not trace volume fog, translucent leaves or maps on box-projected materials, a 1080p still of a 181,708 triangle room at 64 samples still does not finish inside the 240 s job limit, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point, spot and area 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, shrunk deterministically to a ray work budget of 10 million so a preset finishes on a 56 part room; scene_inspect reports what it used, whether it reduced, bake seconds and skipped parts, which include hair, particle and cloth nodes), 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 and 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, or up to four cascades through `addons/cascaded-shadows` (`shadowCascades` on the renderer; recipes do not reach it): scene `long-street` scores 0.1555 against Cycles with one map and 0.1398 with three cascades, for about 0.2 ms more a frame on an RTX 3060 when the camera moves. | [lighting](../tests/lighting.test.js), [cascades](../tests/cascaded-shadows.test.js), `npm run reference` scenes `spot-area` and `long-street` | #52 |
+| 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, or up to four cascades through `addons/cascaded-shadows` (`shadowCascades` on the renderer and `environment.shadowCascades` in recipes, three by themselves when `shadow.extent` is above 40): scene `long-street` scores 0.1555 against Cycles with one map and 0.1398 with three cascades, for about 0.2 ms more a frame on an RTX 3060 when the camera moves. | [lighting](../tests/lighting.test.js), [cascades](../tests/cascaded-shadows.test.js), `npm run reference` scenes `spot-area` and `long-street` | #52 |
| Rendering > Lights > Light Linking | partial | `addons/light-linking`: a light's `affects` list (and `environment.keyAffects` for the sun) limits it to the named parts through `applyLightLinks`, as a Blender receiver collection does; the shader skips a light whose bit in the part's mask is clear. Linking changes what a light adds, not what it shadows. The path tracer and the light bake ignore it, recipes do not reach it (`lightLinking: false` in `scene_capabilities`) and there is no blocker list. Scene `light-linking` scores 0.0998 against Cycles. | [light-linking](../tests/light-linking.test.js), `npm run reference` scene `light-linking` | #52 |
| Rendering > Lights > World Environment | partial | Recipes pick a named setup (`daylight`, `overcast`, `sunset`, `studio`) that carries a procedural environment map, with opt-in screen-space ambient occlusion. Code can load any HDRI; recipes reach only the named maps, with no URLs or files. No reflections between objects yet. The MCP preview adds an automatic floor with a contact shadow (`environment.ground: false` removes it). Cold-run reference-free score for sitting on a surface: 0 before, 1 to 2 after, on the three-quarter view only. | [environment](../tests/environment.test.js), [default look](../tests/default-look.test.js) | #53 |
| Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps, a clear coat, transmission with thickness, attenuation and IOR, sheen, and specular weight and tint. Anisotropic highlights and a thin-film iridescence layer, as in the glTF extensions, are compiled in only when a part uses them. There is no subsurface scattering, volume material or displacement. | [texture-set](../tests/texture-set.test.js), [material-layers](../tests/material-layers.test.js) | #50, #51 |
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 79b9a093..63cc97e9 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -6,6 +6,7 @@ import { installRenderPasses } from '../src/render-passes.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';
+import { agentSceneModule } from '../src/agent-scene-modules.js';
import { agentGroundPlacement, createAgentGround, placeAgentGround } from '../src/agent-ground.js';
import { createAgentAssetScene } from '../src/agent-asset.js';
import { parseGltf } from '../src/gltf.js';
@@ -98,6 +99,15 @@ function syncAutomaticGround(record) {
}
}
+// A renderer takes its cascades at construction, so a change of the count (or of the extent that picks it) rebuilds.
+function syncShadowCascades(record) {
+ const count = cascadeCountFor(record.scene);
+ if (count !== (record.renderer.shadowCascades?.count ?? 0)) {
+ rebuildRenderer(record);
+ record.renderer.resize();
+ }
+}
+
function draw(record, time = 0, camera = record.scene.camera, frameOptions = {}) {
if (!record.renderer) throw new Error('The scene renderer is leased to a render job.');
if (record.renderer.context.isContextLost()) {
@@ -120,6 +130,7 @@ function draw(record, time = 0, camera = record.scene.camera, frameOptions = {})
record.renderer.updateParts(record.scene.parts);
}
syncAutomaticGround(record);
+ syncShadowCascades(record);
const environment = record.scene.environment;
const effects = record.scene.effects;
const shadow = record.scene.shadow;
@@ -185,6 +196,16 @@ function resetCanvas() {
canvas = replacement;
}
+// The cascade code is a loaded module, so a scene with one shadow map never runs it.
+function cascadeCountFor(scene) {
+ return agentSceneModule('cascades').effectiveShadowCascades(scene.environment, scene.shadow);
+}
+
+function cascadesFor(scene) {
+ const count = cascadeCountFor(scene);
+ return count > 0 ? agentSceneModule('cascades').createCascadedShadows({ count }) : null;
+}
+
function initializeRenderer(scene, { memoryBudgetMiB, backend }) {
const placement = agentGroundPlacement(scene.parts, scene.environment);
return installRenderPasses(installCameraEffects(new Renderer67(canvas, scene.parts, {
@@ -194,6 +215,7 @@ function initializeRenderer(scene, { memoryBudgetMiB, backend }) {
world: scene.environment.world,
environment: { ...scene.environment, map: agentEnvironmentMap(scene.environment) },
shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),
+ shadowCascades: cascadesFor(scene),
pixelRatio: 1,
samples: backend === 'cpu' ? 1 : 4,
memoryBudgetMiB,
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index ba470bd6..2e1c95a2 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -142,51 +142,57 @@ const volumeFog = z.strictObject({
noiseScale: bounded(0.001, 100).optional(),
maxDistance: bounded(0.01, 1e4).optional(),
});
+const affects = z.array(z.string()).optional();
const environment = z.strictObject({
world: z.boolean().optional().describe('Draw the sky and apply surface fog.'),
ground: z.boolean().optional().describe('false: no automatic floor.'),
- setup: z.enum(LIGHTING_SETUP_NAMES).optional().describe('Named lighting. Default daylight. Resets key, fill and ambient fields; same-call fields win.'),
+ setup: z.enum(LIGHTING_SETUP_NAMES).optional().describe('Named lighting; resets key, fill and ambient fields. Default daylight.'),
environmentIntensity: bounded(0, 100).optional().describe('Scales the setup environment light and its reflections.'),
environmentRotation: bounded(-100, 100).optional().describe('Turns the setup environment around the vertical axis, in radians.'),
- lightDirection: boundedVector(-1e6, 1e6).optional().describe('Nonzero direction toward the key light; shadows follow it.'),
+ lightDirection: boundedVector(-1e6, 1e6).optional().describe('Direction toward the key light; shadows follow.'),
keyColor: boundedVector(0, 1000).optional(),
keyIntensity: bounded(0, 100).optional(),
fillIntensity: bounded(0, 100).optional(),
ambientIntensity: bounded(0, 100).optional(),
daylight: bounded(0, 100).optional(),
+ keyAffects: affects.describe('Node IDs lit; default all.'),
+ shadowCascades: z.number().int().min(0).max(4).optional().describe('Sun shadow slices; 0 one map.'),
pointLights: z.array(z.strictObject({
position: boundedVector(-1e6, 1e6),
color: color.optional(),
intensity: bounded(0, 1e5).optional(),
radius: bounded(0.001, 1e6).optional(),
range: z.union([z.literal(0), bounded(0.001, 1e6)]).optional(),
- castShadow: z.boolean().optional().describe('Casts a cube shadow; uses 6 of the 24 shadow atlas tiles.'),
- })).max(8).optional().describe('Replace the entire list; [] removes all point lights. Intensity is candela: inverse-square falloff.'),
+ castShadow: z.boolean().optional().describe('Casts a shadow; 6 atlas tiles.'),
+ affects,
+ })).max(8).optional().describe('Replaces the list; [] clears. Intensity in candela.'),
spotLights: z.array(z.strictObject({
position: boundedVector(-1e6, 1e6),
direction: boundedVector(-1e6, 1e6).describe('Nonzero direction the cone points along.'),
- angle: bounded(0.01, Math.PI / 2 - 0.01).optional().describe('Outer half angle of the cone in radians; default pi/4.'),
- penumbra: unit.optional().describe('Fraction of the cone cosine range that fades out; 0 is a hard edge, default 0.15.'),
+ angle: bounded(0.01, Math.PI / 2 - 0.01).optional().describe('Outer half angle, radians; default pi/4.'),
+ penumbra: unit.optional().describe('Soft edge, 0 hard; default 0.15.'),
color: color.optional(),
- intensity: bounded(0, 1e5).optional().describe('Candela, the same units as a point light.'),
+ intensity: bounded(0, 1e5).optional().describe('Candela.'),
radius: bounded(0.001, 1e6).optional(),
range: z.union([z.literal(0), bounded(0.001, 1e6)]).optional(),
- castShadow: z.boolean().optional().describe('Casts a shadow; uses 1 of the 24 shadow atlas tiles.'),
- })).max(8).optional().describe('Replace the entire list; [] removes all spot lights.'),
+ castShadow: z.boolean().optional().describe('Casts a shadow; 1 atlas tile.'),
+ affects,
+ })).max(8).optional().describe('Replaces the list; [] clears.'),
areaLights: z.array(z.strictObject({
position: boundedVector(-1e6, 1e6).describe('Center of the rectangle.'),
- direction: boundedVector(-1e6, 1e6).describe('Nonzero direction the rectangle faces; it emits to that side only.'),
- up: boundedVector(-1e6, 1e6).optional().describe('Sets which way the height axis runs; default world up.'),
+ direction: boundedVector(-1e6, 1e6).describe('Direction the rectangle faces; emits that side only.'),
+ up: boundedVector(-1e6, 1e6).optional().describe('Height axis direction; default world up.'),
width: bounded(0.001, 1e4),
height: bounded(0.001, 1e4),
color: color.optional(),
- intensity: bounded(0, 1e5).optional().describe('Candela of the whole rectangle seen head on.'),
- })).max(4).optional().describe('Replace the entire list; [] removes all area lights. Area lights cast no shadow.'),
+ intensity: bounded(0, 1e5).optional().describe('Candela head on.'),
+ affects,
+ })).max(4).optional().describe('Replaces the list; [] clears. No shadow.'),
skyTop: color.optional(),
skyBottom: color.optional(),
fogColor: color.optional(),
fogDensity: bounded(0, 10).optional(),
- volumeFog: volumeFog.optional().describe('Bounded depth-clipped directional scattering; requires HDR support.'),
+ volumeFog: volumeFog.optional().describe('Directional scattering; needs HDR.'),
liquid: liquidOptics.optional().describe('Optics for materials tagged liquid or foam.'),
});
const effects = z.strictObject({
diff --git a/scripts/smoke-mcp-linking.mjs b/scripts/smoke-mcp-linking.mjs
new file mode 100644
index 00000000..f40fc5d8
--- /dev/null
+++ b/scripts/smoke-mcp-linking.mjs
@@ -0,0 +1,90 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { constants, setPriority } from 'node:os';
+import { Client } from '@modelcontextprotocol/client';
+import { PatientStdioClientTransport } from './patient-stdio-transport.mjs';
+
+// One recipe through the real MCP server that uses light linking and cascaded sun shadows together: a long street under
+// the sun, a lamp that lights only the left wall, and a car that moves, so a seek has something to redraw.
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const backend = process.argv[2] ?? 'cpu';
+await mkdir('artifacts', { recursive: true });
+
+function streetRecipe() {
+ const buildings = Array.from({ length: 8 }, (_, index) => ({
+ id: `building-${index}`, geometry: 'box', material: 'wall', translation: [index % 2 === 0 ? -6 : 6, 3, -index * 14], scale: [4, 6, 10],
+ }));
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }],
+ materials: [{ id: 'wall', color: [0.75, 0.7, 0.62], roughness: 0.9 }, { id: 'paint', color: [0.7, 0.1, 0.08], roughness: 0.4 }],
+ nodes: [
+ { id: 'road', geometry: 'box', material: 'wall', translation: [0, -0.1, -50], scale: [14, 0.2, 130] },
+ ...buildings,
+ { id: 'car', geometry: 'box', material: 'paint', translation: [2, 0.6, -6], scale: [1.8, 1.2, 4] },
+ ],
+ camera: { eye: [0, 2.2, 8], target: [0, 1.5, -30], fov: 55, near: 0.2, far: 300 },
+ environment: {
+ lightDirection: [-0.5, 0.8, 0.4],
+ shadowCascades: 3,
+ keyAffects: ['road', 'car', 'building-1', 'building-3', 'building-5'],
+ pointLights: [{ position: [-3, 3, -4], color: [1, 0.7, 0.4], intensity: 60, range: 14, affects: ['building-0', 'building-2'] }],
+ },
+ shadow: { target: [0, 0, -40], extent: 85, distance: 120, near: 1, far: 260 },
+ motion: { duration: 2, tracks: [{ kind: 'node', id: 'car', property: 'translation', interpolation: 'LINEAR',
+ keyframes: [{ time: 0, value: [2, 0.6, -6] }, { time: 2, value: [2, 0.6, -20] }] }] },
+ };
+}
+
+const transport = new PatientStdioClientTransport({
+ command: process.execPath,
+ args: [resolve('scripts/mcp-server.mjs'), '--backend', backend, '--memory', '192'],
+ stderr: 'pipe',
+ cwd: process.cwd(),
+});
+const client = new Client({ name: '67js-linking-proof', version: '1' }, { versionNegotiation: { mode: { pin: '2026-07-28' } } });
+
+async function call(name, argumentsValue = {}) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 120000 });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function look(sessionId, motionTime) {
+ const result = await call('scene_look', { sessionId, motionTime, width: 640, height: 360 });
+ return Buffer.from(result.content.find(item => item.type === 'image').data, 'base64');
+}
+
+let report;
+try {
+ await client.connect(transport);
+ const capabilities = (await call('scene_capabilities')).structuredContent;
+ assert.ok(capabilities.scene.lightLinking.fields.length > 0);
+ const created = (await call('scene_create', { recipe: streetRecipe() })).structuredContent;
+ const { sessionId } = created;
+ assert.ok(created.render.graphics, 'the scene rendered');
+ const firstSeek = await look(sessionId, 1);
+ await look(sessionId, 0);
+ const secondSeek = await look(sessionId, 1);
+ assert.deepEqual(secondSeek, firstSeek, 'seeking to the same time gives the same bytes');
+ await writeFile(`artifacts/mcp-linking-${backend}.png`, firstSeek);
+
+ const unknown = await client.callTool({ name: 'scene_apply', arguments: { sessionId, expectedRevision: created.revision,
+ operations: [{ type: 'set-environment', environment: { keyAffects: ['no-such-node'] } }] } });
+ assert.equal(unknown.isError, true);
+ assert.match(unknown.content[0].text, /no-such-node.*scene_inspect/);
+
+ const exported = (await call('scene_export_recipe', { sessionId })).structuredContent.recipe;
+ assert.equal(exported.environment.shadowCascades, 3);
+ assert.deepEqual(exported.environment.pointLights[0].affects, ['building-0', 'building-2']);
+ assert.equal(exported.environment.keyAffects.length, 5);
+ await call('scene_dispose', { sessionId });
+ report = { backend, graphics: created.render.graphics, seekSha256: createHash('sha256').update(firstSeek).digest('hex'), seekBytes: firstSeek.byteLength,
+ unknownNodeRejected: true, recipeKeepsLinksAndCascades: true };
+} finally {
+ await client.close();
+}
+await writeFile(`artifacts/mcp-linking-${backend}.json`, JSON.stringify(report, null, 2));
+console.log(JSON.stringify(report));
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index dcf5a848..46ce1889 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -69,7 +69,7 @@ Local `environment.pointLights` support eight world-space sources with inverse-s
Each light provides `position` and optional `color`, `intensity`, `radius`, `range` and `castShadow`.
`environment.spotLights` (eight) take `position`, `direction`, and optional `angle` (outer half angle in radians, default 0.785), `penumbra` (0 to 1, default 0.15), `color`, `intensity`, `radius`, `range` and `castShadow`. Intensity is candela, the same unit as a point light.
`environment.areaLights` (four) are rectangles with `position`, `direction` (the side that emits), `width`, `height`, optional `up`, `color` and `intensity` (candela seen head on). They cast no shadow.
-`castShadow: true` on a point light uses 6 of the 24 shadow tiles, on a spot light 1. Past 24 the edit is rejected. Shadows reach `range`, or 30 units when `range` is 0. Set `castShadow` on the few lights that show a visible shadow, because each one adds a depth pass. Recipes cannot link a light to some parts or cascade the sun shadow (`lightLinking` is false in `scene_capabilities`); those are engine options for code that builds its own `Renderer67` (`addons/light-linking`, `addons/cascaded-shadows`; see docs/lighting.md).
+`castShadow: true` on a point light uses 6 of the 24 shadow tiles, on a spot light 1. Past 24 the edit is rejected. Shadows reach `range`, or 30 units when `range` is 0. Set `castShadow` on the few lights that show a visible shadow, because each one adds a depth pass. `affects: ['node-id', ...]` on a point, spot or area light, and `environment.keyAffects` for the sun, limit a light to those nodes (a light without it lights every node; an unknown ID is rejected; the bake honours it, the path tracer ignores it and says so). `environment.shadowCascades` (1 to 4, 0 for one map) sharpens a long sun shadow near the camera; it turns on by itself at 3 when `shadow.extent` is above 40, so set it only to choose another count or 0. Details: docs/lighting.md.
`keyIntensity`, `fillIntensity` and `ambientIntensity` independently scale existing lighting.
Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.
Point lights currently cast no local shadows. Radius limits attenuation without creating an area emitter.
diff --git a/src/agent-look.js b/src/agent-look.js
index 92e9c4fb..b8047577 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -8,19 +8,47 @@ import { DEFAULT_LIGHTING_SETUP, LIGHTING_SETUP_NAMES, DEFAULT_AMBIENT_OCCLUSION
const ENVIRONMENT_FIELDS = [
'world', 'ground', 'setup', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',
- 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid',
+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects',
];
const LIQUID_FIELDS = ['thickness', 'ior', 'refraction', 'scattering', 'foamOpacity', 'foamSoftness'];
const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];
const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];
-const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range', 'castShadow'];
-const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow'];
-const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity'];
+const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range', 'castShadow', 'affects'];
+const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow', 'affects'];
+const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity', 'affects'];
const VOLUME_VECTOR_FIELDS = ['minimum', 'maximum', 'color', 'ambient', 'drift'];
const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance'];
const BLOOM_FIELDS = ['strength', 'threshold', 'radius'];
const DEPTH_OF_FIELD_FIELDS = ['blur', 'focusDistance'];
const MOTION_BLUR_FIELDS = ['shutter'];
+const MAXIMUM_SHADOW_CASCADES = 4;
+const MAXIMUM_AFFECTED_NODES = 1024;
+
+// Only a light that is linked carries the field, so recipes without links keep their exported shape.
+function affectsFrom(light, label) {
+ if (light.affects === undefined) {
+ return {};
+ }
+ const names = light.affects;
+ if (!Array.isArray(names) || names.length > MAXIMUM_AFFECTED_NODES || names.some(name => typeof name !== 'string' || name.length < 1 || name.length > 128)) {
+ throw new TypeError(`${label} affects must be a list of at most ${MAXIMUM_AFFECTED_NODES} node IDs.`);
+ }
+ return { affects: [...names] };
+}
+
+function shadowCascadesFrom(value) {
+ if (!Number.isInteger(value) || value < 0 || value > MAXIMUM_SHADOW_CASCADES) {
+ throw new RangeError(`environment.shadowCascades must be an integer from 1 to ${MAXIMUM_SHADOW_CASCADES}, or 0 for the single shadow map.`);
+ }
+ return value;
+}
+
+/** Whether any light of the environment is limited to a list of nodes. */
+export function environmentLinksLights(environment) {
+ const lights = [...(environment.pointLights ?? []), ...(environment.spotLights ?? []), ...(environment.areaLights ?? [])];
+ return environment.keyAffects !== undefined || lights.some(light => light.affects !== undefined);
+}
+
function plainObject(value, label) {
if (!value || typeof value !== 'object' || Array.isArray(value) ||
@@ -149,6 +177,7 @@ function pointLightFrom(light) {
radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'point light radius'),
range: rangeFrom(light, 'point light'),
...shadowFieldFrom(light, 'point light'),
+ ...affectsFrom(light, 'point light'),
};
}
@@ -164,6 +193,7 @@ function spotLightFrom(light) {
radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'spot light radius'),
range: rangeFrom(light, 'spot light'),
...shadowFieldFrom(light, 'spot light'),
+ ...affectsFrom(light, 'spot light'),
};
}
@@ -178,7 +208,7 @@ function areaLightFrom(light) {
intensity: numberInRange(fallback(light.intensity, 1), 0, 1e5, 'area light intensity'),
};
if (light.up !== undefined) resolved.up = directionFrom(light.up, 'area light up').direction;
- return resolved;
+ return { ...resolved, ...affectsFrom(light, 'area light') };
}
function volumeFogFrom(input = {}) {
@@ -238,6 +268,12 @@ function environmentFrom(input = {}) {
if (input.areaLights !== undefined) {
environment.areaLights = lightListFrom(input.areaLights, MAX_AREA_LIGHTS, 'areaLights').map(areaLightFrom);
}
+ if (input.shadowCascades !== undefined) {
+ environment.shadowCascades = shadowCascadesFrom(input.shadowCascades);
+ }
+ if (input.keyAffects !== undefined) {
+ environment.keyAffects = affectsFrom({ affects: input.keyAffects }, 'environment keyAffects').affects;
+ }
if (input.liquid !== undefined) {
knownKeys(input.liquid, LIQUID_FIELDS, 'liquid');
environment.liquid = copiedJson(resolveLiquidOptics(copiedJson(input.liquid)));
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index e92e7ae0..337f6cf5 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -190,10 +190,11 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
lightingSetups: LIGHTING_SETUP_NAMES, defaultLightingSetup: DEFAULT_LIGHTING_SETUP,
ambientOcclusion: Object.freeze({ default: DEFAULT_AMBIENT_OCCLUSION, defaultRadius: 0.5, off: 0 }),
// Local lights: spot and rectangular area lights. Shadows share one 2048 x 3072 depth atlas of 24 tiles; a shadowed
- // point light uses 6 tiles and a shadowed spot light 1. Area lights cast no shadow. Light linking (addons/light-linking) and cascaded sun shadows (addons/cascaded-shadows) are engine options that recipes do not reach; lightLinking stays false here.
+ // point light uses 6 tiles and a shadowed spot light 1. Area lights cast no shadow. Recipes reach light linking and cascaded sun shadows through lightLinking and shadowCascades below.
maxSpotLights: 8, maxAreaLights: 4,
localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),
- lightLinking: false,
+ lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),
+ shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
// Authored rigs: armatures expand into bone nodes, and a node `skin` binds a mesh with automatic weights (four influences).
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 63c6bac1..56e29318 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -1,5 +1,5 @@
// Code that most recipes never run loads on demand, so the agent scene entry stays small. A recipe that uses mesh
-// editing, procedural modeling, motion, material patterns, terrain or the anisotropy and iridescence layers needs its module loaded before createAgentScene runs:
+// editing, procedural modeling, motion, material patterns, terrain, light linking, cascaded shadows or the anisotropy and iridescence layers needs its module loaded before createAgentScene runs:
// call `await loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()` in a host that does not mind the
// size). createAgentScene is still synchronous; when a needed module is missing it says which call to make.
@@ -17,6 +17,8 @@ const MODULE_LOADERS = {
timeline: () => import('./film-timeline.js'),
layerShaders: () => import('./material-layer-shaders.js'),
terrain: () => import('./agent-terrain.js'),
+ lightLinking: () => import('./light-linking.js'),
+ cascades: () => import('./cascaded-shadows.js'),
};
const loadedModules = {};
@@ -39,6 +41,8 @@ const MODULE_MARKERS = {
timeline: ['"timeline":{'],
layerShaders: ['"anisotropy"', '"iridescence"'],
terrain: ['"type":"terrain"'],
+ lightLinking: ['"affects"', '"keyAffects"'],
+ cascades: ['"shadowCascades"'],
};
/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 9847835d..774ec42c 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -2,10 +2,10 @@ import { mat4, mat3 } from 'gl-matrix';
import { box, cylinder, grid, sphere, torus } from './geometry.js';
import { createSceneGraph } from './scene-graph.js';
import { applyProjection } from './camera.js';
-import { normalizeAgentLook, environmentPatchWithSetup } from './agent-look.js';
+import { normalizeAgentLook, environmentPatchWithSetup, environmentLinksLights } from './agent-look.js';
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 { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
+import { ALL_LIGHTS_MASK, MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { recipeDiagnostics } from './agent-diagnostics.js';
import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
@@ -603,6 +603,39 @@ function withDefaultMaterial(recipe) {
return alreadyDefined ? materials : [...materials, { id: DEFAULT_MATERIAL_ID }];
}
+// A name that matches no node would leave the light lighting nothing without a sign, so it fails and says what to do.
+function checkLightLinkNames(recipe) {
+ if (!environmentLinksLights(recipe.environment)) {
+ return;
+ }
+ const unknown = agentSceneModule('lightLinking').unknownLightLinkNames(recipe.environment, recipe.nodes);
+ if (unknown.length > 0) {
+ throw new RangeError(`Light links name nodes that do not exist (${unknown.slice(0, 4).join('; ')}). List node IDs with scene_inspect, then fix the affects list or add the node.`);
+ }
+}
+
+// Every light's affects list in light order: the mask of a part depends on these lists and nothing else of the environment.
+function lightLinksKey(environment) {
+ const lights = [...environment.pointLights, ...(environment.spotLights ?? []), ...(environment.areaLights ?? [])];
+ return JSON.stringify([environment.keyAffects ?? null, ...lights.map(light => light.affects ?? null)]);
+}
+
+// A part that a light skips needs its own material object with the light mask, but it must still read every other
+// field from the live material, so motion tracks keep driving it. One wrapper per material and mask keeps batches.
+function linkedMaterial(liveMaterial, lightMask, wrappers) {
+ const byMask = wrappers.get(liveMaterial) ?? new Map();
+ wrappers.set(liveMaterial, byMask);
+ if (!byMask.has(lightMask)) {
+ const wrapper = {};
+ for (const field of Object.keys(liveMaterial)) {
+ Object.defineProperty(wrapper, field, { enumerable: true, get: () => liveMaterial[field] });
+ }
+ Object.defineProperty(wrapper, 'lightMask', { enumerable: true, value: lightMask });
+ byMask.set(lightMask, Object.freeze(wrapper));
+ }
+ return byMask.get(lightMask);
+}
+
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth', 'timeline', 'particles', 'bake'], 'recipe');
@@ -649,6 +682,7 @@ function normalizeRecipe(input, limits) {
}
}
Object.assign(recipe, normalizeAgentLook(look));
+ checkLightLinkNames(recipe);
if (Object.hasOwn(recipe, 'motion')) {
recipe.motion = recipe.motion === null || recipe.motion === undefined ? null : agentSceneModule('motion').normalizeAgentMotion(recipe.motion, recipe);
}
@@ -882,6 +916,7 @@ export function createAgentScene(input, inputLimits = {}) {
let clothBake = null;
let particleBake = null;
let lightBake = null;
+ let lightLinkCache = null;
const skinCache = new Map();
const checkpoints = new Map();
@@ -994,7 +1029,7 @@ export function createAgentScene(input, inputLimits = {}) {
state.sourceRestParts.every((part, index) => part === nextParts[index]);
const sourceRestParts = sameParts ? state.sourceRestParts : Object.freeze(nextParts);
const lightBakeResult = stageLightBake(recipe, sourceRestParts, graph);
- const restParts = lightBakeResult ? lightBakeResult.parts : sourceRestParts;
+ const restParts = stageLightLinks(recipe, lightBakeResult ? lightBakeResult.parts : sourceRestParts);
const stagedState = {
recipe, geometryRecords, geometries, graph, materialHandles,
// Part identity decides what the next stage reuses, so it compares the parts as built, before any bake.
@@ -1018,6 +1053,26 @@ export function createAgentScene(input, inputLimits = {}) {
return stagedState;
}
+ // Parts a linked light skips carry a light mask in their material. The same parts and links give the same objects, so
+ // an edit that changes neither is not a topology change for the renderer.
+ function stageLightLinks(recipe, parts) {
+ if (!environmentLinksLights(recipe.environment)) {
+ return parts;
+ }
+ const { environment } = recipe;
+ const linksKey = lightLinksKey(environment);
+ if (lightLinkCache?.parts === parts && lightLinkCache.linksKey === linksKey) {
+ return lightLinkCache.linked;
+ }
+ const linking = agentSceneModule('lightLinking');
+ const masks = linking.lightMasksFor(parts, environment);
+ const wrappers = new Map();
+ const linked = Object.freeze(parts.map((part, index) => (masks[index] === ALL_LIGHTS_MASK ? part
+ : Object.freeze({ ...part, material: linkedMaterial(part.material, masks[index], wrappers) }))));
+ lightLinkCache = { parts, linksKey, linked };
+ return linked;
+ }
+
// A light bake costs seconds of ray tracing: it runs when the parts, the lights, the materials or the bake fields
// change, and every other edit, seek or camera move reuses the last result.
function stageLightBake(recipe, sourceRestParts, graph) {
@@ -1034,7 +1089,7 @@ export function createAgentScene(input, inputLimits = {}) {
generatedGeometryGenerators.set(sheet.node, 'a cloth simulation');
}
const { spotLights, areaLights } = recipe.environment;
- const key = JSON.stringify([recipe.bake, [...generatedGeometryGenerators], pointLights, spotLights, areaLights, keyColor, keyIntensity, lightDirection, recipe.materials,
+ const key = JSON.stringify([recipe.bake, [...generatedGeometryGenerators], pointLights, spotLights, areaLights, keyColor, keyIntensity, lightDirection, recipe.environment.keyAffects, recipe.materials,
[...worldMatrices].map(([name, matrix]) => [name, Array.from(matrix)])]);
if (lightBake?.key === key && lightBake.sourceRestParts === sourceRestParts) {
return { ...lightBake, reused: true };
@@ -1231,8 +1286,8 @@ export function createAgentScene(input, inputLimits = {}) {
if (lookField) {
knownKeys(operation, ['type', lookField], 'operation');
const patch = operation[lookField];
- // Spot and area lights are absent from a recipe until it sets them.
- const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights'] : [];
+ // Spot and area lights, cascades and sun links are absent from a recipe until it sets them.
+ const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights', 'shadowCascades', 'keyAffects'] : [];
knownKeys(patch, [...Object.keys(candidate[lookField]), ...optionalFields], lookField);
const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;
const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };
diff --git a/src/cascaded-shadows.js b/src/cascaded-shadows.js
index 08abb0d4..aac50454 100644
--- a/src/cascaded-shadows.js
+++ b/src/cascaded-shadows.js
@@ -14,6 +14,8 @@ import { registerShaderFeatureCode } from './shaders.js';
// - The final #define makes the main shader's shadowVisibility(normal) call read the cascades; the classic map stays unused.
export const MAXIMUM_CASCADES = 4;
+const AUTOMATIC_CASCADE_EXTENT = 40;
+const AUTOMATIC_CASCADE_COUNT = 3;
const DEFAULT_RESOLUTION = 2048;
const DEFAULT_MAXIMUM_DISTANCE = 150;
const DEFAULT_SPLIT_LAMBDA = 0.7;
@@ -269,3 +271,17 @@ export class CascadedShadows {
export function createCascadedShadows(options) {
return new CascadedShadows(options);
}
+
+/**
+ * The cascade count a scene draws its sun shadow with. An explicit shadowCascades wins (0 forces the single map). Without
+ * one, a scene whose single 2048 map is coarse gets three cascades: the map covers 2 x shadow.extent metres, so a texel is
+ * extent / 1024 metres, and from 4 cm (extent above 40 m) a lamp post near the camera is two texels wide.
+ * Measured on long-street (extent 85): 0.1555 against Cycles with one map, 0.1398 with three, +0.2 ms on an RTX 3060.
+ * It reads only recipe numbers, so a recipe always resolves the same way, and the default extent of 3.5 never trips it.
+ */
+export function effectiveShadowCascades(environment, shadow) {
+ if (environment.shadowCascades !== undefined) {
+ return environment.shadowCascades;
+ }
+ return shadow.extent > AUTOMATIC_CASCADE_EXTENT ? AUTOMATIC_CASCADE_COUNT : 0;
+}
diff --git a/src/light-bake.js b/src/light-bake.js
index 534d8508..63f315af 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -113,6 +113,29 @@ function normalizeAreaLights(areaLights) {
});
}
+function withAffects(normalizedLights, sourceLights) {
+ return normalizedLights.map((light, index) => ({ ...light, affects: sourceLights[index].affects ?? null }));
+}
+
+/**
+ * Each light gets `reach`, one byte per part: 1 when the light lights that part, or null when it lights every part.
+ * A light limited by `affects` adds nothing at a surface of a part it skips, as in the renderer, so a part that a
+ * light does not reach is not lit by it even as the bounce of another part.
+ */
+function withReach(lights, parts) {
+ const reachOf = (light) => {
+ if (light.affects === null) return null;
+ const names = new Set(light.affects);
+ return Uint8Array.from(parts, part => (names.has(part.name) ? 1 : 0));
+ };
+ const linked = light => ({ ...light, reach: reachOf(light) });
+ return { pointLights: lights.pointLights.map(linked), spotLights: lights.spotLights.map(linked), areaLights: lights.areaLights.map(linked), sun: lights.sun && linked(lights.sun) };
+}
+
+function lightReaches(light, owner) {
+ return light.reach === null || light.reach[owner] === 1;
+}
+
function normalizeLights(lighting) {
if (lighting === null || typeof lighting !== 'object') throw new TypeError('Light bake needs a lighting object.');
const pointLights = lighting.pointLights ?? [];
@@ -126,15 +149,17 @@ function normalizeLights(lighting) {
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 spotLights = normalizeSpotLights(lighting.spotLights ?? []);
- const areaLights = normalizeAreaLights(lighting.areaLights ?? []);
+ const spotSources = lighting.spotLights ?? [];
+ const areaSources = lighting.areaLights ?? [];
+ const spotLights = withAffects(normalizeSpotLights(spotSources), spotSources);
+ const areaLights = withAffects(normalizeAreaLights(areaSources), areaSources);
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, spotLights, areaLights, sun: hasSun ? { color: Array.from(keyColor), direction: sunDirection } : null };
+ return { pointLights: withAffects(normalizedPoints, pointLights), spotLights, areaLights, sun: hasSun ? { color: Array.from(keyColor), direction: sunDirection, affects: lighting.keyAffects ?? null } : null };
}
function validatePart(part, index) {
@@ -354,11 +379,12 @@ function createDirectIrradiance(tracer, lights, offset, scale) {
for (let channel = 0; channel < 3; channel++) power[channel] = light.color[channel] * strength;
addLight(point, normal, toLight, distance - offset, power);
}
- return function directIrradiance(point, normal) {
+ return function directIrradiance(point, normal, owner) {
result[0] = 0;
result[1] = 0;
result[2] = 0;
for (const light of lights.pointLights) {
+ if (!lightReaches(light, owner)) continue;
const deltaX = light.position[0] - point[0];
const deltaY = light.position[1] - point[1];
const deltaZ = light.position[2] - point[2];
@@ -372,9 +398,13 @@ function createDirectIrradiance(tracer, lights, offset, scale) {
for (let channel = 0; channel < 3; channel++) power[channel] = light.color[channel] * strength;
addLight(point, normal, toLight, distance - offset, power);
}
- for (const light of lights.spotLights) addSpotLight(point, normal, light);
- for (let index = 0; index < lights.areaLights.length; index++) addAreaLight(point, normal, lights.areaLights[index], index);
- if (lights.sun) addLight(point, normal, lights.sun.direction, shadowReach, lights.sun.color);
+ for (const light of lights.spotLights) {
+ if (lightReaches(light, owner)) addSpotLight(point, normal, light);
+ }
+ for (let index = 0; index < lights.areaLights.length; index++) {
+ if (lightReaches(lights.areaLights[index], owner)) addAreaLight(point, normal, lights.areaLights[index], index);
+ }
+ if (lights.sun && lightReaches(lights.sun, owner)) addLight(point, normal, lights.sun.direction, shadowReach, lights.sun.color);
return result;
};
}
@@ -434,7 +464,7 @@ function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrr
const owner = world.triangleOwner[hit.nearestTriangle];
const albedo = albedoOfPart[owner];
const emission = emissionOfPart[owner];
- const irradiance = directIrradiance(hitPoint, normal);
+ const irradiance = directIrradiance(hitPoint, normal, owner);
for (let channel = 0; channel < 3; channel++) {
sum[channel] += throughput[channel] * (emission[channel] + albedo[channel] * irradiance[channel] / Math.PI);
throughput[channel] *= albedo[channel];
@@ -703,7 +733,7 @@ export function traceLightmaps(plan, tracedSettings) {
const scale = sceneScale(world.positions);
const offset = scale * 1e-4;
const tracer = createTracer(world);
- const directIrradiance = createDirectIrradiance(tracer, lights, offset, scale);
+ 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 });
diff --git a/src/light-linking.js b/src/light-linking.js
index 826598cb..e48423f8 100644
--- a/src/light-linking.js
+++ b/src/light-linking.js
@@ -6,7 +6,7 @@ import { ALL_LIGHTS_MASK } from './material-layers.js';
// renderer, so a scene without linking never downloads it and its shader has no mask test.
// Bit 0 is the sun (the key light), bits 1 to 8 the point lights, 9 to 16 the spot lights and 17 to 20 the area lights,
// in the order of the environment lists. Linking changes what a light adds, not what it shadows: a part that a light
-// does not reach still blocks that light for the others. The path tracer and the light bake ignore linking.
+// does not reach still blocks that light for the others. The path tracer ignores linking and says so in its report; the light bake honours it.
// The GLSL has no comments, because comments ship to every page.
export const SUN_BIT = 0;
@@ -54,15 +54,35 @@ function collectLinks(environment) {
}
/**
- * Parts with the light masks that the lights' `affects` lists ask for: a light with `affects: ['name', ...]` lights only
- * those parts, a light without it lights every part. `environment.keyAffects` does the same for the sun. A part that
- * every light reaches is returned unchanged, so a scene without links keeps its batches.
+ * The light mask of each part, in order, or null when no light is limited (every part keeps all lights). A light with
+ * `affects: ['name', ...]` lights only those parts, a light without it lights every part; `environment.keyAffects` does
+ * the same for the sun.
*/
-export function applyLightLinks(parts, environment) {
+export function lightMasksFor(parts, environment) {
const links = collectLinks(environment);
- if (links.every(([, names]) => names === null)) return parts;
- return parts.map((part) => {
- const mask = lightMaskFor(part.name, links);
- return mask === ALL_LIGHTS_MASK ? part : { ...part, material: { ...part.material, lightMask: mask } };
- });
+ if (links.every(([, names]) => names === null)) return null;
+ return parts.map(part => lightMaskFor(part.name, links));
+}
+
+/**
+ * Parts with the light masks that the lights' `affects` lists ask for. A part that every light reaches is returned
+ * unchanged, so a scene without links keeps its batches.
+ */
+export function applyLightLinks(parts, environment) {
+ const masks = lightMasksFor(parts, environment);
+ if (masks === null) return parts;
+ return parts.map((part, index) => (masks[index] === ALL_LIGHTS_MASK ? part : { ...part, material: { ...part.material, lightMask: masks[index] } }));
+}
+
+/**
+ * Names in a light's `affects` list that are not nodes of the recipe, as "where: name" strings. A linked light lights
+ * only those nodes, so a misspelled name would silently darken a part; the caller fails with the next action instead.
+ */
+export function unknownLightLinkNames(environment, nodes) {
+ const known = new Set(nodes.map(node => node.id));
+ const lists = [['environment.keyAffects', environment.keyAffects]];
+ for (const field of ['pointLights', 'spotLights', 'areaLights']) {
+ (environment[field] ?? []).forEach((light, index) => lists.push([`${field}[${index}].affects`, light.affects]));
+ }
+ return lists.flatMap(([where, names]) => (names ?? []).filter(name => !known.has(name)).map(name => `${where}: ${name}`));
}
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 6632aa9a..dc3cf51e 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -670,6 +670,7 @@ export function describeIgnoredFeatures(parts, environment) {
}
if (material.tag && material.tag !== 'surface') notes.add(`${material.tag} materials are traced as plain surfaces.`);
if (material.alphaMode === 'blend') notes.add('Blended transparency is traced as opaque.');
+ if (material.lightMask !== undefined) notes.add('Light linking (affects) is not traced: every light lights every part.');
}
return [...notes];
}
diff --git a/tests/recipe-cascades-linking.test.js b/tests/recipe-cascades-linking.test.js
new file mode 100644
index 00000000..d1fa27a1
--- /dev/null
+++ b/tests/recipe-cascades-linking.test.js
@@ -0,0 +1,143 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAgentScene, loadAgentSceneModules, agentSceneModulesNeeded } from '../src/agent-scene.js';
+import { effectiveShadowCascades } from '../src/cascaded-shadows.js';
+import { bakeLightmaps } from '../src/light-bake.js';
+import { box } from '../src/geometry.js';
+import { describeIgnoredFeatures } from '../src/path-tracer.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+import { SUN_BIT, POINT_FIRST_BIT } from '../src/light-linking.js';
+
+function sceneRecipe(environment = {}, shadow = undefined) {
+ const node = (id, x) => ({ id, geometry: 'box', translation: [x, 0.5, 0] });
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }],
+ materials: [],
+ nodes: [node('left', -2), node('right', 2), node('floor', 0)],
+ environment,
+ ...(shadow ? { shadow } : {}),
+ };
+}
+
+async function sceneFrom(recipe) {
+ await loadAgentSceneModules(recipe);
+ return createAgentScene(recipe);
+}
+
+function maskOf(scene, name) {
+ return scene.parts.find(part => part.name === name).material.lightMask;
+}
+
+test('a recipe that names no links or cascades loads neither module', () => {
+ assert.deepEqual(agentSceneModulesNeeded(sceneRecipe({ keyIntensity: 2 })).filter(name => name === 'lightLinking' || name === 'cascades'), []);
+ assert.deepEqual(agentSceneModulesNeeded(sceneRecipe({ shadowCascades: 2, keyAffects: ['left'] })).filter(name => name === 'lightLinking' || name === 'cascades').sort(), ['cascades', 'lightLinking']);
+});
+
+test('affects and keyAffects limit lights to the named nodes and keep their shape through export', async () => {
+ const environment = { pointLights: [{ position: [0, 3, 0], affects: ['left'] }, { position: [0, 3, 1] }], keyAffects: ['right'], shadowCascades: 2 };
+ const scene = await sceneFrom(sceneRecipe(environment));
+ const pointBit = index => 1 << (POINT_FIRST_BIT + index);
+ assert.equal(maskOf(scene, 'left') & pointBit(0), pointBit(0));
+ assert.equal(maskOf(scene, 'right') & pointBit(0), 0);
+ assert.equal(maskOf(scene, 'left') & pointBit(1), pointBit(1), 'a light without affects lights every node');
+ assert.equal(maskOf(scene, 'left') & (1 << SUN_BIT), 0);
+ assert.equal(maskOf(scene, 'right') & (1 << SUN_BIT), 1);
+ const exported = scene.exportRecipe().environment;
+ assert.deepEqual(exported.pointLights[0].affects, ['left']);
+ assert.equal(exported.pointLights[1].affects, undefined);
+ assert.deepEqual(exported.keyAffects, ['right']);
+ assert.equal(exported.shadowCascades, 2);
+});
+
+test('a scene without links keeps plain parts and a recipe shape without the new fields', async () => {
+ const scene = await sceneFrom(sceneRecipe({ pointLights: [{ position: [0, 3, 0] }] }));
+ assert.equal(maskOf(scene, 'left'), undefined);
+ const exported = scene.exportRecipe().environment;
+ assert.equal('keyAffects' in exported, false);
+ assert.equal('shadowCascades' in exported, false);
+});
+
+test('an unknown node in affects fails and names the next action', async () => {
+ const recipe = sceneRecipe({ pointLights: [{ position: [0, 3, 0], affects: ['lefft'] }] });
+ await loadAgentSceneModules(recipe);
+ assert.throws(() => createAgentScene(recipe), /pointLights\[0\]\.affects: lefft.*scene_inspect/);
+ assert.throws(() => createAgentScene(sceneRecipe({ keyAffects: ['nowhere'] })), /environment\.keyAffects: nowhere/);
+});
+
+test('set-environment carries links, and removing a linked node is refused until the list changes', async () => {
+ const scene = await sceneFrom(sceneRecipe());
+ await loadAgentSceneModules({ keyAffects: [] });
+ scene.apply([{ type: 'set-environment', environment: { keyAffects: ['left'], shadowCascades: 3 } }], { expectedRevision: scene.revision });
+ assert.equal(maskOf(scene, 'right') & 1, 0);
+ assert.equal(scene.environment.shadowCascades, 3);
+ assert.throws(() => scene.apply([{ type: 'remove-node', id: 'left' }], { expectedRevision: scene.revision }), /keyAffects: left/);
+ scene.apply([{ type: 'set-environment', environment: { keyAffects: ['right'] } }, { type: 'remove-node', id: 'left' }], { expectedRevision: scene.revision });
+ assert.equal(maskOf(scene, 'floor') & 1, 0);
+});
+
+test('an edit that leaves the links alone keeps the same part objects', async () => {
+ const scene = await sceneFrom(sceneRecipe({ keyAffects: ['left'] }));
+ const before = scene.parts;
+ scene.apply([{ type: 'set-camera', fov: 50 }], { expectedRevision: scene.revision });
+ assert.equal(scene.parts, before);
+});
+
+test('cascade counts and affects lists are validated', () => {
+ for (const shadowCascades of [5, -1, 1.5, '3']) {
+ assert.throws(() => createAgentScene(sceneRecipe({ shadowCascades })), /shadowCascades/);
+ }
+ assert.throws(() => createAgentScene(sceneRecipe({ keyAffects: 'left' })), /affects must be a list/);
+ assert.throws(() => createAgentScene(sceneRecipe({ pointLights: [{ position: [0, 1, 0], affects: [3] }] })), /affects must be a list/);
+});
+
+test('cascades turn on by themselves only where one map is coarse, and an explicit count always wins', () => {
+ const narrow = { extent: 3.5 };
+ const street = { extent: 85 };
+ assert.equal(effectiveShadowCascades({}, narrow), 0);
+ assert.equal(effectiveShadowCascades({}, { extent: 40 }), 0);
+ assert.equal(effectiveShadowCascades({}, street), 3);
+ assert.equal(effectiveShadowCascades({ shadowCascades: 0 }, street), 0);
+ assert.equal(effectiveShadowCascades({ shadowCascades: 2 }, narrow), 2);
+});
+
+test('scene_capabilities says recipes reach linking and cascades', () => {
+ assert.ok(AGENT_SCENE_CAPABILITIES.lightLinking.fields.includes('environment.keyAffects'));
+ assert.deepEqual([...AGENT_SCENE_CAPABILITIES.shadowCascades.counts], [0, 1, 2, 3, 4]);
+});
+
+test('the path tracer names linking as not traced', async () => {
+ const scene = await sceneFrom(sceneRecipe({ keyAffects: ['left'] }));
+ assert.ok(describeIgnoredFeatures(scene.parts, {}).some(note => /Light linking/.test(note)));
+ const plain = await sceneFrom(sceneRecipe());
+ assert.ok(!describeIgnoredFeatures(plain.parts, {}).some(note => /Light linking/.test(note)));
+});
+
+function bakeRoom() {
+ const cube = box(0, 1);
+ const placed = (name, translation, scale) => ({
+ name, geometry: cube, matrix: new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, ...translation, 1]),
+ material: { tag: 'surface', color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.8, emission: 0 },
+ });
+ 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]),
+ ];
+}
+
+function bakedPeaks(pointLight) {
+ const lighting = { pointLights: [{ position: [0, 2.5, 0], color: [1, 1, 1], intensity: 8, radius: 0.05, ...pointLight }], keyColor: [0, 0, 0] };
+ const { report } = bakeLightmaps(bakeRoom(), lighting, { samples: 8, bounces: 2, texelsPerUnit: 2, maxResolution: 32 });
+ return Object.fromEntries(report.parts.map(part => [part.name, part.peak]));
+}
+
+test('the bake adds no light from a lamp onto parts it skips, even as a bounce', () => {
+ const everywhere = bakedPeaks({});
+ const nowhere = bakedPeaks({ affects: [] });
+ const floorOnly = bakedPeaks({ affects: ['floor'] });
+ assert.ok(everywhere.ceiling > 0);
+ assert.ok(Object.values(nowhere).every(peak => peak === 0), 'a light that reaches no part bakes nothing');
+ assert.ok(floorOnly.ceiling > 0, 'the floor it lights still bounces light');
+ assert.ok(floorOnly.ceiling < everywhere.ceiling, 'but the walls it skips no longer bounce the lamp');
+});
diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjs
index 0f38ef7a..7819a415 100644
--- a/tests/support/preview-harness.mjs
+++ b/tests/support/preview-harness.mjs
@@ -4,6 +4,7 @@ import { mat4 } from 'gl-matrix';
import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded } from '../../src/agent-scene.js';
import { applyProjection } from '../../src/camera.js';
import { resolveAgentShadow, agentEnvironmentMap } from '../../src/agent-look.js';
+import { agentSceneModule } from '../../src/agent-scene-modules.js';
import { createAgentAssetScene } from '../../src/agent-asset.js';
import { parseGltf } from '../../src/gltf.js';
import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../../src/agent-branches.js';
@@ -29,7 +30,7 @@ export function previewHarness() {
class FaultInjectedRenderer {
memoryPlan = { estimatedBytes: 1024 };
capabilities = { hdr: true, samples: 4 };
- constructor() { currentRenderer = this; }
+ constructor(canvasElement, parts, options = {}) { currentRenderer = this; this.shadowCascades = options.shadowCascades ?? null; }
context = {
isContextLost: () => lost,
getError: () => renderError,
@@ -73,7 +74,7 @@ export function previewHarness() {
setManifoldModuleLoader: () => {},
needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},
parseGltf, Uint8Array, atob, sessionProblem,
- applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS, createBranchStore, printableLabel,
+ applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, agentSceneModule, BRANCH_LIMITS, createBranchStore, printableLabel,
Renderer67: FaultInjectedRenderer,
// The fault-injected renderer has no floor part; the automatic floor is covered by agent-ground.test.js and the live smokes.
agentGroundPlacement: () => null, createAgentGround: () => null, placeAgentGround: () => {},