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-studio): Scenes composer + custom palettes + per-row batch + walkable explore
Matt Kissinger22a9924be2b1
diff --git a/__tests__/scene-palette.test.ts b/__tests__/scene-palette.test.tsnew file mode 100644index 00000000..48472bb6--- /dev/null+++ b/__tests__/scene-palette.test.ts@@ -0,0 +1,182 @@+/**+ * Scene palettes — the configurable-palette snap + scene composition primitives.+ *+ * Covers:+ * - palette-snap pure math: hex→linear, kind-aware chooseSlot (greens→green,+ * neutrals→neutral, emissive→glow, transparent→glass)+ * - snapGlbToPalette: rewrites a finished GLB's flat materials to a user palette,+ * collapses the material count, re-grades; undefined on junk bytes / empty palette+ * - composeSceneGLB: merges N placed GLBs into one (transforms applied, rotation→quat,+ * dedup collapses repeated blueprints, animations dropped by default)+ * - renderPaletteDirective(slots) generalizes to a custom palette+ */+import { describe, it, expect } from 'bun:test';+import * as THREE from 'three';+import { WebIO } from '@gltf-transform/core';+import {+ createRoot,+ createPart,+ boxGeo,+ gameMaterial,+ glassMaterial,+} from '../primitives';+import {+ renderSceneToGLB,+ snapGlbToPalette,+ composeSceneGLB,+ type SnapPaletteSlot,+} from '../render';+import { collectGlbMetrics } from '../metrics';+import { hexToLinearRgb, buildSlotIndex, chooseSlot } from '../palette-snap';+import { renderPaletteDirective, OPTIMIZED_PALETTE } from '../palette';++const hue = (i: number, n: number): number => new THREE.Color().setHSL(i / n, 0.7, 0.5).getHex();++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;+}++const PAL: SnapPaletteSlot[] = [+ { color: '#e8e8e6' }, // 0 white+ { color: '#1a1c1f' }, // 1 black+ { color: '#4f8f3f' }, // 2 green+ { color: '#b8584a' }, // 3 red+ { color: '#2f6fd0' }, // 4 blue+ { color: '#cdb27a' }, // 5 sand+];++describe('palette-snap (pure)', () => {+ it('hexToLinearRgb maps the endpoints', () => {+ expect(hexToLinearRgb('#000000')).toEqual([0, 0, 0]);+ const w = hexToLinearRgb('#ffffff');+ expect(w[0]).toBeCloseTo(1, 5);+ expect(w[1]).toBeCloseTo(1, 5);+ expect(w[2]).toBeCloseTo(1, 5);+ // shorthand + missing-hash both parse+ expect(hexToLinearRgb('fff')).toEqual(hexToLinearRgb('#ffffff'));+ });++ it('chooseSlot routes by hue, not lightness (greens→green, reds→red)', () => {+ const idx = buildSlotIndex(PAL);+ const pick = (hex: string) => chooseSlot(idx, { baseLinear: hexToLinearRgb(hex) });+ expect(pick('#3a8f30')).toBe(2); // a green → green+ expect(pick('#c23a2a')).toBe(3); // a red → red+ expect(pick('#3a5fc0')).toBe(4); // a blue → blue+ });++ it('neutrals snap to neutral slots (a grey never picks up a tint)', () => {+ const idx = buildSlotIndex(PAL);+ const pick = chooseSlot(idx, { baseLinear: hexToLinearRgb('#8a8a8a') });+ expect(pick).toBeDefined();+ expect([0, 1]).toContain(pick!); // white or black, never green/red/blue+ });++ it('emissive → glow slot, transparent → glass slot when present', () => {+ const idx = buildSlotIndex([+ { color: '#888888' },+ { color: '#aacbe0', kind: 'glass' },+ { color: '#ffd9a0', kind: 'glow' },+ ]);+ expect(chooseSlot(idx, { baseLinear: [0.1, 0.1, 0.1], emissiveLinear: [0.8, 0.6, 0.3] })).toBe(2);+ expect(chooseSlot(idx, { baseLinear: [0.5, 0.6, 0.7], transparent: true })).toBe(1);+ expect(chooseSlot(idx, { baseLinear: [0.05, 0.05, 0.05] })).toBe(0); // opaque fallback+ });+});++describe('snapGlbToPalette', () => {+ it('rewrites flat materials to the palette and collapses the material count', async () => {+ const baked = await renderSceneToGLB(manyColorScene(14));+ expect(baked.instanceability!.grade).toBe('F'); // 14 distinct materials++ const out = await snapGlbToPalette(baked.bytes, PAL, { category: 'prop' });+ expect(out).toBeDefined();+ expect(out!.snapped).toBe(14);+ expect(out!.skipped).toBe(0);+ expect(out!.summary.materialsBefore).toBe(14);+ // 14 distinct hues collapse to ≤ the palette's slot count (here they land on 4 slots),+ // lifting the grade off F — the snap's guarantee is a bounded, coherent material set.+ expect(out!.report!.metrics.uniqueMaterials).toBeLessThanOrEqual(PAL.length);+ expect(out!.summary.materialsAfter).toBeLessThan(out!.summary.materialsBefore);+ expect(out!.report!.grade).not.toBe('F');+ // valid GLB out+ const doc = await new WebIO().readBinary(out!.bytes);+ expect(doc.getRoot().listNodes().length).toBeGreaterThan(0);+ });++ it('snaps a transparent material to the glass slot (transparency preserved)', async () => {+ const root = createRoot('Glassy');+ for (let i = 0; i < 6; i++) {+ createPart(`Wall${i}`, boxGeo(1, 1, 1), gameMaterial(hue(i, 6)), { 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 baked = await renderSceneToGLB(root);+ const palWithGlass: SnapPaletteSlot[] = [...PAL, { color: '#aacbe0', kind: 'glass', opacity: 0.4 }];+ const out = await snapGlbToPalette(baked.bytes, palWithGlass);+ expect(out!.report!.metrics.transparentMaterials).toBeGreaterThanOrEqual(1);+ });++ it('returns undefined on junk bytes or an empty palette', async () => {+ expect(await snapGlbToPalette(new Uint8Array([1, 2, 3, 4]), PAL)).toBeUndefined();+ const baked = await renderSceneToGLB(manyColorScene(3));+ expect(await snapGlbToPalette(baked.bytes, [])).toBeUndefined();+ });+});++describe('composeSceneGLB', () => {+ async function glbOf(scene: THREE.Object3D): Promise<Uint8Array> {+ return (await renderSceneToGLB(scene)).bytes;+ }++ it('merges parts, applies transforms, and sums triangles', async () => {+ const a = await glbOf(manyColorScene(3));+ const b = await glbOf((() => { const r = createRoot('B'); createPart('BBox', boxGeo(2, 2, 2), gameMaterial(0x4444ff), { parent: r }); return r; })());+ const aTris = (await renderSceneToGLB(manyColorScene(3))).tris;++ const out = await composeSceneGLB([+ { bytes: a, transform: { pos: [0, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] }, name: 'PLACE_A' },+ { bytes: b, transform: { pos: [10, 0, 0], rotDeg: [0, 90, 0], scale: [1, 1, 1] }, name: 'PLACE_B' },+ ]);+ expect(out.tris).toBe(aTris + 12); // a 2×2×2 box = 12 tris+ expect(out.draws).toBeGreaterThan(0);++ // The wrapper node carries the placement transform (pos + a 90° Y quaternion). Use a+ // unique name so it can't collide with a source GLB's own root node.+ const doc = await new WebIO().readBinary(out.bytes);+ const bNode = doc.getRoot().listNodes().find((nd) => nd.getName() === 'PLACE_B');+ expect(bNode).toBeDefined();+ const t = bNode!.getTranslation();+ expect(t[0]).toBeCloseTo(10, 4);+ const q = bNode!.getRotation();+ expect(q[1]).toBeCloseTo(Math.SQRT1_2, 3); // y of a 90° Y rotation+ expect(q[3]).toBeCloseTo(Math.SQRT1_2, 3); // w+ });++ it('dedup collapses a repeated blueprint (same GLB placed twice shares geometry)', async () => {+ const a = await glbOf((() => { const r = createRoot('One'); createPart('Box', boxGeo(1, 1, 1), gameMaterial(0x808080), { parent: r }); return r; })());+ const out = await composeSceneGLB([+ { bytes: a, transform: { pos: [0, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] } },+ { bytes: a, transform: { pos: [5, 0, 0], rotDeg: [0, 0, 0], scale: [1, 1, 1] } },+ ]);+ const metrics = collectGlbMetrics(await new WebIO().readBinary(out.bytes));+ expect(metrics.uniqueGeometries).toBe(1); // two placements, one shared geometry+ expect(metrics.triangles).toBe(24); // both boxes still drawn (12 each)+ });+});++describe('renderPaletteDirective(slots)', () => {+ it('defaults to the canonical palette and adapts to a custom one', () => {+ expect(renderPaletteDirective()).toBe(renderPaletteDirective(OPTIMIZED_PALETTE));+ const custom = renderPaletteDirective([+ { index: 0, name: 'siding-mint', color: '#9fc9a3', metalness: 0, roughness: 0.8, use: 'house siding' },+ { index: 1, name: 'asphalt', color: '#45454a', metalness: 0, roughness: 0.9, use: 'road' },+ ]);+ expect(custom).toContain('siding-mint: house siding');+ expect(custom).toContain('asphalt: road');+ // no glass/glow slot → directive says keep everything opaque, names no glass role+ expect(custom).toContain('no transparent role');+ });+});diff --git a/palette-snap.ts b/palette-snap.tsnew file mode 100644index 00000000..2ca0bfa4--- /dev/null+++ b/palette-snap.ts@@ -0,0 +1,173 @@+/**+ * Palette snap — the pure OKLab nearest-slot algorithm, generalized to ANY+ * caller-supplied palette.+ *+ * This is the server/core mirror anticipated by the Kiln City frontend palette+ * (`packages/kiln-studio/frontend/src/city/palette.ts` — "the configurable-palettes+ * arc generalizes it… a server/core mirror of the slot DATA gets a parity test").+ * The city snaps THREE materials at render time to the fixed 30-slot Kiln City set;+ * this snaps a finished GLB's materials at BAKE time to a user-defined scene palette.+ * Same perceptual math, so a given hex routes to the same slot in both worlds.+ *+ * PURE: no `three`, no node, no gltf-transform. The sRGB→linear transfer function+ * is reproduced inline (it's exactly what THREE.Color + ColorManagement applies),+ * so a slot hex converts to the identical linear OKLab the city computes. The+ * caller (render.ts `snapGlbToPalette`) reads gltf-transform's LINEAR baseColor /+ * emissive factors and feeds them straight in.+ */++export type SnapSlotKind = 'opaque' | 'glass' | 'glow';++/** The minimum a slot needs for the snap: a color + an optional kind. */+export interface SnapSlot {+ /** sRGB hex (e.g. `#9fc9a3`). */+ color: string;+ /** Defaults to 'opaque'. transparent→glass, emissive→glow. */+ kind?: SnapSlotKind;+}++export type Vec3 = [number, number, number];++// ── sRGB → linear. Matches three's SRGBToLinear (the gamma transfer function),+// so a slot hex yields the same linear value the GLB's linear factors carry. ──+function srgbChannelToLinear(c: number): number {+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);+}++/** Parse an sRGB hex (`#rrggbb` or `rrggbb`) to LINEAR RGB in [0..1]. */+export function hexToLinearRgb(hex: string): Vec3 {+ const h = hex.trim().replace(/^#/, '');+ const full = h.length === 3 ? h[0]! + h[0]! + h[1]! + h[1]! + h[2]! + h[2]! : h;+ const n = Number.parseInt(full.slice(0, 6).padEnd(6, '0'), 16);+ const r = ((n >> 16) & 0xff) / 255;+ const g = ((n >> 8) & 0xff) / 255;+ const b = (n & 0xff) / 255;+ return [srgbChannelToLinear(r), srgbChannelToLinear(g), srgbChannelToLinear(b)];+}++// ── OKLab (Björn Ottosson). Inputs are LINEAR sRGB [0..1]. Ported verbatim from+// the Kiln City palette so the two snaps agree. ──+export function linToOklab(r: number, g: number, b: number): Vec3 {+ const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;+ const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;+ const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;+ const l_ = Math.cbrt(l), m_ = Math.cbrt(m), s_ = Math.cbrt(s);+ return [+ 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,+ 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,+ ];+}++const dE2 = (a: Vec3, b: Vec3): number => {+ const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];+ return dl * dl + da * da + db * db;+};+// CHROMATIC distance with lightness DOWN-WEIGHTED — full OKLab over-weights L, so a+// dark desaturated green matched a dark BROWN of similar lightness instead of a dark+// GREEN. Weighting hue/chroma above L makes "what colour is it" win over "how bright".+const L_WEIGHT_CHROMA = 0.3;+const dE2Chroma = (a: Vec3, b: Vec3): number => {+ const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];+ return L_WEIGHT_CHROMA * dl * dl + da * da + db * db;+};+const chroma = (lab: Vec3): number => Math.hypot(lab[1], lab[2]);+// Lightness-compensated chroma gate — OKLab chroma compresses at low lightness, so an+// absolute gate misreads dark muted colors (dark green leaf / brown bark read as "grey"+// and snap to black). Normalizing by lightness keeps "is this colored?" stable dark↔light.+const REL_CHROMA_GATE = 0.04;+const relChroma = (lab: Vec3): number => chroma(lab) / Math.max(lab[0], 0.25);++interface SlotLab { i: number; lab: Vec3 }++/** Precomputed OKLab partition of a palette — built once per snap, reused per material. */+export interface SlotIndex {+ slots: readonly SnapSlot[];+ /** All opaque slots (fallback when a partition is empty). */+ opaque: SlotLab[];+ /** Opaque NEUTRAL slots (greys/white/black) — snapped by full dE2 (lightness IS the discriminator). */+ neutral: SlotLab[];+ /** Opaque CHROMATIC slots — snapped by hue-weighted dE2Chroma (so greens→greens). */+ chromatic: SlotLab[];+ /** Glass (transparent) slot indices. */+ glass: number[];+ /** Glow (emissive) slots — snapped by base/emissive color. */+ glow: SlotLab[];+}++/** Partition a palette into neutral/chromatic/glass/glow OKLab candidate lists. */+export function buildSlotIndex(slots: readonly SnapSlot[]): SlotIndex {+ const opaque: SlotLab[] = [];+ const neutral: SlotLab[] = [];+ const chromatic: SlotLab[] = [];+ const glass: number[] = [];+ const glow: SlotLab[] = [];+ slots.forEach((s, i) => {+ const kind = s.kind ?? 'opaque';+ const [r, g, b] = hexToLinearRgb(s.color);+ const lab = linToOklab(r, g, b);+ if (kind === 'glass') { glass.push(i); return; }+ if (kind === 'glow') { glow.push({ i, lab }); return; }+ opaque.push({ i, lab });+ if (relChroma(lab) >= REL_CHROMA_GATE) chromatic.push({ i, lab });+ else neutral.push({ i, lab });+ });+ return { slots, opaque, neutral, chromatic, glass, glow };+}++function nearestIn(cands: SlotLab[], lab: Vec3, dist: (a: Vec3, b: Vec3) => number): number {+ let best = cands[0]!.i, bd = Infinity;+ for (const c of cands) { const d = dist(c.lab, lab); if (d < bd) { bd = d; best = c.i; } }+ return best;+}++/** Nearest OPAQUE slot index for a LINEAR-RGB color (OKLab + chroma gate). */+export function nearestOpaqueSlot(idx: SlotIndex, lin: Vec3): number | undefined {+ if (idx.opaque.length === 0) return undefined;+ const lab = linToOklab(lin[0], lin[1], lin[2]);+ if (relChroma(lab) >= REL_CHROMA_GATE) {+ return idx.chromatic.length ? nearestIn(idx.chromatic, lab, dE2Chroma) : nearestIn(idx.opaque, lab, dE2);+ }+ return idx.neutral.length ? nearestIn(idx.neutral, lab, dE2) : nearestIn(idx.opaque, lab, dE2);+}++/** Nearest GLOW slot index for a linear emissive color (or `undefined` if the palette has none). */+export function nearestGlowSlot(idx: SlotIndex, emissiveLin: Vec3): number | undefined {+ if (idx.glow.length === 0) return undefined;+ return nearestIn(idx.glow, linToOklab(emissiveLin[0], emissiveLin[1], emissiveLin[2]), dE2);+}++/** Classification inputs read off a material (all LINEAR). */+export interface MaterialColor {+ baseLinear: Vec3;+ emissiveLinear?: Vec3;+ transparent?: boolean;+}++/**+ * Choose the palette slot a material snaps to, kind-aware:+ * emissive (with a glow slot) → nearest glow; transparent (with a glass slot) → glass;+ * else → nearest opaque. Returns the slot index, or `undefined` when the palette has+ * no eligible slot (caller leaves the material unchanged).+ */+export function chooseSlot(idx: SlotIndex, m: MaterialColor): number | undefined {+ const emi = m.emissiveLinear;+ const isEmissive = !!emi && (emi[0] > 0.0025 || emi[1] > 0.0025 || emi[2] > 0.0025);+ if (isEmissive) {+ const g = nearestGlowSlot(idx, emi!);+ if (g !== undefined) return g;+ }+ if (m.transparent && idx.glass.length > 0) {+ // Pick the glass slot nearest the source base color (palettes rarely have >1).+ if (idx.glass.length === 1) return idx.glass[0];+ const lab = linToOklab(m.baseLinear[0], m.baseLinear[1], m.baseLinear[2]);+ let best = idx.glass[0]!, bd = Infinity;+ for (const gi of idx.glass) {+ const [r, g, b] = hexToLinearRgb(idx.slots[gi]!.color);+ const d = dE2(linToOklab(r, g, b), lab);+ if (d < bd) { bd = d; best = gi; }+ }+ return best;+ }+ return nearestOpaqueSlot(idx, m.baseLinear);+}diff --git a/palette.ts b/palette.tsindex 99cd8732..213daad5 100644--- a/palette.ts+++ b/palette.ts@@ -72,15 +72,30 @@ export const OPTIMIZED_PALETTE: readonly PaletteSlot[] = [/*** 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).+ * "Optimized palette" toggle is on (or a custom scene palette is chosen). 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 per role (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.+ * Pass `slots` to point the directive at a user-defined scene palette (the+ * configurable-palettes arc); the default is the canonical {@link OPTIMIZED_PALETTE}.+ * The glass/glow sentences adapt to whether the palette actually has such a slot, so+ * a custom palette without transparent/emissive roles doesn't name a role that isn't+ * there. Deterministic; the kiln-studio `OPTIMIZED_PALETTE_DIRECTIVE` mirror (no-arg+ * call) 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');+export function renderPaletteDirective(slots: readonly PaletteSlot[] = OPTIMIZED_PALETTE): string {+ const lines = slots.map((s) => `- ${s.name}: ${s.use}`).join('\n');+ const glass = slots.find((s) => s.transparent);+ const glow = slots.find((s) => s.emissive);+ const glassSentence = glass+ ? `"${glass.name}" is the ONLY transparent material — use it for every window, lens, or ` ++ 'see-through part and nothing else; keep all other materials fully opaque. '+ : 'Keep every material fully opaque (this palette has no transparent role). ';+ const glowSentence = glow+ ? `"${glow.name}" is the ONLY emissive material — use it for anything that should look lit ` ++ '(lamps, fire cores, neon, magic). '+ : '';return ('## Optimized, instanceable build\n' +'A game-ready asset is cheap to render in bulk when its parts SHARE materials and SHARE ' +@@ -92,9 +107,9 @@ export function renderPaletteDirective(): string {`${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). ' ++ 'merged. ' ++ glassSentence ++ glowSentence +'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, ' +diff --git a/render.ts b/render.tsindex 891c7055..d4e7e658 100644--- a/render.ts+++ b/render.ts@@ -12,7 +12,14 @@import * as THREE from 'three';import { Document, WebIO } from '@gltf-transform/core';-import { dedup, palette, flatten, join, weld, prune } from '@gltf-transform/functions';+import { dedup, palette, flatten, join, weld, prune, mergeDocuments } from '@gltf-transform/functions';++import {+ buildSlotIndex,+ chooseSlot,+ hexToLinearRgb,+ type SnapSlot,+} from './palette-snap';import {buildSandboxGlobals,@@ -37,6 +44,7 @@ type GtMesh = import('@gltf-transform/core').Mesh;type GtMaterial = import('@gltf-transform/core').Material;type GtBuffer = import('@gltf-transform/core').Buffer;type GtTexture = import('@gltf-transform/core').Texture;+type GtScene = import('@gltf-transform/core').Scene;// Accessor.Type is typed as Record<string, AccessorType> which runs afoul of// noUncheckedIndexedAccess. Use the literal strings directly - same values,@@ -739,6 +747,250 @@ export async function optimizeGlbBytes(}}+// =============================================================================+// Palette snap (scene palettes) — web-side hard snap to a user-defined palette+// =============================================================================++/** One slot the GLB snap targets: a color + kind + optional PBR/opacity. */+export interface SnapPaletteSlot {+ /** sRGB hex (e.g. `#9fc9a3`). */+ color: string;+ /** Defaults to 'opaque'. transparent material → glass, emissive → glow. */+ kind?: 'opaque' | 'glass' | 'glow';+ metalness?: number;+ roughness?: number;+ /** Opacity for a glass slot (default 0.4). */+ opacity?: number;+}++/** Result of {@link snapGlbToPalette}. */+export interface SnapGlbResult {+ /** The snapped + consolidated GLB bytes. */+ bytes: Uint8Array;+ /** Instanceability report recomputed on the snapped bytes. */+ report?: InstanceabilityReport;+ /** What the consolidation pass did. */+ summary: OptimizeSummary;+ /** Materials whose color was rewritten to a slot. */+ snapped: number;+ /** Materials left unchanged (textured / hero, or no eligible slot). */+ skipped: number;+}++/**+ * Hard-snap a finished GLB's materials to a user-defined palette — the bake-time,+ * persisted counterpart of the Kiln City frontend snap. Each flat-color material's+ * base color is rewritten to the perceptually-nearest slot (OKLab, via+ * {@link chooseSlot}) and its PBR set from that slot, so a whole batch generated+ * against one palette lands on exactly those colors and collapses (after+ * `consolidateMaterials`) to ~one material per slot — "reads as one place" + a few+ * draws. Textured / hero materials are left untouched (they carry their own color).+ *+ * Pure read+write (parses GLB, rewrites, re-serializes); returns `undefined` if the+ * bytes can't be parsed or the transform throws (caller keeps the original GLB),+ * mirroring {@link optimizeGlbBytes}.+ */+export async function snapGlbToPalette(+ bytes: Uint8Array,+ slots: readonly SnapPaletteSlot[],+ opts: { category?: string } = {},+): Promise<SnapGlbResult | undefined> {+ if (slots.length === 0) return undefined;+ try {+ const io = new WebIO();+ const doc = await io.readBinary(bytes);+ const before = collectGlbMetrics(doc);+ const idx = buildSlotIndex(slots as readonly SnapSlot[]);+ let snapped = 0;+ let skipped = 0;+ for (const mat of doc.getRoot().listMaterials()) {+ // Hero exception — never recolor a textured material (it carries its own color).+ if (mat.getBaseColorTexture()) { skipped++; continue; }+ const base = mat.getBaseColorFactor();+ const emissive = mat.getEmissiveFactor();+ const transparent = mat.getAlphaMode() === 'BLEND' || mat.getAlpha() < 0.98;+ const slotI = chooseSlot(idx, {+ baseLinear: [base[0], base[1], base[2]],+ emissiveLinear: [emissive[0], emissive[1], emissive[2]],+ transparent,+ });+ if (slotI === undefined) { skipped++; continue; }+ const slot = slots[slotI]!;+ const kind = slot.kind ?? 'opaque';+ const [lr, lg, lb] = hexToLinearRgb(slot.color);+ const alpha = kind === 'glass' ? (slot.opacity ?? 0.4) : 1;+ mat.setBaseColorFactor([lr, lg, lb, alpha]);+ mat.setMetallicFactor(slot.metalness ?? 0);+ mat.setRoughnessFactor(slot.roughness ?? (kind === 'glass' ? 0.1 : 0.85));+ if (kind === 'glass') mat.setAlphaMode('BLEND');+ else if (mat.getAlphaMode() === 'BLEND') mat.setAlphaMode('OPAQUE');+ // Glow keeps a "lit" look by emitting its slot color; clear stray emissive otherwise.+ mat.setEmissiveFactor(kind === 'glow' ? [lr, lg, lb] : [0, 0, 0]);+ snapped++;+ }+ // Snapping made many materials value-identical — dedup merges those objects first+ // (palette() alone keeps distinct objects), then consolidate collapses further.+ await doc.transform(dedup());+ await consolidateMaterials(doc, 'palette');+ // Summary spans the WHOLE snap (original → final), not just the consolidation sub-step,+ // so provenance shows the true material collapse (e.g. 14 → 4).+ const after = collectGlbMetrics(doc);+ const summary: OptimizeSummary = {+ mode: 'palette',+ materialsBefore: before.uniqueMaterials,+ materialsAfter: after.uniqueMaterials,+ drawsBefore: before.drawCalls,+ drawsAfter: after.drawCalls,+ };+ const outBytes = await io.writeBinary(doc);+ let report: InstanceabilityReport | undefined;+ try {+ report = gradeInstanceability(after, { category: opts.category });+ } catch {+ report = undefined;+ }+ return { bytes: outBytes, ...(report ? { report } : {}), summary, snapped, skipped };+ } catch {+ return undefined;+ }+}++// =============================================================================+// Scene composition — merge N placed GLBs into one scene GLB (export)+// =============================================================================++/** One placed asset to compose into the scene: its GLB bytes + a world transform. */+export interface SceneComposePart {+ bytes: Uint8Array;+ transform: {+ /** World position [x, y, z], engine frame (+X fwd, +Y up, ground Y=0), meters. */+ pos: [number, number, number];+ /** Euler rotation in DEGREES, XYZ order (the Kiln/Placement convention). */+ rotDeg: [number, number, number];+ /** Per-axis scale. */+ scale: [number, number, number];+ };+ /** Wrapper node name (e.g. an instanceId) — a debug aid in the exported file. */+ name?: string;+}++export interface SceneComposeOptions {+ /** glTF scene name. Default 'Scene'. */+ sceneName?: string;+ /** Material consolidation across the merged scene. Default 'palette' (a few draws). */+ optimize?: OptimizeMode;+ /** Keep each asset's animation clips. Default false (static dressing). */+ keepAnimations?: boolean;+}++export interface SceneComposeResult {+ /** The composed scene GLB bytes. */+ bytes: Uint8Array;+ tris: number;+ /** Draw calls in the composed scene (post-optimize). */+ draws: number;+ /** Distinct materials in the composed scene (post-optimize). */+ materials: number;+ /** Per-part skip notes + transform warnings (never throws on one bad part). */+ warnings: string[];+}++/** Euler degrees (XYZ) → a glTF quaternion [x, y, z, w] via THREE (the viewer's frame). */+function eulerDegToQuat(deg: [number, number, number]): [number, number, number, number] {+ const e = new THREE.Euler(+ THREE.MathUtils.degToRad(deg[0]),+ THREE.MathUtils.degToRad(deg[1]),+ THREE.MathUtils.degToRad(deg[2]),+ 'XYZ',+ );+ const q = new THREE.Quaternion().setFromEuler(e);+ return [q.x, q.y, q.z, q.w];+}++/**+ * Compose N placed GLBs into a single scene GLB — the Scenes-page export primitive.+ *+ * Pure gltf-transform (no THREE GLTFLoader, whose texture path is browser-DOM-bound):+ * each part's bytes are read into a Document, `mergeDocuments` copies its graph into a+ * master Document (textures copied as bytes, lossless), and its scene roots are+ * reparented under a fresh transform node carrying the placement's TRS. One merge per+ * placement (a Node can't have two parents); a final `dedup()` collapses repeated+ * blueprints (e.g. 30 identical fence posts) and `consolidateMaterials` keeps the+ * export to a few draws. A corrupt/unreadable part becomes a warning and is skipped,+ * never failing the whole export.+ *+ * Runs under Bun in the web tier (same WebIO read→transform→write path as+ * {@link optimizeGlbBytes}). Pure: no fs / globals / WebGL.+ */+export async function composeSceneGLB(+ parts: readonly SceneComposePart[],+ opts: SceneComposeOptions = {},+): Promise<SceneComposeResult> {+ const warnings: string[] = [];+ const io = new WebIO();+ const master = new Document();+ const masterScene = master.createScene(opts.sceneName ?? 'Scene');+ let composed = 0;++ for (let i = 0; i < parts.length; i++) {+ const part = parts[i]!;+ try {+ const src = await io.readBinary(part.bytes);+ const srcScene = src.getRoot().listScenes()[0];+ const map = mergeDocuments(master, src);+ const wrap = master+ .createNode(part.name ?? `part_${i}`)+ .setTranslation([part.transform.pos[0], part.transform.pos[1], part.transform.pos[2]])+ .setRotation(eulerDegToQuat(part.transform.rotDeg))+ .setScale([part.transform.scale[0], part.transform.scale[1], part.transform.scale[2]]);+ const mergedScene = srcScene ? (map.get(srcScene) as GtScene | undefined) : undefined;+ if (mergedScene) {+ for (const child of mergedScene.listChildren()) wrap.addChild(child);+ mergedScene.dispose();+ }+ masterScene.addChild(wrap);+ composed++;+ } catch (err) {+ warnings.push(`part ${i} (${part.name ?? ''}) skipped: ${err instanceof Error ? err.message : String(err)}`);+ }+ }++ if (composed === 0) throw new Error('composeSceneGLB: no parts could be merged');++ // Static dressing has no shared timeline — drop per-asset clips unless asked to keep.+ if (!opts.keepAnimations) {+ for (const anim of master.getRoot().listAnimations()) anim.dispose();+ }++ try {+ await master.transform(dedup());+ } catch (err) {+ warnings.push(`dedup failed: ${err instanceof Error ? err.message : String(err)}`);+ }++ const optimizeMode: OptimizeMode = opts.optimize ?? 'palette';+ if (optimizeMode !== 'off') {+ try {+ await consolidateMaterials(master, optimizeMode);+ } catch (err) {+ warnings.push(`optimize (${optimizeMode}) failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ }++ // mergeDocuments brings each source's Buffer across, but a GLB allows ≤1 buffer.+ // Reassign every accessor to the first buffer and drop the rest.+ const rootBuffers = master.getRoot().listBuffers();+ if (rootBuffers.length > 1) {+ const main = rootBuffers[0]!;+ for (const acc of master.getRoot().listAccessors()) acc.setBuffer(main);+ for (let i = 1; i < rootBuffers.length; i++) rootBuffers[i]!.dispose();+ }++ const metrics = collectGlbMetrics(master);+ const bytes = await io.writeBinary(master);+ return { bytes, tris: metrics.triangles, draws: metrics.drawCalls, materials: metrics.uniqueMaterials, warnings };+}+// =============================================================================// Runtime-aware animation inspection// =============================================================================