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): material-consolidation cycle — opt-in instanceable assets
Matt Kissingerb459adce2625
diff --git a/__tests__/optimize.test.ts b/__tests__/optimize.test.tsnew file mode 100644index 00000000..da5d6ff5--- /dev/null+++ b/__tests__/optimize.test.ts@@ -0,0 +1,155 @@+/**+ * Move 1 — bake-time material consolidation (the opt-in `optimize` pass).+ *+ * Covers the load-bearing guarantees from docs/kiln-material-consolidation-cycle.md:+ * - palette collapses many distinct flat materials -> ~1 and lifts the grade+ * - the grade is recomputed on the OPTIMIZED document+ * - `full` auto-degrades to `palette` when the asset is animated (rig-safe)+ * - transparency is never flattened into opaque (glass stays its own material)+ * - prune keeps named pivots (Kiln City behaviors target createPivot Joint_ by name)+ * - `optimize='off'` is byte-stable (deterministic, no consolidation)+ * - optimizeGlbBytes() does the same pass web-side from finished bytes+ */+import { describe, it, expect } from 'bun:test';+import * as THREE from 'three';+import {+ createRoot,+ createPart,+ createInstance,+ createPivot,+ boxGeo,+ cylinderGeo,+ gameMaterial,+ glassMaterial,+} from '../primitives';+import { renderSceneToGLB, optimizeGlbBytes } from '../render';+import { WebIO } from '@gltf-transform/core';++/** A distinct flat color per index (HSL hue sweep — guaranteed unique materials). */+const hue = (i: number, n: number): number => new THREE.Color().setHSL(i / n, 0.7, 0.5).getHex();++/** A scene with N distinct flat-color opaque materials on N boxes. */+function manyColorScene(n: number): THREE.Object3D {+ const root = createRoot('Palette');+ for (let i = 0; i < n; i++) {+ createPart(`Box${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, n)), { position: [i * 1.5, 0, 0], parent: root });+ }+ return root;+}++async function nodeNamesOf(bytes: Uint8Array): Promise<Set<string>> {+ const doc = await new WebIO().readBinary(bytes);+ return new Set(doc.getRoot().listNodes().map((nd) => nd.getName()).filter(Boolean));+}++describe('optimize=off (byte-stable)', () => {+ it('omitting optimize and optimize:"off" are byte-identical, and deterministic', async () => {+ const a = await renderSceneToGLB(manyColorScene(6));+ const b = await renderSceneToGLB(manyColorScene(6), { optimize: 'off' });+ expect(a.optimize).toBeUndefined();+ expect(b.optimize).toBeUndefined();+ expect(Buffer.from(a.bytes).equals(Buffer.from(b.bytes))).toBe(true);+ });+});++describe('optimize=palette (material collapse)', () => {+ it('collapses many distinct flat materials to ~1 and lifts the grade', async () => {+ const before = await renderSceneToGLB(manyColorScene(14));+ expect(before.instanceability!.grade).toBe('F'); // 14 materials++ const after = await renderSceneToGLB(manyColorScene(14), { optimize: 'palette' });+ expect(after.optimize).toBeDefined();+ expect(after.optimize!.mode).toBe('palette');+ expect(after.optimize!.materialsBefore).toBe(14);+ expect(after.optimize!.materialsAfter).toBeLessThan(after.optimize!.materialsBefore);+ expect(after.optimize!.materialsAfter).toBeLessThanOrEqual(2);+ // The recorded grade reflects the OPTIMIZED document.+ expect(['A', 'B']).toContain(after.instanceability!.grade);+ expect(after.instanceability!.metrics.uniqueMaterials).toBe(after.optimize!.materialsAfter);+ });++ it('keeps transparency separate — glass is never merged into opaque', async () => {+ const root = createRoot('Glassy');+ for (let i = 0; i < 8; i++) {+ createPart(`Wall${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 8)), { position: [i * 1.5, 0, 0], parent: root });+ }+ createPart('Window', boxGeo(1, 1, 0.05), glassMaterial(0x88ccff, { opacity: 0.4 }), {+ position: [0, 2, 0],+ parent: root,+ });++ const after = await renderSceneToGLB(root, { optimize: 'palette' });+ // At least one transparent material survives (opaque palette + the glass slot).+ expect(after.instanceability!.metrics.transparentMaterials).toBeGreaterThanOrEqual(1);+ });++ it('keeps named pivots (Kiln City behaviors target createPivot Joint_ by name)', async () => {+ const root = createRoot('Rig');+ // A named pivot carrying a moving part (the realistic Kiln City case)...+ const lid = createPivot('Lid', [0, 1, 0], root);+ createPart('LidPanel', boxGeo(0.9, 0.1, 0.9), gameMaterial(0x886644), { position: [0, 0.2, 0], parent: lid });+ // ...and a named empty pivot (a leaf the behavior could still reference).+ createPivot('Marker', [0, 2, 0], root);+ // Pad with distinct materials so palette actually runs.+ for (let i = 0; i < 8; i++) {+ createPart(`Body${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 8)), { position: [i * 1.5, -2, 0], parent: root });+ }++ const after = await renderSceneToGLB(root, { optimize: 'palette' });+ const names = await nodeNamesOf(after.bytes);+ expect(names.has('Joint_Lid')).toBe(true);+ expect(names.has('Joint_Marker')).toBe(true);+ });+});++describe('optimize=full (static-only; auto-degrade on animation)', () => {+ it('auto-degrades to palette when the asset is animated', async () => {+ const root = createRoot('Spinner');+ const hub = createPivot('Spin', [0, 1, 0], root);+ for (let i = 0; i < 8; i++) {+ createPart(`Blade${i}`, boxGeo(0.2, 0.05, 1.2), gameMaterial(hue(i, 8)), { position: [0, 0, 0], parent: hub });+ }+ const track = new THREE.QuaternionKeyframeTrack(+ 'Joint_Spin.quaternion',+ [0, 1],+ [0, 0, 0, 1, 0, 0.7071, 0, 0.7071],+ );+ const clip = new THREE.AnimationClip('spin', 1, [track]);++ const after = await renderSceneToGLB(root, { optimize: 'full', clips: [clip] });+ expect(after.optimize).toBeDefined();+ // full requested, but animated -> degrades to palette (rig stays intact).+ expect(after.optimize!.mode).toBe('palette');+ const names = await nodeNamesOf(after.bytes);+ expect(names.has('Joint_Spin')).toBe(true);+ });+});++describe('optimizeGlbBytes (web-side path)', () => {+ it('consolidates a finished GLB from its bytes and re-grades it', async () => {+ const baked = await renderSceneToGLB(manyColorScene(14)); // un-optimized, grade F+ expect(baked.instanceability!.grade).toBe('F');++ const opt = await optimizeGlbBytes(baked.bytes, { mode: 'palette', category: 'prop' });+ expect(opt).toBeDefined();+ expect(opt!.summary.materialsAfter).toBeLessThan(opt!.summary.materialsBefore);+ expect(['A', 'B']).toContain(opt!.report!.grade);+ // The returned bytes are a valid GLB.+ const names = await nodeNamesOf(opt!.bytes);+ expect(names.size).toBeGreaterThan(0);+ });++ it('returns undefined on unparseable bytes (caller keeps the original)', async () => {+ expect(await optimizeGlbBytes(new Uint8Array([1, 2, 3, 4]))).toBeUndefined();+ });++ it('an instanced scene keeps shared geometry through consolidation', async () => {+ const root = createRoot('Fence');+ const post = createPart('Post0', boxGeo(0.1, 1, 0.1), gameMaterial(0x8a5a2b), { position: [0, 0.5, 0], parent: root });+ for (let i = 1; i < 10; i++) createInstance(`Post${i}`, post, { position: [i * 0.5, 0.5, 0], parent: root });+ const baked = await renderSceneToGLB(root);+ expect(baked.instanceability!.metrics.uniqueGeometries).toBe(1);+ const opt = await optimizeGlbBytes(baked.bytes, { mode: 'palette' });+ expect(opt!.report!.metrics.uniqueGeometries).toBe(1); // instancing preserved+ });+});diff --git a/palette.ts b/palette.tsnew file mode 100644index 00000000..99cd8732--- /dev/null+++ b/palette.ts@@ -0,0 +1,110 @@+/**+ * Kiln canonical material palette — the single source of truth for the+ * "Optimized palette" authoring directive (Move 2) and a future shared palette+ * texture (Phase C, cross-asset batching).+ *+ * PURE DATA + a text helper. NO `three`, NO node, NO gltf-transform imports — so+ * it is browser-safe and can be consumed anywhere (the leaf subpath+ * `@pixel-forge/core/kiln/palette`) without dragging runtime code into a bundle.+ *+ * Why it lives in core: the palette is the shared contract both the authoring+ * prompt (instruct the model to build against these roles) and a later bake-time+ * shared-palette texture (Phase C) target. The slot SET + ORDER are stable so the+ * future texture is deterministic; the implementer may tune individual color /+ * metalness / roughness values without breaking that contract.+ *+ * The rendered directive string is mirrored verbatim in+ * `@pixel-forge/kiln-studio/shared` as `OPTIMIZED_PALETTE_DIRECTIVE` (so that+ * import-free, browser-critical module stays dependency-free); a parity test in+ * kiln-studio asserts the two never drift. See docs/kiln-material-consolidation-cycle.md.+ */++/** One material role in the canonical palette. A PBR spec the directive names and+ * a future shared palette texture bakes from. */+export interface PaletteSlot {+ /** Stable index (the slot's position in a future palette texture). */+ index: number;+ /** Role name the directive surfaces and the model authors against. */+ name: string;+ /** Base color, hex string. */+ color: string;+ /** PBR metalness 0..1. */+ metalness: number;+ /** PBR roughness 0..1. */+ roughness: number;+ /** The ONE transparent slot (glass). At most one slot sets this. */+ transparent?: boolean;+ /** Approx opacity for the transparent slot. */+ opacity?: number;+ /** The ONE emissive slot (glow). At most one slot sets this. */+ emissive?: boolean;+ /** Short "use for" hint surfaced in the directive. */+ use: string;+}++/**+ * The canonical 19-slot palette covering war / city / fantasy / sci-fi / organic /+ * character domains. Stable order; values are tunable. `glass` is the only+ * transparent slot and `glow` the only emissive — keeping the alpha-mode story+ * simple (opaque everything + the one glass slot).+ */+export const OPTIMIZED_PALETTE: readonly PaletteSlot[] = [+ { index: 0, name: 'steel', color: '#8a8f99', metalness: 0.9, roughness: 0.5, use: 'bare metal, blades, machinery, hulls' },+ { index: 1, name: 'gunmetal', color: '#3a3f47', metalness: 0.9, roughness: 0.45, use: 'dark metal, weapons, iron fittings' },+ { index: 2, name: 'brass', color: '#c8a64b', metalness: 0.95, roughness: 0.4, use: 'gold/brass trim, horns, ornament' },+ { index: 3, name: 'copper', color: '#b06a3a', metalness: 0.9, roughness: 0.45, use: 'copper/bronze, worn metal' },+ { index: 4, name: 'wood', color: '#9a6a3c', metalness: 0.0, roughness: 0.8, use: 'planks, handles, crates, trunks' },+ { index: 5, name: 'dark-wood', color: '#5a3a22', metalness: 0.0, roughness: 0.8, use: 'aged timber, bark, framing' },+ { index: 6, name: 'stone', color: '#8d8a82', metalness: 0.0, roughness: 0.95, use: 'rock, masonry, boulders' },+ { index: 7, name: 'concrete', color: '#b8b4ad', metalness: 0.0, roughness: 0.95, use: 'concrete, plaster, pale walls' },+ { index: 8, name: 'brick', color: '#9e4b34', metalness: 0.0, roughness: 0.9, use: 'brick, terracotta, clay' },+ { index: 9, name: 'sand', color: '#cdb27a', metalness: 0.0, roughness: 1.0, use: 'sand, adobe, tan earth' },+ { index: 10, name: 'dirt', color: '#5b4632', metalness: 0.0, roughness: 1.0, use: 'soil, mud, dark ground' },+ { index: 11, name: 'foliage', color: '#4f8f3f', metalness: 0.0, roughness: 0.9, use: 'leaves, grass, plants' },+ { index: 12, name: 'glass', color: '#aacbe0', metalness: 0.0, roughness: 0.1, transparent: true, opacity: 0.35, use: 'windows, lenses — the ONE transparent slot' },+ { index: 13, name: 'white', color: '#e8e8e6', metalness: 0.0, roughness: 0.7, use: 'white paint, cloth, paper' },+ { index: 14, name: 'black', color: '#1a1c1f', metalness: 0.0, roughness: 0.6, use: 'black, rubber, charred, tires' },+ { index: 15, name: 'accent-warm', color: '#c0392b', metalness: 0.0, roughness: 0.7, use: 'red/orange paint, flags, signs' },+ { index: 16, name: 'accent-cool', color: '#2f6fd0', metalness: 0.0, roughness: 0.7, use: 'blue/teal paint, water, signs' },+ { index: 17, name: 'skin', color: '#c8946a', metalness: 0.0, roughness: 0.75, use: 'character skin / flesh' },+ { index: 18, name: 'glow', color: '#ffd9a0', metalness: 0.0, roughness: 1.0, emissive: true, use: 'lamps, neon, fire cores, vfx — the ONE emissive slot' },+];++/**+ * Render the authoring directive appended to the agent prompt when the+ * "Optimized palette" toggle is on. Natural-language guidance that names the+ * shared roles and instructs the model to reuse them rather than authoring a+ * unique material per part — so the asset bakes down to ~1 material (grade A/B).+ *+ * Deterministic (pure function of {@link OPTIMIZED_PALETTE}); the kiln-studio+ * `OPTIMIZED_PALETTE_DIRECTIVE` mirror is asserted equal to this in a parity test.+ */+export function renderPaletteDirective(): string {+ const lines = OPTIMIZED_PALETTE.map((s) => `- ${s.name}: ${s.use}`).join('\n');+ return (+ '## Optimized, instanceable build\n' ++ 'A game-ready asset is cheap to render in bulk when its parts SHARE materials and SHARE ' ++ 'geometry. Aim for both.\n\n' ++ 'MATERIALS — build this asset using ONLY the shared material roles below. Pick the nearest role ' ++ 'for each part and REUSE the same role across every part that shares a look; do not author a ' ++ 'unique material or a one-off color per part. Far fewer distinct materials makes the asset ' ++ 'dramatically cheaper to draw, with no change to how it reads at a glance.\n\n' ++ `${lines}\n\n` ++ 'Use FLAT SOLID COLORS for every role — no image textures, gradients, or per-part color maps. ' ++ 'Flat colors are exactly what let the materials collapse into one; a textured material cannot be ' ++ 'merged. "glass" is the ONLY transparent material — use it for every window, lens, or ' ++ 'see-through part and nothing else; keep all other materials fully opaque. "glow" is the ONLY ' ++ 'emissive material — use it for anything that should look lit (lamps, fire cores, neon, magic). ' ++ 'When a color you want is not named exactly, choose the closest role rather than introducing a ' ++ 'new material; it is good and expected for many parts to share one role.\n\n' ++ 'GEOMETRY — when the asset has repeated identical parts (wheels, windows, railings, fence posts, ' ++ 'bolts, balusters, planks, columns), build the part ONCE and reuse that same part for every copy ' ++ 'with createInstance, instead of modeling each separately. Instances share one geometry buffer, ' ++ 'so a fence of 30 identical posts costs almost the same as one. Keep each part a clean closed ' ++ 'solid and spend triangles on the silhouette, not on faces no one sees. The result should read ' ++ 'correctly and be cheap to render many times over.'+ );+}++/** The rendered directive, precomputed. Canonical source for the kiln-studio mirror. */+export const OPTIMIZED_PALETTE_DIRECTIVE: string = renderPaletteDirective();diff --git a/render.ts b/render.tsindex 4a5ed5b9..891c7055 100644--- a/render.ts+++ b/render.ts@@ -12,7 +12,7 @@import * as THREE from 'three';import { Document, WebIO } from '@gltf-transform/core';-import { dedup } from '@gltf-transform/functions';+import { dedup, palette, flatten, join, weld, prune } from '@gltf-transform/functions';import {buildSandboxGlobals,@@ -68,6 +68,8 @@ export interface KilnCodeMeta {instanceability?: InstanceabilityReport;/** Set if metric computation threw; the GLB is still valid. */metricsError?: string;+ /** Set when an opt-in consolidation pass ran (optimize !== 'off'). */+ optimize?: OptimizeSummary;[key: string]: unknown;}@@ -437,15 +439,43 @@ export interface RenderResult {warnings: string[];}+/**+ * Bake-time material-consolidation mode (opt-in, default off).+ * - `off` — today's output, byte-identical across every consumer.+ * - `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+ * for animated assets + Kiln City behaviors. Lifts the grade by+ * collapsing the material count (the grade's primary axis).+ * - `full` — `palette` plus `flatten → join` to also cut draw calls. STATIC+ * assets only: auto-degrades to `palette` when the Document has+ * 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';++/** What a consolidation pass did (recorded in provenance / render.meta). */+export interface OptimizeSummary {+ /** The mode actually applied (may differ from the request after auto-degrade). */+ mode: 'palette' | 'full';+ materialsBefore: number;+ materialsAfter: number;+ drawsBefore: number;+ drawsAfter: number;+}+export interface RenderSceneResult {/** Binary GLB bytes, platform-agnostic (Buffer-compatible in Node). */bytes: Uint8Array;tris: number;warnings: string[];- /** Post-dedup instanceability report (informational). Undefined if it threw. */+ /** Post-dedup (and post-optimize, when enabled) instanceability report+ * (informational). Undefined if it threw. */instanceability?: InstanceabilityReport;/** Set if metric computation threw; bytes are still valid. */metricsError?: string;+ /** Set when an opt-in consolidation pass ran (optimize !== 'off'). */+ optimize?: OptimizeSummary;}export interface RenderSceneOptions {@@ -460,6 +490,66 @@ export interface RenderSceneOptions {dedup?: boolean;/** Asset category, threaded into the instanceability grade context. */category?: string;+ /**+ * Opt-in material consolidation, applied after dedup. Defaults to the+ * `KILN_BAKE_OPTIMIZE` env (else `off`). `off` is byte-identical to today.+ * See {@link OptimizeMode}.+ */+ optimize?: OptimizeMode;+}++/** Minimum distinct material-value blocks before palette() generates a texture.+ * Below this it is a no-op (an asset with very few materials is already cheap). */+const PALETTE_MIN = 5;++/** Resolve the effective optimize mode: explicit option wins, else the env, else off. */+function resolveOptimize(opt?: OptimizeMode): OptimizeMode {+ if (opt) return opt;+ const env = process.env['KILN_BAKE_OPTIMIZE'];+ return env === 'palette' || env === 'full' ? env : 'off';+}++/**+ * Run the opt-in consolidation transforms on a baked Document, in place.+ *+ * `palette` collapses distinct untextured flat-color materials into one palette+ * material + a small palette texture (textured materials pass through untouched);+ * `weld` + `prune` clean up. `full` adds `flatten → join` to also reduce draws,+ * but ONLY for static assets — if the Document carries animations or skins it+ * auto-degrades to `palette` so a rig is never disturbed (flatten leaves animated+ * nodes + skeletons in place by design, and join({keepNamed:true}) never merges a+ * named pivot, but degrading is the belt-and-braces guarantee). `prune` keeps+ * empty leaf nodes + extras so named pivots that Kiln City behaviors target by+ * name survive. palette groups by alpha mode, so opaque + the one glass slot stay+ * distinct materials (transparency is never flattened into opaque).+ *+ * Returns what it did; throws are the caller's to handle (the GLB is otherwise+ * valid). Pure w.r.t. inputs other than the mutated Document.+ */+async function consolidateMaterials(doc: Document, mode: 'palette' | 'full'): Promise<OptimizeSummary> {+ const before = collectGlbMetrics(doc);+ const root = doc.getRoot();+ const animatedOrSkinned = root.listAnimations().length > 0 || root.listSkins().length > 0;+ const effective: 'palette' | 'full' = mode === 'full' && animatedOrSkinned ? 'palette' : mode;++ const steps = [palette({ min: PALETTE_MIN })];+ if (effective === 'full') {+ // flatten() leaves skeletons + animation-targeted nodes in place; join keeps+ // named meshes/nodes intact so pivots survive. Both only run on static assets.+ steps.push(flatten(), join({ keepNamed: true }));+ }+ steps.push(weld(), prune({ keepLeaves: true, keepExtras: true }));++ await doc.transform(...steps);++ const after = collectGlbMetrics(doc);+ return {+ mode: effective,+ materialsBefore: before.uniqueMaterials,+ materialsAfter: after.uniqueMaterials,+ drawsBefore: before.drawCalls,+ drawsAfter: after.drawCalls,+ };}/**@@ -519,13 +609,28 @@ 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.+ // Opt-in material consolidation (default off => byte-identical to today). Runs+ // after dedup so palette() works on the already-merged material set. Failure is+ // swallowed with a warning — the dedup'd GLB is still valid.+ const optimizeMode = resolveOptimize(opts.optimize);+ let optimize: OptimizeSummary | undefined;+ if (optimizeMode !== 'off') {+ try {+ optimize = await consolidateMaterials(doc, optimizeMode);+ } catch (err) {+ warnings.push(`optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ }++ // Instanceability metrics, measured against the post-dedup() (and post-optimize,+ // when enabled) 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. Triangle count can change under `full` (join welds+ // primitives), so derive it from the final Document rather than the pre-bake tris.let instanceability: InstanceabilityReport | undefined;let metricsError: string | undefined;try {- const metrics: InstanceabilityMetrics = collectGlbMetrics(doc, tris);+ const metrics: InstanceabilityMetrics = collectGlbMetrics(doc, optimize ? undefined : tris);instanceability = gradeInstanceability(metrics, { category: opts.category });} catch (err) {metricsError = err instanceof Error ? err.message : String(err);@@ -534,7 +639,7 @@ export async function renderSceneToGLB(const io = new WebIO();const bytes = await io.writeBinary(doc);- return { bytes, tris, warnings, instanceability, metricsError };+ return { bytes, tris, warnings, instanceability, metricsError, ...(optimize ? { optimize } : {}) };}/**@@ -546,12 +651,13 @@ export async function renderSceneToGLB(** Pure function: no file I/O, no globals, no WebGL.*/-export async function renderGLB(code: string): Promise<RenderResult> {+export async function renderGLB(code: string, opts: { optimize?: OptimizeMode } = {}): Promise<RenderResult> {const { meta, root, clips, primitiveUsage } = await executeKilnCode(code);const scene = await renderSceneToGLB(root, {sceneName: meta.name || 'Scene',clips,category: typeof meta.category === 'string' ? meta.category : undefined,+ ...(opts.optimize ? { optimize: opts.optimize } : {}),});return {@@ -563,6 +669,7 @@ export async function renderGLB(code: string): Promise<RenderResult> {primitiveUsage,...(scene.instanceability ? { instanceability: scene.instanceability } : {}),...(scene.metricsError ? { metricsError: scene.metricsError } : {}),+ ...(scene.optimize ? { optimize: scene.optimize } : {}),},warnings: scene.warnings,};@@ -589,6 +696,49 @@ export async function gradeGlbBytes(}}+/** Result of {@link optimizeGlbBytes}: the consolidated GLB + its re-graded report. */+export interface OptimizeGlbResult {+ /** The consolidated GLB bytes. */+ bytes: Uint8Array;+ /** Instanceability report recomputed on the optimized bytes. */+ report?: InstanceabilityReport;+ /** What the pass did. */+ summary: OptimizeSummary;+}++/**+ * Consolidate materials in a finished GLB, working from bytes — the web-side+ * counterpart to {@link renderGLB}'s bake-time `optimize` option.+ *+ * Used by Kiln Studio: the AgentCore runtime returns an un-optimized GLB, and the+ * web tier re-bakes it here before persisting, so consolidation reaches prod with+ * NO wire bump / runtime change (the runtime never sees an `optimize` flag). Same+ * `consolidateMaterials` pass + re-grade as the render path. Pure read+write:+ * parses the GLB, transforms, re-serializes; returns `undefined` if the bytes+ * can't be parsed or the transform throws (caller keeps the original GLB).+ */+export async function optimizeGlbBytes(+ bytes: Uint8Array,+ opts: { mode?: 'palette' | 'full'; category?: string } = {},+): Promise<OptimizeGlbResult | undefined> {+ const mode = opts.mode ?? 'palette';+ try {+ const io = new WebIO();+ const doc = await io.readBinary(bytes);+ const summary = await consolidateMaterials(doc, mode);+ const outBytes = await io.writeBinary(doc);+ let report: InstanceabilityReport | undefined;+ try {+ report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });+ } catch {+ report = undefined;+ }+ return { bytes: outBytes, ...(report ? { report } : {}), summary };+ } catch {+ return undefined;+ }+}+// =============================================================================// Runtime-aware animation inspection// =============================================================================