Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Let every material helper take an author name (#297)
Matthew Kissingerf5e9eb593814
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db2eedf0..40ce5239 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,18 @@ does not publish a package.[#213](https://github.com/instruktlabs/kiln/issues/213). Library export:`textureSharingReport` from `@instruktlabs/kiln/asset-export`([#287](https://github.com/instruktlabs/kiln/issues/287)).+- Every material helper takes an optional `name`, written to the exported glTF+ `materials[].name`: `gameMaterial`, `basicMaterial`, `glassMaterial` and+ `lambertMaterial` in their options object, `pbrMaterial` and `foliageMaterial` in+ theirs. Both exporters already carried a name that was set, and it survives the+ sandbox, `dedup` and every optimize level; what was missing was any way for an+ author to set one, so delivered assets arrived with unnamed materials and the+ authored distinctions were lost. A name is 1..200 visible characters, matching the+ portable material spec's own bound, and control characters are rejected. This gives+ a destination runtime a stable authored key to group draws by, instead of hashing+ material factors. `materialRecipe` and the portable material specs already named+ their output and are unchanged+ ([#288](https://github.com/instruktlabs/kiln/issues/288)).## 1.5.0 (2026-10-25)diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex f7426e0c..8facb08b 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -3433,6 +3433,8 @@ function authoringDiagnosticAdvice(diagnostic) {return PROCEDURAL_TEXTURE_USAGE_ADVICE;if (diagnostic === "MATERIAL_FRACTION_RANGE")return MATERIAL_FRACTION_RANGE_ADVICE;+ if (diagnostic === "MATERIAL_NAME")+ return MATERIAL_NAME_ADVICE;if (diagnostic === "PROFILE_HOLES_UNSUPPORTED")return PROFILE_HOLES_UNSUPPORTED_ADVICE;if (diagnostic === "PROFILE_SOLID_FAILED")@@ -3441,13 +3443,18 @@ function authoringDiagnosticAdvice(diagnostic) {return PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE;return diagnostic === "PARAMETRIC_PERIODIC_ENDPOINT" ? PARAMETRIC_PERIODIC_ENDPOINT_ADVICE : "";}+function assertMaterialName(name, fn) {+ if (typeof name !== "string" || !name.length || name.length > MATERIAL_NAME_MAX_LENGTH || [...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127))+ throw new AuthoringDiagnosticError("MATERIAL_NAME", `${fn}: name must be 1..${MATERIAL_NAME_MAX_LENGTH} visible characters, got ${typeof name === "string" ? JSON.stringify(name.slice(0, 32)) : typeof name}. ${MATERIAL_NAME_ADVICE}`);+ return name;+}function rethrowAuthoringError(error) {if (error instanceof ReferenceError && /(?: is not defined$|^Can't find variable: )/.test(error.message) && !/\b(?:loadTexture|process|fetch|globalThis|require|Bun|Deno)\b/.test(error.message)) {throw new AuthoringDiagnosticError("UNBOUND_VARIABLE");}throw error;}-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError;+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_NAME_ADVICE = 'A material name is the key a destination runtime groups draws by, so it is 1 to 200 visible characters: a plain string, no control characters. gameMaterial, basicMaterial, glassMaterial and lambertMaterial take it in their options object, pbrMaterial and foliageMaterial in theirs, for example gameMaterial(0x25342a, { roughness: 0.58, name: "ParkerisedSteel" }). Omit it to leave the material unnamed; materialRecipe and the portable material specs name their output already.', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError, MATERIAL_NAME_MAX_LENGTH = 200;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -7759,7 +7766,7 @@ var init_material_recipes = __esm(() => {function listHelperSpecs() {return PRIMITIVES.map((p) => ({ ...p }));}-var RECIPE_OVERRIDES_NOTE, PRIMITIVES;+var MATERIAL_NAME_NOTE = "Set name to the authored finish when a destination runtime groups draws by material: it is written to the glTF material name, 1..200 visible characters. materialRecipe and the portable material specs name their output already.", RECIPE_OVERRIDES_NOTE, PRIMITIVES;var init_helper_specs = __esm(() => {init_geometry_catalog();init_material_recipes();@@ -8288,11 +8295,12 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "gameMaterial",- signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "PBR material with flat shading by default; choose shading and material settings for the intended surface.",- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9, name: 'OiledWalnut' });",+ promptNotes: MATERIAL_NAME_NOTE},{name: "materialRecipe",@@ -8323,7 +8331,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "basicMaterial",- signature: "basicMaterial(color, opts?: { transparent, opacity })",+ signature: "basicMaterial(color, opts?: { transparent, opacity, name })",returns: "THREE.MeshBasicMaterial",category: "material",description: "Unlit flat material. For UI / effects where lighting is baked in.",@@ -8331,7 +8339,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "glassMaterial",- signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",@@ -8339,7 +8347,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "lambertMaterial",- signature: "lambertMaterial(color, opts?: { flatShading, emissive })",+ signature: "lambertMaterial(color, opts?: { flatShading, emissive, name })",returns: "THREE.MeshLambertMaterial",category: "material",description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",@@ -8664,16 +8672,17 @@ const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { stre},{name: "pbrMaterial",- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.",example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0, name: 'CrateWood' });`,+ promptNotes: MATERIAL_NAME_NOTE},{name: "foliageMaterial",- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",@@ -11250,6 +11259,8 @@ function pbrMaterial(opts = {}) {...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},doubleSided: opts.doubleSided === true};+ if (opts.name !== undefined)+ mat.name = assertMaterialName(opts.name, "pbrMaterial");return mat;}function foliageMaterial(albedo, opts = {}) {@@ -11259,7 +11270,8 @@ function foliageMaterial(albedo, opts = {}) {metalness: 0,alphaMode: "mask",alphaCutoff: opts.alphaCutoff ?? 0.5,- doubleSided: opts.doubleSided ?? true+ doubleSided: opts.doubleSided ?? true,+ ...opts.name !== undefined ? { name: opts.name } : {}});}var init_textures = __esm(() => {@@ -32144,7 +32156,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- return new THREE49.MeshStandardMaterial({+ const material = new THREE49.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -32152,18 +32164,24 @@ function gameMaterial(color, options = {}) {emissiveIntensity: options.emissiveIntensity ?? 1,flatShading: options.flatShading ?? true});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "gameMaterial");+ return material;}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- return new THREE49.MeshBasicMaterial({+ const material = new THREE49.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "basicMaterial");+ return material;}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- return new THREE49.MeshStandardMaterial({+ const material = new THREE49.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,@@ -32171,14 +32189,20 @@ function glassMaterial(color, options = {}) {metalness: options.metalness ?? 0,side: THREE49.DoubleSide});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "glassMaterial");+ return material;}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- return new THREE49.MeshLambertMaterial({+ const material = new THREE49.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "lambertMaterial");+ return material;}function threeInterpolation(mode) {if (mode !== undefined && !TRACK_INTERPOLATIONS.includes(mode)) {diff --git a/dist/build.json b/dist/build.jsonindex 2088083b..5f11d176 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:44d1307d1b8ddc24c8a3aca8e11a152ae201201a1826b9786cf4ad234d687d78",+ "identity": "sha256:edf7989be0c54163d7b260a8bd9ada32d207a140d153fb079e78a1f5ac288185","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "5e0bc90a2e66a62db1120589e2f23862d6a615349e14af0bd27346a7774a0efc",+ "sourceHash": "639ce14184fda78b29f721efed22124d667751f1fef1a2b5e322c25154ec1959","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:e24d955bc16f47b1368e77f1833afaaaf4f11018c9c9e5e5b8f5eaeca34efd16"+ "bundleHash": "sha256:b729bef5fda52674cabf362880ed986bbe9cbabb67bc0341c0a7cdb0c5619f66"},"agent-run": {- "identity": "sha256:44d1307d1b8ddc24c8a3aca8e11a152ae201201a1826b9786cf4ad234d687d78",+ "identity": "sha256:edf7989be0c54163d7b260a8bd9ada32d207a140d153fb079e78a1f5ac288185","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "5e0bc90a2e66a62db1120589e2f23862d6a615349e14af0bd27346a7774a0efc",+ "sourceHash": "639ce14184fda78b29f721efed22124d667751f1fef1a2b5e322c25154ec1959","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:b166dd44800e3f83301a427ca2b4072092a20017087e8307f8abb2c614107b4b"+ "bundleHash": "sha256:2b36abd5b141e03287ce5b8f628df3d1347598a5079ed6edfaf50e6ae011cec1"},"agent-providers": {- "identity": "sha256:44d1307d1b8ddc24c8a3aca8e11a152ae201201a1826b9786cf4ad234d687d78",+ "identity": "sha256:edf7989be0c54163d7b260a8bd9ada32d207a140d153fb079e78a1f5ac288185","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "5e0bc90a2e66a62db1120589e2f23862d6a615349e14af0bd27346a7774a0efc",+ "sourceHash": "639ce14184fda78b29f721efed22124d667751f1fef1a2b5e322c25154ec1959","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:44d1307d1b8ddc24c8a3aca8e11a152ae201201a1826b9786cf4ad234d687d78",+ "identity": "sha256:edf7989be0c54163d7b260a8bd9ada32d207a140d153fb079e78a1f5ac288185","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "5e0bc90a2e66a62db1120589e2f23862d6a615349e14af0bd27346a7774a0efc",+ "sourceHash": "639ce14184fda78b29f721efed22124d667751f1fef1a2b5e322c25154ec1959","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:deeb947091b693e92337a2081678ed06cd0a2d23f813a375001c31dbf529a815"},"cli": {- "identity": "sha256:44d1307d1b8ddc24c8a3aca8e11a152ae201201a1826b9786cf4ad234d687d78",+ "identity": "sha256:edf7989be0c54163d7b260a8bd9ada32d207a140d153fb079e78a1f5ac288185","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "5e0bc90a2e66a62db1120589e2f23862d6a615349e14af0bd27346a7774a0efc",+ "sourceHash": "639ce14184fda78b29f721efed22124d667751f1fef1a2b5e322c25154ec1959","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:adee2762e10bc145052205a57a91448f97b9d56888df7c1ae688203891d8757f"+ "bundleHash": "sha256:20b3c895e2bb7523e32216e0508c4079ab53fcd572446a3b66bd5053c8e9b1d0"},"engine": {- "identity": "sha256:44d1307d1b8ddc24c8a3aca8e11a152ae201201a1826b9786cf4ad234d687d78",+ "identity": "sha256:edf7989be0c54163d7b260a8bd9ada32d207a140d153fb079e78a1f5ac288185","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "5e0bc90a2e66a62db1120589e2f23862d6a615349e14af0bd27346a7774a0efc",+ "sourceHash": "639ce14184fda78b29f721efed22124d667751f1fef1a2b5e322c25154ec1959","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:4d3b7812dd8e6392f63dfb72ed7883b3171926035f06c202e55ccb77b4110006"+ "bundleHash": "sha256:635ac9bbc43d2ca046d284afb5698c20380aa4e9ecc53fe5dc307f1e55b861f2"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex d0386af0..2c89efc7 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -260,6 +260,8 @@ function authoringDiagnosticAdvice(diagnostic) {return PROCEDURAL_TEXTURE_USAGE_ADVICE;if (diagnostic === "MATERIAL_FRACTION_RANGE")return MATERIAL_FRACTION_RANGE_ADVICE;+ if (diagnostic === "MATERIAL_NAME")+ return MATERIAL_NAME_ADVICE;if (diagnostic === "PROFILE_HOLES_UNSUPPORTED")return PROFILE_HOLES_UNSUPPORTED_ADVICE;if (diagnostic === "PROFILE_SOLID_FAILED")@@ -268,13 +270,18 @@ function authoringDiagnosticAdvice(diagnostic) {return PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE;return diagnostic === "PARAMETRIC_PERIODIC_ENDPOINT" ? PARAMETRIC_PERIODIC_ENDPOINT_ADVICE : "";}+function assertMaterialName(name, fn) {+ if (typeof name !== "string" || !name.length || name.length > MATERIAL_NAME_MAX_LENGTH || [...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127))+ throw new AuthoringDiagnosticError("MATERIAL_NAME", `${fn}: name must be 1..${MATERIAL_NAME_MAX_LENGTH} visible characters, got ${typeof name === "string" ? JSON.stringify(name.slice(0, 32)) : typeof name}. ${MATERIAL_NAME_ADVICE}`);+ return name;+}function rethrowAuthoringError(error) {if (error instanceof ReferenceError && /(?: is not defined$|^Can't find variable: )/.test(error.message) && !/\b(?:loadTexture|process|fetch|globalThis|require|Bun|Deno)\b/.test(error.message)) {throw new AuthoringDiagnosticError("UNBOUND_VARIABLE");}throw error;}-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError;+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_NAME_ADVICE = 'A material name is the key a destination runtime groups draws by, so it is 1 to 200 visible characters: a plain string, no control characters. gameMaterial, basicMaterial, glassMaterial and lambertMaterial take it in their options object, pbrMaterial and foliageMaterial in theirs, for example gameMaterial(0x25342a, { roughness: 0.58, name: "ParkerisedSteel" }). Omit it to leave the material unnamed; materialRecipe and the portable material specs name their output already.', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError, MATERIAL_NAME_MAX_LENGTH = 200;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -17836,6 +17843,8 @@ function pbrMaterial(opts = {}) {...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},doubleSided: opts.doubleSided === true};+ if (opts.name !== undefined)+ mat.name = assertMaterialName(opts.name, "pbrMaterial");return mat;}function foliageMaterial(albedo, opts = {}) {@@ -17845,7 +17854,8 @@ function foliageMaterial(albedo, opts = {}) {metalness: 0,alphaMode: "mask",alphaCutoff: opts.alphaCutoff ?? 0.5,- doubleSided: opts.doubleSided ?? true+ doubleSided: opts.doubleSided ?? true,+ ...opts.name !== undefined ? { name: opts.name } : {}});}var init_textures = __esm(() => {@@ -28839,7 +28849,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- return new THREE48.MeshStandardMaterial({+ const material = new THREE48.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -28847,18 +28857,24 @@ function gameMaterial(color, options = {}) {emissiveIntensity: options.emissiveIntensity ?? 1,flatShading: options.flatShading ?? true});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "gameMaterial");+ return material;}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- return new THREE48.MeshBasicMaterial({+ const material = new THREE48.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "basicMaterial");+ return material;}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- return new THREE48.MeshStandardMaterial({+ const material = new THREE48.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,@@ -28866,14 +28882,20 @@ function glassMaterial(color, options = {}) {metalness: options.metalness ?? 0,side: THREE48.DoubleSide});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "glassMaterial");+ return material;}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- return new THREE48.MeshLambertMaterial({+ const material = new THREE48.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "lambertMaterial");+ return material;}function threeInterpolation(mode) {if (mode !== undefined && !TRACK_INTERPOLATIONS.includes(mode)) {@@ -30258,7 +30280,7 @@ var init_geometry_catalog = __esm(() => {function listHelperSpecs() {return PRIMITIVES.map((p) => ({ ...p }));}-var RECIPE_OVERRIDES_NOTE, PRIMITIVES;+var MATERIAL_NAME_NOTE = "Set name to the authored finish when a destination runtime groups draws by material: it is written to the glTF material name, 1..200 visible characters. materialRecipe and the portable material specs name their output already.", RECIPE_OVERRIDES_NOTE, PRIMITIVES;var init_helper_specs = __esm(() => {init_geometry_catalog();init_material_recipes();@@ -30787,11 +30809,12 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "gameMaterial",- signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "PBR material with flat shading by default; choose shading and material settings for the intended surface.",- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9, name: 'OiledWalnut' });",+ promptNotes: MATERIAL_NAME_NOTE},{name: "materialRecipe",@@ -30822,7 +30845,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "basicMaterial",- signature: "basicMaterial(color, opts?: { transparent, opacity })",+ signature: "basicMaterial(color, opts?: { transparent, opacity, name })",returns: "THREE.MeshBasicMaterial",category: "material",description: "Unlit flat material. For UI / effects where lighting is baked in.",@@ -30830,7 +30853,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "glassMaterial",- signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",@@ -30838,7 +30861,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "lambertMaterial",- signature: "lambertMaterial(color, opts?: { flatShading, emissive })",+ signature: "lambertMaterial(color, opts?: { flatShading, emissive, name })",returns: "THREE.MeshLambertMaterial",category: "material",description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",@@ -31163,16 +31186,17 @@ const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { stre},{name: "pbrMaterial",- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.",example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0, name: 'CrateWood' });`,+ promptNotes: MATERIAL_NAME_NOTE},{name: "foliageMaterial",- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex c6b6514a..eca09aee 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -100,6 +100,8 @@ function authoringDiagnosticAdvice(diagnostic) {return PROCEDURAL_TEXTURE_USAGE_ADVICE;if (diagnostic === "MATERIAL_FRACTION_RANGE")return MATERIAL_FRACTION_RANGE_ADVICE;+ if (diagnostic === "MATERIAL_NAME")+ return MATERIAL_NAME_ADVICE;if (diagnostic === "PROFILE_HOLES_UNSUPPORTED")return PROFILE_HOLES_UNSUPPORTED_ADVICE;if (diagnostic === "PROFILE_SOLID_FAILED")@@ -108,6 +110,11 @@ function authoringDiagnosticAdvice(diagnostic) {return PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE;return diagnostic === "PARAMETRIC_PERIODIC_ENDPOINT" ? PARAMETRIC_PERIODIC_ENDPOINT_ADVICE : "";}+function assertMaterialName(name, fn) {+ if (typeof name !== "string" || !name.length || name.length > MATERIAL_NAME_MAX_LENGTH || [...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127))+ throw new AuthoringDiagnosticError("MATERIAL_NAME", `${fn}: name must be 1..${MATERIAL_NAME_MAX_LENGTH} visible characters, got ${typeof name === "string" ? JSON.stringify(name.slice(0, 32)) : typeof name}. ${MATERIAL_NAME_ADVICE}`);+ return name;+}function programErrorDiagnostic(error) {if (error instanceof AuthoringDiagnosticError)return error.diagnostic;@@ -125,7 +132,7 @@ function rethrowAuthoringError(error) {}throw error;}-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError;+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_NAME_ADVICE = 'A material name is the key a destination runtime groups draws by, so it is 1 to 200 visible characters: a plain string, no control characters. gameMaterial, basicMaterial, glassMaterial and lambertMaterial take it in their options object, pbrMaterial and foliageMaterial in theirs, for example gameMaterial(0x25342a, { roughness: 0.58, name: "ParkerisedSteel" }). Omit it to leave the material unnamed; materialRecipe and the portable material specs name their output already.', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError, MATERIAL_NAME_MAX_LENGTH = 200;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -22419,6 +22426,8 @@ function pbrMaterial(opts = {}) {...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},doubleSided: opts.doubleSided === true};+ if (opts.name !== undefined)+ mat.name = assertMaterialName(opts.name, "pbrMaterial");return mat;}function foliageMaterial(albedo, opts = {}) {@@ -22428,7 +22437,8 @@ function foliageMaterial(albedo, opts = {}) {metalness: 0,alphaMode: "mask",alphaCutoff: opts.alphaCutoff ?? 0.5,- doubleSided: opts.doubleSided ?? true+ doubleSided: opts.doubleSided ?? true,+ ...opts.name !== undefined ? { name: opts.name } : {}});}var init_textures = __esm(() => {@@ -26482,7 +26492,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- return new THREE48.MeshStandardMaterial({+ const material = new THREE48.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -26490,18 +26500,24 @@ function gameMaterial(color, options = {}) {emissiveIntensity: options.emissiveIntensity ?? 1,flatShading: options.flatShading ?? true});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "gameMaterial");+ return material;}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- return new THREE48.MeshBasicMaterial({+ const material = new THREE48.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "basicMaterial");+ return material;}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- return new THREE48.MeshStandardMaterial({+ const material = new THREE48.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,@@ -26509,14 +26525,20 @@ function glassMaterial(color, options = {}) {metalness: options.metalness ?? 0,side: THREE48.DoubleSide});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "glassMaterial");+ return material;}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- return new THREE48.MeshLambertMaterial({+ const material = new THREE48.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "lambertMaterial");+ return material;}function threeInterpolation(mode) {if (mode !== undefined && !TRACK_INTERPOLATIONS.includes(mode)) {@@ -27901,7 +27923,7 @@ var init_geometry_catalog = __esm(() => {function listHelperSpecs() {return PRIMITIVES.map((p) => ({ ...p }));}-var RECIPE_OVERRIDES_NOTE, PRIMITIVES;+var MATERIAL_NAME_NOTE = "Set name to the authored finish when a destination runtime groups draws by material: it is written to the glTF material name, 1..200 visible characters. materialRecipe and the portable material specs name their output already.", RECIPE_OVERRIDES_NOTE, PRIMITIVES;var init_helper_specs = __esm(() => {init_geometry_catalog();init_material_recipes();@@ -28430,11 +28452,12 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "gameMaterial",- signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "PBR material with flat shading by default; choose shading and material settings for the intended surface.",- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9, name: 'OiledWalnut' });",+ promptNotes: MATERIAL_NAME_NOTE},{name: "materialRecipe",@@ -28465,7 +28488,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "basicMaterial",- signature: "basicMaterial(color, opts?: { transparent, opacity })",+ signature: "basicMaterial(color, opts?: { transparent, opacity, name })",returns: "THREE.MeshBasicMaterial",category: "material",description: "Unlit flat material. For UI / effects where lighting is baked in.",@@ -28473,7 +28496,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "glassMaterial",- signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",@@ -28481,7 +28504,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "lambertMaterial",- signature: "lambertMaterial(color, opts?: { flatShading, emissive })",+ signature: "lambertMaterial(color, opts?: { flatShading, emissive, name })",returns: "THREE.MeshLambertMaterial",category: "material",description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",@@ -28806,16 +28829,17 @@ const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { stre},{name: "pbrMaterial",- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.",example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0, name: 'CrateWood' });`,+ promptNotes: MATERIAL_NAME_NOTE},{name: "foliageMaterial",- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex a432f370..8fa17ff1 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -141,6 +141,8 @@ function authoringDiagnosticAdvice(diagnostic) {return PROCEDURAL_TEXTURE_USAGE_ADVICE;if (diagnostic === "MATERIAL_FRACTION_RANGE")return MATERIAL_FRACTION_RANGE_ADVICE;+ if (diagnostic === "MATERIAL_NAME")+ return MATERIAL_NAME_ADVICE;if (diagnostic === "PROFILE_HOLES_UNSUPPORTED")return PROFILE_HOLES_UNSUPPORTED_ADVICE;if (diagnostic === "PROFILE_SOLID_FAILED")@@ -149,13 +151,18 @@ function authoringDiagnosticAdvice(diagnostic) {return PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE;return diagnostic === "PARAMETRIC_PERIODIC_ENDPOINT" ? PARAMETRIC_PERIODIC_ENDPOINT_ADVICE : "";}+function assertMaterialName(name, fn) {+ if (typeof name !== "string" || !name.length || name.length > MATERIAL_NAME_MAX_LENGTH || [...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127))+ throw new AuthoringDiagnosticError("MATERIAL_NAME", `${fn}: name must be 1..${MATERIAL_NAME_MAX_LENGTH} visible characters, got ${typeof name === "string" ? JSON.stringify(name.slice(0, 32)) : typeof name}. ${MATERIAL_NAME_ADVICE}`);+ return name;+}function rethrowAuthoringError(error) {if (error instanceof ReferenceError && /(?: is not defined$|^Can't find variable: )/.test(error.message) && !/\b(?:loadTexture|process|fetch|globalThis|require|Bun|Deno)\b/.test(error.message)) {throw new AuthoringDiagnosticError("UNBOUND_VARIABLE");}throw error;}-var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError;+var UNBOUND_VARIABLE_ADVICE = "Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.", GEAR_RADII_ORDER_ADVICE = "gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.", ROUNDED_BOX_RADIUS_ADVICE = "roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.", PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE = 'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.', PROCEDURAL_TEXTURE_USAGE_ADVICE = 'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].', MATERIAL_NAME_ADVICE = 'A material name is the key a destination runtime groups draws by, so it is 1 to 200 visible characters: a plain string, no control characters. gameMaterial, basicMaterial, glassMaterial and lambertMaterial take it in their options object, pbrMaterial and foliageMaterial in theirs, for example gameMaterial(0x25342a, { roughness: 0.58, name: "ParkerisedSteel" }). Omit it to leave the material unnamed; materialRecipe and the portable material specs name their output already.', MATERIAL_FRACTION_RANGE_ADVICE = "Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.", PARAMETRIC_PERIODIC_ENDPOINT_ADVICE = "Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.", PROFILE_HOLES_UNSUPPORTED_ADVICE = "loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.", PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE = "loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.", PROFILE_SOLID_FAILED_ADVICE = 'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].', UNINITIALIZED_BINDING_ADVICE = "A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.", BUILD_RESULT_ADVICE = 'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.', MATERIAL_RECIPE_OVERRIDE_ADVICE = 'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.', PROGRAM_TYPE_ERROR_ADVICE = "The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.", PROGRAM_RANGE_ERROR_ADVICE = "The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.", LOD_SET_ADVICE = 'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].', OPEN_SHELL_ADVICE = 'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].', DELIVERY_CONTRACT_ADVICE = 'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].', REQUIRE_SOLID_ADVICE = 'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].', EXECUTION_REJECTED_ADVICE = "No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.", AuthoringDiagnosticError, MATERIAL_NAME_MAX_LENGTH = 200;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -3349,6 +3356,8 @@ function pbrMaterial(opts = {}) {...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},doubleSided: opts.doubleSided === true};+ if (opts.name !== undefined)+ mat.name = assertMaterialName(opts.name, "pbrMaterial");return mat;}function foliageMaterial(albedo, opts = {}) {@@ -3358,7 +3367,8 @@ function foliageMaterial(albedo, opts = {}) {metalness: 0,alphaMode: "mask",alphaCutoff: opts.alphaCutoff ?? 0.5,- doubleSided: opts.doubleSided ?? true+ doubleSided: opts.doubleSided ?? true,+ ...opts.name !== undefined ? { name: opts.name } : {}});}var init_textures = __esm(() => {@@ -29936,7 +29946,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- return new THREE50.MeshStandardMaterial({+ const material = new THREE50.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -29944,18 +29954,24 @@ function gameMaterial(color, options = {}) {emissiveIntensity: options.emissiveIntensity ?? 1,flatShading: options.flatShading ?? true});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "gameMaterial");+ return material;}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- return new THREE50.MeshBasicMaterial({+ const material = new THREE50.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "basicMaterial");+ return material;}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- return new THREE50.MeshStandardMaterial({+ const material = new THREE50.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,@@ -29963,14 +29979,20 @@ function glassMaterial(color, options = {}) {metalness: options.metalness ?? 0,side: THREE50.DoubleSide});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "glassMaterial");+ return material;}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- return new THREE50.MeshLambertMaterial({+ const material = new THREE50.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, "lambertMaterial");+ return material;}function threeInterpolation(mode) {if (mode !== undefined && !TRACK_INTERPOLATIONS.includes(mode)) {@@ -31341,7 +31363,7 @@ var init_geometry_catalog = __esm(() => {function listHelperSpecs() {return PRIMITIVES.map((p) => ({ ...p }));}-var RECIPE_OVERRIDES_NOTE, PRIMITIVES;+var MATERIAL_NAME_NOTE = "Set name to the authored finish when a destination runtime groups draws by material: it is written to the glTF material name, 1..200 visible characters. materialRecipe and the portable material specs name their output already.", RECIPE_OVERRIDES_NOTE, PRIMITIVES;var init_helper_specs = __esm(() => {init_geometry_catalog();init_material_recipes();@@ -31870,11 +31892,12 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "gameMaterial",- signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",+ signature: "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "PBR material with flat shading by default; choose shading and material settings for the intended surface.",- example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9, name: 'OiledWalnut' });",+ promptNotes: MATERIAL_NAME_NOTE},{name: "materialRecipe",@@ -31905,7 +31928,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "basicMaterial",- signature: "basicMaterial(color, opts?: { transparent, opacity })",+ signature: "basicMaterial(color, opts?: { transparent, opacity, name })",returns: "THREE.MeshBasicMaterial",category: "material",description: "Unlit flat material. For UI / effects where lighting is baked in.",@@ -31913,7 +31936,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "glassMaterial",- signature: "glassMaterial(color, opts?: { opacity, roughness, metalness })",+ signature: "glassMaterial(color, opts?: { opacity, roughness, metalness, name })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.",@@ -31921,7 +31944,7 @@ createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });`},{name: "lambertMaterial",- signature: "lambertMaterial(color, opts?: { flatShading, emissive })",+ signature: "lambertMaterial(color, opts?: { flatShading, emissive, name })",returns: "THREE.MeshLambertMaterial",category: "material",description: "Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.",@@ -32246,16 +32269,17 @@ const mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { stre},{name: "pbrMaterial",- signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",+ signature: "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.",example: `const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });-const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });`+const crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0, name: 'CrateWood' });`,+ promptNotes: MATERIAL_NAME_NOTE},{name: "foliageMaterial",- signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",+ signature: "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided?, name? })",returns: "THREE.MeshStandardMaterial",category: "material",description: "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex 5d6a528f..ea2f9596 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -356,10 +356,13 @@ bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?:// createPart('Blade', b, steel, { position: [0, 0, 0], parent: root });// Materials-gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })+gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading, name })// PBR material with flat shading by default; choose shading and material settings for the// intended surface.- // e.g. const mat = gameMaterial(0x8b7355, { roughness: 0.9 });+ // NOTE: Set name to the authored finish when a destination runtime groups draws by material:+ // it is written to the glTF material name, 1..200 visible characters. materialRecipe and the+ // portable material specs name their output already.+ // e.g. const mat = gameMaterial(0x8b7355, { roughness: 0.9, name: 'OiledWalnut' });await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })// Resolves a versioned portable// bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF@@ -408,24 +411,27 @@ await compilePortableMaterialSpecV3({ schemaVersion: 3, model: 'pbrMetallicRough// background: [0, 0, 0, 0], operations: [{ op: 'paint', shape: { kind: 'ellipse', x: 2, y: 1,// width: 12, height: 30 }, rgba: [60, 90, 40, 255] }] }, sampler: { minFilter: 'nearest',// magFilter: 'nearest', wrapS: 'clamp-to-edge', wrapT: 'clamp-to-edge' } } } });-basicMaterial(color, opts?: { transparent, opacity })+basicMaterial(color, opts?: { transparent, opacity, name })// Unlit flat material. For UI / effects where lighting is baked in.// e.g. const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });-glassMaterial(color, opts?: { opacity, roughness, metalness })+glassMaterial(color, opts?: { opacity, roughness, metalness, name })// Semi-transparent double-sided material. Panels need ~0.05 offset to avoid z-fighting.// e.g. const mat = glassMaterial(0x66ccff, { opacity: 0.3 });-lambertMaterial(color, opts?: { flatShading, emissive })+lambertMaterial(color, opts?: { flatShading, emissive, name })// Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.// e.g. const mat = lambertMaterial(0x2a4d14, { flatShading: true });-pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })+pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided?, name? })// Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness,// B=metalness); separate data maps are rejected instead of silently dropping a channel.// alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports// double-sided output.+ // NOTE: Set name to the authored finish when a destination runtime groups draws by material:+ // it is written to the glTF material name, 1..200 visible characters. materialRecipe and the+ // portable material specs name their output already.// e.g. const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op:// 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] }); const- // crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });-foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })+ // crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0, name: 'CrateWood' });+foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided?, name? })// Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and// double-sided. Use an alpha-bearing albedo texture.// NOTE: The example uses an approved 4x4 teaching placeholder. Check GPU and destinationdiff --git a/src/__tests__/material-names.test.ts b/src/__tests__/material-names.test.tsnew file mode 100644index 00000000..d5983309--- /dev/null+++ b/src/__tests__/material-names.test.ts@@ -0,0 +1,112 @@+/**+ * Material names, authoring to exported bytes.+ *+ * A consuming runtime that batches draws keys on material *instance* identity, so+ * ten GLBs that share a finish still arrive as ten material instances and nothing+ * merges. The fix on that side is a registry that swaps each loaded mesh's material+ * for one canonical instance, and that needs a stable authored key in the file.+ *+ * Both exporters already write `material.name` when one is set, and the name+ * survives the sandbox, dedup and every optimize level — the `carries` tests below+ * pin that, because it is the guarantee the registry rests on. What was missing is+ * any way for an author to SET a name: the texture helpers take `name`, the material+ * helpers did not, so a delivered asset's materials were unnamed and the author's+ * distinctions ("parkerised steel", "polymer furniture") were lost on the way out.+ */+import { expect, test } from 'bun:test';+import * as THREE from 'three';+import { WebIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';+import { basicMaterial, gameMaterial, glassMaterial, lambertMaterial } from '../primitives';+import { foliageMaterial, pbrMaterial } from '../textures';+import { executeKilnCode, renderSceneToGLB } from '../render';+import { AuthoringDiagnosticError } from '../evaluator/authoring-diagnostic';++const io = () => new WebIO().registerExtensions(ALL_EXTENSIONS);++const PROGRAM = `+function build() {+ const root = createRoot('Rifle');+ const steel = gameMaterial(0x25342a, { metalness: 0.58, roughness: 0.58, name: 'ParkerisedSteel' });+ const poly = pbrMaterial({ albedo: 0x050605, roughness: 0.82, metalness: 0, name: 'PolymerFurniture' });+ createPart('Barrel', boxGeo(1, 0.1, 0.1), steel, { parent: root });+ createPart('Handguard', boxGeo(0.3, 0.2, 0.1), poly, { parent: root, position: [0.5, 0, 0] });+ return root;+}+`;++test('every material helper takes an author name', () => {+ expect(gameMaterial(0x25342a, { name: 'ParkerisedSteel' }).name).toBe('ParkerisedSteel');+ expect(pbrMaterial({ albedo: 0x050605, name: 'PolymerFurniture' }).name).toBe('PolymerFurniture');+ expect(basicMaterial(0xffffff, { name: 'Decal' }).name).toBe('Decal');+ expect(glassMaterial(0x66ccff, { name: 'ScopeLens' }).name).toBe('ScopeLens');+ expect(lambertMaterial(0x2a4d14, { name: 'Webbing' }).name).toBe('Webbing');+ expect(foliageMaterial(0x2a4d14, { name: 'Frond' }).name).toBe('Frond');+ // Omitting the option leaves three.js's own empty default, which both exporters+ // read as "no name" rather than writing an empty string.+ expect(gameMaterial(0x25342a).name).toBe('');+});++// The bound matches the portable material spec's own, so the two naming routes agree.+test('a material name is bounded and free of control characters', () => {+ for (const bad of ['', 'a'.repeat(201), 'Steel\u0000', 'Steel\nPolymer', 'Steel\u007f']) {+ expect(() => gameMaterial(0x25342a, { name: bad })).toThrow(AuthoringDiagnosticError);+ expect(() => pbrMaterial({ albedo: 0x25342a, name: bad })).toThrow(AuthoringDiagnosticError);+ }+ expect(gameMaterial(0x25342a, { name: 'a'.repeat(200) }).name).toBe('a'.repeat(200));+ // A non-string from a half-remembered API fails closed rather than stringifying.+ expect(() => gameMaterial(0x25342a, { name: 7 as unknown as string })).toThrow(+ AuthoringDiagnosticError,+ );+});++for (const exporter of ['legacy', 'three'] as const) {+ test(`${exporter} exporter carries authored material names into the GLB`, async () => {+ const { root } = await executeKilnCode(PROGRAM);+ const result = await renderSceneToGLB(root, { gltfExporter: exporter, derivative: true });+ const doc = await io().readBinary(result.bytes);+ expect(+ doc+ .getRoot()+ .listMaterials()+ .map((m) => m.getName())+ .sort(),+ ).toEqual(['ParkerisedSteel', 'PolymerFurniture']);+ });++ test(`${exporter} exporter carries names at every optimize level`, async () => {+ // The three finishes a delivered M16A1 actually carried, which arrived unnamed.+ // The consolidating passes (dedup, palette, rigid merge) keep all three names,+ // so a destination registry can key on them whatever optimize level shipped.+ const finishes = [+ ['ParkerisedSteel', 0x25342a, 0.58, 0.58],+ ['PolymerFurniture', 0x050605, 0, 0.82],+ ['Recesses', 0x010102, 0.1, 0.95],+ ] as const;+ for (const optimize of ['off', 'auto', 'palette', 'full'] as const) {+ const root = new THREE.Group();+ root.name = 'Rifle';+ finishes.forEach(([name, color, metalness, roughness], i) => {+ const mesh = new THREE.Mesh(+ new THREE.BoxGeometry(0.4, 0.1, 0.1),+ gameMaterial(color, { metalness, roughness, name }),+ );+ mesh.name = `Part${i}`;+ mesh.position.set(i * 0.5, 0, 0);+ root.add(mesh);+ });+ const result = await renderSceneToGLB(root, {+ gltfExporter: exporter,+ derivative: true,+ optimize,+ });+ const doc = await io().readBinary(result.bytes);+ expect(+ doc+ .getRoot()+ .listMaterials()+ .map((m) => m.getName()),+ ).toEqual(finishes.map(([name]) => name));+ }+ });+}diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex ed7eb758..1ccc699d 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -15,6 +15,10 @@import { geometryPrimitives } from '../geometry-catalog';import { MATERIAL_RECIPE_IDS, MATERIAL_RECIPE_LIBRARY_V1 } from '../material-recipes';+/** Why a material carries an author name at all, shared by the helpers that take one. */+const MATERIAL_NAME_NOTE =+ 'Set name to the authored finish when a destination runtime groups draws by material: it is written to the glTF material name, 1..200 visible characters. materialRecipe and the portable material specs name their output already.';+/** Allowed overrides per recipe, generated from the library so the note cannot drift. */const RECIPE_OVERRIDES_NOTE = (() => {const groups = new Map<string, string[]>();@@ -714,12 +718,13 @@ const PRIMITIVES: HelperSpec[] = [{name: 'gameMaterial',signature:- 'gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })',+ 'gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading, name })',returns: 'THREE.MeshStandardMaterial',category: 'material',description:'PBR material with flat shading by default; choose shading and material settings for the intended surface.',- example: 'const mat = gameMaterial(0x8b7355, { roughness: 0.9 });',+ example: "const mat = gameMaterial(0x8b7355, { roughness: 0.9, name: 'OiledWalnut' });",+ promptNotes: MATERIAL_NAME_NOTE,},{name: 'materialRecipe',@@ -763,7 +768,7 @@ const PRIMITIVES: HelperSpec[] = [},{name: 'basicMaterial',- signature: 'basicMaterial(color, opts?: { transparent, opacity })',+ signature: 'basicMaterial(color, opts?: { transparent, opacity, name })',returns: 'THREE.MeshBasicMaterial',category: 'material',description: 'Unlit flat material. For UI / effects where lighting is baked in.',@@ -771,7 +776,7 @@ const PRIMITIVES: HelperSpec[] = [},{name: 'glassMaterial',- signature: 'glassMaterial(color, opts?: { opacity, roughness, metalness })',+ signature: 'glassMaterial(color, opts?: { opacity, roughness, metalness, name })',returns: 'THREE.MeshStandardMaterial',category: 'material',description:@@ -780,7 +785,7 @@ const PRIMITIVES: HelperSpec[] = [},{name: 'lambertMaterial',- signature: 'lambertMaterial(color, opts?: { flatShading, emissive })',+ signature: 'lambertMaterial(color, opts?: { flatShading, emissive, name })',returns: 'THREE.MeshLambertMaterial',category: 'material',description: 'Cheaper than gameMaterial. No metalness/roughness. Use when PBR is overkill.',@@ -1203,17 +1208,18 @@ const PRIMITIVES: HelperSpec[] = [{name: 'pbrMaterial',signature:- "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",+ "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided?, name? })",returns: 'THREE.MeshStandardMaterial',category: 'material',description:'Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.',example:- "const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });",+ "const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0, name: 'CrateWood' });",+ promptNotes: MATERIAL_NAME_NOTE,},{name: 'foliageMaterial',- signature: 'foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })',+ signature: 'foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided?, name? })',returns: 'THREE.MeshStandardMaterial',category: 'material',description:diff --git a/src/evaluator/authoring-diagnostic.ts b/src/evaluator/authoring-diagnostic.tsindex 00126b83..ab6cc839 100644--- a/src/evaluator/authoring-diagnostic.ts+++ b/src/evaluator/authoring-diagnostic.ts@@ -6,6 +6,7 @@ export type AuthoringDiagnostic =| 'MESH_DATA_NONFINITE'| 'MATERIAL_ALPHA_MODE'| 'MATERIAL_COLOR_ARGUMENT'+ | 'MATERIAL_NAME'| 'MATERIAL_PACKED_CHANNELS'| 'MATERIAL_RECIPE_TEXTURE_BINDING'| 'PORTABLE_TEXTURE_REFERENCE'@@ -57,6 +58,8 @@ export const PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE ='Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.';export const PROCEDURAL_TEXTURE_USAGE_ADVICE ='proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].';+export const MATERIAL_NAME_ADVICE =+ 'A material name is the key a destination runtime groups draws by, so it is 1 to 200 visible characters: a plain string, no control characters. gameMaterial, basicMaterial, glassMaterial and lambertMaterial take it in their options object, pbrMaterial and foliageMaterial in theirs, for example gameMaterial(0x25342a, { roughness: 0.58, name: "ParkerisedSteel" }). Omit it to leave the material unnamed; materialRecipe and the portable material specs name their output already.';export const MATERIAL_FRACTION_RANGE_ADVICE ='Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.';export const PARAMETRIC_PERIODIC_ENDPOINT_ADVICE =@@ -155,6 +158,7 @@ export function authoringDiagnosticAdvice(diagnostic: AuthoringDiagnostic | undeif (diagnostic === 'PROCEDURAL_TEXTURE_UNKNOWN_KEY') return PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE;if (diagnostic === 'PROCEDURAL_TEXTURE_USAGE') return PROCEDURAL_TEXTURE_USAGE_ADVICE;if (diagnostic === 'MATERIAL_FRACTION_RANGE') return MATERIAL_FRACTION_RANGE_ADVICE;+ if (diagnostic === 'MATERIAL_NAME') return MATERIAL_NAME_ADVICE;if (diagnostic === 'PROFILE_HOLES_UNSUPPORTED') return PROFILE_HOLES_UNSUPPORTED_ADVICE;if (diagnostic === 'PROFILE_SOLID_FAILED') return PROFILE_SOLID_FAILED_ADVICE;if (diagnostic === 'PROFILE_CORRESPONDENCE_COLLAPSE')@@ -170,6 +174,46 @@ export class AuthoringDiagnosticError extends Error {this.name = 'AuthoringDiagnosticError';}}+/**+ * Longest author material name written to a glTF `materials[].name`.+ *+ * Matches the portable material spec's own 1..200 name bound, so naming a material+ * through a helper and naming one through `compilePortableMaterialSpecV3` accept the+ * same strings; that contract checks length only, and this path also rejects control+ * characters.+ */+export const MATERIAL_NAME_MAX_LENGTH = 200;++/**+ * Bound an author material name on the way into the file.+ *+ * A destination runtime groups draws by this string, so it is worth having, but it+ * is also the only author-supplied text the exporters copy verbatim into a+ * `materials[].name`. Rejecting C0 controls and DEL, as `proceduralTexture`'s name+ * rule does, keeps a name out of the business of smuggling a newline into a log+ * line or a NUL into a consumer's string handling; the length bound keeps it from+ * arriving as an unbounded blob in everything that reads the manifest.+ *+ * Fails closed on a non-string for the reason `requireColor` does: a model that+ * half-remembers a different engine passes the wrong shape, and silently+ * stringifying it would put `[object Object]` on a part and call it named.+ */+export function assertMaterialName(name: unknown, fn: string): string {+ if (+ typeof name !== 'string' ||+ !name.length ||+ name.length > MATERIAL_NAME_MAX_LENGTH ||+ [...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)+ )+ throw new AuthoringDiagnosticError(+ 'MATERIAL_NAME',+ `${fn}: name must be 1..${MATERIAL_NAME_MAX_LENGTH} visible characters, got ${+ typeof name === 'string' ? JSON.stringify(name.slice(0, 32)) : typeof name+ }. ${MATERIAL_NAME_ADVICE}`,+ );+ return name;+}+/*** Closed cause for an error that crosses the worker boundary without a diagnostic.* Built-in error classes only, never message text: a temporal-dead-zone read isdiff --git a/src/primitives.ts b/src/primitives.tsindex caa56389..370fe9dc 100644--- a/src/primitives.ts+++ b/src/primitives.ts@@ -10,7 +10,7 @@*/import * as THREE from 'three';-import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';+import { AuthoringDiagnosticError, assertMaterialName } from './evaluator/authoring-diagnostic';import {assertDimension,assertPrimitiveSegments,@@ -1519,10 +1519,12 @@ export function gameMaterial(emissive?: number | string;emissiveIntensity?: number;flatShading?: boolean;+ /** Stable name written to the exported glTF material. */+ name?: string;} = {},): THREE.MeshStandardMaterial {requireColor(color, 'gameMaterial');- return new THREE.MeshStandardMaterial({+ const material = new THREE.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -1530,26 +1532,30 @@ export function gameMaterial(emissiveIntensity: options.emissiveIntensity ?? 1,flatShading: options.flatShading ?? true,});+ if (options.name !== undefined) material.name = assertMaterialName(options.name, 'gameMaterial');+ return material;}export function basicMaterial(color: number | string,- options: { transparent?: boolean; opacity?: number } = {},+ options: { transparent?: boolean; opacity?: number; name?: string } = {},): THREE.MeshBasicMaterial {requireColor(color, 'basicMaterial');- return new THREE.MeshBasicMaterial({+ const material = new THREE.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1,});+ if (options.name !== undefined) material.name = assertMaterialName(options.name, 'basicMaterial');+ return material;}export function glassMaterial(color: number | string,- options: { opacity?: number; roughness?: number; metalness?: number } = {},+ options: { opacity?: number; roughness?: number; metalness?: number; name?: string } = {},): THREE.MeshStandardMaterial {requireColor(color, 'glassMaterial');- return new THREE.MeshStandardMaterial({+ const material = new THREE.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,@@ -1557,18 +1563,23 @@ export function glassMaterial(metalness: options.metalness ?? 0,side: THREE.DoubleSide,});+ if (options.name !== undefined) material.name = assertMaterialName(options.name, 'glassMaterial');+ return material;}export function lambertMaterial(color: number | string,- options: { flatShading?: boolean; emissive?: number | string } = {},+ options: { flatShading?: boolean; emissive?: number | string; name?: string } = {},): THREE.MeshLambertMaterial {requireColor(color, 'lambertMaterial');- return new THREE.MeshLambertMaterial({+ const material = new THREE.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0x000000,});+ if (options.name !== undefined)+ material.name = assertMaterialName(options.name, 'lambertMaterial');+ return material;}// =============================================================================diff --git a/src/textures.ts b/src/textures.tsindex 7561b853..34d69d8f 100644--- a/src/textures.ts+++ b/src/textures.ts@@ -9,7 +9,7 @@*/import * as THREE from 'three';-import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';+import { AuthoringDiagnosticError, assertMaterialName } from './evaluator/authoring-diagnostic';import type { TextureUsage } from './texture-contract';export { TEXTURE_USAGES, type TextureUsage } from './texture-contract';@@ -177,6 +177,8 @@ export interface PbrMaterialOptions {alphaCutoff?: number;/** Render both sides of the surface. Defaults false. */doubleSided?: boolean;+ /** Stable name written to the exported glTF material. */+ name?: string;}function textureMetadata(texture: THREE.Texture): KilnTextureMetadata | undefined {@@ -319,6 +321,7 @@ export function pbrMaterial(opts: PbrMaterialOptions = {}): THREE.MeshStandardMa...(alphaMode === 'mask' ? { alphaCutoff: mat.alphaTest } : {}),doubleSided: opts.doubleSided === true,};+ if (opts.name !== undefined) mat.name = assertMaterialName(opts.name, 'pbrMaterial');return mat;}@@ -327,6 +330,8 @@ export interface FoliageMaterialOptions {alphaCutoff?: number;roughness?: number;doubleSided?: boolean;+ /** Stable name written to the exported glTF material. */+ name?: string;}/** Portable foliage material: glTF MASK + cutoff + double-sided by default. */@@ -341,5 +346,6 @@ export function foliageMaterial(alphaMode: 'mask',alphaCutoff: opts.alphaCutoff ?? 0.5,doubleSided: opts.doubleSided ?? true,+ ...(opts.name !== undefined ? { name: opts.name } : {}),});}