3D engine that AI agents drive
Allow 16 point lights and 7 area lights per frame
Nguyen Xuan An79a05fa1d8dc
diff --git a/bench/lighting/frame-time.mjs b/bench/lighting/frame-time.mjsnew file mode 100644index 00000000..e8165663--- /dev/null+++ b/bench/lighting/frame-time.mjs@@ -0,0 +1,77 @@+// Frame time of a server hall with different numbers of point and area lights.+// node bench/lighting/frame-time.mjs [gpu|cpu] [--rounds=N]+import { constants, setPriority } from 'node:os';+import { mkdir, writeFile } from 'node:fs/promises';+import { chromium } from 'playwright';+import { createServer } from 'vite';+import { MAX_POINT_LIGHTS, MAX_AREA_LIGHTS } from '../../src/light-limits.js';++const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const PAGE_LOAD_TIMEOUT = 180000;+const backend = process.argv[2] === 'cpu' ? 'cpu' : 'gpu';+const roundsArgument = process.argv.find(argument => argument.startsWith('--rounds='));+const rounds = roundsArgument ? Number(roundsArgument.split('=')[1]) : 3;+const BACKEND_ARGUMENTS = {+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],+};+const VARIANTS = [+ { pointCount: 0, areaCount: 0 },+ { pointCount: 8, areaCount: 0 },+ { pointCount: 16, areaCount: 0 },+ { pointCount: 32, areaCount: 0 },+ { pointCount: 0, areaCount: 4 },+ { pointCount: 0, areaCount: 7 },+ { pointCount: 0, areaCount: 8 },+ { pointCount: 12, areaCount: 7 },+ { pointCount: 16, areaCount: 7 },+ { pointCount: 32, areaCount: 8 },+ { pointCount: 32, areaCount: 0, range: 6 },+];++// A light count above the renderer's limit throws, so a limit that is raised for a measurement widens the table by itself.+const supportedVariants = VARIANTS.filter(variant => variant.pointCount <= MAX_POINT_LIGHTS && variant.areaCount <= MAX_AREA_LIGHTS);++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });+await server.listen();+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });+try {+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ await page.goto(`${serverUrl}/bench/lighting/harness.html`, { timeout: PAGE_LOAD_TIMEOUT });+ await page.waitForFunction(() => window.measureLightCounts, null, { timeout: PAGE_LOAD_TIMEOUT });+ if (process.argv.includes('--each-light')) {+ const report = await page.evaluate(() => window.checkEachLightVisible({ pointCount: 12, areaCount: 7 }));+ const lights = Object.values(report.changedPixels).flat();+ console.log(JSON.stringify({ backend, ...report, everyLightVisible: report.glError === 0 && lights.every(count => count > 0) }, null, 1));+ await browser.close();+ await server.close();+ process.exit(0);+ }+ const samples = new Map();+ for (let round = 0; round < rounds; round++) {+ // Alternate the order so a drifting machine load does not favor one side.+ const order = round % 2 === 0 ? supportedVariants : [...supportedVariants].reverse();+ for (const variant of order) {+ const result = await page.evaluate(options => window.measureLightCounts(options), variant);+ const key = `${variant.pointCount} point, ${variant.areaCount} area${variant.range ? `, range ${variant.range}` : ''}`;+ if (!samples.has(key)) samples.set(key, { glError: result.glError, uniformVectors: result.uniformVectors, medians: [], image: result.image, variant });+ samples.get(key).medians.push(result.medianMilliseconds);+ }+ }+ const summary = {};+ for (const [key, entry] of samples) {+ const sorted = [...entry.medians].sort((first, second) => first - second);+ summary[key] = { medianMilliseconds: Number(sorted[Math.floor(sorted.length / 2)].toFixed(3)), rangeMilliseconds: [sorted[0], sorted.at(-1)].map(value => Number(value.toFixed(3))), glError: entry.glError };+ }+ const withLights = [...samples].find(([, entry]) => entry.variant.pointCount === 12 && entry.variant.areaCount === 7);+ if (withLights) {+ await mkdir('artifacts', { recursive: true });+ await writeFile('artifacts/lighting-hall-12-point-7-area.png', Buffer.from(withLights[1].image, 'base64'));+ }+ console.log(JSON.stringify({ backend, maxFragmentUniformVectors: [...samples.values()][0].uniformVectors, summary }, null, 1));+} finally {+ await browser.close();+ await server.close();+}diff --git a/bench/lighting/harness.html b/bench/lighting/harness.htmlnew file mode 100644index 00000000..4cb9a49a--- /dev/null+++ b/bench/lighting/harness.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+<head>+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>+</head>+<body>+<canvas></canvas>+<script type="module" src="./harness.js"></script>+</body>+</html>diff --git a/bench/lighting/harness.js b/bench/lighting/harness.jsnew file mode 100644index 00000000..6ec87015--- /dev/null+++ b/bench/lighting/harness.js@@ -0,0 +1,113 @@+// Runs in the page: draws a server hall lit by a chosen number of point and area lights and times the frames.+import { Renderer67 } from '/src/renderer.js';+import { box } from '/src/geometry.js';++const HALL_WIDTH = 24;+const HALL_DEPTH = 16;+const RACK_ROWS = 6;+const RACKS_PER_ROW = 8;++function placed(center, size) {+ return new Float32Array([size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1]);+}++function hallParts() {+ const material = { color: [0.6, 0.62, 0.65], metallic: 0, roughness: 0.6 };+ const parts = [{ geometry: box(), matrix: placed([0, -0.1, 0], [HALL_WIDTH, 0.2, HALL_DEPTH]), material }];+ for (let row = 0; row < RACK_ROWS; row++) {+ for (let rack = 0; rack < RACKS_PER_ROW; rack++) {+ const x = (rack - (RACKS_PER_ROW - 1) / 2) * 2.6;+ const z = (row - (RACK_ROWS - 1) / 2) * 2.4;+ parts.push({ geometry: box(), matrix: placed([x, 1.1, z], [0.8, 2.2, 1.2]), material });+ }+ }+ return parts;+}++function spread(count, width, depth, height, lightFor) {+ return Array.from({ length: count }, (_, index) => {+ const x = ((index + 0.5) / count - 0.5) * width;+ const z = ((((index * 5) % count) + 0.5) / count - 0.5) * depth;+ return lightFor([x, height, z], index);+ });+}++function environmentFor(pointCount, areaCount, range) {+ return {+ keyIntensity: 0,+ fillIntensity: 0.2,+ ambientIntensity: 0.2,+ pointLights: spread(pointCount, HALL_WIDTH, HALL_DEPTH, 3, position => ({ position, color: [1, 0.9, 0.8], intensity: 6, radius: 0.1, range })),+ areaLights: spread(areaCount, HALL_WIDTH, HALL_DEPTH, 3.4, position => ({ position, direction: [0, -1, 0], width: 3, height: 0.3, color: [0.8, 0.9, 1], intensity: 40 })),+ };+}++const camera = { eye: [0, 1.7, 7.5], target: [0, 1.2, 0], fov: 60 };++async function measureLightCounts({ pointCount, areaCount, range = 0, warmupFrames = 20, measuredFrames = 200 }) {+ const canvas = document.querySelector('canvas');+ const renderer = new Renderer67(canvas, hallParts(), { ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024 });+ renderer.resize();+ const frame = { ...camera, environment: environmentFor(pointCount, areaCount, range), time: 0, exposure: 1, effects: { ambientOcclusion: 0 } };+ // Reading one pixel back is what waits for a hardware GPU to finish the frame.+ const pixel = new Uint8Array(4);+ const finishDrawing = () => renderer.context.readPixels(0, 0, 1, 1, renderer.context.RGBA, renderer.context.UNSIGNED_BYTE, pixel);+ for (let index = 0; index < warmupFrames; index++) {+ renderer.render(frame);+ finishDrawing();+ }+ const frameMilliseconds = [];+ for (let index = 0; index < measuredFrames; index++) {+ const started = performance.now();+ renderer.render(frame);+ finishDrawing();+ frameMilliseconds.push(performance.now() - started);+ }+ const glError = renderer.context.getError();+ const uniformVectors = renderer.context.getParameter(renderer.context.MAX_FRAGMENT_UNIFORM_VECTORS);+ const image = canvas.toDataURL('image/png').split(',')[1];+ renderer.dispose();+ frameMilliseconds.sort((first, second) => first - second);+ return { pointCount, areaCount, range, glError, uniformVectors, image, medianMilliseconds: frameMilliseconds[Math.floor(measuredFrames / 2)] };+}++window.measureLightCounts = measureLightCounts;++function framePixels(renderer, canvas, frame) {+ renderer.render(frame);+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);+ renderer.context.readPixels(0, 0, canvas.width, canvas.height, renderer.context.RGBA, renderer.context.UNSIGNED_BYTE, pixels);+ return pixels;+}++function changedPixelCount(first, second) {+ let changed = 0;+ for (let index = 0; index < first.length; index += 4) {+ const difference = Math.abs(first[index] - second[index]) + Math.abs(first[index + 1] - second[index + 1]) + Math.abs(first[index + 2] - second[index + 2]);+ if (difference > 2) changed++;+ }+ return changed;+}++// Draws the hall with every light, then once more without each light in turn. A light that the shader ignored would leave the+// picture as it was, so each removal has to change some pixels.+async function checkEachLightVisible({ pointCount, areaCount }) {+ const canvas = document.querySelector('canvas');+ const renderer = new Renderer67(canvas, hallParts(), { ground: false, hdr: true, depth: true, samples: 1, pixelRatio: 1, memoryBudgetMiB: 1024 });+ renderer.resize();+ const environment = environmentFor(pointCount, areaCount, 0);+ const frame = { ...camera, environment, time: 0, exposure: 1, effects: { ambientOcclusion: 0 } };+ const everything = framePixels(renderer, canvas, frame);+ const changedPixels = { pointLights: [], areaLights: [] };+ for (const list of ['pointLights', 'areaLights']) {+ for (let index = 0; index < environment[list].length; index++) {+ const without = { ...environment, [list]: environment[list].filter((light, other) => other !== index) };+ changedPixels[list].push(changedPixelCount(everything, framePixels(renderer, canvas, { ...frame, environment: without })));+ }+ }+ const glError = renderer.context.getError();+ renderer.dispose();+ return { glError, changedPixels };+}++window.checkEachLightVisible = checkEachLightVisible;diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 347d4ab3..bbd3eca4 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -6,7 +6,7 @@"agent-scene": 100000},"budgets": {- "entry:core": 87540,+ "entry:core": 87600,"entry:model": 14400,"entry:nature": 13200,"entry:motion": 13600,@@ -34,21 +34,21 @@"entry:ground-bounce": 9460,"entry:path-tracer": 14600,"entry:texture-set": 900,- "entry:agent-scene": 78550,- "entry:agent-scene+lazy": 261000,- "entry:agent-asset": 109920,- "entry:agent-asset+lazy": 272400,+ "entry:agent-scene": 78650,+ "entry:agent-scene+lazy": 261170,+ "entry:agent-asset": 109990,+ "entry:agent-asset+lazy": 272540,"entry:hdri": 3300,"entry:camera-effects": 8600,- "entry:water-reflection": 26540,+ "entry:water-reflection": 26580,"entry:render-passes": 1700,- "entry:material-layer-shaders": 21360,- "entry:light-linking": 19680,- "entry:cascaded-shadows": 28480,- "scene:lit-box": 64890,+ "entry:material-layer-shaders": 21400,+ "entry:light-linking": 19720,+ "entry:cascaded-shadows": 28530,+ "scene:lit-box": 64970,"scene:gltf-box": 86880,"scene:gltf-box+lazy": 90200,- "scene:agent-scene": 106710,- "scene:agent-scene+lazy": 289120+ "scene:agent-scene": 106800,+ "scene:agent-scene+lazy": 289320}}diff --git a/changes/261.md b/changes/261.mdnew file mode 100644index 00000000..bc476ee8--- /dev/null+++ b/changes/261.md@@ -0,0 +1 @@+- Raise the light limits to 16 point lights, 8 spot lights and 7 area lights (issue #261), from 8, 8 and 4. A server hall lit by 12 point and 7 area lights renders with every light visible. On an RTX 3060 at 960x540 each point light adds about 0.04 to 0.05 ms and each area light about 0.04 ms (16 point and 7 area lights: 1.92 ms, none: 1.07 ms; `bench/lighting/frame-time.mjs`). The light bake takes the same limits, the area limit is 7 so that the sun and all lights fit the 32 bit light-linking mask, and `material.lightMask` now defaults to `-1` (every bit) instead of `0x1fffff`.diff --git a/docs/agent-look.md b/docs/agent-look.mdindex 66ec6c47..80167f3d 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -117,7 +117,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac| `fillIntensity` | `0` | `0` to `100` || `ambientIntensity` | `1` | `0` to `100`. Scales the environment light || `daylight` | `1` | `0` to `100` |-| `pointLights` | `[]` | At most eight point light records |+| `pointLights` | `[]` | At most 16 point light records || `skyTop` | `[0.2, 0.38, 0.52]` | Components from `0` to `1` || `skyBottom` | `[0.62, 0.7, 0.67]` | Components from `0` to `1` || `fogColor` | `[0.35, 0.43, 0.43]` | Components from `0` to `1` |@@ -263,7 +263,7 @@ Every object rejects unknown keys.Inputs must contain ordinary plain JSON objects and dense arrays without extra fields or hidden properties.Accessors, executable values, cyclic references, typed arrays, and nonfinite numbers reject.The helpers return independent arrays, including volume defaults.-JSON nesting has a maximum depth of 32, and look arrays have at most eight entries.+JSON nesting has a maximum depth of 32, and look arrays have at most 16 entries.| Design | Benefit | Cost || --- | --- | --- |diff --git a/docs/guide.md b/docs/guide.mdindex e5c28aba..f2f14d2a 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -385,7 +385,7 @@ Outdoor `environment` accepts `skyTop`, `skyBottom` (display RGB), `fogColor` (l## Local lights and volume fogVersion `0.4.0` supports local lighting through the renderer's `environment` option and per-frame environment overrides.-`pointLights` accepts at most eight world-space lights with linear RGB colors.+`pointLights` accepts at most 16 world-space lights with linear RGB colors.`keyIntensity`, `fillIntensity` and `ambientIntensity` control the existing studio lighting.1. Set the environment's lighting controls when creating the renderer.diff --git a/docs/light-bake.md b/docs/light-bake.mdindex 1e2c4564..46192f8b 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -43,7 +43,7 @@ A node that hosts cloth is skipped like a hair host: the cloth simulation replacThe bake traces cosine-weighted paths from each texel through up to `bounces` reflections. Each hit adds its own emission and the direct light it receives from the point lights and the sun, with shadow rays. A texel stores that light times its own albedo. Direct light is not baked: it stays live, so shadows and moving lights keep working. The stored light is only what has bounced at least once, so a scene needs the same lights at run time that it gave the bake.-Spot lights take the cone and soft edge the renderer uses (`angle`, `penumbra`, default 0.15), with `range` and `radius` as for a point light. An area light is a rectangle that emits from its front side only, with the path tracer's `intensity * cosine / distance squared`. A hit is lit by one shadow ray per area light to a point of the rectangle that changes on every call; the sequence is a hash of the call count, so it repeats exactly, and the many paths of a texel average the soft shadow. At most 8 spot and 4 area lights. A scene without spot or area lights bakes the same bytes as before.+Spot lights take the cone and soft edge the renderer uses (`angle`, `penumbra`, default 0.15), with `range` and `radius` as for a point light. An area light is a rectangle that emits from its front side only, with the path tracer's `intensity * cosine / distance squared`. A hit is lit by one shadow ray per area light to a point of the rectangle that changes on every call; the sequence is a hash of the call count, so it repeats exactly, and the many paths of a texel average the soft shadow. At most 8 spot and 7 area lights. A scene without spot or area lights bakes the same bytes as before.Not baked: the environment map (it already lights every surface at run time) and specular reflection. A metal part reflects no baked light. Fresnel and sheen are ignored.@@ -92,7 +92,7 @@ Cost per frame (RTX 3060, `lit-interior`, medians of three alternating rounds of| `maxResolution` | 128 | 4 to 256 | Largest lightmap side for one part. || `maxSeconds` | 60 | 1 to 600 | Wall-clock limit. Passing it throws; a bake never returns a partial result. |-Also checked before any ray is traced: at most 256 parts, 200,000 triangles in total, 8 point lights, 1,000,000 texels and 400 million units of ray work (texels, samples, bounces and lights multiplied). Positions, indices, matrices, colours and lights must be finite and in range, and an error names the field.+Also checked before any ray is traced: at most 256 parts, 200,000 triangles in total, 16 point lights, 1,000,000 texels and 400 million units of ray work (texels, samples, bounces and lights multiplied). Positions, indices, matrices, colours and lights must be finite and in range, and an error names the field.The result is deterministic: the same parts, lights and options give the same bytes, with no `Math.random` and no clock in the output. `report.seconds` is the only value that varies from run to run.diff --git a/docs/lighting.md b/docs/lighting.mdindex b9ca3595..f28e8b8f 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -63,7 +63,7 @@ Limits: the diffuse term uses L2 spherical harmonics, so a very small intense su## Point lights-At most eight lights are supported per frame. Each light supplies `position`. Optional fields default to white `color`, `intensity: 1`, `radius: 0.05` and unlimited `range: 0`.+At most 16 lights are supported per frame. Each light supplies `position`. Optional fields default to white `color`, `intensity: 1`, `radius: 0.05` and unlimited `range: 0`.The light uses inverse-square falloff outside its radius. Doubling distance reduces incoming illumination to one quarter before material response. Intensity follows the candela convention for a point source, but the renderer's existing exposure and environment are not a calibrated photographic pipeline.@@ -83,10 +83,34 @@ A point light casts a shadow only with `castShadow: true` (see [Local shadows](### Area lights-`environment.areaLights` holds at most four rectangles. Each has `position` (the center), `direction` (the side it emits to), `width` and `height` in scene units, and optional `up`, `color` and `intensity`. The width axis is `up x direction`, so a downward panel with `up: [0, 0, 1]` has its width along X. `intensity` is the candela of the whole rectangle seen head on, and the light has Lambert emission, so it fades with the cosine to the side.+`environment.areaLights` holds at most seven rectangles. Each has `position` (the center), `direction` (the side it emits to), `width` and `height` in scene units, and optional `up`, `color` and `intensity`. The width axis is `up x direction`, so a downward panel with `up: [0, 0, 1]` has its width along X. `intensity` is the candela of the whole rectangle seen head on, and the light has Lambert emission, so it fades with the cosine to the side.Method: representative point, not a light-transform lookup table. The closest point of the rectangle to the shaded point stands in for the source, and the light is `intensity * cos(emission) / (d^2 + area / pi)`. The `area / pi` term keeps it finite at the surface and equals a disc source on its axis. Measured against Cycles on a white plane, a Blender area light of W watts matches `W / pi` candela, and this formula is within 1.2 percent on the axis for 1 m and 2 m squares from 0.2 m to 2 m away (measured). Off-axis error and the shape of a specular highlight are not measured: the highlight is a point highlight from the representative point, so a large panel does not give a stretched reflection. Area lights cast no shadow and a rectangle seen from behind gives no light.+## Light counts and frame cost++A frame takes at most 16 point lights, 8 spot lights and 7 area lights, and `agent-look`, the scene capabilities (`maxPointLights`, `maxSpotLights`, `maxAreaLights`) and the light bake use the same numbers. The three limits and the sun share the 32 bits of the light-linking mask, which is why the area limit is 7 and not 8. Every light is added in a loop in the fragment shader, so a frame costs about the same for each light whether or not it reaches a pixel; a `range` lets the loop skip a light that is out of reach.++Measured on an RTX 3060 at 960x540 with 4 samples, a server hall of 49 boxes drawn with the lights spread over the ceiling (`node bench/lighting/frame-time.mjs gpu`, median of 3 runs of 200 frames each, below-normal priority; the machine was shared with other jobs, so read the spread as load). The 32 point light and 8 area light rows come from a run with the limits raised for the measurement:++| Lights | Median frame time |+| --- | --- |+| none | 1.07 ms |+| 8 point | 1.42 ms |+| 16 point | 1.81 ms |+| 32 point | 2.38 ms |+| 4 area | 1.28 ms |+| 7 area | 1.32 ms |+| 8 area | 1.38 ms |+| 12 point and 7 area | 1.88 ms |+| 16 point and 7 area | 1.92 ms |+| 32 point and 8 area | 2.53 ms |+| 32 point with `range: 6` | 1.63 ms |++A point light costs about 0.04 to 0.05 ms and an area light about 0.04 ms at this size, and a software rasterizer (SwiftShader, one run) shows the same order: 134 ms with no lights, 172 ms with 16 point lights and 246 ms with 12 point and 7 area lights. 32 point lights would have cost 2.4 ms and fit the GPU's 1,024 fragment uniform vectors, but they do not fit the mask without dropping spot or area lights, so the limit stays at 16. Point lights are not culled by tile or cluster; that would pay off at hundreds of lights, which the bit mask and the uniform arrays could not hold anyway.++`node bench/lighting/frame-time.mjs gpu --each-light` draws the hall with 12 point and 7 area lights and again without each light in turn; every removal changes the picture (checked on the software rasterizer).+## Local shadows`castShadow: true` on a point or spot light draws that light's depth into one shared atlas of 2048 x 3072 texels: 24 tiles of 512 x 512, a 24 MiB depth texture allocated on first use. A spot light takes one tile with a perspective view of `2 * angle + 4` degrees (170 at most). A point light takes six tiles, one per cube face, each 92 degrees wide. Lights are given tiles in order: point lights, then spot lights. A request for more than 24 tiles, for example five shadowed point lights, throws `RangeError` and changes nothing. So the most is four shadowed point lights, or for example two point lights and eight spot lights.@@ -123,7 +147,7 @@ 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 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.+A part gets a bit mask in `material.lightMask` (bit 0 the sun, bits 1 to 16 the point lights, 17 to 24 the spot lights, 25 to 31 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.diff --git a/docs/parity.md b/docs/parity.mdindex 27648217..61024b5f 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -186,11 +186,11 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Physics > Collision | partial | Rapier collisions with sensors (enter and leave events) and 16 collision layers with masks, in code and recipes. `scene_inspect` reports contacts and resting state. | [physics-colliders](../tests/physics-colliders.test.js) | #61 || Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 || Physics > Simulation Nodes | missing | No node graph. | | #43 |-| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. Reflection probes exist behind `bake.probes` (on by default with a bake; specular only, no parallax; [light-bake](light-bake.md)); no irradiance or box probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |+| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 16 point lights, fog and bloom. Reflection probes exist behind `bake.probes` (on by default with a bake; specular only, no parallax; [light-bake](light-bake.md)); no irradiance or box probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 || Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps (issue #129) and runs about 2.8 times faster per thread, and 3.5 to 3.9 times with the shadow-ray change (inferred from 8,360 to about 30,000 paths per second on the demo room), than at that table, whose scores and seconds predate both (the second table in the reference README has the current ones); it draws them on box-projected materials too, can stop converged pixels on request (`noiseThreshold`, off by default because it costs `spot-area` score, see the reference README), and finishes a 1920 by 1080 still of a 181,708 triangle room at 64 samples in 246 s on 8 threads with `noiseThreshold` 0.03 (about 8 to 9 minutes with every sample, inferred) under a job limit now 600 s; it does not trace volume fog, translucent leaves, occlusion or emissive maps, and it is not Cycles parity. The darker floor was the diffuse layer losing light at grazing angles, fixed in issue #215, which also added light linking: at 64 samples against Cycles `outdoor-hdri` is 0.0226, `character` 0.0287 and `light-linking` 0.0213, and the current scores of every scene are in `bench/reference/path-tracer.json`. `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 and standard presets, with fine the same as standard, shrunk deterministically to a path step budget of 5 million, then by bounces, so a preset bakes even a large hall; 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 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 Objects | partial | One directional light with a shadow, 16 point lights, 8 spot lights and 7 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 (issue #215) and the light bake honour it, and recipes reach it through `affects` and `environment.keyAffects` (`lightLinking` in `scene_capabilities`). 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, summed over six tasks and 0 to 3 each: 0 before, 6 with the floor and 7 after a lone flat object (a gear) stopped being read as a floor; the front and side cameras see it edge-on, so only the three-quarter view shows it. A blind pairwise Sonnet judge (`default-judge.mjs`, six cold recipes, two cameras, 18 calls) prefers the floor to none 18 of 18 (p 0.0000076) and the darker floor now used (0.22) to the first one (0.6) 18 of 18; its control, one image against itself, picks the first 17 of 18. | [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/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 46ce1889..bc8f6552 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -65,7 +65,7 @@ An outdoor renderer receives `world: true`, `ground: false` and the scene enviroThe environment provides `fogColor`, `fogDensity`, `skyTop`, `skyBottom`, `lightDirection` and optional `daylight`.The sky colors are display RGB. Fog colors are linear RGB.-Local `environment.pointLights` support eight world-space sources with inverse-square falloff.+Local `environment.pointLights` support 16 world-space sources with inverse-square falloff.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.diff --git a/src/agent-look.js b/src/agent-look.jsindex 26489943..e5c693df 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -6,6 +6,9 @@ import { resolveLiquidOptics } from './renderer.js';import { createLightingSetupMap, lightingSetupFields } from './lighting-setups.js';import { DEFAULT_LIGHTING_SETUP, LIGHTING_SETUP_NAMES, DEFAULT_AMBIENT_OCCLUSION } from './agent-scene-capabilities.js';+// The longest list in a look is the longest light list.+const MAX_LOOK_ARRAY_ENTRIES = Math.max(MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS);+const ENVIRONMENT_FIELDS = ['world', 'ground', 'setup', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity','daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections',@@ -84,8 +87,8 @@ function copiedJson(input, depth = 0, ancestors = new Set()) {throw new TypeError('Look must contain acyclic plain JSON data.');}const array = Array.isArray(input);- if (array && (Object.getPrototypeOf(input) !== Array.prototype || input.length > MAX_POINT_LIGHTS)) {- throw new TypeError(`Look JSON arrays must be ordinary arrays with at most ${MAX_POINT_LIGHTS} entries.`);+ if (array && (Object.getPrototypeOf(input) !== Array.prototype || input.length > MAX_LOOK_ARRAY_ENTRIES)) {+ throw new TypeError(`Look JSON arrays must be ordinary arrays with at most ${MAX_LOOK_ARRAY_ENTRIES} entries.`);}if (!array) {plainObject(input, 'Look');diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 8eae4128..fc01c092 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -1,3 +1,4 @@+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';import {MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES,FIELD_OPERATOR_NAMES, FIELD_ATTRIBUTES, MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES,@@ -197,12 +198,12 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({rejects: 'On a skinned or morphed part an edit farther than maxTransferFraction of the part bounds diagonal from the original surface; booleans on open parts (fill_holes first).',}),fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,- authoredLook: true, maxPointLights: 8,+ authoredLook: true, maxPointLights: MAX_POINT_LIGHTS,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. Recipes reach light linking and cascaded sun shadows through lightLinking and shadowCascades below.- maxSpotLights: 8, maxAreaLights: 4,+ maxSpotLights: MAX_SPOT_LIGHTS, maxAreaLights: MAX_AREA_LIGHTS,localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),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' }),@@ -253,7 +254,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({fields: 'preset, or samples (1-256), bounces (1-3), texelsPerUnit (1-12) over it; probes room by default, false for none, or up to 4 {position, radius?}. Same recipe, same bytes.',presets: BAKE_PRESETS,notes: 'Bounced light from point, spot, area and key lights. Reruns when parts, lights, materials or bake change. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit, never refuses (bake.used, bake.reduction); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular. Probes: specular only, none in glTF.',- limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: 8 }),+ limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: MAX_POINT_LIGHTS }),}),motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),});diff --git a/src/light-bake.js b/src/light-bake.jsindex fa668d85..d6c56417 100644--- a/src/light-bake.js+++ b/src/light-bake.js@@ -1,3 +1,4 @@+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';import { buildTriangleBvh } from './triangle-bvh.js';import { readTriangle } from './triangle-math.js';import { createTracer, pointLightFalloff } from './ray-query.js';@@ -23,9 +24,9 @@ export const MAX_BAKE_RAY_WORK = 400_000_000;export const MAX_BAKE_TEXELS = 1_000_000;export const MAX_BAKE_TRIANGLES = 200_000;export const MAX_BAKE_PARTS = 256;-export const MAX_BAKE_POINT_LIGHTS = 8;-export const MAX_BAKE_SPOT_LIGHTS = 8;-export const MAX_BAKE_AREA_LIGHTS = 4;+export const MAX_BAKE_POINT_LIGHTS = MAX_POINT_LIGHTS;+export const MAX_BAKE_SPOT_LIGHTS = MAX_SPOT_LIGHTS;+export const MAX_BAKE_AREA_LIGHTS = MAX_AREA_LIGHTS;// A part that sees at least this share of the sky keeps its live sky light as it is.const SKY_VISIBLE_ENOUGH = 0.98;// The renderer's own soft edge for a spot light that gives none.diff --git a/src/light-limits.js b/src/light-limits.jsnew file mode 100644index 00000000..cdf25075--- /dev/null+++ b/src/light-limits.js@@ -0,0 +1,5 @@+// How many lights of each kind one frame takes. Light linking keeps one mask bit for the sun and one for each of these+// lights in a 32 bit integer, so the three limits and the sun together must fit in 32 bits.+export const MAX_POINT_LIGHTS = 16;+export const MAX_SPOT_LIGHTS = 8;+export const MAX_AREA_LIGHTS = 7;diff --git a/src/light-link-bits.js b/src/light-link-bits.jsindex cc6025bd..7a82d0b0 100644--- a/src/light-link-bits.js+++ b/src/light-link-bits.js@@ -1,6 +1,8 @@+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from './light-limits.js';+// Which bit of a part's `material.lightMask` belongs to which light, in the order of the environment lists. Kept apart// from the shader code in light-linking.js so the path tracer can read the masks without pulling in the shaders.export const SUN_BIT = 0;export const POINT_FIRST_BIT = 1;-export const SPOT_FIRST_BIT = 9;-export const AREA_FIRST_BIT = 17;+export const SPOT_FIRST_BIT = POINT_FIRST_BIT + MAX_POINT_LIGHTS;+export const AREA_FIRST_BIT = SPOT_FIRST_BIT + MAX_SPOT_LIGHTS;diff --git a/src/light-linking.js b/src/light-linking.jsindex 58ae8def..1c8bec7d 100644--- a/src/light-linking.js+++ b/src/light-linking.js@@ -5,7 +5,7 @@ import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from './ligh// Light linking: a light can be limited to the parts it lights, as Blender's receiver collection does. A part carries// a bit mask in `material.lightMask`; the shader skips a light whose bit is clear. The code lives here, not in the// 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,+// Bit 0 is the sun, then one bit for each point light, spot light and area light up to the limits in light-limits.js,// 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 honour it too.// The GLSL has no comments, because comments ship to every page.@@ -19,9 +19,9 @@ bool lightLinked(int bit) {}`,linkSun: ' * float(lightLinked(0))',- linkPoint: ' if (!lightLinked(1 + index)) continue;\n',- linkSpot: ' if (!lightLinked(9 + index)) continue;\n',- linkArea: ' if (!lightLinked(17 + index)) continue;\n',+ linkPoint: ` if (!lightLinked(${POINT_FIRST_BIT} + index)) continue;\n`,+ linkSpot: ` if (!lightLinked(${SPOT_FIRST_BIT} + index)) continue;\n`,+ linkArea: ` if (!lightLinked(${AREA_FIRST_BIT} + index)) continue;\n`,});const LIGHT_LISTS = [['pointLights', POINT_FIRST_BIT], ['spotLights', SPOT_FIRST_BIT], ['areaLights', AREA_FIRST_BIT]];diff --git a/src/lighting.js b/src/lighting.jsindex 2acb6a32..56b6fde8 100644--- a/src/lighting.js+++ b/src/lighting.js@@ -1,6 +1,6 @@-export const MAX_POINT_LIGHTS = 8;-export const MAX_SPOT_LIGHTS = 8;-export const MAX_AREA_LIGHTS = 4;+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';++export { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS };// One 2048 x 3072 depth atlas holds 24 tiles of 512 x 512 (24 MiB). A shadowed spot light uses one tile and a shadowed point// light uses six, one for each cube face.export const SHADOW_ATLAS_TILES = 24;diff --git a/src/material-layers.js b/src/material-layers.jsindex e9b85613..5fdd495f 100644--- a/src/material-layers.js+++ b/src/material-layers.js@@ -2,9 +2,8 @@// This module holds plain data only, so the MCP server, recipes, the glTF code and the renderer share one set of ranges.const UNIT = Object.freeze([0, 1]);--// Bit 0 is the sun, bits 1 to 8 the point lights, 9 to 16 the spot lights and 17 to 20 the area lights (light-linking.js).-export const ALL_LIGHTS_MASK = 0x1fffff;+// Bit 0 is the sun, then the point, spot and area lights in that order (light-link-bits.js). Every bit of the 32 bit integer is set.+export const ALL_LIGHTS_MASK = -1;export const MATERIAL_LAYER_DEFAULTS = Object.freeze({clearcoat: 0,diff --git a/src/shaders.js b/src/shaders.jsindex 9677b3d0..5ef1c55d 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -1,4 +1,5 @@import { MAX_MORPH_TARGETS } from './morph.js';+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';import { environmentLookupGlsl, environmentShadingGlsl } from './environment.js';import { splatGlsl } from './splat-shader.js';@@ -384,20 +385,20 @@ uniform float time;uniform float daylight;uniform vec3 lightDirection;uniform int pointLightCount;-uniform vec4 pointLightPositions[8];-uniform vec4 pointLightColors[8];-uniform float pointLightRadii[8];-uniform float pointLightShadowTiles[8];+uniform vec4 pointLightPositions[${MAX_POINT_LIGHTS}];+uniform vec4 pointLightColors[${MAX_POINT_LIGHTS}];+uniform float pointLightRadii[${MAX_POINT_LIGHTS}];+uniform float pointLightShadowTiles[${MAX_POINT_LIGHTS}];uniform int spotLightCount;-uniform vec4 spotLightPositions[8];-uniform vec4 spotLightColors[8];-uniform vec4 spotLightDirections[8];-uniform vec4 spotLightParameters[8];+uniform vec4 spotLightPositions[${MAX_SPOT_LIGHTS}];+uniform vec4 spotLightColors[${MAX_SPOT_LIGHTS}];+uniform vec4 spotLightDirections[${MAX_SPOT_LIGHTS}];+uniform vec4 spotLightParameters[${MAX_SPOT_LIGHTS}];uniform int areaLightCount;-uniform vec4 areaLightPositions[4];-uniform vec4 areaLightColors[4];-uniform vec4 areaLightNormals[4];-uniform vec4 areaLightTangents[4];+uniform vec4 areaLightPositions[${MAX_AREA_LIGHTS}];+uniform vec4 areaLightColors[${MAX_AREA_LIGHTS}];+uniform vec4 areaLightNormals[${MAX_AREA_LIGHTS}];+uniform vec4 areaLightTangents[${MAX_AREA_LIGHTS}];uniform sampler2D localShadowAtlas;uniform mat4 localShadowMatrices[24];uniform float localShadowTexelAngles[24];@@ -825,7 +826,7 @@ ${featureCode("mainSetup")} if (ENVIRONMENT_ENABLED && !LIGHT_SHADING) {radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity * mix(1.0, vertexSkyVisibility, worldMode), color, metallic, roughness);}- for (int index = 0; index < 8; index++) {+ for (int index = 0; index < ${MAX_POINT_LIGHTS}; index++) {if (index >= pointLightCount) break;vec3 offset = pointLightPositions[index].xyz - worldPosition;float distanceSquared = dot(offset, offset);@@ -840,7 +841,7 @@ ${featureCode("linkPoint")} vec3 lightRadiance = pointLightColors[index].rgbradiance += illuminate(normal, viewDirection, offset * inversesqrt(distanceSquared), lightRadiance, color, metallic, roughness);}if (USES_SPOT_LIGHTS) {- for (int index = 0; index < 8; index++) {+ for (int index = 0; index < ${MAX_SPOT_LIGHTS}; index++) {if (index >= spotLightCount) break;vec3 offset = spotLightPositions[index].xyz - worldPosition;float distanceSquared = dot(offset, offset);@@ -859,7 +860,7 @@ ${featureCode("linkSpot")} vec3 lightRadiance = spotLightColors[index].rgb}}if (USES_AREA_LIGHTS) {- for (int index = 0; index < 4; index++) {+ for (int index = 0; index < ${MAX_AREA_LIGHTS}; index++) {if (index >= areaLightCount) break;${featureCode("linkArea")} vec3 lightNormal = areaLightNormals[index].xyz;vec3 widthAxis = areaLightTangents[index].xyz;diff --git a/tests/agent-look.test.js b/tests/agent-look.test.jsindex c6a1323c..bbe8954b 100644--- a/tests/agent-look.test.js+++ b/tests/agent-look.test.js@@ -2,7 +2,7 @@ import test from 'node:test';import assert from 'node:assert/strict';import { mat4 } from 'gl-matrix';import { normalizeAgentLook, resolveAgentShadow } from '../src/agent-look.js';-import { createLightingState, updateLightingState } from '../src/lighting.js';+import { createLightingState, updateLightingState, MAX_POINT_LIGHTS } from '../src/lighting.js';import { resolveVolumeFog } from '../src/volumetric.js';test('default look is complete, detached JSON and idempotent', () => {@@ -127,12 +127,12 @@ test('malformed JSON, getters, sparse arrays and executable values reject withou});test('lighting ranges include zero intensity and unlimited point range while rejecting invalid edge values', () => {- const lights = Array.from({ length: 8 }, (_, index) => ({ position: [index, 0, 0], intensity: 0, range: 0 }));+ const lights = Array.from({ length: MAX_POINT_LIGHTS }, (_, index) => ({ position: [index, 0, 0], intensity: 0, range: 0 }));const look = normalizeAgentLook({ environment: { pointLights: lights, keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, daylight: 0, fogDensity: 0 } });- assert.equal(look.environment.pointLights.length, 8);+ assert.equal(look.environment.pointLights.length, MAX_POINT_LIGHTS);assert.equal(look.environment.keyIntensity, 0);assert.deepEqual(normalizeAgentLook({ environment: { pointLights: [] } }).environment.pointLights, []);- assert.throws(() => normalizeAgentLook({ environment: { pointLights: [...lights, lights[0]] } }), /8/);+ assert.throws(() => normalizeAgentLook({ environment: { pointLights: [...lights, lights[0]] } }), new RegExp(String(MAX_POINT_LIGHTS)));const invalid = [{ pointLights: [{ position: [0, 0, 0], range: 0.0001 }] },{ pointLights: [{ position: [0, 0, 0], radius: 0 }] },diff --git a/tests/light-bake.test.js b/tests/light-bake.test.jsindex baa7df27..a9995782 100644--- a/tests/light-bake.test.js+++ b/tests/light-bake.test.js@@ -2,7 +2,7 @@ import test from 'node:test';import assert from 'node:assert/strict';import { box } from '../src/geometry.js';import { exportGlb } from '../src/export.js';-import { BAKE_LIMITS, MAX_BAKE_POINT_LIGHTS, bakeLightmaps, normalizeBakeOptions } from '../src/light-bake.js';+import { BAKE_LIMITS, MAX_BAKE_POINT_LIGHTS, MAX_BAKE_SPOT_LIGHTS, MAX_BAKE_AREA_LIGHTS, bakeLightmaps, normalizeBakeOptions } from '../src/light-bake.js';const cube = box(0, 1);@@ -153,10 +153,10 @@ test('hostile spot and area lights are refused before any ray is traced', () =>[{ spotLights: [{ ...spot, direction: [0, 0, 0] }] }, /spot light 0.*direction/],[{ spotLights: [{ ...spot, position: [0, Number.NaN, 0] }] }, /spot light 0/],[{ spotLights: [{ ...spot, angle: 4 }] }, /spot light 0.*angle/],- [{ spotLights: Array(9).fill(spot) }, /at most 8 spot lights/],+ [{ spotLights: Array(MAX_BAKE_SPOT_LIGHTS + 1).fill(spot) }, new RegExp(`at most ${MAX_BAKE_SPOT_LIGHTS} spot lights`)],[{ areaLights: [{ ...area, width: -1 }] }, /area light 0.*width/],[{ areaLights: [{ ...area, intensity: Infinity }] }, /area light 0/],- [{ areaLights: Array(5).fill(area) }, /at most 4 area lights/],+ [{ areaLights: Array(MAX_BAKE_AREA_LIGHTS + 1).fill(area) }, new RegExp(`at most ${MAX_BAKE_AREA_LIGHTS} area lights`)],];for (const [lights, message] of refused) {assert.throws(() => bakeLightmaps(smallRoom(), { ...lamp, ...lights }, fastOptions), message);@@ -188,7 +188,7 @@ test('hostile parts and lights are refused before any ray is traced', () => {assert.throws(() => bakeLightmaps([], lamp, fastOptions), /from 1 to/);assert.throws(() => bakeLightmaps(null, lamp, fastOptions), /from 1 to/);const tooManyLights = { pointLights: Array.from({ length: MAX_BAKE_POINT_LIGHTS + 1 }, () => lamp.pointLights[0]) };- assert.throws(() => bakeLightmaps(smallRoom(), tooManyLights, fastOptions), /at most 8 point lights/);+ assert.throws(() => bakeLightmaps(smallRoom(), tooManyLights, fastOptions), new RegExp(`at most ${MAX_BAKE_POINT_LIGHTS} point lights`));for (const light of [{ position: [Number.NaN, 0, 0], intensity: 1 }, { position: [0, 0, 0], intensity: -1 }, { position: [0, 0, 0], intensity: Infinity }, { position: [0, 0], intensity: 1 }, { position: [0, 0, 0], intensity: 1, range: -2 }]) {assert.throws(() => bakeLightmaps(smallRoom(), { pointLights: [light] }, fastOptions), RangeError);}diff --git a/tests/light-linking.test.js b/tests/light-linking.test.jsindex 8aa8648a..7146290e 100644--- a/tests/light-linking.test.js+++ b/tests/light-linking.test.js@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';import test from 'node:test';import { createFragmentShader } from '../src/shaders.js';import { ALL_LIGHTS_MASK, materialLayerState } from '../src/material-layers.js';+import { MAX_AREA_LIGHTS } from '../src/light-limits.js';import { applyLightLinks, lightMaskFor, AREA_FIRST_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, SUN_BIT } from '../src/light-linking.js';function part(name) {@@ -50,12 +51,12 @@ test('lightMaskFor treats a null list as every part', () => {test('the layer state carries the mask and defaults to every light', () => {assert.equal(materialLayerState({}).at(-1), ALL_LIGHTS_MASK);assert.equal(materialLayerState({ lightMask: 5 }).at(-1), 5);- assert.equal(ALL_LIGHTS_MASK, (1 << (AREA_FIRST_BIT + 4)) - 1);+ assert.equal(AREA_FIRST_BIT + MAX_AREA_LIGHTS, 32);});test('the mask test compiles in only with the feature', () => {const linked = createFragmentShader(['lightLinking']);- for (const statement of ['lightLinked(1 + index)', 'lightLinked(9 + index)', 'lightLinked(17 + index)', 'float(lightLinked(0))']) {+ for (const statement of [`lightLinked(${POINT_FIRST_BIT} + index)`, `lightLinked(${SPOT_FIRST_BIT} + index)`, `lightLinked(${AREA_FIRST_BIT} + index)`, 'float(lightLinked(0))']) {assert.ok(linked.includes(statement), statement);}const plain = createFragmentShader([]);diff --git a/tests/lighting.test.js b/tests/lighting.test.jsindex 05f9c54a..deeade08 100644--- a/tests/lighting.test.js+++ b/tests/lighting.test.js@@ -1,6 +1,6 @@import test from 'node:test';import assert from 'node:assert/strict';-import { createLightingState, updateLightingState } from '../src/lighting.js';+import { createLightingState, updateLightingState, MAX_POINT_LIGHTS, MAX_AREA_LIGHTS } from '../src/lighting.js';test('lighting preserves legacy key defaults and independently controls direct fill and ambient light', () => {const state = createLightingState();@@ -51,7 +51,7 @@ test('malformed later lights reject atomically before replacing any retained ligassert.throws(() => updateLightingState(state, { pointLights: [light, malformed], fillIntensity: 0 }));assert.deepEqual(state, snapshot);}- assert.throws(() => updateLightingState(state, { pointLights: Array(9).fill(light) }), /at most/);+ assert.throws(() => updateLightingState(state, { pointLights: Array(MAX_POINT_LIGHTS + 1).fill(light) }), /at most/);assert.throws(() => updateLightingState(state, { keyIntensity: -1 }));assert.throws(() => updateLightingState(state, { ambientIntensity: Infinity }));assert.deepEqual(state, snapshot);@@ -107,10 +107,23 @@ test('area lights store a unit normal and a width axis perpendicular to it', ()assert.equal(state.areaColors[3], 5);});+test('twelve point lights and seven area lights fill the uniform arrays', () => {+ const state = createLightingState();+ const pointLights = Array.from({ length: 12 }, (_, index) => ({ position: [index, 1, 0], intensity: index + 1 }));+ const areaLights = Array.from({ length: 7 }, (_, index) => ({ position: [index, 3, 0], direction: [0, -1, 0], width: 1, height: 1, intensity: index + 1 }));+ updateLightingState(state, { pointLights, areaLights });+ assert.equal(state.pointCount, 12);+ assert.equal(state.areaCount, 7);+ assert.equal(state.colors[11 * 4 + 3], 12);+ assert.equal(state.areaColors[6 * 4 + 3], 7);+ assert.equal(state.positions.length, MAX_POINT_LIGHTS * 4);+ assert.equal(state.areaPositions.length, MAX_AREA_LIGHTS * 4);+});+test('malformed spot and area lights are rejected', () => {const state = createLightingState();assert.throws(() => updateLightingState(state, { spotLights: [{ position: [0, 0, 0], direction: [0, 0, 0] }] }), /zero length/);assert.throws(() => updateLightingState(state, { spotLights: [{ position: [0, 0, 0], direction: [0, -1, 0], angle: 2 }] }), /angle/);assert.throws(() => updateLightingState(state, { areaLights: [{ position: [0, 0, 0], direction: [0, -1, 0], width: 0, height: 1 }] }), /width/);- assert.throws(() => updateLightingState(state, { areaLights: new Array(5).fill({ position: [0, 0, 0], direction: [0, -1, 0], width: 1, height: 1 }) }), /at most 4/);+ assert.throws(() => updateLightingState(state, { areaLights: new Array(MAX_AREA_LIGHTS + 1).fill({ position: [0, 0, 0], direction: [0, -1, 0], width: 1, height: 1 }) }), new RegExp(`at most ${MAX_AREA_LIGHTS}`));});diff --git a/tests/path-tracer-light-linking.test.js b/tests/path-tracer-light-linking.test.jsindex 538dafab..284777ff 100644--- a/tests/path-tracer-light-linking.test.js+++ b/tests/path-tracer-light-linking.test.js@@ -4,7 +4,7 @@ import test from 'node:test';import { box, sphere } from '../src/geometry.js';import { createEnvironmentMap } from '../src/environment.js';-import { SUN_BIT, POINT_FIRST_BIT } from '../src/light-link-bits.js';+import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from '../src/light-link-bits.js';import { describeIgnoredFeatures, renderPathTracedImage } from '../src/path-tracer.js';function placed(translation, scale) {@@ -15,7 +15,7 @@ function surface(color, extra = {}) {return { tag: 'surface', metallic: 0, roughness: 0.5, emission: 0, color, ...extra };}-const EVERY_BIT = 0x1fffff;+const EVERY_BIT = -1;const without = (...bits) => bits.reduce((mask, bit) => mask & ~(1 << bit), EVERY_BIT);// A scene with no linking at all. Its pixels were hashed on the code before the path tracer read light masks, so a@@ -90,7 +90,7 @@ test('a spot light and an area light honour their bits too', async () => {areaLights: [{ position: [100, 3, 0], direction: [0, -1, 0], width: 1, height: 1, color: [1, 1, 1], intensity: 8 }],};assert.ok(await centreOf(twoFloors(EVERY_BIT, environment).parts, environment, 100) > 0.05);- assert.equal(await centreOf(twoFloors(without(9, 17), environment).parts, environment, 100), 0);+ assert.equal(await centreOf(twoFloors(without(SPOT_FIRST_BIT, AREA_FIRST_BIT), environment).parts, environment, 100), 0);});test('the path tracer no longer names light linking as ignored', () => {