Skip to content

3D engine that AI agents drive

Shrink an oversized explicit bake to fit instead of failing (#1218)

Nguyen Xuan Anc2ac490df7e8
diff --git a/changes/1218.md b/changes/1218.md
new file mode 100644
index 00000000..c1bd3f72
--- /dev/null
+++ b/changes/1218.md
@@ -0,0 +1 @@
+- A light bake whose explicit `samples`, `bounces` and `texelsPerUnit` are over the 24 million path step limit now shrinks to fit it, as a preset does, and reports what ran in `bake.used` and `bake.reduction`, instead of failing; a scene too large even at the lowest settings is refused with the texels or path steps it needs. A test pins that every `bake.irradianceGrid` node count the recipe accepts fits the node cap.
diff --git a/docs/light-bake.md b/docs/light-bake.md
index 209c6c5e..0959afe0 100644
--- a/docs/light-bake.md
+++ b/docs/light-bake.md
@@ -28,14 +28,14 @@ const renderer = new CrucibleRenderer(canvas, bakedParts, rendererOptions);
| `standard` (default) | 128 | 2 | 6 |
| `fine` | 192 | 2 | 7 |
-Ranges are 1 to 256 samples, 1 to 8 bounces and 1 to 12 texels per unit. The bake lights the rest pose with the recipe's point lights and key light (key colour times `keyIntensity`). It runs when the scene builds and again only when a part, its matrix, a light, a material or the bake fields change: camera edits, effects edits, motion seeks and renders reuse the result. A bake that passes its time limit fails the edit and leaves the scene as it was. A rebake that cannot run at all because of a size limit (over the part cap, 24 million path steps for explicit settings, or the irradiance grid and probe part cap of 256, which trace on the CPU) does not fail a `scene_apply` on a scene that already exists: the edit stays applied, the old bake is dropped (it no longer fits the edited parts), the scene is drawn without baked light, and the answer carries a `bake-skipped` diagnostic with the reason and how to fit (fewer parts, lower `samples` or `texelsPerUnit`). The next edit tries again, and a `set-bake` that fits bakes. `scene_create` with a bake that cannot run still fails. The limit is 90 s when the bake runs on a worker (the MCP preview does this, so it blocks nothing) and 20 s on the page's own thread when there is no Worker. The preview's call deadline grows by the 90 s for a `scene_create` whose recipe has a `bake` and for a `scene_apply` with `set-bake`; other calls keep 30 s. A `scene_apply` also gets it whenever the active scene already has a bake, because an ordinary edit such as moving a part rebakes. The same recipe gives the same lightmap bytes. `scene_inspect` returns `bake`: the resolved fields, `used` (the samples, bounces and texelsPerUnit that were traced), `reduced`, `texels`, `rayWork`, `seconds` (of the run that made the lightmaps), `bakedParts`, `skipped` (name and reason), `reused`, and, while the recipe has `environment.localVolumes`, `skippedLocalVolumes` (index, shape, emissive) and `warnings`: the bake leaves volumes out, read from the recipe on every call, so adding or clearing one updates them without a rebake.
+Ranges are 1 to 256 samples, 1 to 8 bounces and 1 to 12 texels per unit. The bake lights the rest pose with the recipe's point lights and key light (key colour times `keyIntensity`). It runs when the scene builds and again only when a part, its matrix, a light, a material or the bake fields change: camera edits, effects edits, motion seeks and renders reuse the result. A bake that passes its time limit fails the edit and leaves the scene as it was. A rebake that cannot run at all because of a size limit (over the part cap, more texels than the bake takes even at the lowest settings, or the irradiance grid and probe part cap of 256, which trace on the CPU) does not fail a `scene_apply` on a scene that already exists: the edit stays applied, the old bake is dropped (it no longer fits the edited parts), the scene is drawn without baked light, and the answer carries a `bake-skipped` diagnostic with the reason and how to fit (fewer parts, lower `samples` or `texelsPerUnit`). The next edit tries again, and a `set-bake` that fits bakes. `scene_create` with a bake that cannot run still fails. The limit is 90 s when the bake runs on a worker (the MCP preview does this, so it blocks nothing) and 20 s on the page's own thread when there is no Worker. The preview's call deadline grows by the 90 s for a `scene_create` whose recipe has a `bake` and for a `scene_apply` with `set-bake`; other calls keep 30 s. A `scene_apply` also gets it whenever the active scene already has a bake, because an ordinary edit such as moving a part rebakes. The same recipe gives the same lightmap bytes. `scene_inspect` returns `bake`: the resolved fields, `used` (the samples, bounces and texelsPerUnit that were traced), `reduced`, `texels`, `rayWork`, `seconds` (of the run that made the lightmaps), `bakedParts`, `skipped` (name and reason), `reused`, and, while the recipe has `environment.localVolumes`, `skippedLocalVolumes` (index, shape, emissive) and `warnings`: the bake leaves volumes out, read from the recipe on every call, so adding or clearing one updates them without a rebake.
### Work budget
The unwrap gives the texel count before any ray is traced, so the work of a bake is plain arithmetic: path steps, texels x samples x bounces. It reads no clock and does not depend on machine speed, and the same recipe always resolves to the same numbers. Measured on this machine, a path step costs about 1.8 to 3.1 microseconds, in a closed 56 part room and in the 57 node demo room alike (the number of lights did not change it, so it is not counted).
- A preset (all three fields equal to `draft` or `standard`; `fine` has the same numbers as `standard`) is scaled down until it fits 5 million path steps: samples by a fifth and texelsPerUnit by a tenth, repeatedly (samples not below 16, texelsPerUnit not below 1). A hall that still does not fit at that floor gives up one bounce and starts again from the preset, down to one bounce, so a preset bakes any scene the explicit limit allows. That is 9 to 16 s of tracing on an idle machine, under the 20 s inline limit, and a busy machine still finishes inside the 90 s worker limit. `bake.used` shows the result, `bake.reduced` is `true` and `bake.reduction` says what was asked, what ran and how to ask for more (explicit settings). The demo room at `standard` runs at about 64 samples instead of 16 and 2.32 before. A scene that cannot fit even 16 samples, 1 bounce and texelsPerUnit 1 fails with a message to remove parts or lights.
-- Explicit `samples`, `bounces` or `texelsPerUnit` (any combination that is not exactly a preset) are never reduced. They are limited by a hard bound of 24 million path steps (about 5 times the demo room at samples 96, bounces 2, texelsPerUnit 3, which bakes in 11 to 17 s), and by the real time limit (90 s on a worker, 20 s inline). Over the bound they fail before any ray is traced and the message names what fits, for example "samples 120 or fewer with texelsPerUnit 12, or texelsPerUnit 8.61 or less with samples 256". Under the bound they run, and one that passes its limit fails with "The scene is unchanged. Try samples 128, or texelsPerUnit 3.5." (half of what was asked); the clock decides only that failure, never what is traced.
+- Explicit `samples`, `bounces` or `texelsPerUnit` (any combination that is not exactly a preset) that fit a hard bound of 24 million path steps are never reduced (the bound is about 5 times the demo room at samples 96, bounces 2, texelsPerUnit 3, which bakes in 11 to 17 s). They are limited by that bound and by the real time limit (90 s on a worker, 20 s inline); a bake that passes its time limit fails with "The scene is unchanged. Try samples 128, or texelsPerUnit 3.5." (half of what was asked), and the clock decides only that failure, never what is traced. Over the bound they are scaled down the way a preset is (samples by a fifth and texel density by a tenth, repeatedly, then one bounce at a time) until they fit it, so a house-sized scene gets some baked light instead of none; `bake.used` shows what ran, `bake.reduced` is `true` and `bake.reduction` says what was asked and what ran. {since 0.22.0} Before, such a bake failed before any ray was traced. The scene is refused only when it cannot fit at the floor (16 samples or what was asked if lower, 1 bounce, texelsPerUnit 1): the message says how many texels it needs against the 1,000,000 a bake takes, or the path steps against the bound, and asks for fewer parts or lights. Measured on the 56-part test room asked for 256 samples, 3 bounces and texelsPerUnit 12 (2026-11-18): 86.5 million path steps before and a refusal; now samples 83, texelsPerUnit 7.09, 17.7 million path steps, 56 of 56 parts baked in 10.6 s.
A node that hosts cloth is skipped like a hair host: the cloth simulation replaces its geometry every frame, so a lightmap built on the rest geometry would not follow it (and the renderer refuses a light map on geometry without `lightUvs`, which failed every frame after t=0). Baked parts read every other material field live, so motion tracks on colour still work; the lightmap itself is fixed at the rest pose.
diff --git a/src/agent-bake.js b/src/agent-bake.js
index f9a36d18..4c8a87d3 100644
--- a/src/agent-bake.js
+++ b/src/agent-bake.js
@@ -1,5 +1,5 @@
import { invalidField } from './field-error.js';
-import { planLightmaps, estimateBake, traceLightmaps } from './light-bake.js';
+import { planLightmaps, estimateBake, traceLightmaps, MAX_BAKE_TEXELS } from './light-bake.js';
import { runKernel } from './kernel-offload.js';
import { motionEnvironment } from './agent-motion.js';
import { normalizeProbeList, traceProbes } from './probe-trace.js';
@@ -172,87 +172,74 @@ function isPreset(settings) {
// Path steps in total: texels x samples x bounces. Measured, a path costs about the same in a closed room and in an
// open one whatever the number of lights, so this tracks the time of a bake better than a count of rays does.
+// More texels than the bake takes at all counts as infinite work, so the shrinking lowers texelsPerUnit until they fit too.
function pathWorkOf(plan, settings) {
- return estimateBake(plan, settings).texels * settings.samples * settings.bounces;
+ const { texels } = estimateBake(plan, settings);
+ return texels > MAX_BAKE_TEXELS ? Infinity : texels * settings.samples * settings.bounces;
}
-// The densest texelsPerUnit, to two decimals, that still fits the explicit limit at the given samples and bounces (0 when none does).
-function largestFittingTexelsPerUnit(plan, settings) {
- let fitting = 0;
- let tooMuch = settings.texelsPerUnit;
- for (let step = 0; step < 12; step++) {
- const middle = Math.floor((fitting + tooMuch) / 2 * 100) / 100;
- if (middle <= fitting) {
- break;
- }
- if (pathWorkOf(plan, { ...settings, texelsPerUnit: middle }) <= BAKE_EXPLICIT_PATH_WORK_LIMIT) {
- fitting = middle;
- } else {
- tooMuch = middle;
- }
- }
- return fitting >= BAKE_RANGES.texelsPerUnit[0] ? fitting : 0;
-}
-
-function overLimitMessage(plan, settings, pathWork) {
- const fittingSamples = Math.floor(BAKE_EXPLICIT_PATH_WORK_LIMIT * settings.samples / pathWork);
- const fittingTexelsPerUnit = largestFittingTexelsPerUnit(plan, settings);
- const choices = [];
- if (fittingSamples >= BAKE_RANGES.samples[0]) {
- choices.push(`samples ${fittingSamples} or fewer with texelsPerUnit ${settings.texelsPerUnit}`);
- }
- if (fittingTexelsPerUnit > 0) {
- choices.push(`texelsPerUnit ${fittingTexelsPerUnit} or less with samples ${settings.samples}`);
- }
- const advice = choices.length > 0 ? `At bounces ${settings.bounces} this scene fits ${choices.join(', or ')}.` : 'Remove parts or lights, or lower bounces.';
- return `The bake would follow ${pathWork} path steps (texels x samples x bounces); the limit for explicit settings is ${BAKE_EXPLICIT_PATH_WORK_LIMIT}. ${advice}`;
-}
-
-function scalePresetDown(settings) {
+function scaleSettingsDown(settings, floor) {
return {
...settings,
- samples: Math.max(PRESET_SAMPLES_FLOOR, Math.floor(settings.samples * 0.8)),
- texelsPerUnit: Math.max(BAKE_RANGES.texelsPerUnit[0], Math.round(settings.texelsPerUnit * 0.9 * 100) / 100),
+ samples: Math.max(floor.samples, Math.floor(settings.samples * 0.8)),
+ texelsPerUnit: Math.max(floor.texelsPerUnit, Math.round(settings.texelsPerUnit * 0.9 * 100) / 100),
};
}
+// The lowest samples and texel density the shrinking goes to: the preset floor, or what was asked when that is already lower.
+function shrinkFloor(settings) {
+ return { samples: Math.min(settings.samples, PRESET_SAMPLES_FLOOR), texelsPerUnit: Math.min(settings.texelsPerUnit, BAKE_RANGES.texelsPerUnit[0]) };
+}
+
/**
* Keeps a bake inside its work limits before any ray is traced. The estimate counts texels, samples and bounces and reads
- * no clock, so the same recipe always resolves to the same settings. Explicit samples or texelsPerUnit are never changed:
- * they fail up front only over the hard limit, and otherwise run until the real maxSeconds limit. A preset is scaled down
- * (samples by a fifth, texel density by a tenth, repeatedly) until it fits BAKE_PRESET_PATH_WORK.
+ * no clock, so the same recipe always resolves to the same settings. Explicit settings that fit BAKE_EXPLICIT_PATH_WORK_LIMIT
+ * are never changed: they run until the real maxSeconds limit. A preset is scaled down (samples by a fifth, texel density by
+ * a tenth, repeatedly) until it fits BAKE_PRESET_PATH_WORK. Explicit settings over the hard limit are scaled down the same
+ * way until they fit it, and the result says what was asked and what ran, so a large scene gets some baked light instead of
+ * none. Only a scene that does not fit at the floor is refused.
*/
export function fitSettingsToBudget(plan, settings) {
- if (!isPreset(settings)) {
- const pathWork = pathWorkOf(plan, settings);
- if (pathWork > BAKE_EXPLICIT_PATH_WORK_LIMIT) {
- throw new RangeError(overLimitMessage(plan, settings, pathWork));
- }
+ const explicit = !isPreset(settings);
+ const budget = explicit ? BAKE_EXPLICIT_PATH_WORK_LIMIT : BAKE_PRESET_PATH_WORK;
+ if (pathWorkOf(plan, settings) <= budget) {
return { used: settings, reduced: false, reduction: null };
}
+ const floor = shrinkFloor(settings);
// Samples and texel density shrink first. When the floor of both still does not fit (a large hall), a bounce is given up and
- // the density and samples start again from the preset, so the result is the largest bake that fits and never a refusal.
- // One bounce at the floor always fits a scene the explicit limit lets through, and past that the scene is too large to bake.
+ // the density and samples start again from the asked settings, so the result is the largest bake that fits.
for (let bounces = settings.bounces; bounces >= BAKE_RANGES.bounces[0]; bounces--) {
let used = { ...settings, bounces };
- while (pathWorkOf(plan, used) > BAKE_PRESET_PATH_WORK && !atPresetFloor(used)) {
- used = scalePresetDown(used);
+ while (pathWorkOf(plan, used) > budget && !atFloor(used, floor)) {
+ used = scaleSettingsDown(used, floor);
}
- if (pathWorkOf(plan, used) <= BAKE_PRESET_PATH_WORK) {
- const reduced = used.samples !== settings.samples || used.bounces !== settings.bounces || used.texelsPerUnit !== settings.texelsPerUnit;
- return { used, reduced, reduction: reduced ? reductionMessage(settings, used) : null };
+ if (pathWorkOf(plan, used) <= budget) {
+ return { used, reduced: true, reduction: reductionMessage(settings, used, explicit) };
}
}
- throw new RangeError(`Even ${PRESET_SAMPLES_FLOOR} samples, 1 bounce and texelsPerUnit ${BAKE_RANGES.texelsPerUnit[0]} is over the preset budget of ${BAKE_PRESET_PATH_WORK} path steps for this scene. Remove parts or lights.`);
+ throw new RangeError(overLimitMessage(plan, settings, budget, floor));
}
-function atPresetFloor(settings) {
- return settings.samples <= PRESET_SAMPLES_FLOOR && settings.texelsPerUnit <= BAKE_RANGES.texelsPerUnit[0];
+function atFloor(settings, floor) {
+ return settings.samples <= floor.samples && settings.texelsPerUnit <= floor.texelsPerUnit;
+}
+
+// What the agent reads in bake.reduction: what was asked, what ran, and the one thing to do for more.
+function reductionMessage(asked, used, explicit) {
+ const asking = `samples ${asked.samples}, bounces ${asked.bounces}, texelsPerUnit ${asked.texelsPerUnit}`;
+ const running = `samples ${used.samples}, bounces ${used.bounces}, texelsPerUnit ${used.texelsPerUnit} (bake.used)`;
+ if (explicit) {
+ return `The explicit settings asked for ${asking}; this scene is over the hard limit of ${BAKE_EXPLICIT_PATH_WORK_LIMIT} path steps for that, so it baked ${running} instead of failing. For the settings you asked for, remove parts or lights.`;
+ }
+ return `The preset asked for ${asking}; this scene is too large for that within the preset budget of ${BAKE_PRESET_PATH_WORK} path steps, so it baked ${running}. For a denser bake pass explicit samples, bounces and texelsPerUnit, up to ${BAKE_EXPLICIT_PATH_WORK_LIMIT} path steps and ${BAKE_MAXIMUM_SECONDS} s.`;
}
-// What the agent reads in bake.reduction: what the preset asked for, what ran, and the one thing to do for more.
-function reductionMessage(asked, used) {
- return `The preset asked for samples ${asked.samples}, bounces ${asked.bounces}, texelsPerUnit ${asked.texelsPerUnit}; this scene is too large for that within the preset budget of ${BAKE_PRESET_PATH_WORK} path steps, so it baked samples ${used.samples}, bounces ${used.bounces}, texelsPerUnit ${used.texelsPerUnit} (bake.used). For a denser bake pass explicit samples, bounces and texelsPerUnit, up to ${BAKE_EXPLICIT_PATH_WORK_LIMIT} path steps and ${BAKE_MAXIMUM_SECONDS} s.`;
+function overLimitMessage(plan, settings, budget, floor) {
+ const atFloorSettings = { ...settings, samples: floor.samples, texelsPerUnit: floor.texelsPerUnit, bounces: BAKE_RANGES.bounces[0] };
+ const limitName = isPreset(settings) ? 'the preset budget' : 'the limit for explicit settings';
+ const { texels } = estimateBake(plan, atFloorSettings);
+ const size = texels > MAX_BAKE_TEXELS ? `${texels} texels, over the ${MAX_BAKE_TEXELS} the bake takes` : `${pathWorkOf(plan, atFloorSettings)} path steps (texels x samples x bounces), over ${limitName} of ${budget}`;
+ return `Even samples ${atFloorSettings.samples}, bounces 1 and texelsPerUnit ${atFloorSettings.texelsPerUnit} is ${size}. Remove parts or lights.`;
}
function timeLimitMessage(error, settings) {
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index cb685e41..3835587d 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -371,7 +371,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
bake: Object.freeze({
fields: 'preset, or samples (1-256), bounces (1-8), texelsPerUnit (1-12) over it; irradianceGrid true or 8-40 nodes: baked bounced diffuse light in place of lightmaps (opt in, static); gridFog true adds the fog (sunlit closed rooms); probes room by default, false for none, or up to 4 {position, radius?}; rebake true bakes each sampled pose (4 kept).',
presets: BAKE_PRESETS,
- notes: 'Bounced light from point, spot, area and key lights. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit (bake.used, bake.reduction); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular; probes are specular, not in glTF.',
+ notes: 'Bounced light from point, spot, area and key lights. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit (bake.used, bake.reduction); explicit settings over maxPathWork shrink the same way and fail past maxSeconds. No environment map or specular; probes are specular, not in glTF.',
limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: MAX_POINT_LIGHTS }),
}),
explosion: 'scene_apply add-explosion { id, center, size m 0.5-100, start s (0), seed (1), fuel dry|oily, ground y, shake 0-1 (0.4), sparks streaks (default)|specks|none|{ count, speed, lifetime }, motionBlur (true: velocity grids, shutter of effects.motionBlur or 0.0417), debris { node } }: writes flash, ring, one gas-sim grid volume for fire and smoke (physical blackbody, castShadow, lightsScene; frames explosion-<fuel>-<seed>[-velocity]_NNNN.67vg are baked from the name, no files needed), stronger bloom, sparks, dust and rubble particles (delay start), an id-scorch decal and a camera eye shake into plain sections, IDs starting id-. debris.node (convex mesh, after set-physics with a fixed floor) breaks into 12 pieces thrown at start. Needs no other grid volume (one per scene), 3 particle systems; start is bounded by the grid frame list (error gives the limit). docs/agent-scene.md.',
diff --git a/src/irradiance-grid.js b/src/irradiance-grid.js
index 97d8e2ed..66cdc0f3 100644
--- a/src/irradiance-grid.js
+++ b/src/irradiance-grid.js
@@ -83,7 +83,8 @@ function nodePoint(layout, node, point) {
point[2] = layout.origin[2] + Math.floor(node / (width * height)) * layout.cellSize;
}
-function gridLayout(parts, resolution) {
+/** The grid origin, cell size and node counts for the parts' bounds: no side has more than `resolution` nodes. */
+export function gridLayout(parts, resolution) {
const minimum = [Infinity, Infinity, Infinity];
const maximum = [-Infinity, -Infinity, -Infinity];
for (const part of parts) {
diff --git a/tests/agent-bake-cloth-probes-fit.test.js b/tests/agent-bake-cloth-probes-fit.test.js
index dbdc03ca..83f8c215 100644
--- a/tests/agent-bake-cloth-probes-fit.test.js
+++ b/tests/agent-bake-cloth-probes-fit.test.js
@@ -3,8 +3,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createAgentScene } from '../src/agent-scene.js';
import { fitSettingsToBudget } from '../src/agent-bake.js';
-import { estimateBake } from '../src/light-bake.js';
-import { BAKE_PRESETS, BAKE_PRESET_PATH_WORK } from '../src/agent-scene-capabilities.js';
+import { estimateBake, MAX_BAKE_TEXELS } from '../src/light-bake.js';
+import { BAKE_PRESETS, BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT } from '../src/agent-scene-capabilities.js';
import { closedRoom, clothRoom } from './support/agent-bake-rooms.mjs';
test('a cloth sheet is skipped by the bake and still has no lightmap after a seek past t=0', () => {
@@ -65,7 +65,21 @@ test('a preset keeps its bounces when only samples and density need to shrink, a
assert.deepEqual([small.reduced, small.reduction], [false, null]);
});
+test('explicit settings that need more texels than a bake takes shrink until the texels and the path steps fit (#1218)', () => {
+ const house = syntheticPlan(Array.from({ length: 800 }, () => 900));
+ const asked = { samples: 32, bounces: 2, texelsPerUnit: 3, probes: 'room' };
+ assert.ok(estimateBake(house, asked).texels > MAX_BAKE_TEXELS, 'the asked density needs too many texels');
+ const { used, reduced, reduction } = fitSettingsToBudget(house, asked);
+ assert.equal(reduced, true);
+ assert.ok(estimateBake(house, used).texels <= MAX_BAKE_TEXELS);
+ assert.ok(pathWork(house, used) <= BAKE_EXPLICIT_PATH_WORK_LIMIT);
+ assert.ok(used.texelsPerUnit < asked.texelsPerUnit);
+ assert.match(reduction, /^The explicit settings asked for samples 32, bounces 2, texelsPerUnit 3;/);
+ const fitting = { ...asked, samples: 8, bounces: 1, texelsPerUnit: 1 };
+ assert.deepEqual(fitSettingsToBudget(house, fitting).used, fitting, 'settings that fit are left alone');
+});
+
test('a scene too large for one bounce at the floor is still refused, with the budget in the message', () => {
- const impossible = syntheticPlan(Array.from({ length: 2000 }, () => 900));
+ const impossible = syntheticPlan(Array.from({ length: 800 }, () => 900));
assert.throws(() => fitSettingsToBudget(impossible, { ...BAKE_PRESETS.draft, probes: 'room' }), /preset budget/);
});
diff --git a/tests/agent-bake-limits.test.js b/tests/agent-bake-limits.test.js
index c8c0353c..c0fc6653 100644
--- a/tests/agent-bake-limits.test.js
+++ b/tests/agent-bake-limits.test.js
@@ -4,19 +4,32 @@ import test from 'node:test';
import { createAgentScene } from '../src/agent-scene.js';
import { bakeSecondsLimit } from '../src/agent-bake.js';
import { BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT, BAKE_MAXIMUM_SECONDS, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';
-import { largeRoom } from './support/agent-bake-rooms.mjs';
+import { largeRoom, oversizedRoom } from './support/agent-bake-rooms.mjs';
-test('explicit settings over the hard limit fail up front with a lower setting to try', () => {
+test('explicit settings over the hard limit shrink to fit it, keep every part baked and say what ran', () => {
const heavy = { preset: 'draft', samples: 256, bounces: 3, texelsPerUnit: 12 };
- let message = '';
- assert.throws(() => createAgentScene(largeRoom(heavy)), error => {
- message = error.message;
- return /path steps/.test(error.message) && message.includes(String(BAKE_EXPLICIT_PATH_WORK_LIMIT));
- });
- const fittingSamples = Number(/samples (\d+) or fewer/.exec(message)?.[1]);
- const fittingDensity = Number(/texelsPerUnit ([\d.]+) or less/.exec(message)?.[1]);
- assert.ok(fittingSamples >= 1 && fittingSamples < 256, message);
- assert.ok(fittingDensity >= 1 && fittingDensity < 12, message);
+ // A busy machine can pass the real limit here, and this test is about the settings, so the clock stands still.
+ const realNow = performance.now;
+ performance.now = () => 0;
+ try {
+ const bake = createAgentScene(largeRoom(heavy)).inspect().bake;
+ const pathSteps = bake.texels * bake.used.samples * bake.used.bounces;
+ assert.equal(bake.reduced, true);
+ assert.ok(pathSteps <= BAKE_EXPLICIT_PATH_WORK_LIMIT && pathSteps > BAKE_PRESET_PATH_WORK, `${pathSteps} path steps`);
+ assert.ok(bake.used.samples < 256 && bake.used.texelsPerUnit < 12, JSON.stringify(bake.used));
+ assert.equal(bake.bakedParts, 56);
+ assert.ok(bake.reduction.includes('samples 256, bounces 3, texelsPerUnit 12'), bake.reduction);
+ assert.ok(bake.reduction.includes(`samples ${bake.used.samples}`), bake.reduction);
+ assert.ok(bake.reduction.includes(String(BAKE_EXPLICIT_PATH_WORK_LIMIT)), bake.reduction);
+ } finally {
+ performance.now = realNow;
+ }
+});
+
+test('a scene too large for the lowest explicit settings still fails up front and says why', () => {
+ const heavy = { samples: 256, bounces: 3, texelsPerUnit: 12 };
+ assert.throws(() => createAgentScene(oversizedRoom(heavy)), error => error instanceof RangeError
+ && /^Even samples 16, bounces 1 and texelsPerUnit 1 is \d+ texels, over the 1000000 the bake takes\./.test(error.message));
});
test('explicit settings far above the preset budget run when they fit the hard limit, and are never reduced', () => {
diff --git a/tests/agent-bake-refusal.test.js b/tests/agent-bake-refusal.test.js
index 8b6e0493..7458cd18 100644
--- a/tests/agent-bake-refusal.test.js
+++ b/tests/agent-bake-refusal.test.js
@@ -5,10 +5,10 @@ import { createAgentScene } from '../src/agent-scene.js';
import { MAX_BAKE_PARTS, MAX_GPU_BAKE_PARTS } from '../src/light-bake.js';
import { traceIrradianceGrid } from '../src/irradiance-grid.js';
import { traceProbeMaps } from '../src/probe-trace.js';
-import { largeRoom } from './support/agent-bake-rooms.mjs';
+import { growToOversizedOperations, shrinkFromOversizedOperations, largeRoom, oversizedRoom } from './support/agent-bake-rooms.mjs';
const FITTING_BAKE = { samples: 8, bounces: 1, texelsPerUnit: 2 };
-const OVER_THE_PATH_WORK_LIMIT = { preset: 'draft', samples: 256, bounces: 3, texelsPerUnit: 12 };
+const OVER_THE_PATH_WORK_LIMIT = { samples: 32, bounces: 2, texelsPerUnit: 3 };
function tooManyParts() {
return Array.from({ length: MAX_BAKE_PARTS + 1 }, () => ({}));
@@ -30,25 +30,25 @@ test('an edit whose rebake cannot run stays applied, drops the old bake and warn
const bakedFloor = scene.parts.find(part => part.material.emissiveMap);
assert.ok(bakedFloor, 'a part carries a lightmap');
- scene.apply([{ type: 'set-bake', bake: OVER_THE_PATH_WORK_LIMIT }, { type: 'set-camera', fov: 33 }], { expectedRevision: 0 });
+ scene.apply([{ type: 'set-bake', bake: OVER_THE_PATH_WORK_LIMIT }, { type: 'set-camera', fov: 33 }, ...growToOversizedOperations(OVER_THE_PATH_WORK_LIMIT)], { expectedRevision: 0 });
const inspected = scene.inspect();
assert.equal(inspected.revision, 1);
assert.equal(inspected.bake, undefined, 'the old bake is dropped');
assert.equal(scene.parts.some(part => part.material.emissiveMap), false, 'no part keeps the old lightmap');
const warning = inspected.diagnostics.find(diagnostic => diagnostic.kind === 'bake-skipped');
assert.equal(warning.severity, 'warning');
- assert.match(warning.message, /path steps/);
+ assert.match(warning.message, /texels/);
assert.match(warning.fix, /fewer parts|lower bake\.samples/);
scene.apply([{ type: 'set-camera', fov: 40 }], { expectedRevision: 1 });
assert.ok(scene.inspect().diagnostics.some(diagnostic => diagnostic.kind === 'bake-skipped'), 'an unrelated edit keeps the warning');
- scene.apply([{ type: 'set-bake', bake: FITTING_BAKE }], { expectedRevision: 2 });
+ scene.apply([{ type: 'set-bake', bake: FITTING_BAKE }, ...shrinkFromOversizedOperations(FITTING_BAKE)], { expectedRevision: 2 });
const recovered = scene.inspect();
assert.ok(recovered.bake, 'a bake that fits runs again');
assert.equal((recovered.diagnostics ?? []).some(diagnostic => diagnostic.kind === 'bake-skipped'), false);
});
test('a scene whose first bake cannot run still fails to build', () => {
- assert.throws(() => createAgentScene(largeRoom(OVER_THE_PATH_WORK_LIMIT)), /path steps/);
+ assert.throws(() => createAgentScene(oversizedRoom(OVER_THE_PATH_WORK_LIMIT)), /Even samples 16, bounces 1 and texelsPerUnit 1 is \d+ texels/);
});
diff --git a/tests/irradiance-grid.test.js b/tests/irradiance-grid.test.js
index cad113b9..fc120f30 100644
--- a/tests/irradiance-grid.test.js
+++ b/tests/irradiance-grid.test.js
@@ -4,7 +4,7 @@ import test from 'node:test';
import { box } from '../src/geometry.js';
import { createAgentScene } from '../src/agent-scene.js';
import { normalizeAgentBake } from '../src/agent-bake.js';
-import { IRRADIANCE_GRID_TEXTURE_UNIT, evaluateIrradianceGrid, normalizeIrradianceGrid, placeIrradianceGrid, traceIrradianceGrid } from '../src/irradiance-grid.js';
+import { IRRADIANCE_GRID_LIMITS, IRRADIANCE_GRID_TEXTURE_UNIT, gridLayout, evaluateIrradianceGrid, normalizeIrradianceGrid, placeIrradianceGrid, traceIrradianceGrid } from '../src/irradiance-grid.js';
import { createFragmentShader } from '../src/shaders.js';
const cube = box(0, 1);
@@ -156,3 +156,20 @@ test('a grid resolution under 2 or samples under 1 is refused before nodes land
assert.throws(() => traceIrradianceGrid(parts, sun, { resolution: 8, samples, bounces: 1 }), /samples/, `samples ${samples}`);
}
});
+
+test('every node count the recipe accepts fits the node cap on a cubic, a flat and a long scene (#1218)', () => {
+ const [minimum, maximum] = IRRADIANCE_GRID_LIMITS.resolution;
+ const scenes = {
+ cubic: [placed('block', [0, 0, 0], [10, 10, 10], [0.5, 0.5, 0.5])],
+ flat: [placed('plate', [0, 0, 0], [30, 0.2, 30], [0.5, 0.5, 0.5])],
+ long: [placed('hall', [0, 0, 0], [80, 3, 6], [0.5, 0.5, 0.5])],
+ };
+ for (const [name, parts] of Object.entries(scenes)) {
+ for (let resolution = minimum; resolution <= maximum; resolution++) {
+ const nodes = gridLayout(parts, resolution).size.reduce((product, count) => product * count, 1);
+ assert.ok(nodes <= IRRADIANCE_GRID_LIMITS.maxNodes, `${name} at ${resolution}: ${nodes} nodes`);
+ }
+ }
+ assert.equal(gridLayout(scenes.cubic, maximum).size.join('x'), '40x40x40');
+ assert.throws(() => normalizeAgentBake({ irradianceGrid: maximum + 1 }), /bake\.irradianceGrid must be true or an integer node count from 8 to 40/);
+});
diff --git a/tests/kernel-offload.test.js b/tests/kernel-offload.test.js
index af12615a..8d31c18f 100644
--- a/tests/kernel-offload.test.js
+++ b/tests/kernel-offload.test.js
@@ -5,6 +5,7 @@ import { createAgentScene } from '../src/agent-scene.js';
import { buildWithKernels, kernelKey, runKernel } from '../src/kernel-offload.js';
import { answerKernelRequest } from '../src/kernel-registry.js';
import { createInProcessWorker, kernelRoom, sceneDigest } from './support/kernel-offload-fixture.mjs';
+import { oversizedRoom } from './support/agent-bake-rooms.mjs';
import './support/load-agent-scene-modules.mjs';
const BUILD_SCRIPT = new URL('./support/kernel-offload-build.mjs', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
@@ -73,19 +74,14 @@ test('an error a kernel raises on the worker comes back as the same class and me
);
});
-test('an explicit bake setting over the budget fails on the worker with the message that names numbers that fit', async () => {
- // Surfaces four times as wide, so the explicit settings are over the hard path work limit in this small room too.
- const heavyRoom = () => {
- const room = kernelRoom();
- const nodes = room.nodes.map(node => (node.scale ? { ...node, scale: node.scale.map(side => side * 4) } : node));
- return { ...room, nodes, bake: { preset: 'draft', samples: 256, bounces: 3, texelsPerUnit: 12 } };
- };
+test('a scene too large for even the lowest explicit settings fails on the worker with the same message as inline', async () => {
+ const heavyRoom = () => oversizedRoom({ samples: 256, bounces: 3, texelsPerUnit: 12 });
let inlineMessage = '';
assert.throws(() => createAgentScene(heavyRoom()), error => {
inlineMessage = error.message;
return error instanceof RangeError;
});
- assert.match(inlineMessage, /samples \d+ or fewer/);
+ assert.match(inlineMessage, /^Even samples 16, bounces 1 and texelsPerUnit 1 is [0-9]+ texels/);
const requestedKernels = [];
await assert.rejects(
buildWithKernels(() => createAgentScene(heavyRoom()), { createWorker: () => createInProcessWorker(requestedKernels), available: true }),
diff --git a/tests/support/agent-bake-rooms.mjs b/tests/support/agent-bake-rooms.mjs
index 859afedf..965f0685 100644
--- a/tests/support/agent-bake-rooms.mjs
+++ b/tests/support/agent-bake-rooms.mjs
@@ -76,3 +76,36 @@ export function freezeBakeClockForFile() {
performance.now = realNow;
});
}
+
+/**
+ * The large room with every size and distance 300 times as large, plus 30 large crates: it needs more than the million texels
+ * a bake takes even at 1 texel per unit, so no samples or bounces setting fits it.
+ */
+export function oversizedRoom(bake) {
+ const recipe = largeRoom(bake);
+ recipe.nodes = recipe.nodes.map(node => ({
+ ...node,
+ ...(node.scale ? { scale: node.scale.map(side => side * 300) } : {}),
+ ...(node.translation ? { translation: node.translation.map(value => value * 300) } : {}),
+ }));
+ for (let index = 0; index < 30; index++) {
+ recipe.nodes.push({ id: `hangar-${index}`, geometry: 'box', material: 'white', translation: [-400 + (index % 10) * 80, 60, -400 + Math.floor(index / 10) * 80], scale: [60, 120, 60] });
+ }
+ return recipe;
+}
+
+/** The scene_apply operations that turn a scene built from largeRoom into oversizedRoom: the same nodes, resized and moved, and the added crates. */
+export function growToOversizedOperations(bake) {
+ const small = new Set(largeRoom(bake).nodes.map(node => node.id));
+ return oversizedRoom(bake).nodes.map(node => (small.has(node.id)
+ ? { type: 'set-node', id: node.id, translation: node.translation, scale: node.scale }
+ : { type: 'add-node', node }));
+}
+
+/** The scene_apply operations that undo growToOversizedOperations. */
+export function shrinkFromOversizedOperations(bake) {
+ const small = new Map(largeRoom(bake).nodes.map(node => [node.id, node]));
+ return oversizedRoom(bake).nodes.map(node => (small.has(node.id)
+ ? { type: 'set-node', id: node.id, translation: small.get(node.id).translation, scale: small.get(node.id).scale }
+ : { type: 'remove-node', id: node.id }));
+}