3D engine that AI agents drive
Let replaceParts add and remove textured parts (closes #423)
Nguyen Xuan Ana0f17a1f614a
diff --git a/changes/423.md b/changes/423.mdnew file mode 100644index 00000000..55fbfd8a--- /dev/null+++ b/changes/423.md@@ -0,0 +1 @@+- `replaceParts` can now add and remove textured parts, and frees a texture once no part uses it (issue #423); skinned, morphed and layered parts still need a new renderer.diff --git a/changes/423.size.md b/changes/423.size.mdnew file mode 100644index 00000000..9fb931fb--- /dev/null+++ b/changes/423.size.md@@ -0,0 +1,6 @@+- entry:core: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000+- scene:lit-box: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000+- scene:gltf-box: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000+- scene:gltf-box+lazy: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000+- scene:agent-scene: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000+- scene:agent-scene+lazy: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000diff --git a/docs/guide.md b/docs/guide.mdindex 33b44303..e5c33c52 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -567,7 +567,7 @@ The session keeps existing renderer-facing parts and matrices for transform, matAgents can build from an empty recipe with `add-geometry`, `add-material` and `add-node` commands.Explicit removal and rebinding use the same atomic batch contract.Checkpoints retain shared geometry under the session budget. Release unused snapshots before increasing scene detail.-The preview reconciles rigid, untextured topology while keeping unchanged geometry buffers and draw batches.+The preview reconciles rigid topology, textured or not, while keeping unchanged geometry buffers and draw batches.The CPU addon owns recipe state. The separate Node MCP server connects it to browser rendering. Background render jobs remain unsupported.diff --git a/docs/mcp.md b/docs/mcp.mdindex 6256fda0..98c725cf 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -228,8 +228,8 @@ Geometry resources remain immutable. Remove an unused definition and add its repCheckpoints retain their resource handles for exact restoration. Active, checkpoint and staged geometry share a bounded allocation budget.Release unused checkpoints to free that ownership before adding detail.-The preview reconciles rigid, untextured parts while retaining shader programs, render targets and shared geometry buffers.-A scene with material patterns gets a new renderer on each topology change instead, because textured parts are not streamed.+The preview reconciles rigid parts, textured or not, while retaining shader programs, render targets and shared geometry buffers.+A scene with material patterns gets a new renderer on each topology change instead. Skinned, morphed and layered parts are not streamed either; `replaceParts` rejects adding or removing them.Unchanged draw batches remain allocated. Changed instance groups receive new instance buffers. Retired buffers are released.Staging must fit alongside the current render allocations, so a replacement can fail its GPU budget even when the final scene alone fits.diff --git a/docs/terrain.md b/docs/terrain.mdindex 9607b7ca..139bef99 100644--- a/docs/terrain.md+++ b/docs/terrain.md@@ -34,7 +34,7 @@ const renderer = new Renderer67(canvas, [...terrain.parts, ...treeParts], { worl```Each frame, `if (terrain.update(eye).length) renderer.replaceParts(sceneParts)` swaps the chunks whose level of detail changed.-Textured parts such as leaf cards must stay unchanged in `replaceParts`, so rebuild the renderer when the vegetation levels change.+Textured parts such as leaf cards can be added and removed in `replaceParts`; their textures are freed once no part uses them.## loadTextureSetdiff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 4750e95f..1052d19f 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -155,7 +155,7 @@ Read `docs/agent-scene.md` for schema version one, immutable resources and atomiStart with capabilities and bounded inspection. Edit stable IDs through one `apply` batch with the current `expectedRevision`.Checkpoint before uncertain changes, inspect and render the result, then restore or release the checkpoint.-For rigid, untextured scenes, compare `session.topologyRevision` with the uploaded revision after successful edits.+For rigid scenes (textured parts are fine; skinned, morphed and layered parts need a new renderer), compare `session.topologyRevision` with the uploaded revision after successful edits.Call `renderer.replaceParts(session.parts)` for changed topology or `renderer.updateParts(session.parts)` for retained parts, then render the detached camera.Use add/remove commands for nodes and shared resources, and `set-node` geometry/material fields for rebinding.diff --git a/src/renderer.js b/src/renderer.jsindex a8b9f3c8..939e3c78 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -102,7 +102,13 @@ function renderPass(material) {}function partNeedsFullUpload(part) {- return Boolean(part.skin || part.morph || part.geometry.morphTargets || part.geometry.skinIndices || hasMaterialMap(part.material));+ return Boolean(part.skin || part.morph || part.crowd || part.material.layers || part.geometry.morphTargets || part.geometry.skinIndices);+}++// The texture descriptors a batch binds. Layer and splat maps are included so a texture they share is never freed.+function batchTextureDescriptors(batch) {+ const state = batch.mapState;+ return [...state.slice(0, 5), state[14], ...Object.values(state[18] ?? {}), state[17]?.maskMap].filter(Boolean);}function batchPass(batch) {@@ -1013,7 +1019,7 @@ export class Renderer67 {return batch;}- /** Reconcile immutable rigid, untextured geometry without rebuilding programs or render targets. */+ /** Reconcile immutable rigid geometry, textured or not, without rebuilding programs or render targets. */replaceParts(parts) {if (!Array.isArray(parts) || new Set(parts).size !== parts.length) {throw new TypeError('Scene parts must be an array with distinct object identities.');@@ -1044,16 +1050,16 @@ export class Renderer67 {}return { group, batch: null };});- // Textured, skinned and morphed batches stay valid only while retained unchanged; uploading or dropping them is not supported here.+ // Skinned, morphed, crowd and splat-layer batches own pose and layer resources that are not reconciled here; they stay valid only while retained unchanged.for (const item of replacements) {if (!item.batch && item.group.some(partNeedsFullUpload)) {- throw new Error('replaceParts can add or change only rigid, untextured parts. Keep textured, skinned and morphed parts unchanged so their batches are retained.');+ throw new Error('replaceParts can add or change only rigid parts. Keep skinned, morphed, crowd and layered parts unchanged so their batches are retained.');}}for (const [part, location] of this.partLocations) {if (retained.has(location.batch)) continue;- if (location.skin || location.morph || location.morphTargets || location.skinIndices || location.mapState.slice(0, 5).some(Boolean)) {- throw new Error(`replaceParts can remove or regroup only existing rigid, untextured parts; ${part.name} is textured, skinned or morphed and needs a new renderer.`);+ if (location.skin || location.morph || location.morphTargets || location.skinIndices || location.batch.crowd || location.batch.splat) {+ throw new Error(`replaceParts can remove or regroup only existing rigid parts; ${part.name} is skinned, morphed or layered and needs a new renderer.`);}}const newGeometryBytes = [...geometries].filter(geometry => !this.geometryBuffers.has(geometry)).reduce((total, geometry) => total + geometryBufferBytes(geometry), 0);@@ -1067,6 +1073,7 @@ export class Renderer67 {const previousBuffers = [...this.buffers];const previousGeometryBytes = this.geometryBytes;const previousGeometryBuffers = new Map(this.geometryBuffers);+ const previousTextures = new Map(this.textures);const stagedLocations = new Map();const stagedBatches = [];this.partLocations = stagedLocations;@@ -1099,6 +1106,7 @@ export class Renderer67 {this.buffers = previousBuffers;this.geometryBytes = previousGeometryBytes;this.geometryBuffers = previousGeometryBuffers;+ this.dropTextures([...this.textures.keys()].filter(descriptor => !previousTextures.has(descriptor)));this.partLocations = previousLocations;throw error;}@@ -1118,6 +1126,10 @@ export class Renderer67 {}for (const buffer of releasedBuffers) this.context.deleteBuffer(buffer);this.buffers = this.buffers.filter(buffer => !releasedBuffers.has(buffer));+ const bound = new Set(stagedBatches.flatMap(batchTextureDescriptors));+ const added = [...this.textures.keys()].filter(descriptor => descriptor && !previousTextures.has(descriptor));+ const unbound = this.batches.flatMap(batchTextureDescriptors).filter(descriptor => !bound.has(descriptor) && this.textures.has(descriptor));+ this.textureBytes += added.reduce((total, descriptor) => total + textureDescriptorInfo(descriptor).bytes, 0) - this.dropTextures(unbound);this.geometryBytes = [...geometries].reduce((total, geometry) => total + geometryBufferBytes(geometry), 0) + renderParts.length * INSTANCE_STRIDE * 4;this.batches = stagedBatches;this.partCount = parts.length;@@ -1128,6 +1140,17 @@ export class Renderer67 {return parts.length;}+ // Deletes textures no batch binds any more and returns the bytes they held.+ dropTextures(descriptors) {+ let bytes = 0;+ for (const descriptor of new Set(descriptors)) {+ this.context.deleteTexture(this.textures.get(descriptor));+ this.textures.delete(descriptor);+ bytes += textureDescriptorInfo(descriptor).bytes;+ }+ return bytes;+ }+createSkinTexture(cache, identity, matrices, groupSize) {if (cache.has(identity)) return cache.get(identity);const context = this.context;diff --git a/tests/renderer-topology.test.js b/tests/renderer-topology.test.jsindex ea276401..bc7eaa39 100644--- a/tests/renderer-topology.test.js+++ b/tests/renderer-topology.test.js@@ -13,6 +13,7 @@ function allocationRenderer() {const liveBuffers = new Set();const liveArrays = new Set();const uploads = [];+ const liveTextures = new Set();let driverError = 0;let throwingUpload = false;renderer.context = {@@ -29,6 +30,8 @@ function allocationRenderer() {return array;},deleteVertexArray(array) { liveArrays.delete(array); },+ deleteTexture(texture) { liveTextures.delete(texture); },+ getParameter() { return 4096; },bindBuffer() {}, bindVertexArray() {}, enableVertexAttribArray() {}, disableVertexAttribArray() {},vertexAttribPointer() {}, vertexAttribDivisor() {}, vertexAttrib2f() {}, vertexAttrib3f() {},bufferData(target, data, usage) {@@ -56,8 +59,16 @@ function allocationRenderer() {renderer.updateBatches = new Set();renderer.updateSkins = new Set();renderer.updateMorphs = new Set();- renderer.createTexture = () => null;- return { renderer, liveBuffers, liveArrays, uploads,+ renderer.textures = new Map();+ renderer.createTexture = descriptor => {+ if (!renderer.textures.has(descriptor)) {+ const texture = { descriptor };+ liveTextures.add(texture);+ renderer.textures.set(descriptor, texture);+ }+ return renderer.textures.get(descriptor);+ };+ return { renderer, liveBuffers, liveArrays, liveTextures, uploads,failDriver() { driverError = 1285; },failUpload(value) { throwingUpload = value; },};@@ -157,12 +168,13 @@ test('retained textured batches survive while streamed rigid parts change aroundstate.renderer.replaceParts([textured, secondFrame]);assert.equal(state.renderer.batches[0], texturedBatch, 'the textured batch is retained, not reuploaded');assert.equal(state.renderer.partCount, 2);- assert.throws(() => state.renderer.replaceParts([secondFrame]), /existing rigid, untextured/);- const changedTexture = part('new textured', box());- changedTexture.material.map = textured.material.map;- changedTexture.geometry.uvs = new Float32Array(changedTexture.geometry.positions.length / 3 * 2);- assert.throws(() => state.renderer.replaceParts([textured, secondFrame, changedTexture]), /only rigid, untextured/);- assert.equal(state.renderer.batches[0], texturedBatch);+ const addedTexture = part('new textured', box());+ addedTexture.material.map = textured.material.map;+ addedTexture.geometry.uvs = new Float32Array(addedTexture.geometry.positions.length / 3 * 2);+ state.renderer.replaceParts([textured, secondFrame, addedTexture]);+ assert.equal(state.renderer.partCount, 3);+ state.renderer.replaceParts([secondFrame]);+ assert.equal(state.renderer.partLocations.has(textured), false);});test('committed uploaded resource ownership rejects replacement even when callers mutate live handles', () => {@@ -171,15 +183,76 @@ test('committed uploaded resource ownership rejects replacement even when callerstate.renderer.replaceParts([first]);const location = state.renderer.partLocations.get(first);const originalBatch = state.renderer.batches[0];- const allocations = state.uploads.length;- location.mapState[0] = { image: {} };- first.material.map = undefined;- assert.throws(() => state.renderer.replaceParts([]), /existing rigid/);- assert.equal(state.renderer.batches[0], originalBatch);- assert.equal(state.uploads.length, allocations);- location.mapState[0] = null;location.skin = { jointMatrices: new Float32Array(16) };first.skin = undefined;assert.throws(() => state.renderer.replaceParts([]), /existing rigid/);assert.equal(state.renderer.partCount, 1);});++function texturedPart(name, geometry, map) {+ const textured = part(name, { ...geometry, uvs: new Float32Array(geometry.positions.length / 3 * 2) });+ textured.material.map = map;+ return textured;+}++function descriptor(size = 8) {+ return { image: { width: size, height: size }, colorSpace: 'srgb' };+}++test('replaceParts adds a textured part and uploads its texture once', () => {+ const state = allocationRenderer();+ const plain = part('plain', box());+ state.renderer.replaceParts([plain]);+ const bytesBefore = state.renderer.textureBytes;+ const map = descriptor();+ const textured = texturedPart('textured', sphere(12, 8), map);+ state.renderer.replaceParts([plain, textured]);+ const batch = state.renderer.partLocations.get(textured).batch;+ assert.equal(batch.textures[0], state.renderer.textures.get(map));+ assert.equal(batch.textures[0].descriptor, map);+ assert.ok(state.renderer.textureBytes > bytesBefore);+});++test('replaceParts removes a textured part and deletes its batch, buffers and texture', () => {+ const state = allocationRenderer();+ const plain = part('plain', box());+ const map = descriptor();+ const textured = texturedPart('textured', sphere(12, 8), map);+ state.renderer.replaceParts([plain, textured]);+ const texture = state.renderer.textures.get(map);+ assert.ok(state.liveTextures.has(texture));+ const bytesWithTexture = state.renderer.textureBytes;+ state.renderer.replaceParts([plain]);+ assert.equal(state.renderer.batches.length, 1);+ assert.equal(state.renderer.partLocations.has(textured), false);+ assert.equal(state.liveTextures.has(texture), false);+ assert.equal(state.renderer.textures.has(map), false);+ assert.equal(state.liveArrays.size, 1);+ assert.equal(state.liveBuffers.size, 4);+ assert.ok(state.renderer.textureBytes < bytesWithTexture);+ assert.equal(state.renderer.textureBytes, 4);+});++test('a texture shared by two parts survives removing one of them', () => {+ const state = allocationRenderer();+ const map = descriptor();+ const cube = texturedPart('cube', box(), map);+ const ball = texturedPart('ball', sphere(12, 8), map);+ state.renderer.replaceParts([cube, ball]);+ const texture = state.renderer.textures.get(map);+ const bytes = state.renderer.textureBytes;+ state.renderer.replaceParts([cube]);+ assert.equal(state.liveTextures.has(texture), true);+ assert.equal(state.renderer.textures.get(map), texture);+ assert.equal(state.renderer.textureBytes, bytes);+ state.renderer.replaceParts([]);+ assert.equal(state.liveTextures.has(texture), false);+ assert.equal(state.renderer.textureBytes, 4);+});++test('replaceParts no longer rejects textured parts', () => {+ const state = allocationRenderer();+ const textured = texturedPart('textured', box(), descriptor());+ assert.doesNotThrow(() => state.renderer.replaceParts([textured]));+ assert.doesNotThrow(() => state.renderer.replaceParts([]));+});