Skip to content

3D engine that AI agents drive

Keep part geometry independent of earlier scenes (#2305)

Nguyen Xuan Anda2b4511a615
diff --git a/changes/2305.md b/changes/2305.md
new file mode 100644
index 00000000..628db69a
--- /dev/null
+++ b/changes/2305.md
@@ -0,0 +1 @@
+- A scene builds the same parts whatever was built before it in the same process: the flush ranking and the floor sky trace run for a scene only when the host loaded every module or the scene itself asked for them (#2305)
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 0dee6346..bebfa0e2 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -63,6 +63,8 @@ const scene = createAgentScene(recipe);
`loadAllAgentSceneModules()` loads everything, for a host that runs any recipe an agent writes (the MCP preview does).
Call `loadAgentSceneModules(operations)` before `apply` when the operations add such features.
+The default stages that need a lazy module (flush-face ranking, the floor sky trace) run for a scene when the host called `loadAllAgentSceneModules()` or the scene's own recipe or operations name them. A module that another scene loaded earlier in the process does not turn them on, so one recipe builds the same parts in any order.
+
## Recipe contract
The recipe must contain `format`, `schemaVersion`, `geometries`, `materials`, and `nodes`.
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 6c3e2ecb..0f1e1b19 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -55,6 +55,8 @@ const MODULE_LOADERS = {
const loadedModules = {};
const pendingLoads = {};
+// Set by loadAllAgentSceneModules: the host runs any recipe and wants every default stage on (the MCP preview).
+let hostLoadedEveryModule = false;
let manifoldLoader = null;
let physicsLoader = null;
@@ -165,6 +167,7 @@ export async function loadAgentSceneModules(value) {
/** Load every on-demand module, for hosts that run any recipe an agent writes. */
export async function loadAllAgentSceneModules() {
+ hostLoadedEveryModule = true;
await Promise.all(Object.keys(MODULE_LOADERS).map(loadModule));
}
@@ -190,6 +193,15 @@ export function agentSceneModuleLoaded(name) {
return Boolean(loadedModules[name]);
}
+/**
+ * Whether a default stage that needs this module runs for one scene. A module another scene loaded earlier in the same
+ * process does not count: the stage runs when the host loaded every module, or when this scene's own recipe or edits
+ * asked for it (`requestedNames`, from agentSceneModulesNeeded). So a scene builds the same bytes whatever was built before it.
+ */
+export function agentSceneModuleActive(name, requestedNames) {
+ return Boolean(loadedModules[name]) && (hostLoadedEveryModule || requestedNames.has(name));
+}
+
/** Add a font table that recipes can name in a text geometry. Loads the text code first. */
export async function registerAgentSceneFont(name, fontData) {
const module = await loadModule('text');
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 13450e40..1b2f5258 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -7,7 +7,7 @@ import { applyProjection, validateCameraShift, CAMERA_LENS_FIELDS } from './came
import { checkLocalVolumePartNames } from './local-volume-resolve.js';
import { normalizeAgentLook, environmentPatchWithSetup, environmentLinksLights, agentEnvironmentMap, SKY_OVERRIDABLE_FIELDS, VOLUME_FOG_FIELDS } from './agent-look.js';
import { postStepSupport } from './shader-registry.js';
-import { agentSceneModule, agentSceneModuleLoaded } from './agent-scene-modules.js';
+import { agentSceneModule, agentSceneModuleActive, agentSceneModuleLoaded, agentSceneModulesNeeded as modulesNeededBy } from './agent-scene-modules.js';
import { CURVE_TEXT_LIMITS, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
import { normalizeMaterialWear, geometryWithSurfaceMasks } from './material-wear.js';
import { ALL_LIGHTS_MASK, MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
@@ -1601,6 +1601,8 @@ function removeNode(candidate, operation) {
export function createAgentScene(input, inputLimits = {}, options = {}) {
const limits = resolveLimits(inputLimits);
const assetOutputCache = new Map();
+ // The on-demand modules this scene's recipe and edits named. Default stages (flush ranking, floor sky) run only for these.
+ const requestedModules = new Set(modulesNeededBy(input));
let state = null;
let revision = 0;
let topologyRevision = 0;
@@ -1945,7 +1947,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
// A closed room a sun lights gets the sky each floor texel sees; the lazy module decides, keeps its result and honours environment.floorSkyTrace.
function stageFloorSky(recipe, parts) {
- return agentSceneModuleLoaded('floorSky') ? agentSceneModule('floorSky').stageFloorSky(recipe.environment, parts) : parts;
+ return agentSceneModuleActive('floorSky', requestedModules) ? agentSceneModule('floorSky').stageFloorSky(recipe.environment, parts) : parts;
}
// A scene that asks for no bake and looks like a closed room gets one diagnostic naming the bake. The ray test costs a
@@ -1975,7 +1977,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
// runs again only when the parts are new objects.
let flushCache = null;
function stageCoplanarOffsets(recipe, parts) {
- if (!agentSceneModuleLoaded('coplanar')) {
+ if (!agentSceneModuleActive('coplanar', requestedModules)) {
return parts;
}
const coplanar = agentSceneModule('coplanar');
@@ -1999,7 +2001,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
// that check is bounded, runs on inspect only and is kept until the scene changes.
let coplanarReportCache = null;
function coplanarProblems() {
- if (!agentSceneModuleLoaded('coplanar')) {
+ if (!agentSceneModuleActive('coplanar', requestedModules)) {
return [];
}
if (state.recipe.environment.resolveCoplanar !== false) {
@@ -2203,6 +2205,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
throw invalidField('operations', Array.isArray(inputOperations) ? `${inputOperations.length} operations` : inputOperations, `a list of 1 to ${limits.maxOperations} operations, such as [{ "type": "set-camera", "fov": 50 }]`);
}
const operations = copiedJson(inputOperations, limits.maxRecipeBytes);
+ for (const name of modulesNeededBy(operations)) requestedModules.add(name);
const onlyFieldEdits = operations.every(operation => FIELD_EDIT_OPERATIONS.has(operation.type));
const candidate = (onlyFieldEdits && fieldEditCandidate(state.recipe, operations)) || authoredRecipe(state.recipe);
const removedNodes = new Set();
diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.js
index dc5fd324..6ecbe688 100644
--- a/tests/coplanar-overlap.test.js
+++ b/tests/coplanar-overlap.test.js
@@ -4,13 +4,14 @@ import assert from 'node:assert/strict';
import { createAgentScene } from '../src/agent-scene.js';
import { COPLANAR_TOLERANCE, clearFlushParts, findCoplanarOverlaps, coplanarOverlapDiagnostics, flushLeftoverDiagnostics, installCoplanarDiagnostics, resolveFlushParts } from '../src/coplanar-overlap.js';
import { depthLayerOf, flushOrderOf } from '../src/depth-layer.js';
-import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
+import { loadAllAgentSceneModules } from '../src/agent-scene-modules.js';
import { frameDiagnostics } from '../src/frame-diagnostics.js';
import { groupParts } from '../src/renderer.js';
import { resolveEffects } from '../src/effects.js';
import { sphere } from '../src/geometry.js';
-await loadAgentSceneModules({ environment: { resolveCoplanar: 'offset' } });
+// A host that runs any recipe loads every module (the MCP preview does), which turns the default flush ranking on for plain recipes.
+await loadAllAgentSceneModules();
function node(id, translation, scale, extra = {}) {
return { id, geometry: 'box', material: 'paint', translation, scale, ...extra };
diff --git a/tests/scene-order-determinism.test.js b/tests/scene-order-determinism.test.js
new file mode 100644
index 00000000..732f2809
--- /dev/null
+++ b/tests/scene-order-determinism.test.js
@@ -0,0 +1,68 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { createAgentScene } from '../src/agent-scene.js';
+import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
+import { flushOrderOf } from '../src/depth-layer.js';
+import { ROOM_CAMERA, ROOM_MATERIALS, roomNodes } from '../bench/reference/interior-room.mjs';
+
+const CAMERA = { eye: [0, 2, 4], target: [0, 0.5, 0], up: [0, 1, 0], fov: 50, near: 0.1, far: 50 };
+
+// Two boxes whose top and bottom faces lie on the same planes: the flush ranking has pairs to settle.
+function flushRecipe(environment) {
+ return {
+ format: 'crucible.scene', schemaVersion: 1, camera: CAMERA,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.8, 0.8, 0.8] }],
+ nodes: [
+ { id: 'slab', geometry: 'block', material: 'paint', translation: [0, 0.5, 0] },
+ { id: 'step', geometry: 'block', material: 'paint', translation: [0.4, 0.5, 0], scale: [1, 1, 0.5] },
+ ],
+ ...(environment ? { environment } : {}),
+ };
+}
+
+function serialize(key, value) {
+ return ArrayBuffer.isView(value) ? Array.from(value) : value;
+}
+
+function sceneHash(recipe) {
+ const hash = createHash('sha256');
+ for (const part of createAgentScene(recipe).parts) {
+ for (const field of ['positions', 'normals', 'indices']) {
+ const values = part.geometry[field];
+ hash.update(Buffer.from(values.buffer, values.byteOffset, values.byteLength));
+ }
+ hash.update(JSON.stringify(flushOrderOf(part), serialize));
+ }
+ return hash.digest('hex');
+}
+
+test('a plain scene builds the same bytes after another scene loaded the flush ranking', async () => {
+ const before = sceneHash(flushRecipe());
+ await loadAgentSceneModules(flushRecipe({ resolveCoplanar: 'offset' }));
+ assert.equal(sceneHash(flushRecipe()), before);
+});
+
+test('a scene that names resolveCoplanar still gets its faces ranked', async () => {
+ await loadAgentSceneModules(flushRecipe({ resolveCoplanar: 'offset' }));
+ const ranked = createAgentScene(flushRecipe({ resolveCoplanar: 'offset' })).parts.filter(part => flushOrderOf(part));
+ assert.ok(ranked.length > 0, 'the recipe asked for the ranking, so flush faces get a draw order');
+ assert.notEqual(sceneHash(flushRecipe({ resolveCoplanar: 'offset' })), sceneHash(flushRecipe()));
+});
+
+// A closed room with a sun: the floor sky trace changes it when that code is loaded.
+function sealedRoomRecipe() {
+ return {
+ format: 'crucible.scene', schemaVersion: 1, camera: ROOM_CAMERA,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: ROOM_MATERIALS,
+ nodes: roomNodes({ sealed: true, withoutLawn: true }),
+ };
+}
+
+test('a plain room builds the same bytes after another scene loaded the floor sky trace', async () => {
+ const before = sceneHash(sealedRoomRecipe());
+ await loadAgentSceneModules({ ...sealedRoomRecipe(), environment: { keyColor: [3, 3, 3] } });
+ assert.equal(sceneHash(sealedRoomRecipe()), before);
+});