Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Keep scene:agent-scene from growing: move vegetation checks into the lazy module

Nguyen Xuan An1fceb4a668e9
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index a73065bc..aa5ad820 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -6,6 +6,7 @@ import { dirname, isAbsolute, join } from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import packageMetadata from '../package.json' with { type: 'json' };
+import { VEGETATION_CAPABILITY_NOTE } from '../src/agent-vegetation-notes.js';
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';
import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';
import { chooseDenoiser, finishWithOidn } from './agent-path-trace-denoise.mjs';
@@ -521,7 +522,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return Object.freeze({
async capabilities() {
return {
- scene: AGENT_SCENE_CAPABILITIES,
+ scene: { ...AGENT_SCENE_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE },
sceneLimits: SCENE_LIMITS,
preview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: 1, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },
review: { ...REVIEW_LIMITS, backend, memoryBudgetMiB: memory, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS,
diff --git a/scripts/measure-tool-cost.mjs b/scripts/measure-tool-cost.mjs
index 4a92a370..264c4656 100644
--- a/scripts/measure-tool-cost.mjs
+++ b/scripts/measure-tool-cost.mjs
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import { Client } from '@modelcontextprotocol/client';
import { InMemoryTransport } from '@modelcontextprotocol/server';
import { createAgentMcpServer } from './mcp-server.mjs';
+import { VEGETATION_CAPABILITY_NOTE } from '../src/agent-vegetation-notes.js';
import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
@@ -68,7 +69,7 @@ async function typicalResults(recipe) {
const meshReport = scene.inspectMeshes({ geometries: ['seat'] });
const { inspection, ...statusWithoutInspection } = status;
return {
- scene_capabilities: AGENT_SCENE_CAPABILITIES,
+ scene_capabilities: { ...AGENT_SCENE_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE },
scene_create: status,
scene_inspect: { sessionId: SAMPLE_SESSION, ...scene.inspect() },
mesh_inspect: { sessionId: SAMPLE_SESSION, ...meshReport },
diff --git a/src/agent-look.js b/src/agent-look.js
index 47857b09..a8efa92c 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -292,13 +292,7 @@ function environmentFrom(input = {}) {
if (input.shadowCascades !== undefined) {
environment.shadowCascades = shadowCascadesFrom(input.shadowCascades);
}
- if (input.wind !== undefined && input.wind !== null) {
- knownKeys(input.wind, ['strength', 'direction'], 'wind');
- environment.wind = {
- strength: numberInRange(fallback(input.wind.strength, 0.3), 0, 4, 'wind.strength'),
- direction: numberInRange(fallback(input.wind.direction, 0), -360, 360, 'wind.direction'),
- };
- }
+ if (input.wind !== undefined && input.wind !== null) environment.wind = agentSceneModule('vegetation').normalizeWind(input.wind);
if (input.viewTransform !== undefined) {
if (!VIEW_TRANSFORM_NAMES.includes(input.viewTransform)) {
throw new RangeError(`environment.viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 35b4b304..44d36009 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -156,7 +156,6 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'terrain', 'mesh']),
terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',
placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start, on a decoded copy of its own; scene_apply set-motion tracks move the node as usual and scene time seeks the clip. Copies of one asset share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy of its own (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds its wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',
- vegetation: "Node field vegetation turns a group node into trees (src/vegetation.js). One tree: {species: broadleaf|birch|conifer|palm|bush, seed=1, height?, leaves: cards|mesh}, grown at the node transform. A scatter: {mix:{species:weight, also grass and flowers}, seed, leaves, scatter:{ground: terrain node ID, density=0.012 per m2, slopeLimit=32 degrees, area?:{min:[x,z],max:[x,z]}, exclude?:[{center:[x,z],radius}|{min,max}|{node,radius}], variants=3 (1-4), scale?:[min,max]}}; terrain holes stay clear. Instances sit in the ground node frame, so give the group the ground transform. Levels (0 full to 3 far) come from the recipe camera eye at each edit, never from a frame, plus optional cullDistance m and distanceScale, so a seek cannot change them. season 0 summer, 0.35 gold, 0.6 orange, 0.85 brown, 0.9 and up bare for broadleaf, birch and bush (conifer and palm stay green). scatterVegetation from 67js/addons/vegetation gives the same instances for the same options. At most 1000 instances. scene_inspect vegetation lists instances per species and level, culled and triangles. Tags foliage and grass sway with environment.wind {strength 0-4 (0.3), direction degrees, 0 toward +x and 90 toward +z}; a recipe material may use them, and asset materials:[{name, tag:\"foliage\"}] makes the leaves of an imported tree sway and cast moving shadows.",
navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height. Ground and avoided nodes are read at their authored pose. Errors name an unwalkable start or goal, or one that cannot be reached.',
meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),
meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index e5ef21b5..c1e4e764 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -61,7 +61,7 @@ const MODULE_MARKERS = {
lightLinking: ['"affects"', '"keyAffects"'],
cascades: ['"shadowCascades"'],
assets: ['"asset":{'],
- vegetation: ['"vegetation":{'],
+ vegetation: ['"vegetation":{', '"wind":{'],
lineArt: ['"lines":{', '"toon":'],
viewTransform: ['"viewTransform":"agx"', '"viewTransform":"neutral"', '"look":"'],
// The coplanar-overlap warning in scene_inspect appears only once this is loaded, which loadAllAgentSceneModules does; a recipe with resolveCoplanar needs it.
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 3ab2af2f..7acf8e29 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -291,12 +291,7 @@ function nodeFrom(value) {
}
result.asset = agentSceneModule('assets').normalizeAssetPlacement(value.asset);
}
- if (value.vegetation !== undefined) {
- if (value.geometry !== undefined || value.skin !== undefined || value.asset !== undefined) {
- throw new TypeError(`Node ${value.id}: a node that grows vegetation is a group; drop geometry, material, skin and asset.`);
- }
- result.vegetation = agentSceneModule('vegetation').normalizeVegetation(value.vegetation);
- }
+ if (value.vegetation !== undefined) result.vegetation = agentSceneModule('vegetation').normalizeVegetation(value.vegetation, value);
if (value.decal !== undefined && typeof value.decal !== 'boolean') {
throw new TypeError('decal must be boolean.');
}
@@ -518,7 +513,7 @@ function compile(recipe, geometries, localBounds, limits) {
const materials = new Map(recipe.materials.map(material => [material.id, material]));
const graph = createSceneGraph(recipe.nodes.map(node => {
if (node.geometry !== undefined && (!geometries.has(node.geometry) || !materials.has(node.material))) {
- throw new RangeError(`Node ${node.id} uses ${geometries.has(node.geometry) ? `material ${node.material}` : `geometry ${node.geometry}`}, which does not exist. Add it to the recipe, or point the node at one of: ${(geometries.has(node.geometry) ? [...materials.keys()] : [...geometries.keys()]).join(', ')}.`);
+ throw new RangeError(`Node ${node.id} uses ${geometries.has(node.geometry) ? `material ${node.material}` : `geometry ${node.geometry}`}, which does not exist. Add it, or use one of: ${(geometries.has(node.geometry) ? [...materials.keys()] : [...geometries.keys()]).join(', ')}.`);
}
return { name: node.id, parent: node.parent,
matrix: node.assetPart ? mat4.clone(node.assetPart.matrix) : mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale),
@@ -633,7 +628,7 @@ function checkLightLinkNames(recipe) {
}
const unknown = agentSceneModule('lightLinking').unknownLightLinkNames(recipe.environment, recipe.nodes);
if (unknown.length > 0) {
- throw new RangeError(`Light links name nodes that do not exist (${unknown.slice(0, 4).join('; ')}). List node IDs with scene_inspect, then fix the affects list or add the node.`);
+ throw new RangeError(`Light links name nodes that do not exist (${unknown.slice(0, 4).join('; ')}). scene_inspect lists node IDs.`);
}
}
@@ -685,7 +680,7 @@ function normalizeRecipe(input, limits) {
recipe.materials = resources(withDefaultMaterial(recipe), limits.maxMaterials, 'materials', materialFrom);
const distinctPatterns = new Set(recipe.materials.filter(material => material.pattern).map(material => JSON.stringify(material.pattern)));
if (distinctPatterns.size > MAX_MATERIAL_PATTERNS) {
- throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse a pattern and tint it with color.`);
+ throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse one and tint it with color.`);
}
recipe.nodes = withoutArmatureNodes(recipe.nodes);
if (hasInstancedNodes(recipe.nodes)) recipe.nodes = agentSceneModule('mesh').expandInstancedNodes(recipe.nodes, {
@@ -800,15 +795,6 @@ function assetMaterialHandle(snapshot, output, ...candidates) {
return reusable ?? { holder: { snapshot }, output };
}
-function mergedRuntime(placed, vegetation) {
- return {
- ...placed,
- geometryParts: new Map([...placed.geometryParts, ...vegetation.geometryParts]),
- materialOutputs: new Map([...placed.materialOutputs, ...vegetation.materialOutputs]),
- partExtras: new Map([...placed.partExtras, ...vegetation.partExtras]),
- };
-}
-
function retainedMatrices(parts) {
for (const part of parts) {
if (part.matrix.length !== 16 || part.matrix.byteLength !== 64) {
@@ -946,7 +932,7 @@ function removeNode(candidate, operation) {
throw new TypeError('recursive must be boolean.');
}
if (!candidate.nodes.some(node => node.id === operation.id)) {
- throw new RangeError(`${operation.type} target was not found: ${operation.id}. List current IDs with scene_inspect, or add it first with add-node, add-geometry or add-material.`);
+ throw new RangeError(`${operation.type} target was not found: ${operation.id}. scene_inspect lists the IDs; add it first with an add operation.`);
}
const children = new Map();
for (const node of candidate.nodes) {
@@ -977,7 +963,6 @@ function removeNode(candidate, operation) {
export function createAgentScene(input, inputLimits = {}, options = {}) {
const limits = resolveLimits(inputLimits);
const assetOutputCache = new Map();
- let vegetationCache = null;
let state = null;
let revision = 0;
let topologyRevision = 0;
@@ -1034,11 +1019,10 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
const placedRuntime = recipe.nodes.some(node => node.asset)
? agentSceneModule('assets').expandAssetPlacements(recipe, options.assets, limits, assetOutputCache, recipe.nodes.some(node => node.asset?.drive) ? agentSceneModule('drive').createAssetDrive : null)
: NO_ASSETS;
- // Grown vegetation travels the placed-asset channel: generated geometries, materials and part nodes.
- const vegetationRuntime = recipe.nodes.some(node => node.vegetation)
- ? agentSceneModule('vegetation').expandVegetation(recipe, limits, vegetationCache ??= agentSceneModule('vegetation').createVegetationCache())
- : null;
- const assetRuntime = vegetationRuntime ? mergedRuntime(placedRuntime, vegetationRuntime) : placedRuntime;
+ // Grown vegetation travels the placed-asset channel; its module returns the placed runtime with its own parts added.
+ const assetRuntime = recipe.nodes.some(node => node.vegetation)
+ ? agentSceneModule('vegetation').expandVegetation(recipe, limits, assetOutputCache, placedRuntime)
+ : placedRuntime;
if (state) {
retainedMatrices(state.parts);
}
@@ -1060,7 +1044,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
const pendingVertices = pendingPlans.reduce((total, plan) => total + plan.estimatedVertices, 0);
if (residentStats.vertices + pendingVertices > limits.maxVertices ||
residentStats.geometryBytes + pendingVertices * 56 > limits.maxGeometryBytes) {
- throw new RangeError('Geometry preflight exceeds peak maxVertices or maxGeometryBytes across active, checkpoint, and staged resources. Reduce detail or release checkpoints.');
+ throw new RangeError('Geometry preflight exceeds maxVertices or maxGeometryBytes across active, checkpoint and staged resources. Reduce detail or release checkpoints.');
}
// Validate references, hierarchy and matrix arithmetic before generating any new resource.
@@ -1158,7 +1142,6 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
stats: geometryStats(geometryRecords.values()),
};
stagedState.assetRuntime = assetRuntime;
- stagedState.vegetationReport = vegetationRuntime?.report ?? [];
stagedState.localBounds = localBounds;
stagedState.skinBindings = skinBindings;
stagedState.skinStages = createSkinStages(skinBindings);
@@ -1551,7 +1534,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
identifier(operation.id);
const index = candidate[removal].findIndex(record => record.id === operation.id);
if (index < 0) {
- throw new RangeError(`${operation.type} target was not found: ${operation.id}. List current IDs with scene_inspect, or add it first with add-node, add-geometry or add-material.`);
+ throw new RangeError(`${operation.type} target was not found: ${operation.id}. scene_inspect lists the IDs; add it first with an add operation.`);
}
candidate[removal].splice(index, 1);
if (operation.type === 'remove-material') {
@@ -1571,11 +1554,11 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
fields = CAMERA_FIELDS;
target = candidate.camera;
} else {
- throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-cloth, set-timeline, set-particles, set-bake, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);
+ throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of ${AGENT_SCENE_CAPABILITIES.operations.join(', ')}.`);
}
knownKeys(operation, ['type', ...(operation.type === 'set-camera' ? [] : ['id']), ...fields], 'operation');
if (!target) {
- throw new RangeError(`${operation.type} target was not found: ${operation.id}. List current IDs with scene_inspect, or add it first with add-node, add-geometry or add-material.`);
+ throw new RangeError(`${operation.type} target was not found: ${operation.id}. scene_inspect lists the IDs; add it first with an add operation.`);
}
for (const field of fields) {
if (Object.hasOwn(operation, field)) {
@@ -1624,7 +1607,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
physics: state.physicsSampler ? state.physicsSampler.report() : null,
...(state.clothSampler ? { cloth: state.clothSampler.report() } : {}),
...(state.particleSampler ? { particles: state.particleSampler.report() } : {}),
- ...(state.vegetationReport?.length ? { vegetation: state.vegetationReport } : {}),
+ ...(state.assetRuntime.vegetation ? { vegetation: state.assetRuntime.vegetation } : {}),
...(state.assetRuntime.placements.length ? { assets: agentSceneModule('assets').describeAssetPlacements(state.assetRuntime, state.graph, geometry => state.localBounds.get(geometry)) } : {}),
...(state.bakeReport ? { bake: state.bakeReport } : {}),
...(state.reflectionReport ? { reflections: state.reflectionReport } : {}),
diff --git a/src/agent-vegetation-notes.js b/src/agent-vegetation-notes.js
new file mode 100644
index 00000000..92cec1b0
--- /dev/null
+++ b/src/agent-vegetation-notes.js
@@ -0,0 +1,2 @@
+// What scene_capabilities says about recipe vegetation. It lives apart from agent-scene-capabilities.js, which every agent scene bundle carries; the MCP host adds it to the capabilities it returns.
+export const VEGETATION_CAPABILITY_NOTE = "Node field vegetation turns a group node into trees (src/vegetation.js). One tree: {species: broadleaf|birch|conifer|palm|bush, seed=1, height?, leaves: cards|mesh}, grown at the node transform. A scatter: {mix:{species:weight, also grass and flowers}, seed, leaves, scatter:{ground: terrain node ID, density=0.012 per m2, slopeLimit=32 degrees, area?:{min:[x,z],max:[x,z]}, exclude?:[{center:[x,z],radius}|{min,max}|{node,radius}], variants=3 (1-4), scale?:[min,max]}}; terrain holes stay clear. Instances sit in the ground node frame, so give the group the ground transform. Levels (0 full to 3 far) come from the recipe camera eye at each edit, never from a frame, plus optional cullDistance m and distanceScale, so a seek cannot change them. season 0 summer, 0.35 gold, 0.6 orange, 0.85 brown, 0.9 and up bare for broadleaf, birch and bush (conifer and palm stay green). scatterVegetation from 67js/addons/vegetation gives the same instances for the same options. At most 1000 instances. scene_inspect vegetation lists instances per species and level, culled and triangles. Tags foliage and grass sway with environment.wind {strength 0-4 (0.3), direction degrees, 0 toward +x and 90 toward +z}; a recipe material may use them, and asset materials:[{name, tag:\"foliage\"}] makes the leaves of an imported tree sway and cast moving shadows.";
diff --git a/src/agent-vegetation.js b/src/agent-vegetation.js
index 42914e2f..0c5418d7 100644
--- a/src/agent-vegetation.js
+++ b/src/agent-vegetation.js
@@ -90,8 +90,31 @@ function normalizeScatter(value) {
return result;
}
-/** Validate the `vegetation` field of a node. Returns the canonical form kept in the recipe. */
-export function normalizeVegetation(value) {
+/** Validate environment.wind: strength 0 to 4 (0.3) and direction in degrees (0 toward +x, 90 toward +z). */
+export function normalizeWind(value) {
+ knownKeys(value, ['strength', 'direction'], 'wind');
+ return {
+ strength: numberWithin(value.strength ?? 0.3, 0, 4, 'wind.strength'),
+ direction: numberWithin(value.direction ?? 0, -360, 360, 'wind.direction'),
+ };
+}
+
+// The placed-asset runtime with the vegetation maps added to it, and the report for scene_inspect.
+function mergedRuntime(placed, vegetation) {
+ return {
+ ...placed,
+ vegetation: vegetation.report,
+ geometryParts: new Map([...placed.geometryParts, ...vegetation.geometryParts]),
+ materialOutputs: new Map([...placed.materialOutputs, ...vegetation.materialOutputs]),
+ partExtras: new Map([...placed.partExtras, ...vegetation.partExtras]),
+ };
+}
+
+/** Validate the `vegetation` field of a node (`node` is the whole node, which must be a group). Returns the canonical form kept in the recipe. */
+export function normalizeVegetation(value, node) {
+ if (node && (node.geometry !== undefined || node.skin !== undefined || node.asset !== undefined)) {
+ throw new TypeError(`Node ${node.id}: a node that grows vegetation is a group; drop geometry, material, skin and asset.`);
+ }
knownKeys(value, VEGETATION_FIELDS, 'vegetation');
const result = {};
if ((value.species === undefined) === (value.mix === undefined)) {
@@ -237,10 +260,11 @@ function materialJson(material) {
/**
* Generate the geometries, materials and part nodes of every vegetation node into a normalized recipe, in place.
- * `cache` (kept by the scene) holds grown trees across edits, so a camera or season edit does not grow them again.
+ * `cache` (the scene's asset output map) holds grown trees across edits, so a camera or season edit does not grow them again.
* Returns the runtime maps the scene merges with the placed-asset ones, and a report for scene_inspect.
*/
-export function expandVegetation(recipe, limits, cache) {
+export function expandVegetation(recipe, limits, cache, placedRuntime) {
+ cache.serial ??= 0;
const planted = recipe.nodes.filter(node => node.vegetation);
const runtime = { geometryParts: new Map(), materialOutputs: new Map(), partExtras: new Map(), report: [] };
const generatedNodes = [];
@@ -248,9 +272,11 @@ export function expandVegetation(recipe, limits, cache) {
const eye = recipe.camera?.eye ?? [0, 0, 0];
for (const node of planted) {
const { vegetation } = node;
- const key = cacheKey(recipe, node);
+ const key = `vegetation:${cacheKey(recipe, node)}`;
if (!cache.has(key)) {
- if (cache.size >= VEGETATION_LIMITS.maxCachedSets) cache.delete(cache.keys().next().value);
+ // The scene shares this map with its placed assets, so only grown sets are evicted.
+ const grownKeys = [...cache.keys()].filter(candidate => candidate.startsWith('vegetation:'));
+ if (grownKeys.length >= VEGETATION_LIMITS.maxCachedSets) cache.delete(grownKeys[0]);
cache.set(key, { serial: ++cache.serial, grown: grow(recipe, vegetation), outputs: new Map() });
}
const entry = cache.get(key);
@@ -317,12 +343,5 @@ export function expandVegetation(recipe, limits, cache) {
throw new RangeError(`Vegetation expands to ${generatedNodes.length} part nodes, which with the ${recipe.nodes.length} authored nodes exceeds maxNodes ${limits.maxNodes}. Lower density or cull far trees with cullDistance.`);
}
recipe.nodes.push(...generatedNodes);
- return runtime;
-}
-
-/** The cache a scene keeps for grown vegetation; a Map with a serial counter so geometry IDs never repeat. */
-export function createVegetationCache() {
- const cache = new Map();
- cache.serial = 0;
- return cache;
+ return mergedRuntime(placedRuntime, runtime);
}