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
Add the bunker door frame delivery fixture and its GLTFLoader qualification
Matt Kissinger47d045f4a8d9
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex 130a0f66..6585fbe8 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -3330,7 +3330,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.', 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.", 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? }) takes positive integers. 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake 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.', 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.", 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? }) takes positive integers; 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake is named when it is the cause.", AuthoringDiagnosticError;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -7802,6 +7802,15 @@ bakeSurfaceAttributes(root, { edge: { thresholdDegrees: 35 }, cavity: { rays: 32example: "defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });",promptNotes: "Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels."},+ {+ name: "definePalette",+ signature: "definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)",+ returns: "{ schemaVersion: 1, colors, threshold } (the normalised declaration)",+ category: "utility",+ description: "Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry as PALETTE_OFF warnings and a manifest palette report. Advisory: never fails a build.",+ example: "definePalette(['#6b6f73', '#3a3d40', '#8a4b2a', '#c9a227']);",+ promptNotes: "Only when the brief names a palette or a set of exact colours. Call once."+ },{name: "requireSolid",signature: "requireSolid(part: Object3D)",@@ -19682,6 +19691,10 @@ var init_vegetation = __esm(() => {trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }},+ cactus: {+ trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },+ branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] }+ },fungus: {trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }@@ -26169,28 +26182,147 @@ var init_assembly = __esm(() => {threeConstructors = new Set(Object.values(THREE32));});+// src/palette-check.ts+function hex(value, label) {+ if (typeof value !== "string" || !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))+ fail7(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);+ const digits = value.replace("#", "").toLowerCase();+ return `#${digits.length === 3 ? [...digits].map((d) => d + d).join("") : digits}`;+}+function normalizePalette(colors, opts) {+ if (!Array.isArray(colors) || colors.length === 0 || colors.length > PALETTE_MAX_COLORS)+ fail7(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);+ const entries = colors.map((value, i) => hex(value, `colors[${i}]`));+ let threshold = PALETTE_DEFAULT_THRESHOLD;+ if (opts !== undefined) {+ if (!opts || typeof opts !== "object" || Array.isArray(opts))+ fail7("opts must be { threshold? }.");+ for (const key of Object.keys(opts))+ if (key !== "threshold")+ fail7(`unknown option ${JSON.stringify(key)}.`);+ const t = opts.threshold;+ if (t !== undefined) {+ if (typeof t !== "number" || !Number.isFinite(t) || t <= 0 || t > 100)+ fail7(`threshold must be a delta E in (0, 100], got ${String(t)}.`);+ threshold = t;+ }+ }+ return { schemaVersion: 1, colors: [...new Set(entries)], threshold };+}+function definePalette(colors, opts, target) {+ const declaration = normalizePalette(colors, opts);+ if (target !== undefined) {+ if (target?.isObject3D !== true)+ fail7("target must be a scene node, normally the root.");+ target.userData[KILN_PALETTE_KEY] = structuredClone(declaration);+ }+ return declaration;+}+function readPaletteDeclaration(value) {+ if (value === undefined)+ return;+ try {+ const record = value;+ if (record.schemaVersion !== 1)+ return;+ return normalizePalette(record.colors, { threshold: record.threshold });+ } catch {+ return;+ }+}+function linearRgbToLab([r, g, b]) {+ const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047;+ const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b;+ const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883;+ const f = (t) => t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116;+ const [fx, fy, fz] = [f(x), f(y), f(z)];+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}+function evaluatePalette(declaration, doc) {+ const palette = declaration.colors.map((color) => ({+ color,+ lab: linearRgbToLab(hexToLinear(color))+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const materials = new Set;+ const visit = (node, hidden) => {+ const nodeHidden = hidden || isHiddenGltfNode(node);+ if (!nodeHidden)+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material && material.getName() !== COLLIDER_PROXY_MATERIAL_NAME)+ materials.add(material);+ }+ for (const child of node.listChildren())+ visit(child, nodeHidden);+ };+ for (const node of scene?.listChildren() ?? [])+ visit(node, false);+ const offPalette = [];+ for (const material of materials) {+ const factor = material.getBaseColorFactor();+ const lab = linearRgbToLab([factor[0], factor[1], factor[2]]);+ let nearest = palette[0];+ let distance = Number.POSITIVE_INFINITY;+ for (const entry of palette) {+ const d = deltaE(lab, entry.lab);+ if (d < distance) {+ distance = d;+ nearest = entry;+ }+ }+ if (distance > declaration.threshold)+ offPalette.push({+ material: material.getName(),+ color: linearToHex(factor.slice(0, 3)),+ nearest: nearest.color,+ deltaE: Math.round(distance * 100) / 100,+ ...material.getBaseColorTexture() ? { textured: true } : {}+ });+ }+ offPalette.sort((a, b) => b.deltaE - a.deltaE || (a.material < b.material ? -1 : 1));+ return {+ status: offPalette.length ? "warn" : "pass",+ colors: [...declaration.colors],+ threshold: declaration.threshold,+ checkedMaterials: materials.size,+ offPalette+ };+}+var KILN_PALETTE_KEY = "kilnPaletteV1", PALETTE_DEFAULT_THRESHOLD = 10, PALETTE_MAX_COLORS = 64, fail7 = (detail) => {+ throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `definePalette(colors, opts?): ${detail}`);+}, srgbToLinear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, linearToSrgb2 = (c) => c <= 0.0031308 ? c * 12.92 : 1.055 * Math.max(0, c) ** (1 / 2.4) - 0.055, hexToLinear = (value) => {+ const n = Number.parseInt(value.slice(1), 16);+ return [n >> 16 & 255, n >> 8 & 255, n & 255].map((c) => srgbToLinear(c / 255));+}, linearToHex = (rgb) => `#${rgb.map((c) => Math.round(Math.min(1, Math.max(0, linearToSrgb2(c))) * 255).toString(16).padStart(2, "0")).join("")}`, deltaE = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+var init_palette_check = __esm(() => {+ init_delivery();+ init_authoring_diagnostic();+ init_metrics();+});+// src/budget.tsfunction normalizeBudget(spec) {if (!spec || typeof spec !== "object" || Array.isArray(spec))- fail7("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");+ fail8("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");const value = spec;for (const key of Object.keys(value))if (key !== "triangles" && key !== "draws" && key !== "schemaVersion")- fail7(`unknown field ${JSON.stringify(key)}.`);+ fail8(`unknown field ${JSON.stringify(key)}.`);const triangles = {};if (typeof value.triangles === "number")triangles.LOD0 = count3("triangles", value.triangles);else if (value.triangles && typeof value.triangles === "object" && !Array.isArray(value.triangles)) {const entries = Object.entries(value.triangles);if (entries.length === 0)- fail7("triangles needs at least one tier.");+ fail8("triangles needs at least one tier.");for (const [tier, limit] of entries) {if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))- fail7(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);+ fail8(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);triangles[tier] = count3(`triangles.${tier}`, limit);}} else- fail7("triangles must be a positive integer or a record of LOD tiers.");+ fail8("triangles must be a positive integer or a record of LOD tiers.");const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))));return {schemaVersion: 1,@@ -26202,7 +26334,7 @@ function defineBudget(spec, target) {const declaration = normalizeBudget(spec);if (target !== undefined) {if (target?.isObject3D !== true)- fail7("target must be a scene node, normally the root.");+ fail8("target must be a scene node, normally the root.");target.userData[KILN_BUDGET_KEY] = structuredClone(declaration);}return declaration;@@ -26247,11 +26379,11 @@ function evaluateBudget(declaration, measuredLod0, chains) {});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };}-var KILN_BUDGET_KEY = "kilnBudgetV1", fail7 = (detail) => {+var KILN_BUDGET_KEY = "kilnBudgetV1", fail8 = (detail) => {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `defineBudget(spec): ${detail}`);}, count3 = (label, value) => {if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)- fail7(`${label} must be a positive integer, got ${String(value)}.`);+ fail8(`${label} must be a positive integer, got ${String(value)}.`);return value;};var init_budget = __esm(() => {@@ -30323,6 +30455,11 @@ function buildSandboxGlobals(usage, options = {}) {declarations.budget = declaration;return declaration;}),+ definePalette: wrap("definePalette", (colors, opts, target) => {+ const declaration = definePalette(colors, opts, target);+ declarations.palette = declaration;+ return declaration;+ }),capsuleGeo: wrapGeo("capsuleGeo", capsuleGeo),capsuleXGeo: wrapGeo("capsuleXGeo", capsuleXGeo),capsuleYGeo: wrapGeo("capsuleYGeo", capsuleYGeo),@@ -30451,6 +30588,7 @@ var init_primitives = __esm(() => {init_delivery();init_surface_bake();init_require_solid();+ init_palette_check();init_budget();init_animation_cubic();init_animation_spline();@@ -35695,6 +35833,8 @@ async function inspectGlbIntegration(bytes, opts = {}) {const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);+ const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: "kiln.integration-manifest.v1",analyzerVersion: 1,@@ -35738,6 +35878,7 @@ async function inspectGlbIntegration(bytes, opts = {}) {...delivery.kit ? { kit: delivery.kit } : {},...delivery.ports.length ? { ports: delivery.ports } : {},...budget ? { budget } : {},+ ...palette ? { palette } : {},...vertexAttributes.length ? { vertexAttributes } : {},...delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {},structuralQa: {@@ -35778,6 +35919,8 @@ return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof aconst declared = globals[SANDBOX_DECLARATIONS];if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)root.userData[KILN_BUDGET_KEY] = declared.budget;+ if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)+ root.userData[KILN_PALETTE_KEY] = declared.palette;const clips = animate ? await animate(root) ?? [] : [];return { meta: meta ?? {}, root, clips, primitiveUsage };} catch (error) {@@ -36392,6 +36535,14 @@ async function renderSceneToGLB(root, opts = {}) {[KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY])});}+ if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {+ const declared = root.userData[KILN_PALETTE_KEY];+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold })+ });+ }applySurfaceBakeExtras(root, doc);applyNodeVisibility(root, doc);applyLodChains(root, lodSets, doc);@@ -36473,6 +36624,9 @@ async function renderSceneToGLB(root, opts = {}) {throw new Error("renderSceneToGLB: final GLB has no measurable scene");for (const finding of integrationManifest.deliveryDiagnostics ?? [])warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);+ const palette = integrationManifest.palette;+ for (const finding of palette?.offPalette ?? [])+ warnings.push(`PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette.threshold})${finding.textured ? "; the factor tints a texture that is not judged" : ""}.`);const diagnosticViews = [];const rig = requirements.requirements.requirements.rig;const diagnosticParents = new Map(lodSets.map(({ parent }) => [parent, [...parent.children]]));@@ -36773,6 +36927,7 @@ var init_render = __esm(() => {init_geometry_export();init_primitives();init_budget();+ init_palette_check();init_metrics();init_contracts();init_gltf();@@ -40503,6 +40658,34 @@ define2("defineBudget", {limitations: ["Does not simplify geometry or merge draws to meet a budget."],related: [{ name: "defineLod", relation: "companion" }]});+define2("definePalette", {+ units: "Colours are sRGB hex; threshold is a CIE 1976 delta E in CIELAB (D65).",+ axes: "Not a placement operation.",+ origin: "Not a placement operation.",+ ownership: "Records one declaration: on target when given, otherwise on the root build() returns. Export writes it as default-scene extras kilnPaletteV1.",+ coordinates: "Not a placement operation.",+ parameters: [+ "colors: 1..64 hex strings ('#rgb' or '#rrggbb'); duplicates collapse.",+ "opts.threshold: delta E in (0, 100], default 10.",+ "target: optional scene node, normally the root."+ ],+ topology: [noMesh],+ preservation: ["Changes no geometry, material or node."],+ semantics: [+ "Every material drawn by a visible scene node (collider proxies excluded) is compared by its base colour factor, converted from linear to sRGB to CIELAB; a factor that tints a texture is flagged textured.",+ "The integration manifest and CLI receipt report palette: { status: pass | warn, colors, threshold, checkedMaterials, offPalette: [{ material, color, nearest, deltaE, textured? }] }; each off-palette material is also a PALETTE_OFF warning.",+ "Advisory only: no build fails and QA acceptance is unchanged. Invalid input is a DELIVERY_CONTRACT build error."+ ],+ cost: "One colour conversion per drawn material at export."+}, {+ references: ["src/palette-check.ts", "docs/delivery-contract.md"],+ tags: ["delivery", "palette", "color", "art direction"],+ aliases: ["color palette", "palette lock", "art palette", "swatches"],+ intents: ["check materials against a declared colour palette"],+ summary: "Declares a colour palette; receipts list drawn materials off it by delta E, advisory only.",+ limitations: ["Judges base colour factors, not texture pixels. Never fails a build."],+ related: [{ name: "gameMaterial", relation: "companion" }]+});define2("requireSolid", {...nodeFacts,units: "No lengths.",diff --git a/dist/build.json b/dist/build.jsonindex 92fb3713..1d91094b 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:39babe1749d0ac2ed91992c4248d4cf0f69da41cec95826485fea44913ad5121",+ "identity": "sha256:6faddbf66b4a18602b198937133dd80f696af99af525c2b58d82484d7c19f885","engineVersion": "1.2.3","toolchain": "[email protected]",- "sourceHash": "865e2807791727b06717d3278b1a09232dfd5ee45c4ea360882843faca607f13",+ "sourceHash": "1831d3bf721f61f7ccde42f50b6db0d53fd29784a81d6457d8ca770ff5ae57c4","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f","dependencies": {@@ -36,13 +36,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:6cd9119aaf3d78b6075543bb887de98c2eb42e9594173c67b535b65cc74f2d7a"+ "bundleHash": "sha256:ce531903d4338186657f50f079e2ecffa0dd3b04d7765d3f4daccd725bd66804"},"agent-run": {- "identity": "sha256:39babe1749d0ac2ed91992c4248d4cf0f69da41cec95826485fea44913ad5121",+ "identity": "sha256:6faddbf66b4a18602b198937133dd80f696af99af525c2b58d82484d7c19f885","engineVersion": "1.2.3","toolchain": "[email protected]",- "sourceHash": "865e2807791727b06717d3278b1a09232dfd5ee45c4ea360882843faca607f13",+ "sourceHash": "1831d3bf721f61f7ccde42f50b6db0d53fd29784a81d6457d8ca770ff5ae57c4","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f","dependencies": {@@ -73,13 +73,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:4f2523ace08cef6c43491dfdac9277d702d2df92e7299d46f8329e1323c3334f"+ "bundleHash": "sha256:5ddfb55fa50037292a1fba651157ac25d0593e8f721b9b6e3ec74d7a592e79f8"},"agent-providers": {- "identity": "sha256:39babe1749d0ac2ed91992c4248d4cf0f69da41cec95826485fea44913ad5121",+ "identity": "sha256:6faddbf66b4a18602b198937133dd80f696af99af525c2b58d82484d7c19f885","engineVersion": "1.2.3","toolchain": "[email protected]",- "sourceHash": "865e2807791727b06717d3278b1a09232dfd5ee45c4ea360882843faca607f13",+ "sourceHash": "1831d3bf721f61f7ccde42f50b6db0d53fd29784a81d6457d8ca770ff5ae57c4","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f","dependencies": {@@ -113,10 +113,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:39babe1749d0ac2ed91992c4248d4cf0f69da41cec95826485fea44913ad5121",+ "identity": "sha256:6faddbf66b4a18602b198937133dd80f696af99af525c2b58d82484d7c19f885","engineVersion": "1.2.3","toolchain": "[email protected]",- "sourceHash": "865e2807791727b06717d3278b1a09232dfd5ee45c4ea360882843faca607f13",+ "sourceHash": "1831d3bf721f61f7ccde42f50b6db0d53fd29784a81d6457d8ca770ff5ae57c4","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f","dependencies": {@@ -150,10 +150,10 @@"bundleHash": "sha256:0976f6cbeb0fcb605b4cd473ade1b975e21962f407fe69a1f73d6ba1be314d0d"},"cli": {- "identity": "sha256:39babe1749d0ac2ed91992c4248d4cf0f69da41cec95826485fea44913ad5121",+ "identity": "sha256:6faddbf66b4a18602b198937133dd80f696af99af525c2b58d82484d7c19f885","engineVersion": "1.2.3","toolchain": "[email protected]",- "sourceHash": "865e2807791727b06717d3278b1a09232dfd5ee45c4ea360882843faca607f13",+ "sourceHash": "1831d3bf721f61f7ccde42f50b6db0d53fd29784a81d6457d8ca770ff5ae57c4","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f","dependencies": {@@ -184,13 +184,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:cfe7de6e8b4b1425be3731644773e82cb49c7678df1d076dc95366c5014f1023"+ "bundleHash": "sha256:98ef08c58b3098b186f8192e87014b0e17737a749daaea61098f8a320c301e89"},"engine": {- "identity": "sha256:39babe1749d0ac2ed91992c4248d4cf0f69da41cec95826485fea44913ad5121",+ "identity": "sha256:6faddbf66b4a18602b198937133dd80f696af99af525c2b58d82484d7c19f885","engineVersion": "1.2.3","toolchain": "[email protected]",- "sourceHash": "865e2807791727b06717d3278b1a09232dfd5ee45c4ea360882843faca607f13",+ "sourceHash": "1831d3bf721f61f7ccde42f50b6db0d53fd29784a81d6457d8ca770ff5ae57c4","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "bb179f2715f8fd9059898ef3a2028947e8f5f7e7979ad7eafe59d7a464c18f9f","dependencies": {@@ -221,7 +221,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:c8793ea196982afcb70cd785633a730116153b98c1b68e518ce5c41c5de4ef1f"+ "bundleHash": "sha256:a000f617f641e857e4650109f23b088229d1baa2e1126995160475511e9c505e"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex be332b23..1fa48767 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -208,7 +208,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.', 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.", 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? }) takes positive integers. 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake 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.', 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.", 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? }) takes positive integers; 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake is named when it is the cause.", AuthoringDiagnosticError;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -4479,6 +4479,7 @@ var init_asset = __esm(() => {"vine","crop/flower","succulent",+ "cactus","fungus","aquatic","bare/dead",@@ -10268,6 +10269,10 @@ var init_vegetation = __esm(() => {trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }},+ cactus: {+ trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },+ branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] }+ },fungus: {trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }@@ -23893,28 +23898,147 @@ var init_assembly = __esm(() => {threeConstructors = new Set(Object.values(THREE32));});+// src/palette-check.ts+function hex(value, label) {+ if (typeof value !== "string" || !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))+ fail7(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);+ const digits = value.replace("#", "").toLowerCase();+ return `#${digits.length === 3 ? [...digits].map((d) => d + d).join("") : digits}`;+}+function normalizePalette(colors, opts) {+ if (!Array.isArray(colors) || colors.length === 0 || colors.length > PALETTE_MAX_COLORS)+ fail7(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);+ const entries = colors.map((value, i) => hex(value, `colors[${i}]`));+ let threshold = PALETTE_DEFAULT_THRESHOLD;+ if (opts !== undefined) {+ if (!opts || typeof opts !== "object" || Array.isArray(opts))+ fail7("opts must be { threshold? }.");+ for (const key of Object.keys(opts))+ if (key !== "threshold")+ fail7(`unknown option ${JSON.stringify(key)}.`);+ const t = opts.threshold;+ if (t !== undefined) {+ if (typeof t !== "number" || !Number.isFinite(t) || t <= 0 || t > 100)+ fail7(`threshold must be a delta E in (0, 100], got ${String(t)}.`);+ threshold = t;+ }+ }+ return { schemaVersion: 1, colors: [...new Set(entries)], threshold };+}+function definePalette(colors, opts, target) {+ const declaration = normalizePalette(colors, opts);+ if (target !== undefined) {+ if (target?.isObject3D !== true)+ fail7("target must be a scene node, normally the root.");+ target.userData[KILN_PALETTE_KEY] = structuredClone(declaration);+ }+ return declaration;+}+function readPaletteDeclaration(value) {+ if (value === undefined)+ return;+ try {+ const record = value;+ if (record.schemaVersion !== 1)+ return;+ return normalizePalette(record.colors, { threshold: record.threshold });+ } catch {+ return;+ }+}+function linearRgbToLab([r, g, b]) {+ const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047;+ const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b;+ const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883;+ const f = (t) => t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116;+ const [fx, fy, fz] = [f(x), f(y), f(z)];+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}+function evaluatePalette(declaration, doc) {+ const palette = declaration.colors.map((color) => ({+ color,+ lab: linearRgbToLab(hexToLinear(color))+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const materials = new Set;+ const visit = (node, hidden) => {+ const nodeHidden = hidden || isHiddenGltfNode(node);+ if (!nodeHidden)+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material && material.getName() !== COLLIDER_PROXY_MATERIAL_NAME)+ materials.add(material);+ }+ for (const child of node.listChildren())+ visit(child, nodeHidden);+ };+ for (const node of scene?.listChildren() ?? [])+ visit(node, false);+ const offPalette = [];+ for (const material of materials) {+ const factor = material.getBaseColorFactor();+ const lab = linearRgbToLab([factor[0], factor[1], factor[2]]);+ let nearest = palette[0];+ let distance = Number.POSITIVE_INFINITY;+ for (const entry of palette) {+ const d = deltaE(lab, entry.lab);+ if (d < distance) {+ distance = d;+ nearest = entry;+ }+ }+ if (distance > declaration.threshold)+ offPalette.push({+ material: material.getName(),+ color: linearToHex(factor.slice(0, 3)),+ nearest: nearest.color,+ deltaE: Math.round(distance * 100) / 100,+ ...material.getBaseColorTexture() ? { textured: true } : {}+ });+ }+ offPalette.sort((a, b) => b.deltaE - a.deltaE || (a.material < b.material ? -1 : 1));+ return {+ status: offPalette.length ? "warn" : "pass",+ colors: [...declaration.colors],+ threshold: declaration.threshold,+ checkedMaterials: materials.size,+ offPalette+ };+}+var KILN_PALETTE_KEY = "kilnPaletteV1", PALETTE_DEFAULT_THRESHOLD = 10, PALETTE_MAX_COLORS = 64, fail7 = (detail) => {+ throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `definePalette(colors, opts?): ${detail}`);+}, srgbToLinear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, linearToSrgb = (c) => c <= 0.0031308 ? c * 12.92 : 1.055 * Math.max(0, c) ** (1 / 2.4) - 0.055, hexToLinear = (value) => {+ const n = Number.parseInt(value.slice(1), 16);+ return [n >> 16 & 255, n >> 8 & 255, n & 255].map((c) => srgbToLinear(c / 255));+}, linearToHex = (rgb) => `#${rgb.map((c) => Math.round(Math.min(1, Math.max(0, linearToSrgb(c))) * 255).toString(16).padStart(2, "0")).join("")}`, deltaE = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+var init_palette_check = __esm(() => {+ init_delivery();+ init_authoring_diagnostic();+ init_metrics();+});+// src/budget.tsfunction normalizeBudget(spec) {if (!spec || typeof spec !== "object" || Array.isArray(spec))- fail7("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");+ fail8("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");const value = spec;for (const key of Object.keys(value))if (key !== "triangles" && key !== "draws" && key !== "schemaVersion")- fail7(`unknown field ${JSON.stringify(key)}.`);+ fail8(`unknown field ${JSON.stringify(key)}.`);const triangles = {};if (typeof value.triangles === "number")triangles.LOD0 = count3("triangles", value.triangles);else if (value.triangles && typeof value.triangles === "object" && !Array.isArray(value.triangles)) {const entries = Object.entries(value.triangles);if (entries.length === 0)- fail7("triangles needs at least one tier.");+ fail8("triangles needs at least one tier.");for (const [tier, limit] of entries) {if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))- fail7(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);+ fail8(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);triangles[tier] = count3(`triangles.${tier}`, limit);}} else- fail7("triangles must be a positive integer or a record of LOD tiers.");+ fail8("triangles must be a positive integer or a record of LOD tiers.");const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))));return {schemaVersion: 1,@@ -23926,7 +24050,7 @@ function defineBudget(spec, target) {const declaration = normalizeBudget(spec);if (target !== undefined) {if (target?.isObject3D !== true)- fail7("target must be a scene node, normally the root.");+ fail8("target must be a scene node, normally the root.");target.userData[KILN_BUDGET_KEY] = structuredClone(declaration);}return declaration;@@ -23971,11 +24095,11 @@ function evaluateBudget(declaration, measuredLod0, chains) {});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };}-var KILN_BUDGET_KEY = "kilnBudgetV1", fail7 = (detail) => {+var KILN_BUDGET_KEY = "kilnBudgetV1", fail8 = (detail) => {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `defineBudget(spec): ${detail}`);}, count3 = (label, value) => {if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)- fail7(`${label} must be a positive integer, got ${String(value)}.`);+ fail8(`${label} must be a positive integer, got ${String(value)}.`);return value;};var init_budget = __esm(() => {@@ -28047,6 +28171,11 @@ function buildSandboxGlobals(usage, options = {}) {declarations.budget = declaration;return declaration;}),+ definePalette: wrap("definePalette", (colors, opts, target) => {+ const declaration = definePalette(colors, opts, target);+ declarations.palette = declaration;+ return declaration;+ }),capsuleGeo: wrapGeo("capsuleGeo", capsuleGeo),capsuleXGeo: wrapGeo("capsuleXGeo", capsuleXGeo),capsuleYGeo: wrapGeo("capsuleYGeo", capsuleYGeo),@@ -28175,6 +28304,7 @@ var init_primitives = __esm(() => {init_delivery();init_surface_bake();init_require_solid();+ init_palette_check();init_budget();init_animation_cubic();init_animation_spline();@@ -29383,6 +29513,15 @@ bakeSurfaceAttributes(root, { edge: { thresholdDegrees: 35 }, cavity: { rays: 32example: "defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });",promptNotes: "Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels."},+ {+ name: "definePalette",+ signature: "definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)",+ returns: "{ schemaVersion: 1, colors, threshold } (the normalised declaration)",+ category: "utility",+ description: "Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry as PALETTE_OFF warnings and a manifest palette report. Advisory: never fails a build.",+ example: "definePalette(['#6b6f73', '#3a3d40', '#8a4b2a', '#c9a227']);",+ promptNotes: "Only when the brief names a palette or a set of exact colours. Call once."+ },{name: "requireSolid",signature: "requireSolid(part: Object3D)",@@ -33420,7 +33559,7 @@ function collectTriangles(root) {function clamp012(n) {return n < 0 ? 0 : n > 1 ? 1 : n;}-function linearToSrgb(c) {+function linearToSrgb2(c) {const v = clamp012(c);return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;}@@ -33493,9 +33632,9 @@ function rasterizeView(root, dir, opts = {}) {}const lambert = Math.max(0, dot4(N, KEY_DIR) * normalSign);const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);- const r = Math.round(linearToSrgb(tri.color[0] * lit) * 255);- const g = Math.round(linearToSrgb(tri.color[1] * lit) * 255);- const b = Math.round(linearToSrgb(tri.color[2] * lit) * 255);+ const r = Math.round(linearToSrgb2(tri.color[0] * lit) * 255);+ const g = Math.round(linearToSrgb2(tri.color[1] * lit) * 255);+ const b = Math.round(linearToSrgb2(tri.color[2] * lit) * 255);const triangle = prepareTriangleCoverage(sx[0], sy[0], sx[1], sy[1], sx[2], sy[2], size);if (!triangle)continue;@@ -36777,6 +36916,8 @@ async function inspectGlbIntegration(bytes, opts = {}) {const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);+ const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: "kiln.integration-manifest.v1",analyzerVersion: 1,@@ -36820,6 +36961,7 @@ async function inspectGlbIntegration(bytes, opts = {}) {...delivery.kit ? { kit: delivery.kit } : {},...delivery.ports.length ? { ports: delivery.ports } : {},...budget ? { budget } : {},+ ...palette ? { palette } : {},...vertexAttributes.length ? { vertexAttributes } : {},...delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {},structuralQa: {@@ -36860,6 +37002,8 @@ return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof aconst declared = globals[SANDBOX_DECLARATIONS];if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)root.userData[KILN_BUDGET_KEY] = declared.budget;+ if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)+ root.userData[KILN_PALETTE_KEY] = declared.palette;const clips = animate ? await animate(root) ?? [] : [];return { meta: meta ?? {}, root, clips, primitiveUsage };} catch (error) {@@ -37474,6 +37618,14 @@ async function renderSceneToGLB(root, opts = {}) {[KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY])});}+ if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {+ const declared = root.userData[KILN_PALETTE_KEY];+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold })+ });+ }applySurfaceBakeExtras(root, doc);applyNodeVisibility(root, doc);applyLodChains(root, lodSets, doc);@@ -37555,6 +37707,9 @@ async function renderSceneToGLB(root, opts = {}) {throw new Error("renderSceneToGLB: final GLB has no measurable scene");for (const finding of integrationManifest.deliveryDiagnostics ?? [])warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);+ const palette = integrationManifest.palette;+ for (const finding of palette?.offPalette ?? [])+ warnings.push(`PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette.threshold})${finding.textured ? "; the factor tints a texture that is not judged" : ""}.`);const diagnosticViews = [];const rig = requirements.requirements.requirements.rig;const diagnosticParents = new Map(lodSets.map(({ parent }) => [parent, [...parent.children]]));@@ -37865,6 +38020,7 @@ var init_render = __esm(() => {init_geometry_export();init_primitives();init_budget();+ init_palette_check();init_metrics();init_contracts();init_gltf();@@ -37920,7 +38076,7 @@ function isRecord6(value) {function hasExactKeys(value, allowed) {return Object.keys(value).every((key) => allowed.includes(key));}-function fail8(kind) {+function fail9(kind) {throw new Error(`invalid evaluator ${kind}`);}function validRequestId(value) {@@ -37970,18 +38126,18 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {try {value = JSON.parse(json);} catch {- return fail8("result");+ return fail9("result");}if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {- return fail8("result");+ return fail9("result");}if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)- fail8("result");+ fail9("result");if (!value.ok) {if (value.render !== undefined)- return fail8("result");+ return fail9("result");if (!isRecord6(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic"])) {- return fail8("result");+ return fail9("result");}const codes = ["INPUT_INVALID",@@ -37995,21 +38151,21 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {"PROTOCOL_ERROR"];if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {- return fail8("result");+ return fail9("result");}if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_UNKNOWN_KEY" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_BLEND" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_V3_CONTRACT" && value.error.diagnostic !== "PORTABLE_MATERIAL_V3_CONTRACT" && value.error.diagnostic !== "TEXTURE_ATLAS_CONTRACT" && value.error.diagnostic !== "MATERIAL_FRACTION_RANGE" && value.error.diagnostic !== "MATERIAL_RECIPE_TEXTURE_BINDING" && value.error.diagnostic !== "PORTABLE_TEXTURE_REFERENCE" && value.error.diagnostic !== "PORTABLE_COLOR_ARGUMENT" && value.error.diagnostic !== "PARAMETRIC_PERIODIC_ENDPOINT" && value.error.diagnostic !== "PROFILE_HOLES_UNSUPPORTED" && value.error.diagnostic !== "PROFILE_BEVEL_COLLAPSE" && value.error.diagnostic !== "PROFILE_CORRESPONDENCE_COLLAPSE" && value.error.diagnostic !== "REMOVED_HELPER" && value.error.diagnostic !== "TUBE_RADIUS" && value.error.diagnostic !== "TAPER_CONE_AXIS" && value.error.diagnostic !== "SOLID_FLOAT32_COLLAPSE" && value.error.diagnostic !== "MESH_DATA_NONFINITE" && value.error.diagnostic !== "MATERIAL_ALPHA_MODE" && value.error.diagnostic !== "MATERIAL_COLOR_ARGUMENT" && value.error.diagnostic !== "PART_NAME_ARGUMENT" && value.error.diagnostic !== "PART_GEOMETRY_ARGUMENT" && value.error.diagnostic !== "PART_MATERIAL_ARGUMENT" && value.error.diagnostic !== "MATERIAL_PACKED_CHANNELS" && value.error.diagnostic !== "UNINITIALIZED_BINDING" && value.error.diagnostic !== "BUILD_RESULT" && value.error.diagnostic !== "MATERIAL_RECIPE_OVERRIDE" && value.error.diagnostic !== "PROGRAM_TYPE_ERROR" && value.error.diagnostic !== "PROGRAM_RANGE_ERROR" && value.error.diagnostic !== "LOD_SET" && value.error.diagnostic !== "OPEN_SHELL" && value.error.diagnostic !== "DELIVERY_CONTRACT" && value.error.diagnostic !== "REQUIRE_SOLID" && value.error.diagnostic !== "EXPORT_MATERIAL_SIDE_UNSUPPORTED" && value.error.diagnostic !== "BONE_CHAIN_ARGUMENT" && value.error.diagnostic !== "SKIN_BINDING_ARGUMENT"))- return fail8("result");+ return fail9("result");if (value.error.qa !== undefined) {if (value.error.code !== "QA_BLOCKED" || !isRecord6(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validRequirementsQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {- return fail8("result");+ return fail9("result");}} else if (value.error.code === "QA_BLOCKED") {- return fail8("result");+ return fail9("result");}return value;}if (value.error !== undefined || !isRecord6(value.render))- fail8("result");+ fail9("result");const renderKeys = ["glbBase64","artifactGlbSha256",@@ -38027,44 +38183,44 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {"rebuildOptions"];if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord6(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord6(value.render.integrationManifest)) {- fail8("result");+ fail9("result");}let requirements;if (value.render.rebuildOptions !== undefined && !rebuildOptionsSchema.strict().safeParse(value.render.rebuildOptions).success)- fail8("result");+ fail9("result");if (value.render.materialLibraryDependencies !== undefined) {if (!Array.isArray(value.render.materialLibraryDependencies) || value.render.materialLibraryDependencies.length > 16)- fail8("result");+ fail9("result");try {for (const manifest of value.render.materialLibraryDependencies)validateMaterialManifestIdentityAny(manifest);} catch {- return fail8("result");+ return fail9("result");}}try {requirements = validateRequirementsContext(value.render.requirements);validateRequirementsQaReport(value.render.meta.qaReport, requirements);} catch {- return fail8("result");+ return fail9("result");}const glb = Buffer.from(value.render.glbBase64, "base64");if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)- fail8("result");+ fail9("result");if (!isSha256(value.render.artifactGlbSha256))- fail8("result");+ fail9("result");const actualHash = `sha256:${createHash8("sha256").update(glb).digest("hex")}`;if (actualHash !== value.render.artifactGlbSha256)- fail8("result");+ fail9("result");const diagnosticViews = value.render.diagnosticViews;if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))- fail8("result");+ fail9("result");const decodedViews = diagnosticViews?.map((candidate) => {if (!isRecord6(candidate) || typeof candidate.pngBase64 !== "string")- return fail8("result");+ return fail9("result");const png = Buffer.from(candidate.pngBase64, "base64");if (png.toString("base64") !== candidate.pngBase64)- return fail8("result");+ return fail9("result");const { pngBase64: _, ...view } = candidate;return { ...view, png };});@@ -43849,6 +44005,34 @@ var init_helper_contracts = __esm(() => {limitations: ["Does not simplify geometry or merge draws to meet a budget."],related: [{ name: "defineLod", relation: "companion" }]});+ define2("definePalette", {+ units: "Colours are sRGB hex; threshold is a CIE 1976 delta E in CIELAB (D65).",+ axes: "Not a placement operation.",+ origin: "Not a placement operation.",+ ownership: "Records one declaration: on target when given, otherwise on the root build() returns. Export writes it as default-scene extras kilnPaletteV1.",+ coordinates: "Not a placement operation.",+ parameters: [+ "colors: 1..64 hex strings ('#rgb' or '#rrggbb'); duplicates collapse.",+ "opts.threshold: delta E in (0, 100], default 10.",+ "target: optional scene node, normally the root."+ ],+ topology: [noMesh],+ preservation: ["Changes no geometry, material or node."],+ semantics: [+ "Every material drawn by a visible scene node (collider proxies excluded) is compared by its base colour factor, converted from linear to sRGB to CIELAB; a factor that tints a texture is flagged textured.",+ "The integration manifest and CLI receipt report palette: { status: pass | warn, colors, threshold, checkedMaterials, offPalette: [{ material, color, nearest, deltaE, textured? }] }; each off-palette material is also a PALETTE_OFF warning.",+ "Advisory only: no build fails and QA acceptance is unchanged. Invalid input is a DELIVERY_CONTRACT build error."+ ],+ cost: "One colour conversion per drawn material at export."+ }, {+ references: ["src/palette-check.ts", "docs/delivery-contract.md"],+ tags: ["delivery", "palette", "color", "art direction"],+ aliases: ["color palette", "palette lock", "art palette", "swatches"],+ intents: ["check materials against a declared colour palette"],+ summary: "Declares a colour palette; receipts list drawn materials off it by delta E, advisory only.",+ limitations: ["Judges base colour factors, not texture pixels. Never fails a build."],+ related: [{ name: "gameMaterial", relation: "companion" }]+ });define2("requireSolid", {...nodeFacts,units: "No lengths.",@@ -54911,6 +55095,7 @@ async function emit(code, args, context, reviewed, receipt = { files: [] }) {...result.integrationManifest.hiddenNodes ? { hiddenNodes: result.integrationManifest.hiddenNodes } : {},...result.integrationManifest.vertexAttributes ? { vertexAttributes: result.integrationManifest.vertexAttributes } : {},budget: result.integrationManifest.budget ?? { status: "none", tiers: [] },+ ...result.integrationManifest.palette ? { palette: result.integrationManifest.palette } : {},artifactGlbSha256: result.artifactGlbSha256,glbBytes: result.glb.length,warnings: result.warnings,@@ -54948,6 +55133,9 @@ async function emit(code, args, context, reviewed, receipt = { files: [] }) {const tiers = budget.tiers.map((tier) => `${tier.tier} ${tier.measured.triangles}/${tier.declared.triangles ?? "-"} tris${tier.declared.draws === undefined ? "" : ` ${tier.measured.draws}/${tier.declared.draws} draws`} ${tier.status}`).join("; ");log(` budget ${budget.status} ${tiers}`);}+ const palette = result.integrationManifest.palette;+ if (palette)+ log(` palette ${palette.status} ${palette.checkedMaterials} material(s), ${palette.offPalette.length} off palette (delta E > ${palette.threshold})`);for (const attribute of result.integrationManifest.vertexAttributes ?? [])log(` attribute ${attribute.name} on ${attribute.meshes.length} mesh(es)`);if (result.meta.indexBuffers) {diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 9c18ecce..3e3029b3 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -121,7 +121,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.', 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.", 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? }) takes positive integers. 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake 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.', 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.", 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? }) takes positive integers; 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake is named when it is the cause.", AuthoringDiagnosticError;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -10063,6 +10063,10 @@ var init_vegetation = __esm(() => {trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }},+ cactus: {+ trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },+ branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] }+ },fungus: {trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }@@ -17399,28 +17403,147 @@ var init_assembly = __esm(() => {threeConstructors = new Set(Object.values(THREE29));});+// src/palette-check.ts+function hex(value, label) {+ if (typeof value !== "string" || !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))+ fail6(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);+ const digits = value.replace("#", "").toLowerCase();+ return `#${digits.length === 3 ? [...digits].map((d) => d + d).join("") : digits}`;+}+function normalizePalette(colors, opts) {+ if (!Array.isArray(colors) || colors.length === 0 || colors.length > PALETTE_MAX_COLORS)+ fail6(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);+ const entries = colors.map((value, i) => hex(value, `colors[${i}]`));+ let threshold = PALETTE_DEFAULT_THRESHOLD;+ if (opts !== undefined) {+ if (!opts || typeof opts !== "object" || Array.isArray(opts))+ fail6("opts must be { threshold? }.");+ for (const key of Object.keys(opts))+ if (key !== "threshold")+ fail6(`unknown option ${JSON.stringify(key)}.`);+ const t = opts.threshold;+ if (t !== undefined) {+ if (typeof t !== "number" || !Number.isFinite(t) || t <= 0 || t > 100)+ fail6(`threshold must be a delta E in (0, 100], got ${String(t)}.`);+ threshold = t;+ }+ }+ return { schemaVersion: 1, colors: [...new Set(entries)], threshold };+}+function definePalette(colors, opts, target) {+ const declaration = normalizePalette(colors, opts);+ if (target !== undefined) {+ if (target?.isObject3D !== true)+ fail6("target must be a scene node, normally the root.");+ target.userData[KILN_PALETTE_KEY] = structuredClone(declaration);+ }+ return declaration;+}+function readPaletteDeclaration(value) {+ if (value === undefined)+ return;+ try {+ const record = value;+ if (record.schemaVersion !== 1)+ return;+ return normalizePalette(record.colors, { threshold: record.threshold });+ } catch {+ return;+ }+}+function linearRgbToLab([r, g, b]) {+ const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047;+ const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b;+ const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883;+ const f = (t) => t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116;+ const [fx, fy, fz] = [f(x), f(y), f(z)];+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}+function evaluatePalette(declaration, doc) {+ const palette = declaration.colors.map((color) => ({+ color,+ lab: linearRgbToLab(hexToLinear(color))+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const materials = new Set;+ const visit = (node, hidden) => {+ const nodeHidden = hidden || isHiddenGltfNode(node);+ if (!nodeHidden)+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material && material.getName() !== COLLIDER_PROXY_MATERIAL_NAME)+ materials.add(material);+ }+ for (const child of node.listChildren())+ visit(child, nodeHidden);+ };+ for (const node of scene?.listChildren() ?? [])+ visit(node, false);+ const offPalette = [];+ for (const material of materials) {+ const factor = material.getBaseColorFactor();+ const lab = linearRgbToLab([factor[0], factor[1], factor[2]]);+ let nearest = palette[0];+ let distance = Number.POSITIVE_INFINITY;+ for (const entry of palette) {+ const d = deltaE(lab, entry.lab);+ if (d < distance) {+ distance = d;+ nearest = entry;+ }+ }+ if (distance > declaration.threshold)+ offPalette.push({+ material: material.getName(),+ color: linearToHex(factor.slice(0, 3)),+ nearest: nearest.color,+ deltaE: Math.round(distance * 100) / 100,+ ...material.getBaseColorTexture() ? { textured: true } : {}+ });+ }+ offPalette.sort((a, b) => b.deltaE - a.deltaE || (a.material < b.material ? -1 : 1));+ return {+ status: offPalette.length ? "warn" : "pass",+ colors: [...declaration.colors],+ threshold: declaration.threshold,+ checkedMaterials: materials.size,+ offPalette+ };+}+var KILN_PALETTE_KEY = "kilnPaletteV1", PALETTE_DEFAULT_THRESHOLD = 10, PALETTE_MAX_COLORS = 64, fail6 = (detail) => {+ throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `definePalette(colors, opts?): ${detail}`);+}, srgbToLinear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, linearToSrgb = (c) => c <= 0.0031308 ? c * 12.92 : 1.055 * Math.max(0, c) ** (1 / 2.4) - 0.055, hexToLinear = (value) => {+ const n = Number.parseInt(value.slice(1), 16);+ return [n >> 16 & 255, n >> 8 & 255, n & 255].map((c) => srgbToLinear(c / 255));+}, linearToHex = (rgb) => `#${rgb.map((c) => Math.round(Math.min(1, Math.max(0, linearToSrgb(c))) * 255).toString(16).padStart(2, "0")).join("")}`, deltaE = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+var init_palette_check = __esm(() => {+ init_delivery();+ init_authoring_diagnostic();+ init_metrics();+});+// src/budget.tsfunction normalizeBudget(spec) {if (!spec || typeof spec !== "object" || Array.isArray(spec))- fail6("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");+ fail7("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");const value = spec;for (const key of Object.keys(value))if (key !== "triangles" && key !== "draws" && key !== "schemaVersion")- fail6(`unknown field ${JSON.stringify(key)}.`);+ fail7(`unknown field ${JSON.stringify(key)}.`);const triangles = {};if (typeof value.triangles === "number")triangles.LOD0 = count2("triangles", value.triangles);else if (value.triangles && typeof value.triangles === "object" && !Array.isArray(value.triangles)) {const entries = Object.entries(value.triangles);if (entries.length === 0)- fail6("triangles needs at least one tier.");+ fail7("triangles needs at least one tier.");for (const [tier, limit] of entries) {if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))- fail6(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);+ fail7(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);triangles[tier] = count2(`triangles.${tier}`, limit);}} else- fail6("triangles must be a positive integer or a record of LOD tiers.");+ fail7("triangles must be a positive integer or a record of LOD tiers.");const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))));return {schemaVersion: 1,@@ -17432,7 +17555,7 @@ function defineBudget(spec, target) {const declaration = normalizeBudget(spec);if (target !== undefined) {if (target?.isObject3D !== true)- fail6("target must be a scene node, normally the root.");+ fail7("target must be a scene node, normally the root.");target.userData[KILN_BUDGET_KEY] = structuredClone(declaration);}return declaration;@@ -17477,11 +17600,11 @@ function evaluateBudget(declaration, measuredLod0, chains) {});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };}-var KILN_BUDGET_KEY = "kilnBudgetV1", fail6 = (detail) => {+var KILN_BUDGET_KEY = "kilnBudgetV1", fail7 = (detail) => {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `defineBudget(spec): ${detail}`);}, count2 = (label, value) => {if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)- fail6(`${label} must be a positive integer, got ${String(value)}.`);+ fail7(`${label} must be a positive integer, got ${String(value)}.`);return value;};var init_budget = __esm(() => {@@ -23018,57 +23141,57 @@ var init_texture_resolver = __esm(() => {});// src/procedural-material-v3.ts-function fail7(message) {+function fail8(message) {throw new PortableMaterialV3Error(message);}function assertJson(input) {let nodes = 0;const visit = (value, depth) => {if (++nodes > 65536 || depth > 16)- fail7("JSON size/depth budget exceeded.");+ fail8("JSON size/depth budget exceeded.");if (value === null || typeof value === "boolean")return;if (typeof value === "string") {if (value.length > PORTABLE_MATERIAL_V3_LIMITS.maxJsonBytes)- fail7("string budget exceeded.");+ fail8("string budget exceeded.");return;}if (typeof value === "number" && Number.isFinite(value))return;if (!value || typeof value !== "object")- fail7("only plain JSON data is supported.");+ fail8("only plain JSON data is supported.");const array = Array.isArray(value), proto = Object.getPrototypeOf(value);if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null)- fail7("only plain JSON prototypes are supported.");+ fail8("only plain JSON prototypes are supported.");const descriptors = Object.getOwnPropertyDescriptors(value), keys = Reflect.ownKeys(value);if (keys.length > 1025)- fail7("field/array budget exceeded.");+ fail8("field/array budget exceeded.");const length = array ? descriptors["length"]?.value : undefined;if (array && (length > 1024 || keys.length !== length + 1))- fail7("arrays must be bounded dense JSON data.");+ fail8("arrays must be bounded dense JSON data.");for (const key of keys) {if (array && key === "length")continue;if (typeof key !== "string" || ["__proto__", "prototype", "constructor"].includes(key))- fail7("forbidden JSON field.");+ fail8("forbidden JSON field.");const d = descriptors[key];if (!d.enumerable || !("value" in d))- fail7("JSON accessors/hidden fields are unsupported.");+ fail8("JSON accessors/hidden fields are unsupported.");if (array && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= length))- fail7("invalid array key.");+ fail8("invalid array key.");visit(d.value, depth + 1);}};visit(input, 0);if (new TextEncoder().encode(JSON.stringify(input)).length > PORTABLE_MATERIAL_V3_LIMITS.maxJsonBytes)- fail7("JSON byte budget exceeded.");+ fail8("JSON byte budget exceeded.");}function record6(value, keys) {if (!value || typeof value !== "object" || Array.isArray(value))- fail7("expected a JSON object.");+ fail8("expected a JSON object.");const result = value;if (Object.keys(result).some((key) => !keys.includes(key)))- fail7("unknown field in material or texture reference.");+ fail8("unknown field in material or texture reference.");return result;}function admitMaterial(input) {@@ -23085,10 +23208,10 @@ function admitMaterial(input) {];const r = record6(input, ["schemaVersion", "model", "name", "textures", ...scalarKeys]);if (r["schemaVersion"] !== 3 || r["model"] !== "pbrMetallicRoughness")- fail7("requires schemaVersion 3 and model pbrMetallicRoughness.");+ fail8("requires schemaVersion 3 and model pbrMetallicRoughness.");const name = r["name"];if (name !== undefined && (typeof name !== "string" || name.length < 1 || name.length > 200))- fail7("name requires 1..200 characters.");+ fail8("name requires 1..200 characters.");const common = canonicalizePortableMaterialSpecV2({schemaVersion: 2,model: "pbrMetallicRoughness",@@ -23103,23 +23226,23 @@ function admitMaterial(input) {const sampler = canonicalizePortableSamplerV1(ref["sampler"]);if (ref["kind"] === "procedural") {if (ref["resourceId"] !== undefined)- fail7("procedural references cannot carry a resource ID.");+ fail8("procedural references cannot carry a resource ID.");const admitted = admitProceduralTextureSpecV3(ref["spec"]);if (admitted.spec.usage !== PORTABLE_MATERIAL_SLOT_USAGE[slot])- fail7(`${slot} requires ${PORTABLE_MATERIAL_SLOT_USAGE[slot]} data.`);+ fail8(`${slot} requires ${PORTABLE_MATERIAL_SLOT_USAGE[slot]} data.`);texels += admitted.spec.width * admitted.spec.height;work += admitted.estimatedWorkUnits;bytes += admitted.conservativePixelAllocationBytes;textures[slot] = { kind: "procedural", spec: admitted.spec, sampler };} else if (ref["kind"] === "resource") {if (ref["spec"] !== undefined || typeof ref["resourceId"] !== "string" || ref["resourceId"].length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(ref["resourceId"]))- fail7("resource requires only a bounded closed kiln.* ID and sampler.");+ fail8("resource requires only a bounded closed kiln.* ID and sampler.");textures[slot] = { kind: "resource", resourceId: ref["resourceId"], sampler };} else- fail7("texture kind must be procedural or resource.");+ fail8("texture kind must be procedural or resource.");}if (texels > PORTABLE_MATERIAL_V3_LIMITS.maxTexels || work > PORTABLE_MATERIAL_V3_LIMITS.maxWork || bytes > PORTABLE_MATERIAL_V3_LIMITS.maxTransientBytes)- fail7("aggregate texel/work/allocation budget exceeded.");+ fail8("aggregate texel/work/allocation budget exceeded.");const { schemaVersion: _, textures: __, ...parameters } = common;return {spec: {@@ -24820,6 +24943,11 @@ function buildSandboxGlobals(usage, options = {}) {declarations.budget = declaration;return declaration;}),+ definePalette: wrap("definePalette", (colors, opts, target) => {+ const declaration = definePalette(colors, opts, target);+ declarations.palette = declaration;+ return declaration;+ }),capsuleGeo: wrapGeo("capsuleGeo", capsuleGeo),capsuleXGeo: wrapGeo("capsuleXGeo", capsuleXGeo),capsuleYGeo: wrapGeo("capsuleYGeo", capsuleYGeo),@@ -24948,6 +25076,7 @@ var init_primitives = __esm(() => {init_delivery();init_surface_bake();init_require_solid();+ init_palette_check();init_budget();init_animation_cubic();init_animation_spline();@@ -26170,6 +26299,15 @@ bakeSurfaceAttributes(root, { edge: { thresholdDegrees: 35 }, cavity: { rays: 32example: "defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });",promptNotes: "Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels."},+ {+ name: "definePalette",+ signature: "definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)",+ returns: "{ schemaVersion: 1, colors, threshold } (the normalised declaration)",+ category: "utility",+ description: "Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry as PALETTE_OFF warnings and a manifest palette report. Advisory: never fails a build.",+ example: "definePalette(['#6b6f73', '#3a3d40', '#8a4b2a', '#c9a227']);",+ promptNotes: "Only when the brief names a palette or a set of exact colours. Call once."+ },{name: "requireSolid",signature: "requireSolid(part: Object3D)",@@ -29249,7 +29387,7 @@ function collectTriangles(root) {function clamp012(n) {return n < 0 ? 0 : n > 1 ? 1 : n;}-function linearToSrgb(c) {+function linearToSrgb2(c) {const v = clamp012(c);return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;}@@ -29322,9 +29460,9 @@ function rasterizeView(root, dir, opts = {}) {}const lambert = Math.max(0, dot4(N, KEY_DIR) * normalSign);const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);- const r = Math.round(linearToSrgb(tri.color[0] * lit) * 255);- const g = Math.round(linearToSrgb(tri.color[1] * lit) * 255);- const b = Math.round(linearToSrgb(tri.color[2] * lit) * 255);+ const r = Math.round(linearToSrgb2(tri.color[0] * lit) * 255);+ const g = Math.round(linearToSrgb2(tri.color[1] * lit) * 255);+ const b = Math.round(linearToSrgb2(tri.color[2] * lit) * 255);const triangle = prepareTriangleCoverage(sx[0], sy[0], sx[1], sy[1], sx[2], sy[2], size);if (!triangle)continue;@@ -31210,7 +31348,7 @@ function isRecord4(value) {function hasExactKeys(value, allowed) {return Object.keys(value).every((key) => allowed.includes(key));}-function fail8(kind) {+function fail9(kind) {throw new Error(`invalid evaluator ${kind}`);}function validRequestId(value) {@@ -31231,34 +31369,34 @@ function parseOptions(value) {"gltfExporter","materialResources"])) {- return fail8("request");+ return fail9("request");}const options = {};if (value.materialResources !== undefined)options.materialResources = validateMaterialLibraryPayloadAny(value.materialResources);if (value.gltfExporter !== undefined) {if (value.gltfExporter !== "legacy" && value.gltfExporter !== "three")- fail8("request");+ fail9("request");options.gltfExporter = value.gltfExporter;}if (value.geometryPolicy !== undefined) {if (!["warn", "strict"].includes(String(value.geometryPolicy)))- fail8("request");+ fail9("request");options.geometryPolicy = value.geometryPolicy;}if (value.indexPolicy !== undefined) {if (value.indexPolicy !== "indexed" && value.indexPolicy !== "asBuilt")- fail8("request");+ fail9("request");options.indexPolicy = value.indexPolicy;}if (value.optimize !== undefined) {if (!["off", "auto", "palette", "full"].includes(String(value.optimize)))- fail8("request");+ fail9("request");options.optimize = value.optimize;}if (value.instance !== undefined) {if (!["off", "auto", "on"].includes(String(value.instance)))- fail8("request");+ fail9("request");options.instance = value.instance;}assertNoLegacyRuntimePolicy(value);@@ -31268,20 +31406,20 @@ function parseOptions(value) {}function decodeEvaluatorRequestV2(json) {if (Buffer.byteLength(json, "utf8") > MAX_EVALUATOR_REQUEST_BYTES)- fail8("request");+ fail9("request");let value;try {value = JSON.parse(json);} catch {- return fail8("request");+ return fail9("request");}if (isRecord4(value) && isRecord4(value.options)) {const { materialResources: _, ...metadataOptions } = value.options;if (Buffer.byteLength(JSON.stringify({ ...value, options: metadataOptions }), "utf8") > 1024 * 1024)- return fail8("request");+ return fail9("request");}if (!isRecord4(value) || !hasExactKeys(value, ["version", "requestId", "operation", "code", "options", "limits"]) || value.version !== EVALUATOR_REQUEST_VERSION || !validRequestId(value.requestId) || value.operation !== "execute-export-glb" || typeof value.code !== "string" || Buffer.byteLength(value.code, "utf8") > MAX_EVALUATOR_CODE_BYTES || !isRecord4(value.limits) || !hasExactKeys(value.limits, ["maxGlbBytes"]) || !validInteger(value.limits.maxGlbBytes, 1, 64 * 1024 * 1024)) {- return fail8("request");+ return fail9("request");}return {version: EVALUATOR_REQUEST_VERSION,@@ -32152,6 +32290,8 @@ async function inspectGlbIntegration(bytes, opts = {}) {const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);+ const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: "kiln.integration-manifest.v1",analyzerVersion: 1,@@ -32195,6 +32335,7 @@ async function inspectGlbIntegration(bytes, opts = {}) {...delivery.kit ? { kit: delivery.kit } : {},...delivery.ports.length ? { ports: delivery.ports } : {},...budget ? { budget } : {},+ ...palette ? { palette } : {},...vertexAttributes.length ? { vertexAttributes } : {},...delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {},structuralQa: {@@ -32235,6 +32376,8 @@ return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof aconst declared = globals[SANDBOX_DECLARATIONS];if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)root.userData[KILN_BUDGET_KEY] = declared.budget;+ if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)+ root.userData[KILN_PALETTE_KEY] = declared.palette;const clips = animate ? await animate(root) ?? [] : [];return { meta: meta ?? {}, root, clips, primitiveUsage };} catch (error) {@@ -32849,6 +32992,14 @@ async function renderSceneToGLB(root, opts = {}) {[KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY])});}+ if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {+ const declared = root.userData[KILN_PALETTE_KEY];+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold })+ });+ }applySurfaceBakeExtras(root, doc);applyNodeVisibility(root, doc);applyLodChains(root, lodSets, doc);@@ -32930,6 +33081,9 @@ async function renderSceneToGLB(root, opts = {}) {throw new Error("renderSceneToGLB: final GLB has no measurable scene");for (const finding of integrationManifest.deliveryDiagnostics ?? [])warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);+ const palette = integrationManifest.palette;+ for (const finding of palette?.offPalette ?? [])+ warnings.push(`PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette.threshold})${finding.textured ? "; the factor tints a texture that is not judged" : ""}.`);const diagnosticViews = [];const rig = requirements.requirements.requirements.rig;const diagnosticParents = new Map(lodSets.map(({ parent }) => [parent, [...parent.children]]));@@ -33230,6 +33384,7 @@ var init_render = __esm(() => {init_geometry_export();init_primitives();init_budget();+ init_palette_check();init_metrics();init_contracts();init_gltf();diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex fcd9009f..8a961e08 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -151,7 +151,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.', 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.", 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? }) takes positive integers. 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake 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.', 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.", 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? }) takes positive integers; 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. Run kiln_validate on the same source for the failing line and code; to read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable or build() mistake is named when it is the cause.", AuthoringDiagnosticError;var init_authoring_diagnostic = __esm(() => {AuthoringDiagnosticError = class AuthoringDiagnosticError extends Error {diagnostic;@@ -15917,6 +15917,10 @@ var init_vegetation = __esm(() => {trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }},+ cactus: {+ trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },+ branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] }+ },fungus: {trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }@@ -23458,28 +23462,147 @@ var init_assembly = __esm(() => {threeConstructors = new Set(Object.values(THREE33));});+// src/palette-check.ts+function hex(value, label) {+ if (typeof value !== "string" || !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))+ fail7(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);+ const digits = value.replace("#", "").toLowerCase();+ return `#${digits.length === 3 ? [...digits].map((d) => d + d).join("") : digits}`;+}+function normalizePalette(colors, opts) {+ if (!Array.isArray(colors) || colors.length === 0 || colors.length > PALETTE_MAX_COLORS)+ fail7(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);+ const entries = colors.map((value, i) => hex(value, `colors[${i}]`));+ let threshold = PALETTE_DEFAULT_THRESHOLD;+ if (opts !== undefined) {+ if (!opts || typeof opts !== "object" || Array.isArray(opts))+ fail7("opts must be { threshold? }.");+ for (const key of Object.keys(opts))+ if (key !== "threshold")+ fail7(`unknown option ${JSON.stringify(key)}.`);+ const t = opts.threshold;+ if (t !== undefined) {+ if (typeof t !== "number" || !Number.isFinite(t) || t <= 0 || t > 100)+ fail7(`threshold must be a delta E in (0, 100], got ${String(t)}.`);+ threshold = t;+ }+ }+ return { schemaVersion: 1, colors: [...new Set(entries)], threshold };+}+function definePalette(colors, opts, target) {+ const declaration = normalizePalette(colors, opts);+ if (target !== undefined) {+ if (target?.isObject3D !== true)+ fail7("target must be a scene node, normally the root.");+ target.userData[KILN_PALETTE_KEY] = structuredClone(declaration);+ }+ return declaration;+}+function readPaletteDeclaration(value) {+ if (value === undefined)+ return;+ try {+ const record = value;+ if (record.schemaVersion !== 1)+ return;+ return normalizePalette(record.colors, { threshold: record.threshold });+ } catch {+ return;+ }+}+function linearRgbToLab([r, g, b]) {+ const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047;+ const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b;+ const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883;+ const f = (t) => t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116;+ const [fx, fy, fz] = [f(x), f(y), f(z)];+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];+}+function evaluatePalette(declaration, doc) {+ const palette = declaration.colors.map((color) => ({+ color,+ lab: linearRgbToLab(hexToLinear(color))+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const materials = new Set;+ const visit = (node, hidden) => {+ const nodeHidden = hidden || isHiddenGltfNode(node);+ if (!nodeHidden)+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material && material.getName() !== COLLIDER_PROXY_MATERIAL_NAME)+ materials.add(material);+ }+ for (const child of node.listChildren())+ visit(child, nodeHidden);+ };+ for (const node of scene?.listChildren() ?? [])+ visit(node, false);+ const offPalette = [];+ for (const material of materials) {+ const factor = material.getBaseColorFactor();+ const lab = linearRgbToLab([factor[0], factor[1], factor[2]]);+ let nearest = palette[0];+ let distance = Number.POSITIVE_INFINITY;+ for (const entry of palette) {+ const d = deltaE(lab, entry.lab);+ if (d < distance) {+ distance = d;+ nearest = entry;+ }+ }+ if (distance > declaration.threshold)+ offPalette.push({+ material: material.getName(),+ color: linearToHex(factor.slice(0, 3)),+ nearest: nearest.color,+ deltaE: Math.round(distance * 100) / 100,+ ...material.getBaseColorTexture() ? { textured: true } : {}+ });+ }+ offPalette.sort((a, b) => b.deltaE - a.deltaE || (a.material < b.material ? -1 : 1));+ return {+ status: offPalette.length ? "warn" : "pass",+ colors: [...declaration.colors],+ threshold: declaration.threshold,+ checkedMaterials: materials.size,+ offPalette+ };+}+var KILN_PALETTE_KEY = "kilnPaletteV1", PALETTE_DEFAULT_THRESHOLD = 10, PALETTE_MAX_COLORS = 64, fail7 = (detail) => {+ throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `definePalette(colors, opts?): ${detail}`);+}, srgbToLinear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, linearToSrgb = (c) => c <= 0.0031308 ? c * 12.92 : 1.055 * Math.max(0, c) ** (1 / 2.4) - 0.055, hexToLinear = (value) => {+ const n = Number.parseInt(value.slice(1), 16);+ return [n >> 16 & 255, n >> 8 & 255, n & 255].map((c) => srgbToLinear(c / 255));+}, linearToHex = (rgb) => `#${rgb.map((c) => Math.round(Math.min(1, Math.max(0, linearToSrgb(c))) * 255).toString(16).padStart(2, "0")).join("")}`, deltaE = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+var init_palette_check = __esm(() => {+ init_delivery();+ init_authoring_diagnostic();+ init_metrics();+});+// src/budget.tsfunction normalizeBudget(spec) {if (!spec || typeof spec !== "object" || Array.isArray(spec))- fail7("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");+ fail8("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");const value = spec;for (const key of Object.keys(value))if (key !== "triangles" && key !== "draws" && key !== "schemaVersion")- fail7(`unknown field ${JSON.stringify(key)}.`);+ fail8(`unknown field ${JSON.stringify(key)}.`);const triangles = {};if (typeof value.triangles === "number")triangles.LOD0 = count3("triangles", value.triangles);else if (value.triangles && typeof value.triangles === "object" && !Array.isArray(value.triangles)) {const entries = Object.entries(value.triangles);if (entries.length === 0)- fail7("triangles needs at least one tier.");+ fail8("triangles needs at least one tier.");for (const [tier, limit] of entries) {if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))- fail7(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);+ fail8(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);triangles[tier] = count3(`triangles.${tier}`, limit);}} else- fail7("triangles must be a positive integer or a record of LOD tiers.");+ fail8("triangles must be a positive integer or a record of LOD tiers.");const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))));return {schemaVersion: 1,@@ -23491,7 +23614,7 @@ function defineBudget(spec, target) {const declaration = normalizeBudget(spec);if (target !== undefined) {if (target?.isObject3D !== true)- fail7("target must be a scene node, normally the root.");+ fail8("target must be a scene node, normally the root.");target.userData[KILN_BUDGET_KEY] = structuredClone(declaration);}return declaration;@@ -23536,11 +23659,11 @@ function evaluateBudget(declaration, measuredLod0, chains) {});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };}-var KILN_BUDGET_KEY = "kilnBudgetV1", fail7 = (detail) => {+var KILN_BUDGET_KEY = "kilnBudgetV1", fail8 = (detail) => {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `defineBudget(spec): ${detail}`);}, count3 = (label, value) => {if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)- fail7(`${label} must be a positive integer, got ${String(value)}.`);+ fail8(`${label} must be a positive integer, got ${String(value)}.`);return value;};var init_budget = __esm(() => {@@ -27612,6 +27735,11 @@ function buildSandboxGlobals(usage, options = {}) {declarations.budget = declaration;return declaration;}),+ definePalette: wrap("definePalette", (colors, opts, target) => {+ const declaration = definePalette(colors, opts, target);+ declarations.palette = declaration;+ return declaration;+ }),capsuleGeo: wrapGeo("capsuleGeo", capsuleGeo),capsuleXGeo: wrapGeo("capsuleXGeo", capsuleXGeo),capsuleYGeo: wrapGeo("capsuleYGeo", capsuleYGeo),@@ -27740,6 +27868,7 @@ var init_primitives = __esm(() => {init_delivery();init_surface_bake();init_require_solid();+ init_palette_check();init_budget();init_animation_cubic();init_animation_spline();@@ -28948,6 +29077,15 @@ bakeSurfaceAttributes(root, { edge: { thresholdDegrees: 35 }, cavity: { rays: 32example: "defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });",promptNotes: "Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels."},+ {+ name: "definePalette",+ signature: "definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)",+ returns: "{ schemaVersion: 1, colors, threshold } (the normalised declaration)",+ category: "utility",+ description: "Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry as PALETTE_OFF warnings and a manifest palette report. Advisory: never fails a build.",+ example: "definePalette(['#6b6f73', '#3a3d40', '#8a4b2a', '#c9a227']);",+ promptNotes: "Only when the brief names a palette or a set of exact colours. Call once."+ },{name: "requireSolid",signature: "requireSolid(part: Object3D)",@@ -32958,7 +33096,7 @@ function collectTriangles(root) {function clamp012(n) {return n < 0 ? 0 : n > 1 ? 1 : n;}-function linearToSrgb(c) {+function linearToSrgb2(c) {const v = clamp012(c);return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;}@@ -33031,9 +33169,9 @@ function rasterizeView(root, dir, opts = {}) {}const lambert = Math.max(0, dot4(N, KEY_DIR) * normalSign);const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);- const r = Math.round(linearToSrgb(tri.color[0] * lit) * 255);- const g = Math.round(linearToSrgb(tri.color[1] * lit) * 255);- const b = Math.round(linearToSrgb(tri.color[2] * lit) * 255);+ const r = Math.round(linearToSrgb2(tri.color[0] * lit) * 255);+ const g = Math.round(linearToSrgb2(tri.color[1] * lit) * 255);+ const b = Math.round(linearToSrgb2(tri.color[2] * lit) * 255);const triangle = prepareTriangleCoverage(sx[0], sy[0], sx[1], sy[1], sx[2], sy[2], size);if (!triangle)continue;@@ -36315,6 +36453,8 @@ async function inspectGlbIntegration(bytes, opts = {}) {const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);+ const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: "kiln.integration-manifest.v1",analyzerVersion: 1,@@ -36358,6 +36498,7 @@ async function inspectGlbIntegration(bytes, opts = {}) {...delivery.kit ? { kit: delivery.kit } : {},...delivery.ports.length ? { ports: delivery.ports } : {},...budget ? { budget } : {},+ ...palette ? { palette } : {},...vertexAttributes.length ? { vertexAttributes } : {},...delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {},structuralQa: {@@ -36398,6 +36539,8 @@ return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof aconst declared = globals[SANDBOX_DECLARATIONS];if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)root.userData[KILN_BUDGET_KEY] = declared.budget;+ if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)+ root.userData[KILN_PALETTE_KEY] = declared.palette;const clips = animate ? await animate(root) ?? [] : [];return { meta: meta ?? {}, root, clips, primitiveUsage };} catch (error) {@@ -37012,6 +37155,14 @@ async function renderSceneToGLB(root, opts = {}) {[KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY])});}+ if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {+ const declared = root.userData[KILN_PALETTE_KEY];+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold })+ });+ }applySurfaceBakeExtras(root, doc);applyNodeVisibility(root, doc);applyLodChains(root, lodSets, doc);@@ -37093,6 +37244,9 @@ async function renderSceneToGLB(root, opts = {}) {throw new Error("renderSceneToGLB: final GLB has no measurable scene");for (const finding of integrationManifest.deliveryDiagnostics ?? [])warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);+ const palette = integrationManifest.palette;+ for (const finding of palette?.offPalette ?? [])+ warnings.push(`PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette.threshold})${finding.textured ? "; the factor tints a texture that is not judged" : ""}.`);const diagnosticViews = [];const rig = requirements.requirements.requirements.rig;const diagnosticParents = new Map(lodSets.map(({ parent }) => [parent, [...parent.children]]));@@ -37403,6 +37557,7 @@ var init_render = __esm(() => {init_geometry_export();init_primitives();init_budget();+ init_palette_check();init_metrics();init_contracts();init_gltf();@@ -37458,7 +37613,7 @@ function isRecord5(value) {function hasExactKeys(value, allowed) {return Object.keys(value).every((key) => allowed.includes(key));}-function fail8(kind) {+function fail9(kind) {throw new Error(`invalid evaluator ${kind}`);}function validRequestId(value) {@@ -37508,18 +37663,18 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {try {value = JSON.parse(json);} catch {- return fail8("result");+ return fail9("result");}if (!isRecord5(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {- return fail8("result");+ return fail9("result");}if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)- fail8("result");+ fail9("result");if (!value.ok) {if (value.render !== undefined)- return fail8("result");+ return fail9("result");if (!isRecord5(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic"])) {- return fail8("result");+ return fail9("result");}const codes = ["INPUT_INVALID",@@ -37533,21 +37688,21 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {"PROTOCOL_ERROR"];if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {- return fail8("result");+ return fail9("result");}if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_UNKNOWN_KEY" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_BLEND" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_V3_CONTRACT" && value.error.diagnostic !== "PORTABLE_MATERIAL_V3_CONTRACT" && value.error.diagnostic !== "TEXTURE_ATLAS_CONTRACT" && value.error.diagnostic !== "MATERIAL_FRACTION_RANGE" && value.error.diagnostic !== "MATERIAL_RECIPE_TEXTURE_BINDING" && value.error.diagnostic !== "PORTABLE_TEXTURE_REFERENCE" && value.error.diagnostic !== "PORTABLE_COLOR_ARGUMENT" && value.error.diagnostic !== "PARAMETRIC_PERIODIC_ENDPOINT" && value.error.diagnostic !== "PROFILE_HOLES_UNSUPPORTED" && value.error.diagnostic !== "PROFILE_BEVEL_COLLAPSE" && value.error.diagnostic !== "PROFILE_CORRESPONDENCE_COLLAPSE" && value.error.diagnostic !== "REMOVED_HELPER" && value.error.diagnostic !== "TUBE_RADIUS" && value.error.diagnostic !== "TAPER_CONE_AXIS" && value.error.diagnostic !== "SOLID_FLOAT32_COLLAPSE" && value.error.diagnostic !== "MESH_DATA_NONFINITE" && value.error.diagnostic !== "MATERIAL_ALPHA_MODE" && value.error.diagnostic !== "MATERIAL_COLOR_ARGUMENT" && value.error.diagnostic !== "PART_NAME_ARGUMENT" && value.error.diagnostic !== "PART_GEOMETRY_ARGUMENT" && value.error.diagnostic !== "PART_MATERIAL_ARGUMENT" && value.error.diagnostic !== "MATERIAL_PACKED_CHANNELS" && value.error.diagnostic !== "UNINITIALIZED_BINDING" && value.error.diagnostic !== "BUILD_RESULT" && value.error.diagnostic !== "MATERIAL_RECIPE_OVERRIDE" && value.error.diagnostic !== "PROGRAM_TYPE_ERROR" && value.error.diagnostic !== "PROGRAM_RANGE_ERROR" && value.error.diagnostic !== "LOD_SET" && value.error.diagnostic !== "OPEN_SHELL" && value.error.diagnostic !== "DELIVERY_CONTRACT" && value.error.diagnostic !== "REQUIRE_SOLID" && value.error.diagnostic !== "EXPORT_MATERIAL_SIDE_UNSUPPORTED" && value.error.diagnostic !== "BONE_CHAIN_ARGUMENT" && value.error.diagnostic !== "SKIN_BINDING_ARGUMENT"))- return fail8("result");+ return fail9("result");if (value.error.qa !== undefined) {if (value.error.code !== "QA_BLOCKED" || !isRecord5(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validRequirementsQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {- return fail8("result");+ return fail9("result");}} else if (value.error.code === "QA_BLOCKED") {- return fail8("result");+ return fail9("result");}return value;}if (value.error !== undefined || !isRecord5(value.render))- fail8("result");+ fail9("result");const renderKeys = ["glbBase64","artifactGlbSha256",@@ -37565,44 +37720,44 @@ function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {"rebuildOptions"];if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord5(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord5(value.render.integrationManifest)) {- fail8("result");+ fail9("result");}let requirements;if (value.render.rebuildOptions !== undefined && !rebuildOptionsSchema.strict().safeParse(value.render.rebuildOptions).success)- fail8("result");+ fail9("result");if (value.render.materialLibraryDependencies !== undefined) {if (!Array.isArray(value.render.materialLibraryDependencies) || value.render.materialLibraryDependencies.length > 16)- fail8("result");+ fail9("result");try {for (const manifest of value.render.materialLibraryDependencies)validateMaterialManifestIdentityAny(manifest);} catch {- return fail8("result");+ return fail9("result");}}try {requirements = validateRequirementsContext(value.render.requirements);validateRequirementsQaReport(value.render.meta.qaReport, requirements);} catch {- return fail8("result");+ return fail9("result");}const glb = Buffer.from(value.render.glbBase64, "base64");if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)- fail8("result");+ fail9("result");if (!isSha256(value.render.artifactGlbSha256))- fail8("result");+ fail9("result");const actualHash = `sha256:${createHash13("sha256").update(glb).digest("hex")}`;if (actualHash !== value.render.artifactGlbSha256)- fail8("result");+ fail9("result");const diagnosticViews = value.render.diagnosticViews;if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))- fail8("result");+ fail9("result");const decodedViews = diagnosticViews?.map((candidate) => {if (!isRecord5(candidate) || typeof candidate.pngBase64 !== "string")- return fail8("result");+ return fail9("result");const png = Buffer.from(candidate.pngBase64, "base64");if (png.toString("base64") !== candidate.pngBase64)- return fail8("result");+ return fail9("result");const { pngBase64: _, ...view } = candidate;return { ...view, png };});@@ -44615,6 +44770,34 @@ define2("defineBudget", {limitations: ["Does not simplify geometry or merge draws to meet a budget."],related: [{ name: "defineLod", relation: "companion" }]});+define2("definePalette", {+ units: "Colours are sRGB hex; threshold is a CIE 1976 delta E in CIELAB (D65).",+ axes: "Not a placement operation.",+ origin: "Not a placement operation.",+ ownership: "Records one declaration: on target when given, otherwise on the root build() returns. Export writes it as default-scene extras kilnPaletteV1.",+ coordinates: "Not a placement operation.",+ parameters: [+ "colors: 1..64 hex strings ('#rgb' or '#rrggbb'); duplicates collapse.",+ "opts.threshold: delta E in (0, 100], default 10.",+ "target: optional scene node, normally the root."+ ],+ topology: [noMesh],+ preservation: ["Changes no geometry, material or node."],+ semantics: [+ "Every material drawn by a visible scene node (collider proxies excluded) is compared by its base colour factor, converted from linear to sRGB to CIELAB; a factor that tints a texture is flagged textured.",+ "The integration manifest and CLI receipt report palette: { status: pass | warn, colors, threshold, checkedMaterials, offPalette: [{ material, color, nearest, deltaE, textured? }] }; each off-palette material is also a PALETTE_OFF warning.",+ "Advisory only: no build fails and QA acceptance is unchanged. Invalid input is a DELIVERY_CONTRACT build error."+ ],+ cost: "One colour conversion per drawn material at export."+}, {+ references: ["src/palette-check.ts", "docs/delivery-contract.md"],+ tags: ["delivery", "palette", "color", "art direction"],+ aliases: ["color palette", "palette lock", "art palette", "swatches"],+ intents: ["check materials against a declared colour palette"],+ summary: "Declares a colour palette; receipts list drawn materials off it by delta E, advisory only.",+ limitations: ["Judges base colour factors, not texture pixels. Never fails a build."],+ related: [{ name: "gameMaterial", relation: "companion" }]+});define2("requireSolid", {...nodeFacts,units: "No lengths.",diff --git a/docs/delivery-contract.md b/docs/delivery-contract.mdindex 111fdd10..fd57a2f7 100644--- a/docs/delivery-contract.md+++ b/docs/delivery-contract.md@@ -118,6 +118,16 @@ Consumer rules that follow from it:- **Collider transforms are exact.** A collider's proxy mesh moves to a child named`<collider>_Proxy`, so the collider node's scale is still its size.- **Custom attributes stay float.** `_EDGE` and `_CAVITY` are never quantized.+- **Find nodes by role, not by name alone.** three's `GLTFLoader` makes object names+ unique, so an asset root that shares the scene's name loads with a numeric suffix.++## Worked example++`src/__tests__/fixtures/bunker-door-frame.kiln.js` uses every element above: a kit+module with two ports, a box collider, three anchors, a two-tier `defineLod` plus an+impostor, baked attributes, a packed two-region atlas, a budget, a required solid and+instanced bolts. `src/__tests__/delivery-fixture.test.ts` renders it through both+converters and loads its three.js runtime export through `GLTFLoader`.## Out of scopediff --git a/docs/plans/2026-10-15-game-delivery-contract.md b/docs/plans/2026-10-15-game-delivery-contract.mdindex 016a00c5..da295809 100644--- a/docs/plans/2026-10-15-game-delivery-contract.md+++ b/docs/plans/2026-10-15-game-delivery-contract.md@@ -328,3 +328,48 @@ from this scope and why. The owner's game session reads this log to monitor.probe this small grows in total size because the extension JSON outweighs the savedgeometry; the test asserts the binary chunk shrinks; (f) MCP `kiln_export` is unchanged(schemas are prompt-cached), so the three target is CLI and library only.+- 2026-10-15 item 7 (small items) done. Files: `src/vegetation-prompt.ts` (`RECIPE_CACTUS_V1`:+ ribbed star-profile `extrudeProfile` trunk, `pipeAlongPath` elbowed arms, spine cards on+ rib crests, explicit `defineLod` tiers with an `impostor` card last; the shared closing+ line now names `defineLod` as the general LOD helper), `src/contracts/asset.ts` (subtype+ `cactus`; "cactus", "saguaro", "cholla", "opuntia" infer it) + `asset.test.ts`,+ `src/qa/vegetation.ts` (observe-only cactus growth band), new `src/palette-check.ts`+ (`definePalette(colors, { threshold? })`, CIE76 delta E in CIELAB from linear base colour+ factors, scene extras `kilnPaletteV1`, manifest `palette`, `PALETTE_OFF` warnings),+ `src/contracts/integration.ts`, `src/render.ts`, `src/primitives.ts`, `src/cli.ts`+ (receipt `palette`, log line), Discovery (`definePalette`), prompt-api snapshot,+ `skills/kiln-author-asset/references/geometry-recipes.md` (game delivery section and the+ cactus recipe), `docs/geometry.md` (solid, bakes, budgets), `docs/export-profiles.md`+ (three target), `docs/procedural-surfaces-v3.md` (packer), new `docs/delivery-contract.md`.+ `bun run docs:tools` and `bun run mcp:manifest` produced no diff (tool schemas unchanged).+ Test: new `src/__tests__/delivery-palette.test.ts` (3, observed failing first). Gates:+ typecheck and lint pass; `bun run check:skills` 6 conform, 2 copies identical; `bun run+ test` 3715 pass, 2 skip, 21 fail = the 19 GNU-tar baseline failures plus the two+ stale-bundle checks. Deviations: (a) the palette module is `src/palette-check.ts` because+ `src/palette.ts` already holds the render palette (my first copy briefly overwrote it; it+ was restored from HEAD and is unchanged); (b) `cactus` is a new vegetation subtype rather+ than a variant of `succulent`, so the recipe is selected by intent; it is additive to the+ asset-intent contract and reaches no MCP tool schema; (c) the palette threshold is CIE76+ delta E (default 10), and textured materials are judged by their factor and flagged+ `textured`.+- 2026-10-15 item 8 (end-to-end fixture) done. Files: new+ `src/__tests__/fixtures/bunker-door-frame.kiln.js` (kit.module with ports `west`/`east`,+ `collider.box.frame`, anchors `door.main`, `light.lintel`, `decal.stencil`, `Frame_LOD0..2`+ with an impostor card last, `bakeSurfaceAttributes` on LOD0, a `pack: { edge: 1024, gutter:+ 4 }` atlas with procedural regions `concrete` and `steel`, `defineBudget`, `requireSolid`+ on the extruded frame, six bolts under `repeatInstances`), new+ `src/__tests__/delivery-fixture.test.ts` (2: legacy and three converters; each checks the+ manifest, the packed v1.2 atlas provenance, then the three target through `GLTFLoader` ++ meshopt decoder: roles, kit extras, hidden collider at its size, float `_edge`/`_cavity`,+ one `InstancedMesh` of 6, the `MSFT_lod` levels with `lod.impostor`); this is the item 6+ qualification subject. `docs/delivery-contract.md` points to it and notes that+ `GLTFLoader` makes names unique (the root shares the scene's name). Test observed failing+ first (fixture absent, ENOENT). Final gate after `node scripts/build-runtime.mjs all` (exit+ 0): `bun run test:coverage` 3719 pass, 2 skip, 19 fail (only the 19 GNU-tar baseline+ failures in `scripts/`); `bun scripts/check-coverage.mjs` passed, functions 95.45% (min+ 94.00%), lines 93.14% (min 92.10%), ratchet unchanged; `bun run test:render-service` 78+ pass, 0 fail; `bun run check:skills` 6 conform, 2 copies identical; `bun run typecheck`+ and `bun run lint` (1003 files) pass; `bun run check:toolchain` pass; `bun run build:sdk`+ 60 entrypoints. Nothing was committed or pushed: the session brief reserves commits for+ the owner, so the per-item commits this plan describes are left to the owner, with one+ patch per item in the agent scratchpad.diff --git a/src/__tests__/delivery-fixture.test.ts b/src/__tests__/delivery-fixture.test.tsnew file mode 100644index 00000000..e8f7d286--- /dev/null+++ b/src/__tests__/delivery-fixture.test.ts@@ -0,0 +1,157 @@+/**+ * End-to-end delivery fixture (delivery contract item 8).+ *+ * `fixtures/bunker-door-frame.kiln.js` is one kit.module with two ports, a box collider,+ * three anchors, a two-tier defineLod plus an impostor, baked _EDGE/_CAVITY, a packed atlas+ * with two procedural regions, a budget, a required solid and instanced bolts. It renders+ * through both converters, and its three.js runtime export is qualified through three's+ * GLTFLoader with the meshopt decoder (the item 6 qualification).+ */+import { describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import type * as THREE from 'three';+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { exportAssetGlb } from '../asset-export';+import type { AssetRecord } from '../assets';+import { renderGLBInProcess } from '../render';++const FIXTURE = readFileSync(resolve('src/__tests__/fixtures/bunker-door-frame.kiln.js'), 'utf8');+const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const record = (bytes: Uint8Array): AssetRecord => ({+ manifest: {+ version: 'kiln.asset.v1',+ assetId: 'a_bunker',+ revisionId: 'r_bunker',+ name: 'BunkerDoorFrame',+ tags: [],+ createdAt: '2026-10-15T00:00:00.000Z',+ editable: false,+ files: { 'asset.glb': { bytes: bytes.length, sha256: sha(bytes) as `sha256:${string}` } },+ },+ files: { 'asset.glb': bytes },+});+const glbJson = (bytes: Uint8Array) =>+ JSON.parse(+ new TextDecoder().decode(+ bytes.subarray(20, 20 + new DataView(bytes.buffer, bytes.byteOffset).getUint32(12, true)),+ ),+ );+const find = (root: THREE.Object3D, name: string) => {+ const found = root.getObjectByName(name);+ if (!found) throw new Error(`missing ${name}`);+ return found;+};++describe('bunker door frame fixture', () => {+ for (const gltfExporter of ['legacy', 'three'] as const)+ test(`delivers every contract element (${gltfExporter} converter, three target)`, async () => {+ const rendered = await renderGLBInProcess(FIXTURE, { gltfExporter });+ const source = new Uint8Array(rendered.glb);+ const manifest = rendered.integrationManifest;++ // Editable GLB: the manifest lists every delivery element.+ expect(manifest.kit).toMatchObject({ name: 'BunkerDoorFrame', footprint: [3.2, 0.6] });+ expect(manifest.ports!.map((p) => p.id)).toEqual(['west', 'east']);+ expect(manifest.colliders!.map((c) => c.role)).toEqual(['collider.box.frame']);+ const shape = manifest.colliders![0]!.shape;+ if (shape.kind !== 'box') throw new Error('expected a box collider');+ [3.2, 3.2, 0.6].forEach((size, axis) => {+ expect(shape.size[axis]).toBeCloseTo(size, 5);+ });+ expect(manifest.anchors!.map((a) => a.role)).toEqual([+ 'anchor.door.main',+ 'anchor.light.lintel',+ 'anchor.decal.stencil',+ ]);+ const [chain] = manifest.levelsOfDetail!;+ expect(chain!.levels).toHaveLength(3);+ expect(chain!.levels.map((level) => level.impostor === true)).toEqual([false, false, true]);+ expect(manifest.vertexAttributes!.map((a) => a.name)).toEqual(['_EDGE', '_CAVITY']);+ expect(manifest.budget!.status).toBe('pass');+ expect(manifest.deliveryDiagnostics).toBeUndefined();+ expect(manifest.structuralQa.validatorErrors).toBe(0);+ // The atlas was packed: compiler v1.2, both regions placed by the packer.+ const [atlas] = glbJson(source).scenes[0].extras.kilnAtlasProvenance.atlases;+ expect(atlas.manifest.compilerId).toBe('kiln.texture-atlas.v1.2');+ expect(+ atlas.spec.regions.map((r: { name: string; packed?: true }) => [r.name, r.packed]),+ ).toEqual([+ ['concrete', true],+ ['steel', true],+ ]);++ // three.js runtime target, loaded the way an application loads it.+ const output = await exportAssetGlb(record(source), {+ profile: 'runtime',+ target: 'three',+ metadataFileName: 'bunker.kiln-metadata.json',+ });+ if (output.profile !== 'runtime') throw new Error('expected runtime');+ const delivery = JSON.parse(new TextDecoder().decode(output.metadata.bytes)).delivery;+ expect(delivery.instancing).toEqual([+ expect.objectContaining({+ count: 6,+ instances: [0, 1, 2, 3, 4, 5].map((i) => `Mesh_Bolt_${i}`),+ }),+ ]);+ expect(delivery.preserved).toMatchObject({+ lodChains: 1,+ colliders: 1,+ anchors: 3,+ ports: 2,+ kitModules: 1,+ });+ expect(+ delivery.nodeScale.some((entry: { node: string }) => entry.node.includes('Mesh_Frame')),+ ).toBe(true);++ await MeshoptDecoder.ready;+ const gltf = await new GLTFLoader()+ .setMeshoptDecoder(MeshoptDecoder)+ .parseAsync(Uint8Array.from(output.glb).buffer, '');+ const scene = gltf.scene;+ // The scene shares the root's name and GLTFLoader makes names unique, so take the+ // asset root as the scene's only child.+ expect(scene.children).toHaveLength(1);+ const root = scene.children[0]!;+ expect(root.userData.kilnSemantic.roles).toContain('kit.module');+ expect(root.userData.kilnKit).toMatchObject({ footprint: [3.2, 0.6], height: 3.2 });+ for (const name of [+ 'Port_west',+ 'Port_east',+ 'Anchor_door_main',+ 'Anchor_light_lintel',+ 'Anchor_decal_stencil',+ ])+ expect(find(scene, name).userData.kilnSemantic.roles).toHaveLength(1);+ const collider = find(scene, 'Collider_box_frame');+ expect(collider.userData.gltfExtensions.KHR_node_visibility).toEqual({ visible: false });+ [3.2, 3.2, 0.6].forEach((size, axis) => {+ expect(collider.scale.getComponent(axis)).toBeCloseTo(size, 5);+ });+ const frame = find(scene, 'Mesh_Frame') as THREE.Mesh;+ const edge = frame.geometry.getAttribute('_edge');+ const cavity = frame.geometry.getAttribute('_cavity');+ expect(edge.array).toBeInstanceOf(Float32Array);+ expect(cavity.array).toBeInstanceOf(Float32Array);+ expect(Math.max(...edge.array)).toBe(1);+ // Quantized positions: the frame's node carries the metre scale.+ expect(frame.scale.x).toBeGreaterThan(1);+ const instanced: THREE.InstancedMesh[] = [];+ scene.traverse((object) => {+ if ((object as THREE.InstancedMesh).isInstancedMesh) instanced.push(object as never);+ });+ expect(instanced.map((mesh) => mesh.count)).toEqual([6]);+ const lod0 = find(scene, 'Frame_LOD0');+ const ids = lod0.userData.gltfExtensions.MSFT_lod.ids as number[];+ expect(ids).toHaveLength(2);+ const levels = await Promise.all(+ ids.map((id) => gltf.parser.getDependency('node', id) as Promise<THREE.Object3D>),+ );+ expect(levels.map((level) => level.name)).toEqual(['Frame_LOD1', 'Frame_LOD2']);+ expect(levels[1]!.userData.kilnSemantic.roles).toContain('lod.impostor');+ });+});diff --git a/src/__tests__/fixtures/bunker-door-frame.kiln.js b/src/__tests__/fixtures/bunker-door-frame.kiln.jsnew file mode 100644index 00000000..b76793ce--- /dev/null+++ b/src/__tests__/fixtures/bunker-door-frame.kiln.js@@ -0,0 +1,149 @@+// A bunker door frame delivered as a modular kit piece: the end-to-end fixture of the+// game delivery contract (docs/delivery-contract.md).+//+// It is one kit.module with two ports, a box collider, three anchors, a two-tier+// defineLod plus an impostor, baked _EDGE/_CAVITY, a packed atlas with two procedural+// regions, a triangle budget, a required solid and repeated bolts marked for+// instancing. Render it with:+//+// kiln render src/__tests__/fixtures/bunker-door-frame.kiln.js --out frame.glb+//+// Kiln's frame is +X forward, +Y up, +Z right. Everything sits on Y=0.++const meta = { name: 'BunkerDoorFrame', category: 'prop' };++const W = 3.2; // module width along X+const D = 0.6; // wall depth along Z+const H = 3.2; // module height+const OPEN_W = 1.8; // door opening width+const OPEN_H = 2.4; // door opening height++async function build() {+ const root = createRoot('BunkerDoorFrame');+ defineModule(root, { footprint: [W, D], height: H, snapAxis: 'x', origin: 'center' });+ port('west', { parent: root, position: [-W / 2, 0, 0], rotation: [0, 180, 0] });+ port('east', { parent: root, position: [W / 2, 0, 0] });+ // LOD2 keeps the shared bolts beside the card, so its budget counts them.+ defineBudget({ triangles: { LOD0: 3000, LOD1: 800, LOD2: 100 }, draws: 12 });++ // Two procedural regions packed into one sheet; no rectangle is laid out by hand.+ const atlas = await textureAtlas({+ schemaVersion: 1,+ usage: 'albedo',+ pack: { edge: 1024, gutter: 4 },+ regions: [+ {+ name: 'concrete',+ source: {+ kind: 'procedural',+ spec: {+ schemaVersion: 3,+ width: 128,+ height: 128,+ background: [118, 116, 110, 255],+ operations: [+ { op: 'paint', shape: { kind: 'rectangle', x: 0, y: 60, width: 128, height: 4 }, rgba: [92, 90, 86, 255] },+ { op: 'paint', shape: { kind: 'ellipse', x: 20, y: 18, width: 30, height: 16 }, rgba: [104, 101, 95, 255] },+ ],+ },+ },+ },+ {+ name: 'steel',+ source: {+ kind: 'procedural',+ spec: {+ schemaVersion: 3,+ width: 64,+ height: 64,+ background: [96, 100, 106, 255],+ operations: [+ { op: 'paint', shape: { kind: 'line', from: [0, 8], to: [64, 8], width: 2 }, rgba: [128, 72, 40, 255] },+ ],+ },+ },+ },+ ],+ });+ const concrete = pbrMaterial({ albedo: atlas, roughness: 0.92, metalness: 0 });+ const steel = pbrMaterial({ albedo: atlas, roughness: 0.5, metalness: 0.7 });+ const uv = (geometry, region) =>+ remapUVToAtlas(geometry, atlas, region, { inputOrigin: 'bottom-left', mode: 'content-boundary' });++ // The frame: a U outline extruded through the wall, a closed solid with bevelled edges.+ const outline = [+ [-W / 2, 0],+ [-OPEN_W / 2, 0],+ [-OPEN_W / 2, OPEN_H],+ [OPEN_W / 2, OPEN_H],+ [OPEN_W / 2, 0],+ [W / 2, 0],+ [W / 2, H],+ [-W / 2, H],+ ];+ // extrudeProfile writes no UV0; a box projection in the geometry frame gives unit UVs.+ const frameGeo = projectUV(await extrudeProfile(outline, { depth: D, axis: 'z', bevel: 0.04 }), {+ projection: 'box',+ });+ const tiers = ['Frame_LOD0', 'Frame_LOD1', 'Frame_LOD2'].map((name) => {+ const group = new THREE.Group();+ group.name = name;+ root.add(group);+ return group;+ });+ const frame = createPart('Frame', uv(frameGeo, 'concrete'), concrete, { parent: tiers[0] });+ requireSolid(frame);++ // Steel jamb plates on both faces of the opening, and the lintel beam.+ for (const side of [-1, 1]) {+ createPart(`Jamb_${side < 0 ? 'L' : 'R'}`, uv(boxGeo(0.08, OPEN_H, D + 0.04), 'steel'), steel, {+ parent: tiers[0],+ position: [side * (OPEN_W / 2 - 0.04), OPEN_H / 2, 0],+ });+ }+ createPart('Lintel', uv(boxGeo(OPEN_W, 0.12, D + 0.04), 'steel'), steel, {+ parent: tiers[0],+ position: [0, OPEN_H - 0.06, 0],+ });++ // LOD1: the frame as three boxes; LOD2: a single card impostor.+ createPart('Frame_Low_L', uv(boxGeo((W - OPEN_W) / 2, H, D), 'concrete'), concrete, {+ parent: tiers[1],+ position: [-(W + OPEN_W) / 4, H / 2, 0],+ });+ createPart('Frame_Low_R', uv(boxGeo((W - OPEN_W) / 2, H, D), 'concrete'), concrete, {+ parent: tiers[1],+ position: [(W + OPEN_W) / 4, H / 2, 0],+ });+ createPart('Frame_Low_Top', uv(boxGeo(OPEN_W, H - OPEN_H, D), 'concrete'), concrete, {+ parent: tiers[1],+ position: [0, (H + OPEN_H) / 2, 0],+ });+ createPart('Frame_Card', uv(planeGeo(W, H), 'concrete'), concrete, {+ parent: tiers[2],+ position: [0, H / 2, D / 2],+ });+ defineLod(tiers, { screenCoverage: [0.3, 0.05, 0], impostor: true });++ // Six identical bolt heads share one geometry and material, outside the LOD set so every+ // tier keeps them; the three.js runtime export turns them into one instanced mesh.+ const bolts = new THREE.Group();+ bolts.name = 'Bolts';+ root.add(bolts);+ const boltGeo = uv(boxGeo(0.06, 0.06, 0.03), 'steel');+ for (let i = 0; i < 6; i++)+ createPart('Bolt_' + i, boltGeo, steel, {+ parent: bolts,+ position: [-1.2 + i * 0.48, OPEN_H + 0.3, D / 2 + 0.015],+ });+ repeatInstances(bolts);++ // One collider for the frame's solid mass; anchors where gameplay attaches.+ colliderBox([W, H, D], { id: 'frame', parent: root, position: [0, H / 2, 0] });+ anchor('door', 'main', { parent: root, position: [0, 0, 0] });+ anchor('light', 'lintel', { parent: root, position: [0, H - 0.2, D / 2 + 0.05] });+ anchor('decal', 'stencil', { parent: root, position: [-1.2, 2.6, D / 2 + 0.01] });++ bakeSurfaceAttributes(tiers[0], { edge: { thresholdDegrees: 35 }, cavity: { rays: 16 } });+ return root;+}diff --git a/src/__tests__/runtime-three-export.test.ts b/src/__tests__/runtime-three-export.test.tsindex 57b47812..235e66a9 100644--- a/src/__tests__/runtime-three-export.test.ts+++ b/src/__tests__/runtime-three-export.test.ts@@ -23,7 +23,7 @@ const binaryChunkBytes = (glb: Uint8Array) =>glb.byteLength - 20 - new DataView(glb.buffer, glb.byteOffset).getUint32(12, true);const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;-export const RUNTIME_PROGRAM = `const meta={name:'Runtime Probe'};+const RUNTIME_PROGRAM = `const meta={name:'Runtime Probe'};function build(){const root=createRoot('Root');const steel=gameMaterial('#777777');@@ -44,7 +44,7 @@ function build(){return root;}`;-export function assetRecord(bytes: Uint8Array): AssetRecord {+function assetRecord(bytes: Uint8Array): AssetRecord {return {manifest: {version: 'kiln.asset.v1',@@ -61,7 +61,7 @@ export function assetRecord(bytes: Uint8Array): AssetRecord {}/** Load a GLB the way a three.js application does: GLTFLoader plus the meshopt decoder. */-export async function loadWithGltfLoader(bytes: Uint8Array) {+async function loadWithGltfLoader(bytes: Uint8Array) {await MeshoptDecoder.ready;const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);return loader.parseAsync(Uint8Array.from(bytes).buffer, '');