Skip to content

armgit / kiln

Public Imported from GitHub
0

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.

feat(render): grade-aware `auto` consolidation + agent role/tier metadata

Matt Kissinger190eb6f1a0a2
diff --git a/src/__tests__/metrics.test.ts b/src/__tests__/metrics.test.ts
index 034ad7af..c73f95ce 100644
--- a/src/__tests__/metrics.test.ts
+++ b/src/__tests__/metrics.test.ts
@@ -124,6 +124,8 @@ describe('render.meta carries the instanceability report', () => {
const res = await renderGLB(code);
expect(res.meta.instanceability).toBeDefined();
expect(res.meta.instanceability!.grade).toBe('A');
+ // tier is auto-filled to mirror the grade (M1d).
+ expect(res.meta.tier).toBe('A');
expect(res.meta.metricsError).toBeUndefined();
});
});
diff --git a/src/__tests__/optimize.test.ts b/src/__tests__/optimize.test.ts
index 2f287ea8..49d67379 100644
--- a/src/__tests__/optimize.test.ts
+++ b/src/__tests__/optimize.test.ts
@@ -178,3 +178,30 @@ describe('optimizeGlbBytes (web-side path)', () => {
expect(opt!.report!.metrics.uniqueGeometries).toBe(1); // instancing preserved
});
});
+
+describe('optimize=auto (grade-aware, the default grade-lift lever)', () => {
+ it('consolidates a material-sprawl asset (>= PALETTE_MIN) and lifts the grade', async () => {
+ const after = await renderSceneToGLB(manyColorScene(14), { optimize: 'auto' });
+ expect(after.optimize).toBeDefined();
+ expect(after.optimize!.mode).toBe('palette');
+ expect(after.optimize!.materialsAfter).toBeLessThanOrEqual(2);
+ expect(['A', 'B']).toContain(after.instanceability!.grade);
+ });
+
+ it('is a byte-stable no-op on a lean asset (< PALETTE_MIN materials)', async () => {
+ const off = await renderSceneToGLB(manyColorScene(3), { optimize: 'off' });
+ const auto = await renderSceneToGLB(manyColorScene(3), { optimize: 'auto' });
+ expect(auto.optimize).toBeUndefined();
+ expect(Buffer.from(off.bytes).equals(Buffer.from(auto.bytes))).toBe(true);
+ });
+
+ it('optimizeGlbBytes mode:auto consolidates a heavy GLB and skips a lean one', async () => {
+ const heavy = await renderSceneToGLB(manyColorScene(14));
+ const opt = await optimizeGlbBytes(heavy.bytes, { mode: 'auto' });
+ expect(opt).toBeDefined();
+ expect(['A', 'B']).toContain(opt!.report!.grade);
+
+ const lean = await renderSceneToGLB(manyColorScene(3));
+ expect(await optimizeGlbBytes(lean.bytes, { mode: 'auto' })).toBeUndefined();
+ });
+});
diff --git a/src/agent/generate.ts b/src/agent/generate.ts
index b26bde5c..0544fcf9 100644
--- a/src/agent/generate.ts
+++ b/src/agent/generate.ts
@@ -193,7 +193,9 @@ export async function generateKilnAsset(
throw new Error(`Kiln agent generation failed: ${agent.error ?? 'agent produced no code'}`);
}
- const render = await renderGLB(agent.code);
+ // Grade-aware consolidation by default: lifts material-sprawl heroes from
+ // grade C/D/F to A/B, byte-stable on already-lean assets (M1a, plan/05 §3.1).
+ const render = await renderGLB(agent.code, { optimize: 'auto' });
// Best-effort views artifact: what the vision loop / review UIs show.
// Never fails the run — a rasterizer error just drops the sidecar.
diff --git a/src/prompt.ts b/src/prompt.ts
index 6d6f415e..1784a6f1 100644
--- a/src/prompt.ts
+++ b/src/prompt.ts
@@ -82,7 +82,9 @@ export const KILN_PROMPT_HEADER = `You are an expert procedural 3D asset generat
CRITICAL: NO import/export statements. Code runs in a sandbox with primitives as globals.`;
export const KILN_FILE_FORMAT = `<file-format>
-const meta = { name: "AssetName", category: "prop" };
+const meta = { name: "AssetName", category: "prop", role: "prop" };
+// role = how the asset sits in a scene (drives composition layout). One of:
+// "ground" | "building" | "wonder" | "poi" | "prop" | "fill" | "vehicle".
// build() may be sync OR async. Mark it async if you use any CSG op
// (boolUnion / boolDiff / boolIntersect / hull) because those await WASM.
diff --git a/src/render.ts b/src/render.ts
index 1ded9c44..6c09d5d1 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -28,6 +28,7 @@ import { buildSandboxGlobals, countTriangles } from './primitives';
import {
collectGlbMetrics,
gradeInstanceability,
+ type InstanceabilityGrade,
type InstanceabilityMetrics,
type InstanceabilityReport,
} from './metrics';
@@ -59,9 +60,19 @@ const TYPE_VEC4: AccessorTypeStr = 'VEC4';
// Execution
// =============================================================================
+/**
+ * Scene-placement role the agent declares in its `meta` block. Drives composer
+ * layout (wonders anchor + scale up, fill scatters, ground is the base, vehicles
+ * snap to roads) and Kiln City density budgeting. Semantic — cannot be recomputed
+ * from GLB bytes, so it travels in provenance. See plan/05-product-depth.md §3.4.
+ */
+export type AssetRole = 'ground' | 'building' | 'wonder' | 'poi' | 'prop' | 'fill' | 'vehicle';
+
export interface KilnCodeMeta {
name?: string;
category?: string;
+ /** Scene-placement role (agent-declared). Drives composer layout + city budgeting. */
+ role?: AssetRole;
tris?: number;
/**
* Count of primitive invocations from the agent-generated build() call.
@@ -74,6 +85,11 @@ export interface KilnCodeMeta {
* Informational only — never a gate. Populated by renderGLB / renderSceneToGLB.
*/
instanceability?: InstanceabilityReport;
+ /**
+ * Convenience copy of {@link KilnCodeMeta.instanceability}.grade (A–F),
+ * auto-filled at bake so consumers read the tier without re-deriving it.
+ */
+ tier?: InstanceabilityGrade;
/** Set if metric computation threw; the GLB is still valid. */
metricsError?: string;
/** Set when an opt-in consolidation pass ran (optimize !== 'off'). */
@@ -462,6 +478,11 @@ export interface RenderResult {
/**
* Bake-time material-consolidation mode (opt-in, default off).
* - `off` — today's output, byte-identical across every consumer.
+ * - `auto` — grade-aware: runs `palette` only when it would actually act
+ * (>= PALETTE_MIN distinct materials — i.e. the asset is grade
+ * C/D/F from material sprawl); below that it is a no-op, byte-
+ * identical to `off`. The default grade-lift lever for the agent
+ * path: lean assets stay untouched, sprawling heroes collapse.
* - `palette` — merge distinct flat-color materials into one palette material
* + palette texture (`palette → weld → prune`). Node graph,
* named pivots, and animations are fully preserved, so it is safe
@@ -472,7 +493,7 @@ export interface RenderResult {
* animations or skins (flatten/join must not disturb a rig).
* See docs/kiln-material-consolidation-cycle.md (Move 1).
*/
-export type OptimizeMode = 'off' | 'palette' | 'full';
+export type OptimizeMode = 'off' | 'auto' | 'palette' | 'full';
/** What a consolidation pass did (recorded in provenance / render.meta). */
export interface OptimizeSummary {
@@ -526,7 +547,7 @@ const PALETTE_MIN = 5;
function resolveOptimize(opt?: OptimizeMode): OptimizeMode {
if (opt) return opt;
const env = process.env['KILN_BAKE_OPTIMIZE'];
- return env === 'palette' || env === 'full' ? env : 'off';
+ return env === 'auto' || env === 'palette' || env === 'full' ? env : 'off';
}
/**
@@ -633,16 +654,23 @@ export async function renderSceneToGLB(
}
// Opt-in material consolidation (default off => byte-identical to today). Runs
- // after dedup so palette() works on the already-merged material set. Failure is
+ // after dedup so palette() works on the already-merged material set. `auto` is
+ // grade-aware: it consolidates only when palette() would actually act
+ // (>= PALETTE_MIN materials), so lean assets stay byte-stable. Failure is
// swallowed with a warning — the dedup'd GLB is still valid.
const optimizeMode = resolveOptimize(opts.optimize);
+ let effectiveOptimize: 'off' | 'palette' | 'full' =
+ optimizeMode === 'auto' ? 'off' : optimizeMode;
+ if (optimizeMode === 'auto' && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {
+ effectiveOptimize = 'palette';
+ }
let optimize: OptimizeSummary | undefined;
- if (optimizeMode !== 'off') {
+ if (effectiveOptimize !== 'off') {
try {
- optimize = await consolidateMaterials(doc, optimizeMode);
+ optimize = await consolidateMaterials(doc, effectiveOptimize);
} catch (err) {
warnings.push(
- `optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`,
+ `optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`,
);
}
}
@@ -702,7 +730,9 @@ export async function renderGLB(
...meta,
tris: scene.tris,
primitiveUsage,
- ...(scene.instanceability ? { instanceability: scene.instanceability } : {}),
+ ...(scene.instanceability
+ ? { instanceability: scene.instanceability, tier: scene.instanceability.grade }
+ : {}),
...(scene.metricsError ? { metricsError: scene.metricsError } : {}),
...(scene.optimize ? { optimize: scene.optimize } : {}),
},
@@ -754,12 +784,23 @@ export interface OptimizeGlbResult {
*/
export async function optimizeGlbBytes(
bytes: Uint8Array,
- opts: { mode?: 'palette' | 'full'; category?: string } = {},
+ opts: { mode?: OptimizeMode; category?: string } = {},
): Promise<OptimizeGlbResult | undefined> {
- const mode = opts.mode ?? 'palette';
+ const requested = opts.mode ?? 'palette';
try {
const io = new WebIO();
const doc = await io.readBinary(bytes);
+ // `auto` is grade-aware: consolidate only when palette() would act
+ // (>= PALETTE_MIN materials); a no-op auto (or an explicit `off`) returns
+ // undefined so the caller simply keeps the original bytes unchanged.
+ if (requested === 'off') return undefined;
+ let mode: 'palette' | 'full';
+ if (requested === 'auto') {
+ if (collectGlbMetrics(doc).uniqueMaterials < PALETTE_MIN) return undefined;
+ mode = 'palette';
+ } else {
+ mode = requested;
+ }
const summary = await consolidateMaterials(doc, mode);
const outBytes = await io.writeBinary(doc);
let report: InstanceabilityReport | undefined;
@@ -1004,12 +1045,17 @@ export async function composeSceneGLB(
}
const optimizeMode: OptimizeMode = opts.optimize ?? 'palette';
- if (optimizeMode !== 'off') {
+ let effectiveOptimize: 'off' | 'palette' | 'full' =
+ optimizeMode === 'auto' ? 'off' : optimizeMode;
+ if (optimizeMode === 'auto' && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {
+ effectiveOptimize = 'palette';
+ }
+ if (effectiveOptimize !== 'off') {
try {
- await consolidateMaterials(master, optimizeMode);
+ await consolidateMaterials(master, effectiveOptimize);
} catch (err) {
warnings.push(
- `optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`,
+ `optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`,
);
}
}