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
feat(kiln): instanceability A-F grade + category/tri-budget fix; Kiln City foundation perf pass
Matt Kissinger671639705dcd
diff --git a/__tests__/geometry-gains.test.ts b/__tests__/geometry-gains.test.tsindex 0ce854ab..f6e10bb6 100644--- a/__tests__/geometry-gains.test.ts+++ b/__tests__/geometry-gains.test.ts@@ -130,9 +130,9 @@ describe('tri estimate upgrades', () => {{ category: 'vfx' }, // 2000 budget — single counting stays silent);expect(r.valid).toBe(true);- // 30 spheres at 32x16 → 30 * 1024 = 30720 >> any budget → advisory fires.+ // 50 spheres at 32x16 → 50 * 1024 = 51200 > prop budget (25000) * 1.5 → advisory fires.const heavy = validate(- wrap(`for (let i = 0; i < 30; i++) {+ wrap(`for (let i = 0; i < 50; i++) {createPart('S' + i, sphereGeo(0.5, 32, 16), gameMaterial('#999999'), { parent: root });}`),{ category: 'prop' },@@ -144,10 +144,10 @@ describe('tri estimate upgrades', () => {const r = validate(wrap(`createPart('Gear', gearGeo({ teeth: 64 }), gameMaterial('#999999'), { parent: root }); // ~2048- const blob = subdivide(sphereGeo(1, 16, 12), 2); // 384 base + 384*15 growth+ const blob = subdivide(sphereGeo(1, 16, 12), 3); // 384 base * 64 → ~24576createPart('Blob', blob, gameMaterial('#999999'), { parent: root });`),- { category: 'vfx' }, // budget 2000 → combined ~8200 trips the advisory+ { category: 'vfx' }, // budget 15000 * 1.5 = 22500 → combined ~26600 trips the advisory);expect(r.warnings.some((w) => w.message.includes('tris'))).toBe(true);});diff --git a/__tests__/metrics.test.ts b/__tests__/metrics.test.tsnew file mode 100644index 00000000..034ad7af--- /dev/null+++ b/__tests__/metrics.test.ts@@ -0,0 +1,150 @@+/**+ * Instanceability metrics + grader (Phase 0/1).+ *+ * Covers: post-dedup metric extraction from a baked Document, the empirical+ * dedup-merges-value-identical-materials question, the grade rubric (advisory),+ * and that render.meta carries the report.+ */++import { describe, it, expect } from 'bun:test';+import {+ createRoot,+ createPart,+ createInstance,+ cylinderGeo,+ boxGeo,+ gameMaterial,+ glassMaterial,+} from '../primitives';+import { renderSceneToGLB, renderGLB, gradeGlbBytes } from '../render';+import { gradeInstanceability, type InstanceabilityMetrics } from '../metrics';++const baseMetrics = (over: Partial<InstanceabilityMetrics> = {}): InstanceabilityMetrics => ({+ uniqueGeometries: 1,+ uniqueMaterials: 1,+ drawCalls: 1,+ textureCount: 0,+ skinned: false,+ transparentMaterials: 0,+ triangles: 100,+ ...over,+});++describe('collectGlbMetrics (post-dedup)', () => {+ it('an instanced 4-wheel scene reports 1 geometry, 1 material, 4 draw calls', async () => {+ const r = createRoot('Truck');+ const wg = cylinderGeo(0.4, 0.4, 0.2, 16);+ const rubber = gameMaterial(0x1a1a1a);+ const fl = createPart('WheelFL', wg, rubber, { position: [-0.8, 0.3, 1.2], parent: r });+ createInstance('WheelFR', fl, { position: [0.8, 0.3, 1.2], parent: r });+ createInstance('WheelRL', fl, { position: [-0.8, 0.3, -1.2], parent: r });+ createInstance('WheelRR', fl, { position: [0.8, 0.3, -1.2], parent: r });++ const scene = await renderSceneToGLB(r);+ const m = scene.instanceability?.metrics;+ expect(m).toBeDefined();+ expect(m!.uniqueGeometries).toBe(1);+ expect(m!.uniqueMaterials).toBe(1);+ expect(m!.drawCalls).toBe(4);+ expect(scene.instanceability!.grade).toBe('A');+ });++ it('records whether dedup() merges value-identical-but-independent materials', async () => {+ // Two distinct THREE materials with identical values (separate gameMaterial+ // calls) on two distinct geometries. This empirically answers the watch-item.+ const r = createRoot('Pair');+ createPart('A', boxGeo(1, 1, 1), gameMaterial(0x808080), { position: [0, 0, 0], parent: r });+ createPart('B', boxGeo(1, 1, 1), gameMaterial(0x808080), { position: [2, 0, 0], parent: r });++ const scene = await renderSceneToGLB(r);+ const mats = scene.instanceability!.metrics.uniqueMaterials;+ // dedup() compares materials structurally, so value-identical materials+ // collapse to 1. If this ever regresses to 2, Phase-2-bake material+ // unification (palette()) becomes worth wiring.+ expect(mats).toBe(1);+ });++ it('distinct-color materials are NOT merged', async () => {+ const r = createRoot('TwoColor');+ createPart('A', boxGeo(1, 1, 1), gameMaterial(0xff0000), { position: [0, 0, 0], parent: r });+ createPart('B', boxGeo(1, 1, 1), gameMaterial(0x00ff00), { position: [2, 0, 0], parent: r });+ const scene = await renderSceneToGLB(r);+ expect(scene.instanceability!.metrics.uniqueMaterials).toBe(2);+ expect(scene.instanceability!.grade).toBe('B');+ });++ it('a blended (glass) material marks transparentMaterials', async () => {+ const r = createRoot('Glassy');+ createPart('Pane', boxGeo(1, 1, 0.05), glassMaterial(0x88ccff, { opacity: 0.4 }), {+ position: [0, 0, 0],+ parent: r,+ });+ const scene = await renderSceneToGLB(r);+ expect(scene.instanceability!.metrics.transparentMaterials).toBeGreaterThanOrEqual(1);+ });+});++describe('gradeInstanceability (advisory rubric)', () => {+ it('1 material -> A', () => {+ expect(gradeInstanceability(baseMetrics()).grade).toBe('A');+ });+ it('2-3 materials -> B', () => {+ expect(gradeInstanceability(baseMetrics({ uniqueMaterials: 3 })).grade).toBe('B');+ });+ it('many materials -> F', () => {+ expect(gradeInstanceability(baseMetrics({ uniqueMaterials: 20 })).grade).toBe('F');+ });+ it('transparency caps an otherwise-A asset at C', () => {+ const r = gradeInstanceability(baseMetrics({ transparentMaterials: 1 }));+ expect(r.grade).toBe('C');+ expect(r.reasons.join(' ')).toMatch(/transparent/i);+ });+ it('skinned is NOT an automatic F and is noted', () => {+ const r = gradeInstanceability(baseMetrics({ skinned: true, uniqueMaterials: 1 }));+ expect(r.grade).toBe('A');+ expect(r.summary).toMatch(/skinned/);+ expect(r.reasons.join(' ')).toMatch(/clone-rendered/i);+ });+ it('texture sprawl demotes toward C', () => {+ const r = gradeInstanceability(baseMetrics({ uniqueMaterials: 1, textureCount: 6 }));+ expect(['C', 'D', 'F']).toContain(r.grade);+ });+});++describe('render.meta carries the instanceability report', () => {+ it('renderGLB merges instanceability into meta', async () => {+ const code = `+ const meta = { name: 'Box', category: 'prop' };+ function build() {+ const root = createRoot('Box');+ createPart('B', boxGeo(1, 1, 1), gameMaterial(0xff0000), { parent: root });+ return root;+ }+ `;+ const res = await renderGLB(code);+ expect(res.meta.instanceability).toBeDefined();+ expect(res.meta.instanceability!.grade).toBe('A');+ expect(res.meta.metricsError).toBeUndefined();+ });+});++describe('gradeGlbBytes (web-side path)', () => {+ it('grades a finished GLB from its bytes and derives triangles', async () => {+ const r = createRoot('Truck');+ const wg = cylinderGeo(0.4, 0.4, 0.2, 16);+ const rubber = gameMaterial(0x1a1a1a);+ const fl = createPart('WheelFL', wg, rubber, { position: [-0.8, 0.3, 1.2], parent: r });+ createInstance('WheelFR', fl, { position: [0.8, 0.3, 1.2], parent: r });+ const scene = await renderSceneToGLB(r);++ const report = await gradeGlbBytes(scene.bytes, { category: 'vehicle' });+ expect(report).toBeDefined();+ expect(report!.grade).toBe('A');+ expect(report!.metrics.triangles).toBeGreaterThan(0);+ expect(report!.metrics.drawCalls).toBe(2);+ });++ it('returns undefined on unparseable bytes', async () => {+ expect(await gradeGlbBytes(new Uint8Array([1, 2, 3, 4]))).toBeUndefined();+ });+});diff --git a/index.ts b/index.tsindex 3caa39da..98bcf5d6 100644--- a/index.ts+++ b/index.ts@@ -12,7 +12,7 @@ import type { KilnCodeMeta } from './render';import { renderGLB } from './render';import { generateKilnCode, resolveCodegenMode } from './generate';-export { renderGLB, renderSceneToGLB, inspectGeneratedAnimation } from './render';+export { renderGLB, renderSceneToGLB, inspectGeneratedAnimation, gradeGlbBytes } from './render';export {generateKilnCode,editKilnCode,@@ -29,6 +29,12 @@ export type {KilnGenerateCallOptions,} from './generate';export { validate, validateKilnCode } from './validation';+export { collectGlbMetrics, gradeInstanceability } from './metrics';+export type {+ InstanceabilityMetrics,+ InstanceabilityGrade,+ InstanceabilityReport,+} from './metrics';export { inspect } from './inspect';export type {InspectResult,diff --git a/metrics.ts b/metrics.tsnew file mode 100644index 00000000..9ba48b1a--- /dev/null+++ b/metrics.ts@@ -0,0 +1,187 @@+/**+ * Kiln instanceability metrics + grader.+ *+ * A pure, deterministic, GPU-free static analysis over a baked glTF Document.+ * Lives in @pixel-forge/core so it can be computed at every natural point with+ * zero deploy coupling:+ * - in render.ts -> render.meta for CLI / MCP / batch (never crosses the wire)+ * - web-side in Kiln Studio from the persisted GLB+ *+ * The AgentCore runtime is a pass-through transport; adding fields to its wire+ * envelope would force a dual-image redeploy. The grade is a pure function over+ * GLB bytes, so we never put it on the wire — we recompute it wherever the GLB+ * already lives.+ *+ * NOTHING here is a hard gate. The metrics and grade are informational signals+ * that help agents and humans understand how cheap an asset is to render at+ * scale. They never reject, block, or fail a generation/validation/bake.+ *+ * See docs/kiln-instanceability-and-runtime-instancing-cycle.md.+ */++import type { Document } from '@gltf-transform/core';++/**+ * Deterministic instanceability inputs, measured against the POST-dedup() glTF+ * Document — i.e. the GLB the runtime actually loads.+ */+export interface InstanceabilityMetrics {+ /** Distinct primitive geometries uploaded to the GPU (shared meshes count once). */+ uniqueGeometries: number;+ /** Distinct materials after dedup(). The "expensive axis" to collapse. */+ uniqueMaterials: number;+ /**+ * Naive three.js draw-call count for a single placement: for every node that+ * references a mesh, the count of that mesh's primitives. Shared meshes+ * referenced by N nodes contribute N times (each node is its own draw).+ */+ drawCalls: number;+ /** Number of texture images in the document. */+ textureCount: number;+ /** True if the document contains any skin (skinned/animated character). */+ skinned: boolean;+ /** Count of materials with a blended alpha mode (force per-object sort). */+ transparentMaterials: number;+ /** Triangle total (carried through from the render pass). */+ triangles: number;+}++export type InstanceabilityGrade = 'A' | 'B' | 'C' | 'D' | 'F';++export interface InstanceabilityReport {+ grade: InstanceabilityGrade;+ /** One-line human summary, e.g. "B — 2 materials, 14 draw calls, opaque". */+ summary: string;+ /** Why the grade landed where it did (advisory bullet points). */+ reasons: string[];+ metrics: InstanceabilityMetrics;+}++/**+ * Collect instanceability metrics from a baked glTF Document.+ *+ * Call AFTER dedup() so shared meshes/materials are already merged and the+ * counts reflect the real GPU upload. Pass `triangles` from the render pass+ * (countTriangles over the THREE scene) to skip re-walking accessors; omit it+ * and the count is derived from the Document (used by the GLB-bytes path).+ */+export function collectGlbMetrics(doc: Document, triangles?: number): InstanceabilityMetrics {+ const root = doc.getRoot();++ const geomSet = new Set<object>();+ const matSet = new Set<object>();+ let drawCalls = 0;+ let derivedTris = 0;++ const primTris = (prim: import('@gltf-transform/core').Primitive): number => {+ const idx = prim.getIndices();+ if (idx) return Math.floor(idx.getCount() / 3);+ const pos = prim.getAttribute('POSITION');+ return pos ? Math.floor(pos.getCount() / 3) : 0;+ };++ // Walk every node in every scene; a node referencing a mesh issues one draw+ // per primitive. Shared meshes (dedup-instanced) are referenced by multiple+ // nodes and therefore counted multiple times — that's the real draw cost,+ // and the real rendered-triangle total.+ const visit = (node: import('@gltf-transform/core').Node): void => {+ const mesh = node.getMesh();+ if (mesh) {+ for (const prim of mesh.listPrimitives()) {+ drawCalls += 1;+ geomSet.add(prim);+ derivedTris += primTris(prim);+ const mat = prim.getMaterial();+ if (mat) matSet.add(mat);+ }+ }+ for (const child of node.listChildren()) visit(child);+ };+ for (const scene of root.listScenes()) {+ for (const node of scene.listChildren()) visit(node);+ }++ const transparentMaterials = root+ .listMaterials()+ .filter((m) => m.getAlphaMode() === 'BLEND').length;++ return {+ uniqueGeometries: geomSet.size,+ uniqueMaterials: matSet.size,+ drawCalls,+ textureCount: root.listTextures().length,+ skinned: root.listSkins().length > 0,+ transparentMaterials,+ triangles: triangles ?? derivedTris,+ };+}++/**+ * Grade instanceability A–F. Kiln-tuned, advisory only.+ *+ * Rubric philosophy: the cheapest-to-scale asset shares one material across+ * shared geometry (a textbook InstancedMesh / BatchedMesh unit). The expensive,+ * un-collapsible axis is distinct-material cardinality, so the grade is driven+ * primarily by `uniqueMaterials`, with draw calls, transparency and texture+ * sprawl as secondary penalties.+ *+ * IMPORTANT Kiln adaptation: a skinned / animated character is NOT an automatic+ * F. Skinning only means the asset is clone-rendered rather than statically GPU-+ * instanced — which is fine at the placement counts Kiln City sees. We note it+ * and grade the remaining axes.+ */+export function gradeInstanceability(+ metrics: InstanceabilityMetrics,+ opts: { category?: string } = {},+): InstanceabilityReport {+ const reasons: string[] = [];+ const m = metrics;++ // Base grade from distinct-material cardinality (the collapsible axis).+ let grade: InstanceabilityGrade;+ if (m.uniqueMaterials <= 1) grade = 'A';+ else if (m.uniqueMaterials <= 3) grade = 'B';+ else if (m.uniqueMaterials <= 6) grade = 'C';+ else if (m.uniqueMaterials <= 12) grade = 'D';+ else grade = 'F';++ const order: InstanceabilityGrade[] = ['A', 'B', 'C', 'D', 'F'];+ const demote = (to: InstanceabilityGrade, why: string) => {+ if (order.indexOf(to) > order.indexOf(grade)) {+ grade = to;+ reasons.push(why);+ } else {+ reasons.push(why);+ }+ };++ reasons.push(+ `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? '' : 's'}, ` ++ `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? 'y' : 'ies'}, ` ++ `${m.drawCalls} draw call${m.drawCalls === 1 ? '' : 's'}`,+ );++ // Transparency forces per-object depth sort — caps at C.+ if (m.transparentMaterials > 0) {+ demote('C', `${m.transparentMaterials} transparent material(s) force per-object sort`);+ }++ // Per-asset texture sprawl (un-atlased) is a scaling cost — soft penalty.+ if (m.textureCount > 4) {+ demote('C', `${m.textureCount} textures (consider atlasing) `.trim());+ }++ // Skinned: informational, NOT a grade penalty. Clone-rendered by design.+ if (m.skinned) {+ reasons.push('skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts');+ }++ if (opts.category) reasons.push(`category: ${opts.category}`);++ const summary =+ `${grade} — ${m.uniqueMaterials} mat / ${m.uniqueGeometries} geo / ${m.drawCalls} draws` ++ (m.transparentMaterials > 0 ? ', transparent' : ', opaque') ++ (m.skinned ? ', skinned' : '');++ return { grade, summary, reasons, metrics: m };+}diff --git a/render.ts b/render.tsindex f3eacbfd..4a5ed5b9 100644--- a/render.ts+++ b/render.ts@@ -18,6 +18,12 @@ import {buildSandboxGlobals,countTriangles,} from './primitives';+import {+ collectGlbMetrics,+ gradeInstanceability,+ type InstanceabilityMetrics,+ type InstanceabilityReport,+} from './metrics';// WebIO (not NodeIO) is used for GLB serialization so the same code path// works in both Node and browser environments. writeBinary() only builds the@@ -55,6 +61,13 @@ export interface KilnCodeMeta {* Used to drive primitive-library prioritization from real usage.*/primitiveUsage?: Record<string, number>;+ /**+ * Instanceability metrics measured against the post-dedup() glTF Document.+ * Informational only — never a gate. Populated by renderGLB / renderSceneToGLB.+ */+ instanceability?: InstanceabilityReport;+ /** Set if metric computation threw; the GLB is still valid. */+ metricsError?: string;[key: string]: unknown;}@@ -429,6 +442,10 @@ export interface RenderSceneResult {bytes: Uint8Array;tris: number;warnings: string[];+ /** Post-dedup instanceability report (informational). Undefined if it threw. */+ instanceability?: InstanceabilityReport;+ /** Set if metric computation threw; bytes are still valid. */+ metricsError?: string;}export interface RenderSceneOptions {@@ -441,6 +458,8 @@ export interface RenderSceneOptions {* to inspect raw bridge output for debugging.*/dedup?: boolean;+ /** Asset category, threaded into the instanceability grade context. */+ category?: string;}/**@@ -500,10 +519,22 @@ export async function renderSceneToGLB(}}+ // Instanceability metrics, measured against the post-dedup() Document so the+ // counts reflect the GLB the runtime actually loads. Informational only —+ // never a gate. Failure is swallowed: the GLB is still valid without it.+ let instanceability: InstanceabilityReport | undefined;+ let metricsError: string | undefined;+ try {+ const metrics: InstanceabilityMetrics = collectGlbMetrics(doc, tris);+ instanceability = gradeInstanceability(metrics, { category: opts.category });+ } catch (err) {+ metricsError = err instanceof Error ? err.message : String(err);+ }+const io = new WebIO();const bytes = await io.writeBinary(doc);- return { bytes, tris, warnings };+ return { bytes, tris, warnings, instanceability, metricsError };}/**@@ -520,16 +551,44 @@ export async function renderGLB(code: string): Promise<RenderResult> {const scene = await renderSceneToGLB(root, {sceneName: meta.name || 'Scene',clips,+ category: typeof meta.category === 'string' ? meta.category : undefined,});return {glb: Buffer.from(scene.bytes),tris: scene.tris,- meta: { ...meta, tris: scene.tris, primitiveUsage },+ meta: {+ ...meta,+ tris: scene.tris,+ primitiveUsage,+ ...(scene.instanceability ? { instanceability: scene.instanceability } : {}),+ ...(scene.metricsError ? { metricsError: scene.metricsError } : {}),+ },warnings: scene.warnings,};}+/**+ * Grade instanceability directly from baked GLB bytes.+ *+ * Used by consumers that hold a finished GLB but not its THREE scene — e.g.+ * Kiln Studio computing the grade web-side from the persisted artifact, so the+ * AgentCore runtime never has to (no wire bump, no runtime image rebuild). Pure+ * read: parses the GLB, walks the post-dedup document, grades. Never throws on a+ * valid GLB; returns undefined if the bytes can't be parsed.+ */+export async function gradeGlbBytes(+ bytes: Uint8Array,+ opts: { category?: string } = {},+): Promise<InstanceabilityReport | undefined> {+ try {+ const doc = await new WebIO().readBinary(bytes);+ return gradeInstanceability(collectGlbMetrics(doc), opts);+ } catch {+ return undefined;+ }+}+// =============================================================================// Runtime-aware animation inspection// =============================================================================diff --git a/tools/registry.ts b/tools/registry.tsindex cbc95870..4d39186b 100644--- a/tools/registry.ts+++ b/tools/registry.ts@@ -130,12 +130,21 @@ function runListPrimitives(input: z.infer<typeof listPrimitivesInput>): {// kiln_validate// =============================================================================+/** Cheaply extract the declared category from the code's `meta` block so the+ * tri advisory has a reference point. The model writes `category` into meta, so+ * this reaches every door (CLI/MCP/studio) without threading external context. */+function extractCategory(code: string): string | undefined {+ const m = /category\s*:\s*['"]([^'"]+)['"]/.exec(code);+ return m?.[1];+}+function runValidate(input: z.infer<typeof validateInput>): {valid: boolean;errors: string[];warnings: string[];} {- const result = validate(input.code);+ const category = extractCategory(input.code);+ const result = validate(input.code, category ? { category } : {});return {valid: result.valid,errors: result.errors,@@ -157,6 +166,8 @@ export interface KilnRenderMetrics {* bbox.min[1] dips below 0, this names the buried part so the agent can* judge intent (earthworks/keels are fine; wheels/tails/missiles are not). */lowestPart?: { name: string; y: number };+ /** Post-dedup instanceability grade (informational): how cheap to render at scale. */+ instanceability?: { grade: string; summary: string };warnings: string[];error?: string;}@@ -222,7 +233,7 @@ function collectSceneMetrics(root: THREE.Object3D): SceneMetrics {*/async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRenderMetrics> {try {- const { root, clips } = await executeKilnCode(input.code);+ const { meta, root, clips } = await executeKilnCode(input.code);// Structural advisories (floating parts / stray planes at origin).const structuralWarnings = inspectSceneStructure(root);@@ -230,7 +241,8 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRender// Render to GLB bytes for the triangle count. Output is discarded — pure// metrics, no files written.- const rendered = await renderSceneToGLB(root, { clips });+ const category = typeof meta.category === 'string' ? meta.category : undefined;+ const rendered = await renderSceneToGLB(root, { clips, category });const warnings = [...structuralWarnings, ...rendered.warnings];@@ -241,6 +253,9 @@ async function runRender(input: z.infer<typeof renderInput>): Promise<KilnRendermaterials: metrics.materials,bbox: metrics.bbox,lowestPart: metrics.lowestPart,+ ...(rendered.instanceability+ ? { instanceability: { grade: rendered.instanceability.grade, summary: rendered.instanceability.summary } }+ : {}),warnings,};} catch (err) {@@ -317,6 +332,8 @@ export interface KilnRenderViewsResult {materials?: number;bbox?: { min: number[]; max: number[]; size: number[] };lowestPart?: { name: string; y: number };+ /** Post-dedup instanceability grade (informational): how cheap to render at scale. */+ instanceability?: { grade: string; summary: string };/** View names in grid order (row-major): Front, Right, Back, Left, Top, 3/4. */views?: string[];gridWidth?: number;@@ -340,13 +357,14 @@ export interface KilnRenderViewsResult {async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnRenderViewsResult> {try {const { renderViewGrid } = await import('../views');- const { root, clips } = await executeKilnCode(input.code);+ const { meta, root, clips } = await executeKilnCode(input.code);const structuralWarnings = inspectSceneStructure(root);const metrics = collectSceneMetrics(root);// Single execution, two consumers — both read-only on `root`.- const rendered = await renderSceneToGLB(root, { clips });+ const category = typeof meta.category === 'string' ? meta.category : undefined;+ const rendered = await renderSceneToGLB(root, { clips, category });const grid = await renderViewGrid(root);const warnings = [...structuralWarnings, ...rendered.warnings];@@ -358,6 +376,9 @@ async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnRmaterials: metrics.materials,bbox: metrics.bbox,lowestPart: metrics.lowestPart,+ ...(rendered.instanceability+ ? { instanceability: { grade: rendered.instanceability.grade, summary: rendered.instanceability.summary } }+ : {}),views: grid.views,gridWidth: grid.width,gridHeight: grid.height,@@ -382,7 +403,7 @@ async function runRenderViews(input: z.infer<typeof renderInput>): Promise<KilnRexport const kilnRenderViewsDef: KilnToolDef = {name: 'kiln_render',description:- 'Execute the current model and SEE it: returns geometry metrics (triangle count, mesh + material counts, world-space bounding box, and lowestPart — the mesh touching the lowest point, which must be intentional below Y=0 like earthworks or keels, never wheels/tails/equipment) TOGETHER with a six-view image grid. ' ++ 'Execute the current model and SEE it: returns geometry metrics (triangle count, mesh + material counts, world-space bounding box, lowestPart — the mesh touching the lowest point, which must be intentional below Y=0 like earthworks or keels, never wheels/tails/equipment, and an instanceability grade A–F — informational, how cheap to render at scale) TOGETHER with a six-view image grid. ' +'Row 1 = Front (camera on +X, the nose/muzzle should face you), Right (+Z, the long profile), Back (-X); ' +'row 2 = Left (-Z), Top (+Y, check symmetry), 3/4 perspective (check part contact and overall read). ' +'Use it to confirm the model builds and to verify orientation (+X forward), attachment (no floating parts), proportion, and silhouette. ' +@@ -612,14 +633,14 @@ export const kilnToolRegistry: KilnToolDef[] = [{name: 'kiln_validate',description:- 'Statically validate Kiln source code before rendering. Checks for the required `meta` const and `build()` function, `value:` keyframe typos, infinite loops, recursive build() calls, syntax errors, and triangle-budget advisories. Returns { valid, errors, warnings }. Run this to catch mistakes cheaply before kiln_render.',+ 'Statically validate Kiln source code before rendering. Checks for the required `meta` const and `build()` function, `value:` keyframe typos, infinite loops, recursive build() calls, and syntax errors. Returns { valid, errors, warnings }. Warnings are advisory only (they never make code invalid), including a soft, generous triangle-count nudge. Run this to catch mistakes cheaply before kiln_render.',inputSchema: validateInput,run: async (input) => runValidate(validateInput.parse(input)),},{name: 'kiln_render',description:- 'Execute Kiln code and render it to an in-memory GLB, returning geometry metrics: triangle count, mesh count, material count, the world-space bounding box, and lowestPart (the mesh touching the lowest point — anything below Y=0 must be intentionally below-grade like earthworks or keels, never wheels/tails/equipment). Includes structural warnings for floating parts and stray planes left at the origin. Use this to confirm a model builds and to inspect its size and structure. Does not write any files.',+ 'Execute Kiln code and render it to an in-memory GLB, returning geometry metrics: triangle count, mesh count, material count, the world-space bounding box, lowestPart (the mesh touching the lowest point — anything below Y=0 must be intentionally below-grade like earthworks or keels, never wheels/tails/equipment), and an instanceability grade (A–F, informational: how cheap the asset is to render at scale — driven by distinct-material count; fewer shared materials grade higher). Includes structural warnings for floating parts and stray planes left at the origin. Use this to confirm a model builds and to inspect its size and structure. Does not write any files.',inputSchema: renderInput,run: async (input) => runRender(renderInput.parse(input)),},diff --git a/validation.ts b/validation.tsindex 79e7b877..9ac4507a 100644--- a/validation.ts+++ b/validation.ts@@ -156,12 +156,26 @@ function estimateGeometryTris(}}+// Advisory-only soft reference points, NOT limits. Raised substantially in the+// 2026-06 instanceability cycle: the old values (character 5000 / prop 3000 /+// vfx 2000 / environment 15000) predated the More-detail toggle and the finding+// that triangles are not a cost driver (input tokens dominate generation cost,+// and runtime cost is draw-calls-not-tris). These exist only so a wildly over-+// budget asset gets a gentle informational nudge; they never gate. See+// docs/kiln-instanceability-and-runtime-instancing-cycle.md.const CATEGORY_TRI_BUDGETS: Record<string, number> = {- character: 5000,- prop: 3000,- vfx: 2000,- environment: 15000,+ character: 40000,+ prop: 25000,+ vfx: 15000,+ environment: 120000,+ vehicle: 40000,+ weapon: 20000,+ building: 60000,+ architecture: 60000,};+// Fallback when a category has no specific entry, so the advisory still has a+// reference point instead of silently never firing.+const DEFAULT_TRI_BUDGET = 40000;// =============================================================================// Core validator@@ -301,14 +315,17 @@ export function validate(});}- // Tri-count advisory. Only warn; LLMs over- and under-estimate both ways.- if (analysis.estimatedTris > 0) {- const budget = opts.category ? CATEGORY_TRI_BUDGETS[opts.category] : undefined;- if (budget && analysis.estimatedTris > budget * 1.5) {+ // Tri-count advisory — INFORMATIONAL ONLY, never a gate (it is a warning, so+ // it never sets valid:false). LLMs over- and under-estimate both ways, tris+ // are not a cost driver, and the More-detail toggle deliberately pushes tris+ // up — so this only nudges on assets well past a generous soft reference.+ if (analysis.estimatedTris > 0 && opts.category) {+ const budget = CATEGORY_TRI_BUDGETS[opts.category] ?? DEFAULT_TRI_BUDGET;+ if (analysis.estimatedTris > budget * 1.5) {warnings.push({code: 'TRI_BUDGET_EXCEEDED',- message: `Estimated ${analysis.estimatedTris} tris — category "${opts.category}" suggests <= ${budget}`,- fixHint: 'Reduce segments on cylinderGeo/sphereGeo, or drop decorative parts.',+ message: `Estimated ${analysis.estimatedTris} tris (informational; "${opts.category}" assets typically land under ~${budget}). This is not a limit — keep the detail if the silhouette needs it.`,+ fixHint: 'Only if the asset feels over-dense: reduce segments on cylinderGeo/sphereGeo, or drop hidden interior parts.',});}}