3D engine that AI agents drive
Edit the topology of imported GLB parts
Nguyen Xuan An81fab2ad379b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 44ccbd3a..f421c3ac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Edit the topology of imported GLB parts (part of issue #48, no new tool). `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` of an imported asset: the part becomes a welded polygon mesh with axis tags and a `material-<n>` tag, the edit log is kept in the asset recipe as `meshEdits` (checkpoints, export and replay work), and every result passes `validateTopology`. New vertices take skin weights, morph deltas and vertex colours from the nearest original surface point and faces left without UVs read the nearest UV island; on a skinned or morphed part an edit more than a quarter of the part's bounds diagonal from the original surface is rejected with the next action. `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`. Measured on RobotExpressive through MCP (`npm run smoke:imported-topology`): a through hole in the closed left leg (98 to 210 triangles, still one closed part), a cut in the skinned right hand (124 to 109) and the morphed head (154 to 134), a 3 m extrude on the head rejected, GLB export and checkpoint restore intact. Suite task `robot-leg-hole`.+- Add relations between parts (part of issue #44, no new tool): a mesh node takes `relations` (`attach`, `gap`, `flush`, `align`, `centered`, up to 8) against other mesh nodes, or against the faces of one carrying a mesh tag (`region`). They work on world bounds, are solved after geometry exists and again on every `scene_apply`, so one edit to a body keeps the parts that sit against it. Unknown IDs and tags, two relations on one axis and cycles (a part waiting on its own child included) are rejected with the next action; solving is deterministic and independent of node order. The code loads on demand (`relations`). The schema carries only a generic `relations` list (597 bytes over `scene_create` and `scene_apply` together); the kinds and fields are in `scene_capabilities` `relations`, and the engine validates them. Measured on Sonnet (3 runs each), relations did not cut tool calls or errors: the kettle resize took 3.3 calls against 3.0, and a 12-part desk with three inspected resizes took 8 against 8, with 13% fewer output tokens (3,833 against 4,403) and the same cost and pass rate. The suite gains `kettle-resize`, `desk-resize` and their plain twins, and `touches` and `centreAt` checks.- Add render passes, depth of field and camera motion blur (issue #54, first slice). Render jobs of kind `image` or `stills` take `settings.passes` (`albedo`, `normal`, `emission`, `depth`, `objectId`) and write each as a raw, unantialiased PNG beside the lit image (`render-depth.png`, `frame-3-objectId.png`); depth is 16 bits over 100 m in red and green, object IDs are 24 bits with the part names in the job metrics. In code, `renderer.render({ pass })` draws a pass into its own non-multisampled target. `effects.depthOfField` (`blur`, `focusDistance`) and `effects.motionBlur` (`shutter`) are new recipe effects: fixed sample patterns and a per-pixel rotation from the pixel position, so a seek to a frame repeats the same pixels. They live in the new `67js/addons/camera-effects` entry; the preview installs it, and the core renderer only gains a stage hook and the pass branch (a compiled-out shader feature). Motion blur follows camera tracks only, sampled from time at `motion.start + elapsed - shutter`. Measured on SwiftShader through MCP (`npm run smoke:render-passes`): 8 stills with 5 passes each, then four seeks, all byte-identical to the same frame in the sequence. Temporal anti-aliasing, accumulation and the compositing graph of #54 are not part of this slice.diff --git a/ROADMAP.md b/ROADMAP.mdindex f6297719..230127c9 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -37,7 +37,7 @@ The npm package includes the prebuilt `67js-mcp` command with lazy browser start## Next-1. Extend imported asset sessions with node-level editing, topology changes and deformed geometry diagnostics.+1. Extend imported asset sessions with deformed geometry diagnostics and merging several parts into one editable mesh (part topology edits are in the next release).2. Extend visual review with posed geometry bounds, automatic framing and compact rendered diagnostics.3. Extend render jobs with hardware encoder selection, audio, longer sequences and measured adaptive output quality.4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjsindex e1fe72a7..b0bb8d3d 100644--- a/bench/agent-modeling/check.mjs+++ b/bench/agent-modeling/check.mjs@@ -134,6 +134,14 @@ function checkOne(check, measures) {const along = offset.reduce((total, value, axis) => total + value * check.direction[axis], 0);return { pass: along >= check.minOffset, detail: `${check.node} sits ${round(along)} m toward ${JSON.stringify(check.direction)} at t=${check.time}` };}+ case 'assetHole': {+ const target = measures.editedParts.find(part => part.label === check.part);+ if (!target) return { pass: false, detail: `no mesh edits on the part ${check.part}; edited parts: ${measures.editedParts.map(part => part.label).join(', ') || 'none'}` };+ const others = measures.editedParts.filter(part => part !== target).map(part => part.label);+ const volumeKept = target.volumeRatio >= check.volumeKept[0] && target.volumeRatio <= check.volumeKept[1];+ const pass = target.genus === check.genus && target.closedParts === 1 && target.partCount === 1 && target.lintOk && volumeKept && others.length === 0;+ return { pass, detail: `${check.part}: genus ${target.genus}, ${target.partCount} part(s), lint ${target.lintOk}, ${round(target.volumeRatio)} of the volume kept, other edited parts ${others.join(', ') || 'none'}` };+ }case 'assetClip': {return { pass: measures.clipName === check.name, detail: `clip ${measures.clipName ?? 'none'}` };}diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjsindex 9e50b14b..aec44cb4 100644--- a/bench/agent-modeling/measure.mjs+++ b/bench/agent-modeling/measure.mjs@@ -239,7 +239,27 @@ async function measureLayerPose(recipe, asset) {}/** Reload an exported recipe for the fixture robot and read which clip and which IK solvers it ended with. */+/** Topology of every imported part the recipe edits: genus, closure, lint, and the volume left after the edits. */+function measureEditedParts(scene, asset, recipe) {+ const labels = new Map(scene.inspect({ limit: 256 }).nodes.map(node => [node.id, node.label]));+ return (recipe.meshEdits ?? []).map(entry => {+ const index = Number(entry.id.slice(5));+ const report = scene.inspectMeshes({ geometries: [entry.id] }).meshes[0];+ const eulerCharacteristic = report.counts.vertices - report.counts.edges + report.counts.faces;+ const originalVolume = signedVolume(asset.parts[index].geometry);+ return {+ id: entry.id, label: labels.get(entry.id), lintOk: report.ok, closedParts: report.parts.closed, partCount: report.parts.count,+ genus: (2 * report.parts.count - eulerCharacteristic) / 2,+ volumeRatio: signedVolume(scene.parts[index].geometry) / originalVolume,+ };+ });+}+export async function measureAssetRecipe(recipe) {+ if (recipe.meshEdits) {+ await loadAllAgentSceneModules();+ await loadMeshBooleans();+ }const asset = await loadFixtureRobot();const scene = createAgentAssetScene(asset, recipe);const layerPose = await measureLayerPose(recipe, await loadFixtureRobot());@@ -254,6 +274,7 @@ export async function measureAssetRecipe(recipe) {return {clipName: recipe.animation ? asset.animations[recipe.animation.clip]?.name : null,layerPose,+ editedParts: measureEditedParts(scene, asset, recipe),camera: recipe.camera ?? null,reachSolvers: solvers.filter(solver => solver.type === 'two-bone').map(solver => {const [firstTarget, lastTarget] = endpoints(solver.target);diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjsindex bc711383..c25c2a35 100644--- a/bench/agent-modeling/references.mjs+++ b/bench/agent-modeling/references.mjs@@ -217,6 +217,13 @@ export const REFERENCES = {],},},+ 'robot-leg-hole': {+ format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),+ meshEdits: [{+ id: 'mesh-10',+ edits: [{ op: 'boolean', operation: 'difference', cutter: { type: 'cylinder', segments: 24 }, scale: [0.0003, 0.01, 0.0003] }],+ }],+ },'robot-reach': {format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),animation: { clip: 2, time: 0 },diff --git a/bench/agent-modeling/results/2026-10-31-12-46-sonnet-imported-topology.json b/bench/agent-modeling/results/2026-10-31-12-46-sonnet-imported-topology.jsonnew file mode 100644index 00000000..998a19d9--- /dev/null+++ b/bench/agent-modeling/results/2026-10-31-12-46-sonnet-imported-topology.json@@ -0,0 +1,73 @@+{+ "run": "2026-10-31-12-46-sonnet-imported-topology",+ "model": "claude-sonnet-5-5",+ "date": "2026-10-31T12:47:26.909Z",+ "skill": false,+ "runsPerTask": 1,+ "passed": 1,+ "tasks": 1,+ "toolCalls": 8,+ "costUsd": 0.36,+ "byModel": {+ "claude-sonnet-5-5": {+ "runs": 1,+ "passed": 1,+ "successRate": 1,+ "toolCalls": 8,+ "toolErrors": 1,+ "inputTokens": 615234,+ "outputTokens": 2130,+ "costUsd": 0.36,+ "tasks": {+ "robot-leg-hole": {+ "runs": 1,+ "passed": 1,+ "successRate": 1,+ "toolCalls": 8,+ "toolErrors": 1,+ "inputTokens": 615234,+ "outputTokens": 2130,+ "costUsd": 0.36+ }+ }+ }+ },+ "records": [+ {+ "task": "robot-leg-hole",+ "attempt": 1,+ "pass": true,+ "passed": 1,+ "total": 1,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 8,+ "toolErrors": 1,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_asset_catalog": 1,+ "scene_create_asset": 1,+ "mesh_inspect": 3,+ "scene_inspect": 1,+ "mesh_edit": 1,+ "scene_export_recipe": 1+ },+ "features": {+ "geometryTypes": [],+ "meshOperations": [],+ "motionIk": [],+ "motionTracks": 0+ },+ "look": {+ "error": "Cannot read properties of undefined (reading 'format')"+ },+ "turns": 10,+ "costUsd": 0.3568561,+ "inputTokens": 615234,+ "outputTokens": 2130,+ "wallSeconds": 37,+ "exitCode": 0,+ "stopped": "success"+ }+ ]+}diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjsindex 9b73685a..b907bcae 100644--- a/bench/agent-modeling/tasks.mjs+++ b/bench/agent-modeling/tasks.mjs@@ -190,6 +190,18 @@ finished, call scene_export_recipe once: the exported recipe is what gets graded{ kind: 'shot', minSideOffset: 2, maxDepthOffset: 2, targetHeight: [0.5, 4], distance: [3, 12] },],},+ {+ id: 'robot-leg-hole',+ assets: true,+ prompt: `The asset catalog holds an imported robot character. Create a scene from it. Cut one round hole, about 0.06 m+across in scene units, straight through the robot's left leg (the part labelled LegL), so that the leg is still a single+closed solid with exactly one hole through it. Do not change any other part. Check the leg with mesh_inspect when you are+done. When it is finished, call scene_export_recipe once: the exported recipe is what gets graded.`,+ ownPreamble: true,+ checks: [+ { kind: 'assetHole', part: 'LegL', genus: 1, volumeKept: [0.9, 0.995] },+ ],+ },];export const TASKS = [diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex 85a56cb9..1adc2853 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 277673,- "gzip": 79031,- "brotli": 67391+ "min": 277742,+ "gzip": 79043,+ "brotli": 67459},"entry:model": {"min": 40093,@@ -64,9 +64,9 @@"brotli": 12998},"entry:mesh": {- "min": 211151,- "gzip": 71754,- "brotli": 60810+ "min": 211217,+ "gzip": 71785,+ "brotli": 60836},"entry:shrinkwrap": {"min": 56188,@@ -129,24 +129,24 @@"brotli": 762},"entry:agent-scene": {- "min": 195659,- "gzip": 59292,- "brotli": 51242+ "min": 196231,+ "gzip": 59549,+ "brotli": 51498},"entry:agent-scene+lazy": {- "min": 513028,- "gzip": 170623,- "brotli": 148898+ "min": 521318,+ "gzip": 173529,+ "brotli": 151186},"entry:agent-asset": {- "min": 286211,- "gzip": 88215,- "brotli": 76934+ "min": 290533,+ "gzip": 90002,+ "brotli": 78364},"entry:agent-asset+lazy": {- "min": 545319,- "gzip": 179573,- "brotli": 156501+ "min": 557359,+ "gzip": 184007,+ "brotli": 160003},"entry:hdri": {"min": 8075,@@ -174,14 +174,14 @@"brotli": 65528},"scene:agent-scene": {- "min": 300023,- "gzip": 86690,- "brotli": 74386+ "min": 300528,+ "gzip": 86909,+ "brotli": 74567},"scene:agent-scene+lazy": {- "min": 617392,- "gzip": 198024,- "brotli": 172011+ "min": 625615,+ "gzip": 200890,+ "brotli": 174248}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 97ad3088..18f652f4 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -30,8 +30,8 @@"entry:texture-set": 900,"entry:agent-scene": 60500,"entry:agent-scene+lazy": 174100,- "entry:agent-asset": 90000,- "entry:agent-asset+lazy": 183200,+ "entry:agent-asset": 90500,+ "entry:agent-asset+lazy": 184500,"entry:hdri": 3300,"entry:camera-effects": 8600,"entry:render-passes": 1700,diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex d8898e1c..caf70bed 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,5 +1,5 @@{- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations",+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; raised by 515 for the scene_capabilities result for imported mesh edits, schema total measured 188953","schemaTotalBytes": 189210,"schemaToolBytes": {"scene_create": 60495,@@ -10,7 +10,7 @@},"schemaOtherToolBytes": 4000,"resultBytes": {- "scene_capabilities": 5885,+ "scene_capabilities": 6400,"scene_create": 1400,"scene_inspect": 1400,"mesh_inspect": 1200,diff --git a/docs/agent-asset.md b/docs/agent-asset.mdindex 7311683e..88a9f77c 100644--- a/docs/agent-asset.md+++ b/docs/agent-asset.md@@ -91,14 +91,22 @@ Changing the clip defaults time to zero. With `clip:null`, omit time.Environment`volumeFog` and effects `bloom` merge partial nested records. A supplied`pointLights` list replaces the full list, including `[]` to clear it.-Geometry and topology commands reject. Imported mesh editing or sculpting-through MCP is outside this module's contract.+`edit-mesh` (`mesh_edit` with a part ID such as `mesh-10`) edits the topology of one imported part with the same+edit vocabulary as a recipe mesh; the log is kept in the recipe as `meshEdits: [{ id, edits }]`. The part becomes a welded+polygon mesh with axis tags and a `material-<n>` tag on every face, and the edits run in the part's local space (imported+parts are often tiny and rotated: `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`). New vertices take+skin weights (four heaviest joints), morph deltas and vertex colours from the nearest original surface point; faces an edit+leaves without UVs read the nearest original UV island. On a skinned or morphed part an edit that puts geometry farther+than a quarter of the part's bounds diagonal from the original surface is rejected, because the transfer would be a guess.+Edits are atomic, undone by checkpoint, and every output passes `validateTopology`. `mesh_stack`, relations and other+geometry commands still reject.`parts` is a frozen, stable list. Part objects, matrices, geometry, skin, morph,and material wrapper identities survive every successful transaction. Materialfactor getters read immutable snapshots. Map descriptors retain their original-references. `topologyRevision` remains zero. Renderer adapters can call their-ordinary update path after edits without replacing geometry resources.+references. Part objects, geometry and `topologyRevision` change only when the edit log changes (`parts` is then a new+frozen list whose matrices are the same arrays); renderer adapters take a new renderer for an edited asset, because skinned+and morphed parts cannot be replaced in place. Pose, look and material edits keep every identity.`checkpoint()` returns an opaque private handle. At most eight handles can belive. `restore(handle, {expectedRevision})` publishes its recipe and increments@@ -114,7 +122,7 @@ budgets still belong to `parseGltf()`. Configure them before decoding.## Inspection and ownership`exportRecipe()` and the camera/look getters return detached JSON.-`inspect({ids?, limit?, includeBounds?})` returns revision, fixed topology+`inspect({ids?, limit?, includeBounds?})` returns revision, topologyrevision, IDs, labels, counts, unique geometry bytes, animation metadata, andat most 64 nodes by default. The limit can be 1 to 256. Bounds requests scan atmost two million authored base vertices across the selected visible nodes.diff --git a/docs/mcp.md b/docs/mcp.mdindex cc91a362..bdb0dc8e 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -207,7 +207,7 @@ The committed revision and separate render failure remain visible in that case.Request a smaller `scene_look` to release large frame targets before retrying reconciliation.The [asset scene contract](agent-asset.md) defines root transforms, material overrides and absolute clip/time samples.-Imported scenes retain their decoded topology. Mesh membership edits remain specific to procedural scenes.+Imported scenes decode once, and `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` to edit or check the topology of one imported part (see [the asset scene contract](agent-asset.md)); `mesh_stack` stays procedural.Their bounds describe authored base vertices in the sampled world transforms, without claiming deformed skin or morph bounds.The tools expose no arbitrary JavaScript execution, remote URLs or arbitrary caller-selected file paths.diff --git a/docs/parity.md b/docs/parity.mdindex 0dc81664..7e4d39a2 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -242,7 +242,7 @@ The goal also needs this work, and no page in the Blender manual covers it.| Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 || Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 || Relations between parts | partial | The agent version of snapping: node `relations` (`attach`, `gap`, `flush`, `align`, `centered`) over world bounds or a tagged region, solved again on every edit, cycles rejected. Tests in [part-relations](../tests/part-relations.test.js); suite tasks `kettle-resize` and `desk-resize` with plain twins (no gain in calls measured on Sonnet). No snapping to edges or vertices, no relation on the part's own tagged region. | #44 |-| Imported mesh editing | missing | Imported assets accept poses and transforms. Their topology is fixed. | #48 |+| Imported mesh editing | partial | `mesh_edit` takes an imported part ID. Skin weights, morph deltas and colours of new vertices come from the nearest original surface point, missing UVs from the nearest island; an edit that reaches too far on a skinned or morphed part is rejected. Not here: merging several parts into one mesh, tags from several material groups. Evidence: tests/agent-asset-mesh.test.js, scripts/smoke-imported-topology.mjs. | #48 || Rendering backend | missing | WebGL2 only. WebGPU is not evaluated. | #56 || Terrain and navigation | partial | Terrain with 4 splat layers and no holes. There is no navmesh. | #64 || Tool cost and errors | partial | Lint and errors exist. No budget limits schema size, and not every error is checked. | #65, #66 |diff --git a/package.json b/package.jsonindex cc0fa3fa..394c1ddf 100644--- a/package.json+++ b/package.json@@ -109,6 +109,7 @@"smoke:site": "node scripts/smoke-site.mjs","publish:ci": "node scripts/publish-ci.mjs","smoke:character": "node scripts/smoke-character.mjs",+ "smoke:imported-topology": "node scripts/smoke-imported-topology.mjs","smoke:agent-character": "node scripts/smoke-agent-character.mjs","smoke:agent-review": "node scripts/smoke-agent-review.mjs","smoke:agent-branches": "node scripts/smoke-agent-branches.mjs",diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex d9556838..7a57d134 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -90,7 +90,8 @@ function draw(record, time = 0, camera = record.scene.camera, frameOptions = {})record.renderer.resize();if (record.rendererTopology !== record.scene.topologyRevision) {const textured = hasPatternTextures(record.scene.parts);- if (textured || record.rendererTextured) {+ // replaceParts refuses skinned and morphed parts, so an edited imported part takes a new renderer as well.+ if (textured || record.rendererTextured || record.asset) {rebuildRenderer(record);} else {record.renderer.replaceParts(record.scene.parts);@@ -274,7 +275,9 @@ function clipExport(record, clipIndex) {const sourceClip = clipFromGltfAnimation(animation);const name = String(animation.name || `clip ${clipIndex}`);const clip = { ...sourceClip, name, tracks: [...sourceClip.tracks, ...weightTracksFromGltfAnimation(animation)] };- return { parts: [...asset.parts], options: { nodes: asset.nodes, clips: [clip] } };+ // Edited parts export their edited geometry on the source part's own matrix, skin and morph.+ const parts = asset.parts.map((part, index) => scene.parts[index].geometry === part.geometry ? part : { ...part, geometry: scene.parts[index].geometry });+ return { parts, options: { nodes: asset.nodes, clips: [clip] } };}function bytesToBase64(bytes) {@@ -454,6 +457,7 @@ window.__agentPreview = {}let asset;try {+ if (input.recipe?.meshEdits) await loadAllAgentSceneModules();asset = await parseGltf(bytes.buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });return createPreview(createAgentAssetScene(asset, input.recipe), input, asset);} catch (error) {@@ -467,8 +471,9 @@ window.__agentPreview = {inspectMeshes({ sessionId, ...options }) {const scene = requireSession(sessionId).scene;if (typeof scene.inspectMeshes !== 'function') {- throw new TypeError('mesh_inspect supports procedural recipe scenes. Imported asset scenes are not inspected as polygon meshes yet.');+ throw new TypeError('mesh_inspect needs a procedural recipe scene or an imported asset scene.');}+ if (!allAgentSceneModulesLoaded()) return loadAllAgentSceneModules().then(() => this.inspectMeshes({ sessionId, ...options }));return { sessionId, ...scene.inspectMeshes(options) };},apply(input) {@@ -492,7 +497,7 @@ window.__agentPreview = {editMesh({ sessionId, expectedRevision, geometry, edits, replace }) {const record = requireSession(sessionId);if (typeof record.scene.inspectMeshes !== 'function') {- throw new TypeError('mesh_edit supports procedural recipe scenes. Imported asset scenes have no editable mesh geometry yet.');+ throw new TypeError('mesh_edit needs a procedural recipe scene or an imported asset scene.');}const operation = { type: 'edit-mesh', geometry, edits, ...(replace === undefined ? {} : { replace }) };return afterMeshBooleans(edits, () => {@@ -503,8 +508,8 @@ window.__agentPreview = {},setMeshStack({ sessionId, expectedRevision, geometry, stack, apply }) {const record = requireSession(sessionId);- if (typeof record.scene.inspectMeshes !== 'function') {- throw new TypeError('mesh_stack supports procedural recipe scenes.');+ if (typeof record.scene.inspectMeshes !== 'function' || record.asset) {+ throw new TypeError('mesh_stack supports procedural recipe scenes. Imported parts take mesh_edit with a mesh ID such as mesh-0.');}const operation = { type: 'set-mesh-stack', geometry, ...(stack === undefined ? {} : { stack }), ...(apply === undefined ? {} : { apply }) };const status = this.applyLoaded({ sessionId, operations: [operation], expectedRevision });diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 9160b0f8..a23937be 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -576,8 +576,8 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));- register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));- register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace driven by field expressions (math, noise, attributes; also a {"field":expr} selection rule), and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));+ register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Also imported asset parts (mesh-0). Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));+ register('mesh_edit', 'Append edits to a recipe mesh geometry or an imported asset part such as mesh-0 (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace driven by field expressions (math, noise, attributes; also a {"field":expr} selection rule), and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh, or an imported part such as mesh-0.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel, uv_unwrap, subdivide, set_position, displace, decimate, remesh), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.'), branch: branchName.optional().describe('Fork: store the result as this branch (up to 8), leaving the scene unchanged.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG, optionally with part labels. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.'), labels: labelsFlag }), readOnly, async argumentsValue => {diff --git a/scripts/smoke-imported-topology.mjs b/scripts/smoke-imported-topology.mjsnew file mode 100644index 00000000..626b4bfb--- /dev/null+++ b/scripts/smoke-imported-topology.mjs@@ -0,0 +1,100 @@+// Edits the topology of RobotExpressive parts through the real MCP server: a through hole in a closed leg, a cut in a+// skinned hand and in a morphed head, an edit that must be rejected, a checkpoint restore and a GLB export of the result.+// Run `npm run prepare:release` first; the preview page comes from its build. Prints the measured outcome per part.+import assert from 'node:assert/strict';+import { copyFile, mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';+import { constants, setPriority, tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { parseGltf } from '../src/gltf.js';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const backend = process.argv[2] ?? 'gpu';+const directory = await mkdtemp(join(tmpdir(), '67js-topology-'));+const assets = join(directory, 'assets');+await mkdir(assets);+await copyFile(resolve('tests/fixtures/RobotExpressive.glb'), join(assets, 'robot.glb'));++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [resolve('scripts/mcp-server.mjs'), '--backend', backend, '--memory', '192', '--assets', assets, '--jobs', join(directory, 'jobs')],+ stderr: 'pipe',+ cwd: process.cwd(),+});+const client = new Client({ name: '67js-topology-smoke', version: '1' });++async function call(name, argumentsValue = {}) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 180000 });+ assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content).slice(0, 700)}`);+ return result.structuredContent;+}++async function callExpectingError(name, argumentsValue) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 180000 });+ assert.ok(result.isError, `${name} should have been rejected`);+ return JSON.stringify(result.content);+}++function summarize(mesh) {+ return { triangles: mesh.counts.triangles, closed: mesh.parts.closed, ok: mesh.ok, transfer: mesh.transfer };+}++const report = {};+try {+ await client.connect(transport);+ const catalog = await call('scene_asset_catalog');+ const created = await call('scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId: catalog.assets[0].assetId } });+ const { sessionId } = created;+ let { revision } = created;+ const before = (await call('mesh_inspect', { sessionId, geometries: ['mesh-10', 'mesh-15', 'mesh-3'] })).meshes;+ report.before = before.map(summarize);+ const checkpoint = await call('scene_checkpoint', { sessionId });++ const hole = await call('mesh_edit', {+ sessionId, expectedRevision: revision, geometry: 'mesh-10',+ edits: [{ op: 'boolean', operation: 'difference', cutter: { type: 'cylinder', segments: 24 }, scale: [0.0003, 0.01, 0.0003] }],+ });+ assert.equal(hole.renderSucceeded, true, hole.renderError);+ assert.equal(hole.topologyRevision, 1);+ revision = hole.revision;+ report.hole = summarize(hole.mesh);+ assert.ok(hole.mesh.parts.closed === 1 && hole.mesh.ok);++ const hand = await call('mesh_edit', { sessionId, expectedRevision: revision, geometry: 'mesh-15', edits: [{ op: 'delete', select: { tag: 'top' } }] });+ revision = hand.revision;+ report.skinnedHand = summarize(hand.mesh);+ const head = await call('mesh_edit', { sessionId, expectedRevision: revision, geometry: 'mesh-3', edits: [{ op: 'delete', select: { tag: 'top' } }] });+ revision = head.revision;+ report.morphedHead = summarize(head.mesh);++ const rejection = await callExpectingError('mesh_edit', {+ sessionId, expectedRevision: revision, geometry: 'mesh-3', edits: [{ op: 'extrude_face_region', select: { tag: 'front' }, offset: 3 }],+ });+ assert.match(rejection, /Keep edits within/);+ report.rejection = rejection.slice(0, 160);++ const withClip = await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-animation', clip: 10, time: 0.3 }] });+ assert.equal(withClip.renderSucceeded, true, withClip.renderError);+ revision = withClip.revision;+ const glb = await call('scene_export_glb', { sessionId });+ report.glbBytes = glb.bytes;+ const reread = await parseGltf((await readFile(glb.path)).buffer.slice(0), { maxVertices: 500000 });+ assert.equal(reread.parts.length, 19);+ const leg = reread.parts[10];+ assert.equal(leg.geometry.indices.length / 3, hole.mesh.counts.triangles, 'the exported leg is the edited one');+ assert.ok(reread.parts[15].skin, 'the edited hand keeps its skin in the export');+ reread.dispose();+ const exported = await call('scene_export_recipe', { sessionId });+ assert.deepEqual((exported.recipe ?? exported).meshEdits.map(entry => entry.id).sort(), ['mesh-10', 'mesh-15', 'mesh-3']);++ const restored = await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: revision });+ assert.equal(restored.renderSucceeded, true, restored.renderError);+ const after = (await call('mesh_inspect', { sessionId, geometries: ['mesh-10'] })).meshes[0];+ assert.equal(after.counts.triangles, before[0].counts.triangles);+ await call('scene_dispose', { sessionId });+ console.log(`Imported topology passed on ${backend}: ${JSON.stringify(report)}`);+} finally {+ await client.close();+ await rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 300 }).catch(error => console.warn(`Left ${directory}: ${error.code}`));+}diff --git a/skills/build-67js-scene/references/mesh-modeling.md b/skills/build-67js-scene/references/mesh-modeling.mdindex 4037ae6b..2c76ba26 100644--- a/skills/build-67js-scene/references/mesh-modeling.md+++ b/skills/build-67js-scene/references/mesh-modeling.md@@ -51,6 +51,10 @@ Booleans first need `await loadMeshBooleans()` from the same module (and the `maUse checkpoints before risky batches. A failed `mesh_edit` changes nothing, so retrying with a corrected edit is safe.+## Imported parts++`mesh_edit` and `mesh_inspect` also take the part ID of an imported asset (`mesh-10`; `scene_inspect` lists them). Read `mesh_inspect` first: bounds are in the part's local space, which is often tiny and rotated, so use `localToWorldScale` and `localAxesInWorld` to size a cutter or pick a direction. A boolean needs a closed part (`parts.closed` equals `parts.count`); on an open one run `fill_holes` first. A cylinder cutter has radius 1 and height 1 along its Y axis before `scale`. New vertices keep skin weights, morphs and colours by copying the nearest original surface; an edit that reaches far from the surface on a skinned or morphed part is rejected, so cut or inset instead of extruding far. `mesh_stack` does not apply to imported parts.+## Choosing faces and edgesFaces carry tags. A base gets `top`, `bottom`, `side`, `left` (-X), `right` (+X), `front` (+Z), `back` (-Z).diff --git a/src/agent-asset-mesh.js b/src/agent-asset-mesh.jsnew file mode 100644index 00000000..8a7ccade--- /dev/null+++ b/src/agent-asset-mesh.js@@ -0,0 +1,100 @@+import { agentSceneModule } from './agent-scene-modules.js';+import { generateCutterGeometry } from './agent-scene.js';+import { IMPORTED_MESH_EDIT_LIMITS } from './mesh-operations.js';+import { MESH_SMOOTH_ANGLE_DEFAULT } from './agent-scene-capabilities.js';+import { validateSkinGeometry } from './skinning.js';+import { validateMorphGeometry } from './morph.js';++// Mesh edits on the parts of an imported asset. The recipe keeps `meshEdits: [{ id: 'mesh-1', edits: [...] }]`, the+// same edit log a recipe mesh has, so a checkpoint or an exported recipe replays them on the decoded asset. The edited+// geometry is built when the recipe is published and cached by its edit log, so a pose change never rebuilds it.++const MAX_EDITED_VERTICES = 250_000;++function partIdList(records) {+ return records.map(record => record.id).join(', ');+}++/** Validate and copy the `meshEdits` of a recipe. Entries with no edits are dropped. */+export function normalizeMeshEditEntries(input, records) {+ if (input === undefined) return [];+ if (!Array.isArray(input) || input.length > IMPORTED_MESH_EDIT_LIMITS.maxEditedParts) {+ throw new RangeError(`meshEdits must be an array of at most ${IMPORTED_MESH_EDIT_LIMITS.maxEditedParts} parts.`);+ }+ const seen = new Set();+ const entries = [];+ for (const entry of input) {+ const unknownKey = Object.keys(entry ?? {}).find(key => key !== 'id' && key !== 'edits');+ if (!entry || typeof entry !== 'object' || unknownKey || !Array.isArray(entry.edits)) {+ throw new TypeError('Each meshEdits entry is { id, edits } with an edits array.');+ }+ if (!records.some(record => record.id === entry.id) || seen.has(entry.id)) {+ throw new RangeError(`Unknown or repeated mesh ID: ${entry.id}. Imported mesh IDs are ${partIdList(records.slice(0, 8))}...; scene_inspect lists them.`);+ }+ seen.add(entry.id);+ agentSceneModule('mesh').normalizeMeshEdits(entry.edits);+ if (entry.edits.length) entries.push({ id: entry.id, edits: structuredClone(entry.edits) });+ }+ return entries;+}++/** The recipe's meshEdits after one `edit-mesh` operation: edits append to the part's log, or replace it. */+export function meshEditEntriesAfter(entries, operation, records) {+ if (!records.some(record => record.id === operation.geometry)) {+ throw new RangeError(`Unknown mesh ID: ${operation.geometry}. Imported mesh IDs are ${partIdList(records.slice(0, 8))}...; scene_inspect lists them.`);+ }+ if (typeof operation.replace !== 'undefined' && typeof operation.replace !== 'boolean') {+ throw new TypeError('replace must be boolean.');+ }+ if (!Array.isArray(operation.edits)) {+ throw new TypeError('edit-mesh needs an edits array.');+ }+ const existing = entries.find(entry => entry.id === operation.geometry);+ const edits = operation.replace || !existing ? operation.edits : [...existing.edits, ...operation.edits];+ const others = entries.filter(entry => entry.id !== operation.geometry);+ return [...others, { id: operation.geometry, edits }];+}++function failureMessage(record, error) {+ const kind = record.source.skin ? 'skin weights' : 'morph targets';+ return `${record.id} cannot keep its ${kind} after this edit: ${error.message} Undo with scene_restore or replace the edit log, and cut within the existing surface.`;+}++function buildEntry(record, key, edits, describe) {+ const source = record.source.geometry;+ const result = agentSceneModule('mesh').editImportedGeometry(source, edits, {+ maxVertices: MAX_EDITED_VERTICES, smoothAngle: MESH_SMOOTH_ANGLE_DEFAULT, materialTag: record.material.id,+ resolveCutter: cutter => generateCutterGeometry(cutter, MAX_EDITED_VERTICES),+ });+ let morphMetadata;+ try {+ validateSkinGeometry(result.geometry, record.source.skin);+ morphMetadata = validateMorphGeometry(result.geometry, record.source.morph);+ } catch (error) {+ throw new RangeError(failureMessage(record, error));+ }+ agentSceneModule('mesh').registerEditedMesh(result.geometry, result.mesh, result.results);+ return { key, geometry: result.geometry, info: describe(result.geometry), morphMetadata, results: result.results, transfer: result.transfer };+}++/** Edited geometry by part ID for the given entries, reusing entries of `previous` whose edit log is unchanged. */+export function realizeMeshEdits(entries, records, previous, describe) {+ const realized = new Map();+ for (const entry of entries) {+ const key = JSON.stringify(entry.edits);+ const record = records.find(candidate => candidate.id === entry.id);+ const kept = previous.get(entry.id);+ try {+ realized.set(entry.id, kept?.key === key ? kept : buildEntry(record, key, entry.edits, describe));+ } catch (error) {+ if (error.message.startsWith(entry.id)) throw error;+ throw new RangeError(`${entry.id}: ${error.message}`);+ }+ }+ return realized;+}++/** Part IDs and edit log signature, so the scene can tell when the renderer geometry must be rebuilt. */+export function meshEditSignature(realized) {+ return [...realized].map(([id, entry]) => `${id}:${entry.key}`).sort().join('|');+}diff --git a/src/agent-asset.js b/src/agent-asset.jsindex 1771a3a8..3761e802 100644--- a/src/agent-asset.js+++ b/src/agent-asset.js@@ -8,10 +8,13 @@ import { validateMorphGeometry, validateMorphTransform } from './morph.js';import * as agentMotion from './agent-motion.js';import { clipLayerContextFromAsset } from './agent-clip-layers.js';import { clipFromGltfAnimation, createAssetLayerEvaluator, morphClipFromGltfAnimation } from './skeleton-pose.js';-import { registerAgentSceneModule } from './agent-scene-modules.js';+import { registerAgentSceneModule, agentSceneModule } from './agent-scene-modules.js';+import { normalizeMeshEditEntries, meshEditEntriesAfter, realizeMeshEdits, meshEditSignature } from './agent-asset-mesh.js';registerAgentSceneModule('motion', agentMotion);+const MAX_MESH_REPORTS = 16;+const MAX_RECIPE_BYTES = 1024 * 1024;const MAX_CHECKPOINTS = 8;const MAX_OPERATIONS = 256;@@ -26,10 +29,10 @@ const LOOK_OPERATIONS = Object.freeze({});export const AGENT_ASSET_CAPABILITIES = Object.freeze({- format: '67js.asset', schemaVersion: 1, fixedTopology: true,+ format: '67js.asset', schemaVersion: 1, fixedTopology: false,operations: Object.freeze(['set-camera', 'set-environment', 'set-effects', 'set-shadow',- 'set-root', 'set-animation', 'set-material', 'set-asset-node', 'set-motion',+ 'set-root', 'set-animation', 'set-material', 'set-asset-node', 'set-motion', 'edit-mesh',]),boundsKind: 'authored-base-world',});@@ -173,11 +176,11 @@ function localBounds(geometry) {return { min: minimum, max: maximum };}-function framingBounds(records, matrices) {+function framingBounds(geometryInfos, matrices) {const minimum = [Infinity, Infinity, Infinity];const maximum = [-Infinity, -Infinity, -Infinity];- for (let index = 0; index < records.length; index++) {- const bounds = records[index].geometry.bounds;+ for (let index = 0; index < geometryInfos.length; index++) {+ const bounds = geometryInfos[index].bounds;const matrix = matrices[index];for (let corner = 0; corner < 8; corner++) {const point = bounds.min.map((component, axis) => corner & (1 << axis) ? bounds.max[axis] : component);@@ -218,11 +221,11 @@ function validatePositionBounds(maxima, world, skin) {}}-function baseBounds(records, matrices) {+function baseBounds(geometries, matrices) {const minimum = [Infinity, Infinity, Infinity];const maximum = [-Infinity, -Infinity, -Infinity];- for (let index = 0; index < records.length; index++) {- const positions = records[index].source.geometry.positions;+ for (let index = 0; index < geometries.length; index++) {+ const positions = geometries[index].positions;const matrix = matrices[index];for (let offset = 0; offset < positions.length; offset += 3) {for (let axis = 0; axis < 3; axis++) {@@ -332,22 +335,48 @@ export function createAgentAssetScene(asset, inputRecipe) {}return [record.id, Object.freeze(output)];}));- const parts = Object.freeze(records.map(record => {- const part = {- name: record.id, geometry: record.source.geometry,- matrix: new Float32Array(record.source.matrix), material: materialOutputs.get(record.material.id),- };- if (record.source.skin) {- part.skin = record.source.skin;- }- if (record.source.morph) {- part.morph = record.source.morph;- }- if (record.source.castShadow !== undefined) {- part.castShadow = record.source.castShadow;- }- return Object.freeze(part);- }));+ // Parts of edited meshes carry rebuilt geometry. The matrices stay the same arrays, so poses keep writing to them.+ const partMatrices = records.map(record => new Float32Array(record.source.matrix));+ let editedParts = new Map();+ let editSignature = meshEditSignature(editedParts);+ let topologyRevision = 0;++ function geometryOf(record, edited = editedParts) {+ return edited.get(record.id)?.geometry ?? record.source.geometry;+ }++ function geometryInfoOf(record, edited = editedParts) {+ return edited.get(record.id)?.info ?? record.geometry;+ }++ function morphMetadataOf(record, edited = editedParts) {+ return edited.get(record.id)?.morphMetadata ?? morphMetadata.get(record.source.geometry);+ }++ function describeGeometry(geometry) {+ return { maxima: geometryMaxima(geometry), bounds: localBounds(geometry) };+ }++ function buildParts(edited) {+ return Object.freeze(records.map((record, index) => {+ const part = {+ name: record.id, geometry: geometryOf(record, edited),+ matrix: partMatrices[index], material: materialOutputs.get(record.material.id),+ };+ if (record.source.skin) {+ part.skin = record.source.skin;+ }+ if (record.source.morph) {+ part.morph = record.source.morph;+ }+ if (record.source.castShadow !== undefined) {+ part.castShadow = record.source.castShadow;+ }+ return Object.freeze(part);+ }));+ }++ let parts = buildParts(editedParts);const capabilities = Object.freeze({...AGENT_ASSET_CAPABILITIES,animations: asset.animations.length,@@ -359,7 +388,7 @@ export function createAgentAssetScene(asset, inputRecipe) {function normalize(input) {const candidate = copiedJson(input);- knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides', 'nodeOverrides', 'motion'], 'asset recipe');+ knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides', 'nodeOverrides', 'motion', 'meshEdits'], 'asset recipe');if (candidate.format !== '67js.asset' || candidate.schemaVersion !== 1 ||typeof candidate.assetId !== 'string' || candidate.assetId.toLowerCase() !== canonicalAssetId) {throw new RangeError('Expected the bound 67js.asset schemaVersion 1 assetId.');@@ -421,6 +450,10 @@ export function createAgentAssetScene(asset, inputRecipe) {camera: view.camera, environment: view.environment, effects: view.effects, shadow: view.shadow,root: rootFrom(candidate.root), animation, materialOverrides: normalizedOverrides, nodeOverrides: normalizedNodes,});+ const meshEdits = normalizeMeshEditEntries(candidate.meshEdits, records);+ if (meshEdits.length) {+ result.meshEdits = meshEdits;+ }if (candidate.motion?.ik?.length && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {throw new RangeError('Motion ik needs a uniform asset root scale.');}@@ -504,10 +537,11 @@ export function createAgentAssetScene(asset, inputRecipe) {if (asset.parts.length !== records.length) {throw new RangeError('Decoded part membership must remain fixed.');}+ const stagedEdits = realizeMeshEdits(candidate.meshEdits ?? [], records, editedParts, describeGeometry);for (let index = 0; index < records.length; index++) {const record = records[index];const source = record.source;- if (asset.parts[index] !== source || source.geometry !== parts[index].geometry ||+ if (asset.parts[index] !== source || geometryOf(record) !== parts[index].geometry ||source.skin !== parts[index].skin || source.morph !== parts[index].morph ||source.matrix !== record.sourceMatrix || source.skin?.jointMatrices !== record.jointMatrices ||source.skin?.jointWorldMatrices !== record.jointWorldMatrices || source.morph?.weights !== record.morphWeights ||@@ -536,17 +570,17 @@ export function createAgentAssetScene(asset, inputRecipe) {throw new RangeError('Asset root/world matrices must remain finite and nonsingular at Float32 precision.');}if (posed.skin) {- validateSkinPose(posed.skin, record.source.geometry, world);+ validateSkinPose(posed.skin, geometryOf(record, stagedEdits), world);}if (posed.morph) {- validateMorphTransform(posed.morph, morphMetadata.get(record.source.geometry), world, posed.skin);+ validateMorphTransform(posed.morph, morphMetadataOf(record, stagedEdits), world, posed.skin);} else {- validatePositionBounds(record.geometry.maxima, world, posed.skin);+ validatePositionBounds(geometryInfoOf(record, stagedEdits).maxima, world, posed.skin);}return world;});if (autoFrame) {- candidate.camera = framedCamera(framingBounds(records, stagedMatrices));+ candidate.camera = framedCamera(framingBounds(records.map(record => geometryInfoOf(record, stagedEdits)), stagedMatrices));candidate = normalize(candidate);stagedSampler = agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate));sampled = targetTime === null ? null : stagedSampler.sample(targetTime);@@ -579,6 +613,13 @@ export function createAgentAssetScene(asset, inputRecipe) {for (let index = 0; index < parts.length; index++) {Float32Array.prototype.set.call(parts[index].matrix, stagedMatrices[index]);}+ const stagedSignature = meshEditSignature(stagedEdits);+ if (stagedSignature !== editSignature) {+ editedParts = stagedEdits;+ editSignature = stagedSignature;+ parts = buildParts(editedParts);+ topologyRevision++;+ }if (transientTime === undefined) {recipe = candidate;sampler = stagedSampler;@@ -629,12 +670,15 @@ export function createAgentAssetScene(asset, inputRecipe) {publish(initialRecipe, cameraOmitted, false);return Object.freeze({- parts, capabilities,+ capabilities,+ get parts() {+ return parts;+ },get revision() {return revision;},get topologyRevision() {- return 0;+ return topologyRevision;},get camera() {return structuredClone(sampledCamera);@@ -756,8 +800,11 @@ export function createAgentAssetScene(asset, inputRecipe) {override[field] = operation[field];}}+ } else if (operation.type === 'edit-mesh') {+ knownKeys(operation, ['type', 'geometry', 'edits', 'replace'], 'operation');+ candidate.meshEdits = meshEditEntriesAfter(candidate.meshEdits ?? [], operation, records);} else {- throw new TypeError('Unsupported asset operation. Geometry and topology editing are unavailable.');+ throw new TypeError('Unsupported asset operation. Imported parts take edit-mesh (mesh_edit with a mesh ID such as mesh-0); other geometry changes are unavailable.');}}return publish(candidate);@@ -789,7 +836,7 @@ export function createAgentAssetScene(asset, inputRecipe) {return sourceNodes.get(id);});const nodes = structuredClone(selected.slice(offset, offset + limit));- return { revision, topologyRevision: 0, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(), ...diagnosticsReport(),+ return { revision, topologyRevision, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(), ...diagnosticsReport(),counts: { nodes: sourceNodes.size, joints: [...sourceNodes.values()].filter(node => node.joint).length },nodes, offset, truncated: offset + nodes.length < selected.length,motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null };@@ -805,26 +852,28 @@ export function createAgentAssetScene(asset, inputRecipe) {return record;});const visible = selected.slice(offset, offset + limit);- if (options.includeBounds && visible.reduce((total, record) => total + record.source.geometry.positions.length / 3, 0) > MAX_INSPECTION_VERTICES) {+ if (options.includeBounds && visible.reduce((total, record) => total + geometryOf(record).positions.length / 3, 0) > MAX_INSPECTION_VERTICES) {throw new RangeError('Bounds inspection exceeds two million authored base vertices. Select fewer meshes.');}const nodes = visible.map(record => {const index = Number(record.id.slice(5));const node = {id: record.id, label: record.label, geometry: record.geometry.id, material: record.material.id,- vertices: record.source.geometry.positions.length / 3,- triangles: record.source.geometry.indices.length / 3,- skinned: Boolean(record.source.skin), morphTargets: record.source.geometry.morphTargets?.length ?? 0,+ vertices: geometryOf(record).positions.length / 3,+ triangles: geometryOf(record).indices.length / 3,+ skinned: Boolean(record.source.skin), morphTargets: geometryOf(record).morphTargets?.length ?? 0,+ ...(editedParts.has(record.id) ? { edited: true } : {}),};if (options.includeBounds) {- node.bounds = baseBounds([record], [matrices[index]]);+ node.bounds = baseBounds([geometryOf(record)], [matrices[index]]);node.boundsKind = AGENT_ASSET_CAPABILITIES.boundsKind;}return node;});let geometryBytes = 0;let vertices = 0;- for (const geometry of geometries.keys()) {+ const activeGeometries = new Set(records.map(record => geometryOf(record)));+ for (const geometry of activeGeometries) {vertices += geometry.positions.length / 3;for (const value of Object.values(geometry)) {if (ArrayBuffer.isView(value)) {@@ -836,14 +885,43 @@ export function createAgentAssetScene(asset, inputRecipe) {}}return {- revision, topologyRevision: 0, assetId: canonicalAssetId, ...diagnosticsReport(),- counts: { nodes: parts.length, parts: parts.length, geometries: geometries.size, materials: materials.size, vertices },+ revision, topologyRevision, assetId: canonicalAssetId, ...diagnosticsReport(),+ counts: { nodes: parts.length, parts: parts.length, geometries: activeGeometries.size, materials: materials.size, vertices },geometryBytes, animation: structuredClone(recipe.animation),motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, layers: recipe.motion.layers?.length ?? 0, time: motionTime } : null,animations: asset.animations.map((clip, index) => ({ id: index, label: String(clip.name ?? `Clip ${index}`).slice(0, 256), duration: clip.duration })),nodes, offset, truncated: selected.length > offset + nodes.length,};},+ /** Polygon reports of imported parts, with the edit results and what was transferred to the edited geometry. */+ inspectMeshes(options = {}) {+ knownKeys(options, ['geometries'], 'mesh inspection');+ const requested = options.geometries ?? records.slice(0, MAX_MESH_REPORTS).map(record => record.id);+ if (!Array.isArray(requested) || requested.length > MAX_MESH_REPORTS) {+ throw new RangeError(`Inspect at most ${MAX_MESH_REPORTS} mesh IDs per call.`);+ }+ const meshes = requested.map(id => {+ const index = records.findIndex(record => record.id === id);+ if (index < 0) {+ throw new RangeError(`Unknown mesh ID: ${id}. Imported mesh IDs look like mesh-0, mesh-1; scene_inspect lists them.`);+ }+ const record = records[index];+ const edited = editedParts.get(id);+ const matrix = matrices[index];+ const scale = mat4.getScaling([0, 0, 0], matrix).map(value => Number(value.toPrecision(4)));+ // Where each local axis points in the world, so an agent can place a cutter or select by direction.+ const localAxesInWorld = [0, 4, 8].map(offset => {+ const length = Math.hypot(matrix[offset], matrix[offset + 1], matrix[offset + 2]) || 1;+ return [0, 1, 2].map(axis => Number((matrix[offset + axis] / length).toFixed(3)));+ });+ return {+ geometry: id, ...agentSceneModule('mesh').importedMeshReport(geometryOf(record)),+ ...(edited ? { transfer: edited.transfer } : {}),+ localToWorldScale: scale, localAxesInWorld,+ };+ });+ return { revision, meshes, truncated: false };+ },checkpoint() {if (checkpoints.size >= MAX_CHECKPOINTS) {throw new RangeError('Asset checkpoint budget exhausted. Release a checkpoint.');diff --git a/src/agent-mesh-engine.js b/src/agent-mesh-engine.jsindex 9c7deee0..b3f4fae8 100644--- a/src/agent-mesh-engine.js+++ b/src/agent-mesh-engine.js@@ -4,3 +4,5 @@ export { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';export { generateMeshLods, generateGeometryLods, generateAssetLods } from './mesh-lod.js';export { expandInstancedNodes } from './mesh-instances.js';export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from './mesh-boolean.js';+export { editImportedGeometry } from './mesh-import.js';+export { meshReport as importedMeshReport, registerEditedMesh } from './agent-mesh.js';diff --git a/src/agent-mesh.js b/src/agent-mesh.jsindex 183d290b..58533a46 100644--- a/src/agent-mesh.js+++ b/src/agent-mesh.js@@ -105,6 +105,11 @@ export function generateMeshGeometry(baseGeometry, edits, {return geometry;}+/** Remember the polygon mesh and edit results behind geometry built outside generateMeshGeometry (imported parts). */+export function registerEditedMesh(geometry, mesh, results) {+ polygonMeshes.set(geometry, { mesh, results, stack: [] });+}+/*** Local-space positions of the faces that carry a mesh tag, shaped like geometry so bounds code can read them. Throws a* message naming the next step when the part is a plain shape, or the tag is unknown or on no faces.diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex fd31bafa..c52ef207 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -1,6 +1,7 @@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,+ IMPORTED_MESH_EDIT_LIMITS,} from './mesh-operations.js';// What agent scenes support and their default limits, as plain data. The MCP server reads these without bundling@@ -75,6 +76,13 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({materialMappings: MATERIAL_MAPPINGS,renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png or frame-N-<pass>.png, raw and unantialiased; opaque and cutout geometry only', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; the job result lists the part names' }),materialGraph: Object.freeze({ outputs: MATERIAL_GRAPH_OUTPUTS, operators: MATERIAL_GRAPH_OPERATORS, ...MATERIAL_GRAPH_LIMITS, nodes: MATERIAL_GRAPH_NODES }),+ // mesh_edit on an imported GLB part (geometry mesh-<n>, listed by scene_inspect). Edits run in the part's local space+ // (mesh_inspect gives localToWorldScale and localAxesInWorld) on a welded mesh with axis tags and a material tag.+ importedMeshEdits: Object.freeze({+ ...IMPORTED_MESH_EDIT_LIMITS,+ transfer: 'New vertices take skin weights, morph deltas and colours from the nearest original surface point; faces left without UVs read the nearest original UV island. Not supported: mesh_stack, relations, instancing.',+ 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,lightingSetups: LIGHTING_SETUP_NAMES, defaultLightingSetup: DEFAULT_LIGHTING_SETUP,diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 0687bd95..4d5afc56 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -425,6 +425,12 @@ function cutterEstimate(cutter) {return geometryEstimate({ id: 'cutter', ...cutter });}+/** Render geometry of a boolean cutter record, checked like the cutters of recipe meshes. Used by imported-part edits. */+export function generateCutterGeometry(cutter, maxVertices) {+ cutterEstimate(cutter);+ return generateGeometry(cutter, maxVertices);+}+function generateGeometry(value, maxVertices) {switch (value.type) {case 'box':diff --git a/src/mesh-import.js b/src/mesh-import.jsnew file mode 100644index 00000000..b2ac312d--- /dev/null+++ b/src/mesh-import.js@@ -0,0 +1,261 @@+import { createMeshData, TAG_PREFIX } from './mesh-data.js';+import { meshFromGeometry, withFaceAttributes } from './mesh-convert.js';+import { editMesh } from './mesh-edit.js';+import { validateTopology } from './mesh-validate.js';+import { extractRender } from './mesh-render.js';+import { applyMeshEdits } from './mesh-recipe.js';+import { buildTriangleBvh, traverseTriangleBvh, pointBoxDistance } from './triangle-bvh.js';+import { barycentricWeights, closestPointOnTriangle, readTriangle } from './triangle-math.js';+import { IMPORTED_MESH_EDIT_LIMITS } from './mesh-operations.js';++// Edits imported renderer geometry (an imported GLB part) with the polygon mesh edit vocabulary. The part becomes a+// welded polygon mesh, the edits run on it, and the result is extracted back to renderer geometry. Vertices the edits+// create or move have no skin weights, morph deltas, vertex colours or UVs of their own, so those are transferred from+// the nearest point of the original surface, as Blender's Data Transfer does. The result says how far the transfer+// reached, and an edit that would turn the transfer into a guess is rejected.++const EXACT_WEIGHT = 1 - 1e-6;+const MAX_INFLUENCES = 4;++/** Nearest-surface lookups on the original triangles: which triangle, the barycentric weights and the distance. */+function createSurfaceSampler(geometry) {+ const positions = Float64Array.from(geometry.positions);+ const bvh = buildTriangleBvh(positions, geometry.indices);+ const triangle = new Float64Array(9);+ const candidate = new Float64Array(3);+ const closest = new Float64Array(3);+ const scratchWeights = new Float64Array(3);+ const query = new Float64Array(3);++ function nearest(x, y, z, result) {+ query[0] = x;+ query[1] = y;+ query[2] = z;+ let bestSquared = Infinity;+ let bestTriangle = 0;+ traverseTriangleBvh(+ bvh,+ (bounds, offset) => pointBoxDistance(query, bounds, offset),+ score => score * score <= bestSquared,+ triangleId => {+ readTriangle(positions, geometry.indices, triangleId, triangle);+ closestPointOnTriangle(query, triangle, candidate);+ const squared = (candidate[0] - x) ** 2 + (candidate[1] - y) ** 2 + (candidate[2] - z) ** 2;+ if (squared < bestSquared) {+ bestSquared = squared;+ bestTriangle = triangleId;+ closest.set(candidate);+ }+ return false;+ },+ );+ readTriangle(positions, geometry.indices, bestTriangle, triangle);+ const weights = barycentricWeights(closest, triangle, scratchWeights);+ result.triangle = bestTriangle;+ result.distance = Math.sqrt(bestSquared);+ for (let corner = 0; corner < 3; corner++) {+ result.weights[corner] = weights ? Math.max(0, weights[corner]) : (corner === 0 ? 1 : 0);+ }+ const total = result.weights[0] + result.weights[1] + result.weights[2];+ for (let corner = 0; corner < 3; corner++) result.weights[corner] /= total;+ return result;+ }++ return { nearest, triangleVertex: (triangleId, corner) => geometry.indices[triangleId * 3 + corner] };+}++function createLookup() {+ return { triangle: 0, distance: 0, weights: new Float64Array(3) };+}++function exactCorner(weights) {+ for (let corner = 0; corner < 3; corner++) {+ if (weights[corner] >= EXACT_WEIGHT) return corner;+ }+ return -1;+}++function blendValues(source, size, vertices, weights, target, targetVertex) {+ const exact = exactCorner(weights);+ for (let component = 0; component < size; component++) {+ let value = 0;+ if (exact >= 0) {+ value = source[vertices[exact] * size + component];+ } else {+ for (let corner = 0; corner < 3; corner++) value += source[vertices[corner] * size + component] * weights[corner];+ }+ target[targetVertex * size + component] = value;+ }+}++/** The four heaviest joints among the three corners' influences, weights summing to what the corners summed to. */+function blendInfluences(indices, skinWeights, vertices, weights, targetIndices, targetWeights, targetVertex) {+ const exact = exactCorner(weights);+ const totals = new Map();+ for (let corner = 0; corner < 3; corner++) {+ if (exact >= 0 && corner !== exact) continue;+ const share = exact >= 0 ? 1 : weights[corner];+ for (let influence = 0; influence < MAX_INFLUENCES; influence++) {+ const weight = skinWeights[vertices[corner] * MAX_INFLUENCES + influence] * share;+ if (weight <= 0) continue;+ const joint = indices[vertices[corner] * MAX_INFLUENCES + influence];+ totals.set(joint, (totals.get(joint) ?? 0) + weight);+ }+ }+ const heaviest = [...totals].sort((first, second) => second[1] - first[1]).slice(0, MAX_INFLUENCES);+ const kept = heaviest.reduce((sum, [, weight]) => sum + weight, 0);+ let original = 0;+ for (const weight of totals.values()) original += weight;+ const scale = exact >= 0 || kept === 0 ? 1 : original / kept;+ for (let influence = 0; influence < MAX_INFLUENCES; influence++) {+ const [joint, weight] = heaviest[influence] ?? [0, 0];+ targetIndices[targetVertex * MAX_INFLUENCES + influence] = joint;+ targetWeights[targetVertex * MAX_INFLUENCES + influence] = weight * scale;+ }+}++function boundsDiagonal(positions) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let offset = 0; offset < positions.length; offset++) {+ const axis = offset % 3;+ minimum[axis] = Math.min(minimum[axis], positions[offset]);+ maximum[axis] = Math.max(maximum[axis], positions[offset]);+ }+ return Math.hypot(maximum[0] - minimum[0], maximum[1] - minimum[1], maximum[2] - minimum[2]);+}++function hasZeroUv(uv, start, end) {+ for (let corner = start; corner < end; corner++) {+ if (uv.data[corner * 2] === 0 && uv.data[corner * 2 + 1] === 0) return true;+ }+ return false;+}++/**+ * UVs for faces whose corners have none (an edit that adds corners leaves them at 0,0, and some edits drop the+ * attribute): each such face reads the UV island of the original triangle nearest its centre, so a face never+ * straddles a seam. Returns the mesh and the count of rebuilt faces.+ */+function rebuildMissingUvs(mesh, source, sampler) {+ const existing = mesh.attributes.corner.uv?.size === 2 ? mesh.attributes.corner.uv : undefined;+ const data = existing ? Float32Array.from(existing.data) : new Float32Array(mesh.cornerCount * 2);+ const lookup = createLookup();+ const triangle = new Float64Array(9);+ const weights = new Float64Array(3);+ const point = new Float64Array(3);+ let rebuilt = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ if (existing && !hasZeroUv(existing, start, end)) continue;+ let centreX = 0;+ let centreY = 0;+ let centreZ = 0;+ for (let corner = start; corner < end; corner++) {+ centreX += mesh.positions[mesh.cornerVertices[corner] * 3] / (end - start);+ centreY += mesh.positions[mesh.cornerVertices[corner] * 3 + 1] / (end - start);+ centreZ += mesh.positions[mesh.cornerVertices[corner] * 3 + 2] / (end - start);+ }+ sampler.nearest(centreX, centreY, centreZ, lookup);+ readTriangle(source.positions, source.indices, lookup.triangle, triangle);+ for (let corner = start; corner < end; corner++) {+ const vertex = mesh.cornerVertices[corner];+ point.set(mesh.positions.subarray(vertex * 3, vertex * 3 + 3));+ const found = barycentricWeights(point, triangle, weights);+ for (let component = 0; component < 2; component++) {+ let value = 0;+ for (let cornerOfTriangle = 0; cornerOfTriangle < 3; cornerOfTriangle++) {+ const weight = found ? found[cornerOfTriangle] : (cornerOfTriangle === 0 ? 1 : 0);+ value += source.uvs[sampler.triangleVertex(lookup.triangle, cornerOfTriangle) * 2 + component] * weight;+ }+ data[corner * 2 + component] = value;+ }+ }+ rebuilt++;+ }+ if (!rebuilt) return { mesh, rebuilt };+ const attributes = { point: { ...mesh.attributes.point }, edge: { ...mesh.attributes.edge }, face: { ...mesh.attributes.face }, corner: { ...mesh.attributes.corner } };+ attributes.corner.uv = { data, size: 2 };+ return {+ rebuilt,+ mesh: createMeshData({+ positions: mesh.positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,+ }),+ };+}++/** What the edited geometry keeps of the source, filled from the nearest original surface. Returns the farthest reach. */+function transferVertexAttributes(source, edited, sampler) {+ const vertexCount = edited.positions.length / 3;+ const skinned = Boolean(source.skinIndices && source.skinWeights);+ const morphTargets = source.morphTargets ?? [];+ if (skinned) {+ edited.skinIndices = new Uint16Array(vertexCount * MAX_INFLUENCES);+ edited.skinWeights = new Float32Array(vertexCount * MAX_INFLUENCES);+ }+ if (source.colors) edited.colors = new Float32Array(vertexCount * 3);+ if (morphTargets.length) {+ edited.morphTargets = morphTargets.map(target => ({+ ...(target.positions ? { positions: new Float32Array(vertexCount * 3) } : {}),+ ...(target.normals ? { normals: new Float32Array(vertexCount * 3) } : {}),+ }));+ }+ if (!skinned && !source.colors && !morphTargets.length) return 0;+ const lookup = createLookup();+ const vertices = [0, 0, 0];+ let farthest = 0;+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ sampler.nearest(edited.positions[vertex * 3], edited.positions[vertex * 3 + 1], edited.positions[vertex * 3 + 2], lookup);+ farthest = Math.max(farthest, lookup.distance);+ for (let corner = 0; corner < 3; corner++) vertices[corner] = sampler.triangleVertex(lookup.triangle, corner);+ if (skinned) blendInfluences(source.skinIndices, source.skinWeights, vertices, lookup.weights, edited.skinIndices, edited.skinWeights, vertex);+ if (source.colors) blendValues(source.colors, 3, vertices, lookup.weights, edited.colors, vertex);+ morphTargets.forEach((target, index) => {+ if (target.positions) blendValues(target.positions, 3, vertices, lookup.weights, edited.morphTargets[index].positions, vertex);+ if (target.normals) blendValues(target.normals, 3, vertices, lookup.weights, edited.morphTargets[index].normals, vertex);+ });+ }+ return farthest;+}++function tagFacesOfMaterial(mesh, materialTag) {+ if (!materialTag) return mesh;+ return withFaceAttributes(mesh, { [`${TAG_PREFIX}${materialTag}`]: { data: new Uint8Array(mesh.faceCount).fill(1), size: 1 } });+}++/**+ * Apply mesh edits to imported renderer geometry. `materialTag` names a face tag on every face (an imported part+ * has one material). Returns the edited geometry, its polygon mesh, the per-edit results and what was transferred.+ * Throws a RangeError that names the next action when skin weights or morph targets cannot follow the edit.+ */+export function editImportedGeometry(source, edits, { maxVertices, smoothAngle, resolveCutter, materialTag }) {+ const base = tagFacesOfMaterial(meshFromGeometry(source), materialTag);+ const outcome = applyMeshEdits(base, edits, {+ maxVertices, maxFaces: maxVertices,+ resolveCutter: resolveCutter && (cutter => meshFromGeometry(resolveCutter(cutter))),+ });+ validateTopology(editMesh(outcome.mesh));+ const sampler = createSurfaceSampler(source);+ const withUvs = source.uvs ? rebuildMissingUvs(outcome.mesh, source, sampler) : { mesh: outcome.mesh, rebuilt: 0 };+ const { geometry } = extractRender(withUvs.mesh, { sharpAngle: smoothAngle * Math.PI / 180 });+ if (geometry.positions.length / 3 > maxVertices) {+ throw new RangeError(`The edited part needs ${geometry.positions.length / 3} render vertices, over maxVertices ${maxVertices}. Use fewer or coarser edits.`);+ }+ const reach = transferVertexAttributes(source, geometry, sampler);+ const limit = boundsDiagonal(source.positions) * IMPORTED_MESH_EDIT_LIMITS.maxTransferFraction;+ const bound = Boolean(source.skinIndices) || Boolean(source.morphTargets?.length);+ if (bound && reach > limit) {+ throw new RangeError(`This edit puts geometry ${reach.toPrecision(3)} from the imported surface, over the ${limit.toPrecision(3)} limit, so skin weights and morph targets would be guesses. Keep edits within ${limit.toPrecision(3)} of the surface (smaller offsets, cut instead of extrude), or edit a part without skin or morphs.`);+ }+ return {+ geometry,+ mesh: withUvs.mesh,+ results: outcome.results,+ transfer: {+ skinWeights: Boolean(source.skinIndices), morphTargets: source.morphTargets?.length ?? 0, colors: Boolean(source.colors),+ uvs: Boolean(source.uvs), uvFacesRebuilt: withUvs.rebuilt, reach: Number(reach.toPrecision(4)), limit: bound ? Number(limit.toPrecision(4)) : null,+ },+ };+}diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 3ed8bc60..19e2f2dd 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -55,3 +55,8 @@ export const FIELD_OPERATOR_NAMES = Object.freeze([]);export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface']);export const MAX_INSTANCE_CANDIDATES = 2048;++// Imported GLB parts take the same edits. Skin weights, morph deltas and vertex colours of new geometry come from the+// nearest point of the original surface; an edit that reaches farther than this fraction of the part's bounds+// diagonal from that surface is rejected on a skinned or morphed part, because the transfer would be a guess.+export const IMPORTED_MESH_EDIT_LIMITS = Object.freeze({ maxTransferFraction: 0.25, maxEditedParts: 64 });diff --git a/tests/agent-asset-mesh.test.js b/tests/agent-asset-mesh.test.jsnew file mode 100644index 00000000..d913003f--- /dev/null+++ b/tests/agent-asset-mesh.test.js@@ -0,0 +1,244 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { mat4 } from 'gl-matrix';+import { exportGlb } from '../src/export.js';+import { parseGltf } from '../src/gltf.js';+import { box } from '../src/geometry.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { loadMeshBooleans } from '../src/agent-scene.js';+import { importedMeshReport } from '../src/agent-mesh-engine.js';+import { validateSkinGeometry } from '../src/skinning.js';++// CC0 RobotExpressive: parts 1 (Torso_1) is rigid, 3 (Head_2) has three morph targets, 15 (HandR_1) is skinned.+const robotBytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));+const ASSET_ID = 'ab'.repeat(32);+const TORSO = 'mesh-1';+const HEAD = 'mesh-3';+const HAND = 'mesh-15';+const LEG = 'mesh-10';++await loadMeshBooleans();++function loadRobot() {+ return parseGltf(robotBytes.buffer.slice(robotBytes.byteOffset, robotBytes.byteOffset + robotBytes.byteLength), { maxVertices: 500000 });+}++function createScene(asset, extra = {}) {+ return createAgentAssetScene(asset, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID, ...extra });+}++function editOperation(geometry, edits, replace) {+ return { type: 'edit-mesh', geometry, edits, ...(replace === undefined ? {} : { replace }) };+}++function applyEdits(scene, geometry, edits) {+ return scene.apply([editOperation(geometry, edits)], { expectedRevision: scene.revision });+}++function partOf(scene, id) {+ return scene.parts[Number(id.slice(5))];+}++function skinWeightSums(geometry) {+ const sums = [];+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {+ let sum = 0;+ for (let influence = 0; influence < 4; influence++) sum += geometry.skinWeights[vertex * 4 + influence];+ sums.push(sum);+ }+ return sums;+}++test('cutting a hole in a rigid imported part keeps its material and passes the topology check', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const before = partOf(scene, TORSO);+ const revisionBefore = scene.revision;+ applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'top' } }]);+ const after = partOf(scene, TORSO);+ assert.equal(scene.revision, revisionBefore + 1);+ assert.equal(scene.topologyRevision, 1);+ assert.notEqual(after.geometry, before.geometry);+ assert.ok(after.geometry.indices.length < before.geometry.indices.length);+ assert.equal(after.material, before.material);+ assert.equal(after.matrix, before.matrix, 'the matrix array keeps its identity so poses keep writing to it');+ const report = scene.inspectMeshes({ geometries: [TORSO] }).meshes[0];+ assert.ok(report.edits.length === 1);+ assert.ok(Object.hasOwn(report.tags, 'material-0'), `tags: ${Object.keys(report.tags)}`);+ assert.ok(report.localToWorldScale.every(value => value > 1), 'imported parts live in a small local space; the report gives the scale');+ assert.equal(scene.exportRecipe().meshEdits[0].id, TORSO);+ asset.dispose();+});++test('a boolean difference cuts a through hole in a closed imported part and an open part says how to close it', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const before = scene.inspectMeshes({ geometries: [LEG] }).meshes[0];+ assert.equal(before.parts.closed, 1);+ const cutter = { type: 'cylinder', segments: 24 };+ applyEdits(scene, LEG, [{ op: 'boolean', operation: 'difference', cutter, scale: [0.0003, 0.01, 0.0003] }]);+ const after = scene.inspectMeshes({ geometries: [LEG] }).meshes[0];+ assert.equal(after.ok, true);+ const eulerCharacteristic = after.counts.vertices - after.counts.edges + after.counts.faces;+ assert.equal((2 * after.parts.count - eulerCharacteristic) / 2, 1, 'a through hole is one handle');+ assert.ok(after.counts.triangles > before.counts.triangles);+ assert.throws(+ () => applyEdits(scene, TORSO, [{ op: 'boolean', operation: 'difference', cutter, scale: [0.004, 0.05, 0.004] }]),+ /must be closed.*fill_holes/s,+ );+ asset.dispose();+});++test('skin weights follow an edit: unmoved vertices keep theirs and new ones sum to one', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const source = partOf(scene, HAND).geometry;+ applyEdits(scene, HAND, [{ op: 'bevel', edges: { all: true }, width: 0.005, segments: 1 }]);+ const beveled = partOf(scene, HAND).geometry;+ assert.ok(beveled.positions.length > source.positions.length);+ validateSkinGeometry(beveled, partOf(scene, HAND).skin);+ for (const sum of skinWeightSums(beveled)) assert.ok(Math.abs(sum - 1) < 1e-4, `weights sum to ${sum}`);+ scene.apply([editOperation(HAND, [{ op: 'delete', select: { tag: 'top' } }], true)], { expectedRevision: scene.revision });+ const edited = partOf(scene, HAND).geometry;+ assert.ok(edited.positions.length < source.positions.length);+ validateSkinGeometry(edited, partOf(scene, HAND).skin);+ const exact = new Map();+ for (let vertex = 0; vertex < source.positions.length / 3; vertex++) {+ exact.set(source.positions.slice(vertex * 3, vertex * 3 + 3).join(), Array.from(source.skinWeights.slice(vertex * 4, vertex * 4 + 4)).join());+ }+ let matched = 0;+ for (let vertex = 0; vertex < edited.positions.length / 3; vertex++) {+ const expected = exact.get(edited.positions.slice(vertex * 3, vertex * 3 + 3).join());+ if (expected === undefined) continue;+ matched++;+ assert.equal(Array.from(edited.skinWeights.slice(vertex * 4, vertex * 4 + 4)).join(), expected);+ }+ assert.ok(matched > 0, 'some vertices sit where source vertices were');+ const pose = scene.apply([{ type: 'set-animation', clip: 0, time: 0.4 }], { expectedRevision: scene.revision });+ assert.equal(pose, scene.revision, 'an edited skinned part still poses through the clip');+ asset.dispose();+});++test('morph targets follow an edit with one delta per vertex and the weights keep their identity', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const morph = partOf(scene, HEAD).morph;+ applyEdits(scene, HEAD, [{ op: 'delete', select: { tag: 'top' } }]);+ const edited = partOf(scene, HEAD);+ assert.equal(edited.morph, morph);+ assert.equal(edited.geometry.morphTargets.length, 3);+ for (const target of edited.geometry.morphTargets) {+ assert.equal(target.positions.length, edited.geometry.positions.length);+ }+ assert.equal(scene.inspectMeshes({ geometries: [HEAD] }).meshes[0].transfer.morphTargets, 3);+ asset.dispose();+});++test('an edit that would turn skin or morph transfer into a guess is rejected and names the next action', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const revision = scene.revision;+ assert.throws(+ () => applyEdits(scene, HEAD, [{ op: 'extrude_face_region', select: { tag: 'top' }, offset: 3 }]),+ error => /skin weights and morph targets would be guesses/.test(error.message) && /Keep edits within/.test(error.message),+ );+ assert.equal(scene.revision, revision);+ assert.equal(scene.topologyRevision, 0);+ assert.equal(partOf(scene, HEAD).geometry, asset.parts[3].geometry);+ asset.dispose();+});++test('a checkpoint undoes a mesh edit and replace swaps the log', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const handle = scene.checkpoint();+ applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'top' } }]);+ const facesAfterOne = partOf(scene, TORSO).geometry.indices.length;+ applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'bottom' } }]);+ assert.ok(partOf(scene, TORSO).geometry.indices.length < facesAfterOne);+ scene.apply([editOperation(TORSO, [{ op: 'delete', select: { tag: 'top' } }], true)], { expectedRevision: scene.revision });+ assert.equal(partOf(scene, TORSO).geometry.indices.length, facesAfterOne);+ scene.restore(handle, { expectedRevision: scene.revision });+ assert.equal(partOf(scene, TORSO).geometry, asset.parts[1].geometry);+ assert.equal(scene.exportRecipe().meshEdits, undefined);+ asset.dispose();+});++test('an exported recipe replays the edits on a fresh decode', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'top' } }]);+ const recipe = scene.exportRecipe();+ const replayAsset = await loadRobot();+ const replay = createScene(replayAsset, recipe);+ assert.deepEqual(Array.from(partOf(replay, TORSO).geometry.positions), Array.from(partOf(scene, TORSO).geometry.positions));+ asset.dispose();+ replayAsset.dispose();+});++test('hostile mesh edits are rejected without changing the scene', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const revision = scene.revision;+ const hostile = [+ ['unknown mesh', () => applyEdits(scene, 'mesh-99', [{ op: 'delete', select: { tag: 'top' } }]), /Unknown mesh ID/],+ ['prototype key', () => applyEdits(scene, '__proto__', [{ op: 'delete', select: { tag: 'top' } }]), /Unknown mesh ID/],+ ['edits not an array', () => scene.apply([{ type: 'edit-mesh', geometry: TORSO, edits: 'delete' }], { expectedRevision: revision }), /edits array/],+ ['unknown operation', () => applyEdits(scene, TORSO, [{ op: 'explode' }]), /explode|op/],+ ['not a number', () => applyEdits(scene, TORSO, [{ op: 'extrude_face_region', select: { tag: 'top' }, offset: Number.NaN }]), /offset|finite/],+ ['selects nothing', () => applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'no-such-tag' } }]), /select|tag|no faces/i],+ ['too many edits', () => applyEdits(scene, TORSO, Array.from({ length: 65 }, () => ({ op: 'flip_normals', select: { tag: 'top' } }))), /64|edits/],+ ['array bomb', () => applyEdits(scene, TORSO, [{ op: 'array', count: 10000, offset: [1, 0, 0] }]), /count|vertices|budget|limit/i],+ ['mesh cutter', () => applyEdits(scene, TORSO, [{ op: 'boolean', operation: 'difference', cutter: { type: 'mesh', id: 'x' } }]), /cutter/i],+ ['extra operation field', () => scene.apply([{ type: 'edit-mesh', geometry: TORSO, edits: [], stack: [] }], { expectedRevision: revision }), /stack|unknown|key/i],+ ['stack operation', () => scene.apply([{ type: 'set-mesh-stack', geometry: TORSO, stack: [] }], { expectedRevision: revision }), /edit-mesh/],+ ['stale revision', () => scene.apply([editOperation(TORSO, [{ op: 'delete', select: { tag: 'top' } }])], { expectedRevision: revision + 5 }), /expectedRevision/],+ ];+ for (const [label, attempt, pattern] of hostile) {+ assert.throws(attempt, pattern, label);+ assert.equal(scene.revision, revision, `${label} left the revision alone`);+ assert.equal(scene.topologyRevision, 0, `${label} left the topology alone`);+ }+ assert.throws(() => createScene(asset, { meshEdits: [{ id: TORSO, edits: [{ op: 'delete', select: { tag: 'top' } }], extra: 1 }] }), /meshEdits/);+ assert.throws(() => createScene(asset, { meshEdits: [{ id: TORSO, edits: [] }, { id: TORSO, edits: [] }] }), /repeated/);+ asset.dispose();+});++function uvBoxGlb() {+ const geometry = box(0, 1);+ const uvs = new Float32Array(geometry.positions.length / 3 * 2);+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {+ uvs[vertex * 2] = geometry.positions[vertex * 3] * 0.5 + 0.5;+ uvs[vertex * 2 + 1] = geometry.positions[vertex * 3 + 2] * 0.5 + 0.5;+ }+ const part = { name: 'Crate', geometry: { ...geometry, uvs }, matrix: mat4.create(), material: { color: [1, 1, 1], metallic: 0, roughness: 1 } };+ return exportGlb([part]);+}++test('UVs survive an edit, and faces an edit leaves without UVs read the nearest original island', async () => {+ const asset = await parseGltf(uvBoxGlb());+ const scene = createScene(asset);+ assert.ok(partOf(scene, 'mesh-0').geometry.uvs);+ applyEdits(scene, 'mesh-0', [{ op: 'bevel', edges: { all: true }, width: 0.05, segments: 2 }]);+ const edited = partOf(scene, 'mesh-0').geometry;+ assert.equal(edited.uvs.length / 2, edited.positions.length / 3);+ let zero = 0;+ for (let vertex = 0; vertex < edited.uvs.length / 2; vertex++) {+ assert.ok(edited.uvs[vertex * 2] >= -0.2 && edited.uvs[vertex * 2] <= 1.2);+ if (edited.uvs[vertex * 2] === 0 && edited.uvs[vertex * 2 + 1] === 0) zero++;+ }+ assert.ok(zero < edited.uvs.length / 2 / 4, `${zero} vertices kept the empty 0,0 UV`);+ assert.ok(scene.inspectMeshes({ geometries: ['mesh-0'] }).meshes[0].transfer.uvFacesRebuilt > 0);+ asset.dispose();+});++test('imported parts report as polygon meshes with the shared lint', async () => {+ const asset = await loadRobot();+ const scene = createScene(asset);+ const meshes = scene.inspectMeshes().meshes;+ assert.equal(meshes.length, 16);+ assert.equal(importedMeshReport(asset.parts[1].geometry).counts.triangles, asset.parts[1].geometry.indices.length / 3);+ assert.throws(() => scene.inspectMeshes({ geometries: Array.from({ length: 17 }, (_, index) => `mesh-${index}`) }), /at most/);+ asset.dispose();+});