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: M1c GPU-instancing pass + M3 composer role/tier awareness (v0.4.0)

Matt Kissingerd4f9af479b2b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3fe9a305..bd626188 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,34 @@ for the consuming app's lockfile + tarball provenance, not public npm releases.
## [Unreleased]
+## [0.4.0] — 2026-07-02
+
+### Added
+- **M1c GPU-instancing pass (plan/05 §3.3).** `renderSceneToGLB`/`renderGLB` gain an
+ `instance: 'off' | 'auto' | 'on'` option (default `auto` = only `role: 'fill'` assets)
+ and `optimizeGlbBytes` gains `{ instance, role }` — the web-tier re-bake seam, so the
+ pass reaches prod with no wire change. Repeated geometry (>= 5 nodes sharing one mesh
+ after dedup) is rewritten to `EXT_mesh_gpu_instancing` batches in the upstream-canonical
+ `dedup → instance → palette` order, cutting draw calls + bytes for fence runs /
+ colonnades / container stacks. **Perf/filesize only — the A–F grade keys on material
+ count and does not move** (tests assert grade + triangle parity). Skipped for
+ animated/skinned docs and any asset carrying `Joint*` pivot names (Kiln City targets
+ those by name). Results are recorded as `InstancingSummary` (`meta.instancing`,
+ `RenderSceneResult.instancing`, `OptimizeGlbResult.instancing` — and
+ `OptimizeGlbResult.summary` is now optional: an instancing-only pass has no
+ consolidation summary). All engine glTF IO now registers `EXTMeshGPUInstancing`
+ (new dep `@gltf-transform/extensions`) so re-reads (grade-from-bytes,
+ optimize-from-bytes, palette snap, scene export merge) preserve the batches, and
+ `collectGlbMetrics` is instance-aware (an instanced node counts one draw but N× its
+ triangles — exactly what a supporting GPU renders).
+- **M3 composer role/tier awareness (plan/05 §4.1).** `CatalogEntry` gains optional
+ `role` (`CatalogAssetRole` — the M1d asset taxonomy) + `tier` (A–F); `catalogList()`
+ (and therefore `scene_list_assets`) surfaces them. Placement roles now DEFAULT from
+ the catalog asset's role via `placementRoleForAsset` (wonder/poi → hero, fill → fill,
+ else support) in `place`/`placeExact`/`cluster`/`ring`/`layout` — an explicit agent
+ role still wins. The composer system prompt teaches the mapping, wonder scale-up, and
+ D/F-tier density budgeting.
+
## [0.3.0] — 2026-07-02
### Added
diff --git a/bun.lock b/bun.lock
index 7a523a98..fc54cb8a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6,6 +6,7 @@
"name": "@kiln/engine",
"dependencies": {
"@gltf-transform/core": "^4.4.0",
+ "@gltf-transform/extensions": "^4.4.0",
"@gltf-transform/functions": "^4.4.0",
"@openrouter/ai-sdk-provider": "^2.9.1",
"@types/three": "^0.184.1",
diff --git a/package.json b/package.json
index 7c72735f..9448598f 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "@kiln/engine",
"private": true,
- "version": "0.3.0",
+ "version": "0.4.0",
"description": "Kiln 3D engine — text-to-GLB codegen agent loop, deterministic CPU render/rasterizer, primitive/CSG library, palette + instanceability grading, and pairwise ranking arena. Extracted from pixel-forge.",
"license": "MIT",
"author": "Matthew Kissinger",
@@ -39,6 +39,7 @@
},
"dependencies": {
"@gltf-transform/core": "^4.4.0",
+ "@gltf-transform/extensions": "^4.4.0",
"@gltf-transform/functions": "^4.4.0",
"@openrouter/ai-sdk-provider": "^2.9.1",
"@types/three": "^0.184.1",
diff --git a/src/__tests__/instancing.test.ts b/src/__tests__/instancing.test.ts
index 357e2656..d769dda1 100644
--- a/src/__tests__/instancing.test.ts
+++ b/src/__tests__/instancing.test.ts
@@ -18,7 +18,7 @@ import {
boxGeo,
gameMaterial,
} from '../primitives';
-import { renderSceneToGLB } from '../render';
+import { gradeGlbBytes, optimizeGlbBytes, renderSceneToGLB } from '../render';
describe('Wave 1B: instancing primitives', () => {
it('cloneGeometry and cloneMaterial return the same reference', () => {
@@ -127,3 +127,109 @@ describe('Wave 1B: instancing primitives', () => {
expect(withDedup.bytes.byteLength).toBeLessThan(withoutDedup.bytes.byteLength);
});
});
+
+// ── M1c: the GPU-instancing pass (EXT_mesh_gpu_instancing) ────────────────────
+// Perf/filesize only — the A–F grade keys on material count and must NOT move.
+
+/** A fence run: `count` posts sharing one geometry/material via createInstance,
+ * plus a ground slab so the asset has a second, un-instanced mesh. */
+function fenceScene(count: number, opts: { jointPivot?: boolean } = {}): THREE.Object3D {
+ const r = createRoot('Fence');
+ createPart('Ground', boxGeo(count * 1.2, 0.1, 2), gameMaterial(0x777788), {
+ position: [0, -0.05, 0],
+ parent: r,
+ });
+ const post = createPart('Post0', boxGeo(0.15, 1.2, 0.15), gameMaterial(0x8a5a2b), {
+ position: [0, 0.6, 0],
+ parent: r,
+ });
+ for (let i = 1; i < count; i++) {
+ createInstance(`Post${i}`, post, { position: [i * 1.1, 0.6, 0], parent: r });
+ }
+ if (opts.jointPivot) {
+ const j = new THREE.Object3D();
+ j.name = 'Joint_Gate';
+ r.add(j);
+ }
+ return r;
+}
+
+function glbJson(bytes: Uint8Array): { extensionsUsed?: string[] } {
+ // GLB: 12-byte header, then chunk 0 header (length + 'JSON') + the JSON chunk.
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const jsonLen = view.getUint32(12, true);
+ return JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + jsonLen)));
+}
+
+describe('M1c: GPU-instancing pass (instance option)', () => {
+ it('instance:"on" emits EXT_mesh_gpu_instancing, cuts bytes+draws, keeps tris+grade', async () => {
+ const plain = await renderSceneToGLB(fenceScene(10));
+ const inst = await renderSceneToGLB(fenceScene(10), { instance: 'on' });
+
+ expect(inst.instancing).toBeDefined();
+ expect(inst.instancing!.batches).toBe(1);
+ expect(inst.instancing!.instances).toBe(10);
+ expect(inst.instancing!.drawsAfter).toBeLessThan(inst.instancing!.drawsBefore);
+ expect(glbJson(inst.bytes).extensionsUsed).toContain('EXT_mesh_gpu_instancing');
+ expect(glbJson(plain.bytes).extensionsUsed ?? []).not.toContain('EXT_mesh_gpu_instancing');
+ // Smaller on the wire (10 node TRS records -> 1 batch + accessors).
+ expect(inst.bytes.byteLength).toBeLessThan(plain.bytes.byteLength);
+ // PERF ONLY: rendered-triangle total and the material-count grade are unchanged.
+ expect(inst.instanceability!.metrics.triangles).toBe(plain.instanceability!.metrics.triangles);
+ expect(inst.instanceability!.grade).toBe(plain.instanceability!.grade);
+ });
+
+ it('instance:"auto" acts only for role:"fill"', async () => {
+ const fill = await renderSceneToGLB(fenceScene(10), { instance: 'auto', role: 'fill' });
+ const prop = await renderSceneToGLB(fenceScene(10), { instance: 'auto', role: 'prop' });
+ const none = await renderSceneToGLB(fenceScene(10), { instance: 'auto' });
+ expect(fill.instancing).toBeDefined();
+ expect(prop.instancing).toBeUndefined();
+ expect(none.instancing).toBeUndefined();
+ });
+
+ it('below the min-node threshold nothing is batched', async () => {
+ const few = await renderSceneToGLB(fenceScene(3), { instance: 'on' });
+ expect(few.instancing).toBeUndefined();
+ expect(glbJson(few.bytes).extensionsUsed ?? []).not.toContain('EXT_mesh_gpu_instancing');
+ });
+
+ it('animated docs and Joint_* pivots are never instanced', async () => {
+ const spin = new THREE.NumberKeyframeTrack('Post0.position[y]', [0, 1], [0.6, 0.8]);
+ const clip = new THREE.AnimationClip('bob', 1, [spin]);
+ const animated = await renderSceneToGLB(fenceScene(10), { instance: 'on', clips: [clip] });
+ expect(animated.instancing).toBeUndefined();
+
+ const rigged = await renderSceneToGLB(fenceScene(10, { jointPivot: true }), {
+ instance: 'on',
+ });
+ expect(rigged.instancing).toBeUndefined();
+ });
+
+ it('an instanced GLB round-trips through gradeGlbBytes and optimizeGlbBytes', async () => {
+ const inst = await renderSceneToGLB(fenceScene(10), { instance: 'on' });
+ // Re-grade from bytes (the studio web-side path) — must read the extension,
+ // not drop it, so tris match the logical (instanced-out) total.
+ const report = await gradeGlbBytes(inst.bytes);
+ expect(report).toBeDefined();
+ expect(report!.metrics.triangles).toBe(inst.instanceability!.metrics.triangles);
+ });
+
+ it('optimizeGlbBytes can instance from bytes (web-tier finalize seam)', async () => {
+ const plain = await renderSceneToGLB(fenceScene(10));
+ const out = await optimizeGlbBytes(plain.bytes, {
+ mode: 'off',
+ instance: 'auto',
+ role: 'fill',
+ });
+ expect(out).toBeDefined();
+ expect(out!.instancing).toBeDefined();
+ expect(out!.instancing!.instances).toBe(10);
+ expect(out!.summary).toBeUndefined();
+ expect(glbJson(out!.bytes).extensionsUsed).toContain('EXT_mesh_gpu_instancing');
+ // And a NO-op call (off + non-fill role) keeps the original bytes.
+ expect(
+ await optimizeGlbBytes(plain.bytes, { mode: 'off', instance: 'auto', role: 'prop' }),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/__tests__/optimize.test.ts b/src/__tests__/optimize.test.ts
index 75196591..3f8e19fe 100644
--- a/src/__tests__/optimize.test.ts
+++ b/src/__tests__/optimize.test.ts
@@ -153,7 +153,7 @@ describe('optimizeGlbBytes (web-side path)', () => {
const opt = await optimizeGlbBytes(baked.bytes, { mode: 'palette', category: 'prop' });
expect(opt).toBeDefined();
- expect(opt!.summary.materialsAfter).toBeLessThan(opt!.summary.materialsBefore);
+ 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);
diff --git a/src/composer/agent/prompt.ts b/src/composer/agent/prompt.ts
index 05a00b27..6415f52b 100644
--- a/src/composer/agent/prompt.ts
+++ b/src/composer/agent/prompt.ts
@@ -24,6 +24,8 @@ You may only place assets from this scene's catalog (call scene_list_assets to s
- Facing carries meaning. Turn heroes toward the viewer or a focal point; turn rows and walls to frame a space; face a ring inward or outward on purpose.
- Group what belongs together. A market row, a courtyard, a camp, a motor-court — build it from a cluster/ring or a group so it moves and reads as one unit.
- Use roles: hero (anchors the scene), support (frames + structures it), fill (density + texture).
+- Catalog assets may carry an authored role (wonder/building/poi/prop/fill/vehicle/ground) and a quality tier (A-F) — scene_list_assets shows them. Placement roles default from the asset role automatically (wonder/poi → hero, fill → fill), so trust the defaults and override only with intent. Scale WONDERS UP (1.5-2.5x) so they own the skyline; keep fill near 1x.
+- Budget by tier: A/B assets can repeat freely; place D/F-tier assets sparingly (a few per scene) and never as the hero — they read rough up close.
- Depth and rhythm beat symmetry. Vary distances; avoid a flat even grid unless the scene is literally a grid.
## Fill a believable place — reuse heavily, repeat architecture
diff --git a/src/composer/model.ts b/src/composer/model.ts
index 650a1da0..c0a70d4d 100644
--- a/src/composer/model.ts
+++ b/src/composer/model.ts
@@ -34,15 +34,44 @@ export interface Bbox {
max: Vec3;
}
+/** Asset-role taxonomy — mirrors the engine render meta's `AssetRole` (kept as a
+ * local union so the composer stays dependency-light; compose hosts cast across). */
+export type CatalogAssetRole =
+ | 'ground'
+ | 'building'
+ | 'wonder'
+ | 'poi'
+ | 'prop'
+ | 'fill'
+ | 'vehicle';
+
+/** A–F instanceability grade — mirrors metrics' InstanceabilityGrade. */
+export type CatalogTier = 'A' | 'B' | 'C' | 'D' | 'F';
+
export interface CatalogEntry {
generationId: string;
bbox: Bbox;
name?: string;
tags?: string[];
+ /** Agent-declared asset role (M1d) — drives role-aware layout defaults. */
+ role?: CatalogAssetRole;
+ /** Instanceability grade of the asset (A–F) — drives density budgeting. */
+ tier?: CatalogTier;
}
export type Role = 'hero' | 'support' | 'fill';
+/** Default composer placement role for an asset role (M3 §4.1): wonders and
+ * points-of-interest anchor (hero — extra clearance, scene centre), fill
+ * scatters to the outskirts, everything else frames as support. Undefined
+ * when the asset carries no role (caller falls back to its own default). */
+export function placementRoleForAsset(role: CatalogAssetRole | undefined): Role | undefined {
+ if (!role) return undefined;
+ if (role === 'wonder' || role === 'poi') return 'hero';
+ if (role === 'fill') return 'fill';
+ return 'support';
+}
+
/** Scene-level terrain/sky theme id — mirrors Studio's GroundThemeId (kept local so
* the engine carries no studio dependency; compose.ts casts across the wire). */
export type SceneGroundTheme =
@@ -264,11 +293,20 @@ export class PlacementModel {
this.catalog.set(entry.generationId, entry);
}
- /** The selectable catalog (id, name, footprint, tags). */
- catalogList(): Array<{ generationId: string; name?: string; size: Vec3; tags?: string[] }> {
+ /** The selectable catalog (id, name, footprint, tags, role/tier when known). */
+ catalogList(): Array<{
+ generationId: string;
+ name?: string;
+ size: Vec3;
+ tags?: string[];
+ role?: CatalogAssetRole;
+ tier?: CatalogTier;
+ }> {
return [...this.catalog.values()].map((e) => ({
generationId: e.generationId,
...(e.name ? { name: e.name } : {}),
+ ...(e.role ? { role: e.role } : {}),
+ ...(e.tier ? { tier: e.tier } : {}),
size: [
r1(e.bbox.max[0] - e.bbox.min[0]),
r1(e.bbox.max[1] - e.bbox.min[1]),
@@ -313,6 +351,12 @@ export class PlacementModel {
return this.byAlias.get(target) ?? this.stmts.find((s) => s.stmtId === target);
}
+ /** Role-aware default (M3): explicit agent role wins, else the catalog asset's
+ * role maps to a placement role (wonder/poi → hero, fill → fill), else `fallback`. */
+ private defaultRole(generationId: string, explicit: Role | undefined, fallback: Role): Role {
+ return explicit ?? placementRoleForAsset(this.catalog.get(generationId)?.role) ?? fallback;
+ }
+
// ── add ops (return the new alias; throw on unknown asset) ──────────────────
addPlace(generationId: string, a: PlaceArgs): string {
@@ -323,7 +367,7 @@ export class PlacementModel {
stmtId: this.nextStmtId(),
alias,
generationId,
- role: a.role ?? 'support',
+ role: this.defaultRole(generationId, a.role, 'support'),
scale: a.scale ?? 1,
at: [a.at[0], a.at[1]],
face: a.face ?? 'center',
@@ -344,7 +388,7 @@ export class PlacementModel {
stmtId: this.nextStmtId(),
alias,
generationId,
- role: a.role ?? 'support',
+ role: this.defaultRole(generationId, a.role, 'support'),
scale: a.scale ?? 1,
at: [a.pos[0], a.pos[2]],
face: a.rotYDeg,
@@ -363,7 +407,7 @@ export class PlacementModel {
stmtId: this.nextStmtId(),
alias,
generationId,
- role: a.role ?? 'fill',
+ role: this.defaultRole(generationId, a.role, 'fill'),
scale: a.scale ?? 1,
around: [a.around[0], a.around[1]],
count: Math.max(1, Math.floor(a.count)),
@@ -382,7 +426,7 @@ export class PlacementModel {
stmtId: this.nextStmtId(),
alias,
generationId,
- role: a.role ?? 'support',
+ role: this.defaultRole(generationId, a.role, 'support'),
scale: a.scale ?? 1,
center: [a.center[0], a.center[1]],
count: Math.max(1, Math.floor(a.count)),
@@ -404,7 +448,10 @@ export class PlacementModel {
localMin: e.bbox.min,
localMax: e.bbox.max,
scale: a.scale ?? 1,
- role: a.role ?? 'support',
+ // Per-asset role-aware default (M3): an explicit layout role applies to
+ // all, else each asset's catalog role decides (wonders anchor, fill
+ // scatters) — the dogfood's "scale/hierarchy" fix, now automatic.
+ role: this.defaultRole(g, a.role, 'support'),
...(a.anchor === 'zonedCenters' ? { zone: zones[i % zones.length]!.id } : {}),
};
});
diff --git a/src/metrics.ts b/src/metrics.ts
index eb87fe5f..cea96195 100644
--- a/src/metrics.ts
+++ b/src/metrics.ts
@@ -81,14 +81,30 @@ export function collectGlbMetrics(doc: Document, triangles?: number): Instanceab
// 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.
+ // and the real rendered-triangle total. A node batched by the M1c pass
+ // (EXT_mesh_gpu_instancing) is ONE draw per primitive but renders N copies,
+ // so its triangles multiply by the instance count while drawCalls stay 1 —
+ // exactly what a supporting GPU does with it.
+ const instanceCopies = (node: import('@gltf-transform/core').Node): number => {
+ const ext = node.getExtension('EXT_mesh_gpu_instancing') as {
+ getAttribute?: (name: string) => { getCount(): number } | null;
+ } | null;
+ if (!ext) return 1;
+ return (
+ ext.getAttribute?.('TRANSLATION')?.getCount() ??
+ ext.getAttribute?.('ROTATION')?.getCount() ??
+ ext.getAttribute?.('SCALE')?.getCount() ??
+ 1
+ );
+ };
const visit = (node: import('@gltf-transform/core').Node): void => {
const mesh = node.getMesh();
if (mesh) {
+ const copies = instanceCopies(node);
for (const prim of mesh.listPrimitives()) {
drawCalls += 1;
geomSet.add(prim);
- derivedTris += primTris(prim);
+ derivedTris += primTris(prim) * copies;
const mat = prim.getMaterial();
if (mat) matSet.add(mat);
}
diff --git a/src/render.ts b/src/render.ts
index 69273310..fe6818aa 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -12,8 +12,10 @@
import * as THREE from 'three';
import { Document, WebIO } from '@gltf-transform/core';
+import { EXTMeshGPUInstancing } from '@gltf-transform/extensions';
import {
dedup,
+ instance,
palette,
flatten,
join,
@@ -39,6 +41,14 @@ import {
// between WebIO and NodeIO is irrelevant on the write side. This lets the
// editor's exportGLB() and headless renderGLB() share one bridge.
+/** Engine-standard glTF IO: WebIO with the extensions Kiln GLBs may carry.
+ * EXT_mesh_gpu_instancing must be REGISTERED on the read side or a re-read
+ * (grade-from-bytes, optimize-from-bytes, palette snap) would silently drop
+ * the instancing a prior bake emitted — the batch node would collapse to a
+ * single copy. Write-side registration is harmless (the extension instance
+ * travels on the Document). */
+const engineIO = (): WebIO => new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+
// Gltf-transform type aliases for local readability.
type GtNode = import('@gltf-transform/core').Node;
type GtMesh = import('@gltf-transform/core').Mesh;
@@ -94,6 +104,8 @@ export interface KilnCodeMeta {
metricsError?: string;
/** Set when an opt-in consolidation pass ran (optimize !== 'off'). */
optimize?: OptimizeSummary;
+ /** Set when the GPU-instancing pass created batches (M1c — perf, not grade). */
+ instancing?: InstancingSummary;
[key: string]: unknown;
}
@@ -509,6 +521,27 @@ export interface OptimizeSummary {
drawsAfter: number;
}
+/**
+ * GPU-instancing pass mode (M1c — a PERF/filesize lever, NOT a grade lever; the
+ * A–F grade keys on material count and is unchanged by instancing):
+ * - `off` — never run the pass.
+ * - `auto` — run only for `role: 'fill'` assets (high-repetition scatter is
+ * where batching pays; hero/vehicle assets keep their node graph).
+ * - `on` — always attempt (still skipped for animated/skinned docs and
+ * assets with `Joint_*` pivots — see {@link applyGpuInstancing}).
+ */
+export type InstanceMode = 'off' | 'auto' | 'on';
+
+/** What a GPU-instancing pass did (recorded in provenance / render.meta). */
+export interface InstancingSummary {
+ /** Instanced batch nodes created (one per shared mesh). */
+ batches: number;
+ /** Total node copies folded into those batches. */
+ instances: number;
+ drawsBefore: number;
+ drawsAfter: number;
+}
+
export interface RenderSceneResult {
/** Binary GLB bytes, platform-agnostic (Buffer-compatible in Node). */
bytes: Uint8Array;
@@ -521,6 +554,8 @@ export interface RenderSceneResult {
metricsError?: string;
/** Set when an opt-in consolidation pass ran (optimize !== 'off'). */
optimize?: OptimizeSummary;
+ /** Set when the GPU-instancing pass created batches (instance !== 'off'). */
+ instancing?: InstancingSummary;
}
export interface RenderSceneOptions {
@@ -541,6 +576,15 @@ export interface RenderSceneOptions {
* See {@link OptimizeMode}.
*/
optimize?: OptimizeMode;
+ /**
+ * GPU-instancing pass (EXT_mesh_gpu_instancing) for repeated geometry,
+ * applied between dedup and optimize (the upstream-canonical order:
+ * dedup → instance → palette). Defaults to the `KILN_BAKE_INSTANCE` env
+ * (else `auto`, which only acts for `role: 'fill'`). See {@link InstanceMode}.
+ */
+ instance?: InstanceMode;
+ /** Agent-declared asset role — drives the `instance: 'auto'` gate. */
+ role?: AssetRole;
}
/** Minimum distinct material-value blocks before palette() generates a texture.
@@ -556,6 +600,81 @@ function resolveOptimize(opt?: OptimizeMode): OptimizeMode {
return env === 'auto' || env === 'palette' || env === 'full' ? env : 'off';
}
+/** Minimum nodes sharing one mesh before the instancing pass batches them.
+ * The gltf-transform default (5) — below that the extension's byte overhead
+ * and loader bookkeeping outweigh the draw savings. */
+const INSTANCE_MIN = 5;
+
+/** Resolve the effective instance mode: explicit option wins, else the env, else auto. */
+function resolveInstance(opt?: InstanceMode): InstanceMode {
+ if (opt) return opt;
+ const env = process.env['KILN_BAKE_INSTANCE'];
+ return env === 'off' || env === 'auto' || env === 'on' ? env : 'auto';
+}
+
+/** True when any node carries a `Joint*` name — the Kiln City runtime targets
+ * those pivots by NAME (wheel spin/steer rigs), and instance() drops per-node
+ * names when it folds nodes into a batch. Such assets are never instanced. */
+function hasJointPivots(doc: Document): boolean {
+ return doc
+ .getRoot()
+ .listNodes()
+ .some((n) => /^joint[_-]/i.test(n.getName()));
+}
+
+/**
+ * Run the opt-in GPU-instancing pass (M1c) on a baked Document, in place.
+ *
+ * Emits `EXT_mesh_gpu_instancing` batches for meshes referenced by
+ * >= {@link INSTANCE_MIN} nodes (colonnades, fence runs, container stacks),
+ * cutting draw calls + bytes at city scale. **Perf/filesize only — the A–F
+ * grade keys on material count and does not move.** Runs after dedup (which
+ * links duplicate meshes so sharing is detectable) and before palette()
+ * (the upstream-canonical dedup → instance → palette order; join() skips
+ * instanced nodes by design so `full` stays safe).
+ *
+ * Skipped (returns undefined) when:
+ * - mode is `off`, or `auto` and the role is not `'fill'`;
+ * - the Document carries animations or skins (the library no-ops on
+ * animated docs; skinned nodes are excluded per-mesh — we skip whole);
+ * - any node is named `Joint*` (city behaviors target pivots by name);
+ * - no mesh crosses the threshold (nothing to batch).
+ */
+async function applyGpuInstancing(
+ doc: Document,
+ mode: InstanceMode,
+ role: AssetRole | undefined,
+): Promise<InstancingSummary | undefined> {
+ if (mode === 'off') return undefined;
+ if (mode === 'auto' && role !== 'fill') return undefined;
+ const root = doc.getRoot();
+ if (root.listAnimations().length > 0 || root.listSkins().length > 0) return undefined;
+ if (hasJointPivots(doc)) return undefined;
+
+ const before = collectGlbMetrics(doc);
+ await doc.transform(instance({ min: INSTANCE_MIN }));
+
+ let batches = 0;
+ let instances = 0;
+ for (const node of root.listNodes()) {
+ const ext = node.getExtension('EXT_mesh_gpu_instancing') as {
+ getAttribute?: (name: string) => { getCount(): number } | null;
+ } | null;
+ if (!ext) continue;
+ batches += 1;
+ // Identity channels are disposed by the library, so read whichever survives.
+ instances +=
+ ext.getAttribute?.('TRANSLATION')?.getCount() ??
+ ext.getAttribute?.('ROTATION')?.getCount() ??
+ ext.getAttribute?.('SCALE')?.getCount() ??
+ 0;
+ }
+ if (batches === 0) return undefined;
+
+ const after = collectGlbMetrics(doc);
+ return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };
+}
+
/**
* Run the opt-in consolidation transforms on a baked Document, in place.
*
@@ -659,6 +778,17 @@ export async function renderSceneToGLB(
}
}
+ // Opt-in GPU-instancing pass (M1c) — dedup → instance → palette is the
+ // upstream-canonical order (dedup links duplicate meshes so sharing is
+ // detectable; join() skips instanced nodes so `full` stays safe). Perf/bytes
+ // only; the grade does not move. Failure is swallowed with a warning.
+ let instancing: InstancingSummary | undefined;
+ try {
+ instancing = await applyGpuInstancing(doc, resolveInstance(opts.instance), opts.role);
+ } catch (err) {
+ warnings.push(`instance transform failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+
// Opt-in material consolidation (default off => byte-identical to today). Runs
// after dedup so palette() works on the already-merged material set. `auto` is
// grade-aware: it consolidates only when palette() would actually act
@@ -689,13 +819,19 @@ export async function renderSceneToGLB(
let instanceability: InstanceabilityReport | undefined;
let metricsError: string | undefined;
try {
- const metrics: InstanceabilityMetrics = collectGlbMetrics(doc, optimize ? undefined : tris);
+ // Derive tris from the Document when a transform reshaped it (join welds
+ // primitives; instancing folds N nodes into one batch whose tris the
+ // instance-aware counter multiplies back out).
+ const metrics: InstanceabilityMetrics = collectGlbMetrics(
+ doc,
+ optimize || instancing ? undefined : tris,
+ );
instanceability = gradeInstanceability(metrics, { category: opts.category });
} catch (err) {
metricsError = err instanceof Error ? err.message : String(err);
}
- const io = new WebIO();
+ const io = engineIO();
const bytes = await io.writeBinary(doc);
return {
@@ -705,6 +841,7 @@ export async function renderSceneToGLB(
instanceability,
metricsError,
...(optimize ? { optimize } : {}),
+ ...(instancing ? { instancing } : {}),
};
}
@@ -719,14 +856,16 @@ export async function renderSceneToGLB(
*/
export async function renderGLB(
code: string,
- opts: { optimize?: OptimizeMode } = {},
+ opts: { optimize?: OptimizeMode; instance?: InstanceMode } = {},
): 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,
+ role: meta.role,
...(opts.optimize ? { optimize: opts.optimize } : {}),
+ ...(opts.instance ? { instance: opts.instance } : {}),
});
return {
@@ -741,6 +880,7 @@ export async function renderGLB(
: {}),
...(scene.metricsError ? { metricsError: scene.metricsError } : {}),
...(scene.optimize ? { optimize: scene.optimize } : {}),
+ ...(scene.instancing ? { instancing: scene.instancing } : {}),
},
warnings: scene.warnings,
};
@@ -760,7 +900,7 @@ export async function gradeGlbBytes(
opts: { category?: string } = {},
): Promise<InstanceabilityReport | undefined> {
try {
- const doc = await new WebIO().readBinary(bytes);
+ const doc = await engineIO().readBinary(bytes);
return gradeInstanceability(collectGlbMetrics(doc), opts);
} catch {
return undefined;
@@ -773,8 +913,10 @@ export interface OptimizeGlbResult {
bytes: Uint8Array;
/** Instanceability report recomputed on the optimized bytes. */
report?: InstanceabilityReport;
- /** What the pass did. */
- summary: OptimizeSummary;
+ /** What the consolidation pass did (absent when only instancing applied). */
+ summary?: OptimizeSummary;
+ /** What the GPU-instancing pass did (absent when it was off / skipped / no-op). */
+ instancing?: InstancingSummary;
}
/**
@@ -790,24 +932,35 @@ export interface OptimizeGlbResult {
*/
export async function optimizeGlbBytes(
bytes: Uint8Array,
- opts: { mode?: OptimizeMode; category?: string } = {},
+ opts: { mode?: OptimizeMode; category?: string; instance?: InstanceMode; role?: AssetRole } = {},
): Promise<OptimizeGlbResult | undefined> {
const requested = opts.mode ?? 'palette';
try {
- const io = new WebIO();
+ const io = engineIO();
const doc = await io.readBinary(bytes);
+ // GPU-instancing first (dedup already ran at bake; instance → palette is the
+ // canonical order). Defaults OFF here — this is the web-tier re-bake seam, and
+ // the caller opts in per-asset (Studio passes instance:'auto' + the record's
+ // role, so only fill assets are batched — same gate as the render path).
+ let instancing: InstancingSummary | undefined;
+ if (opts.instance && opts.instance !== 'off') {
+ instancing = await applyGpuInstancing(doc, opts.instance, opts.role);
+ }
// `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;
+ // (>= PALETTE_MIN materials); a no-op auto (or an explicit `off`) keeps
+ // the original bytes unchanged — unless instancing acted, in which case
+ // the instanced bytes are still worth persisting.
+ let summary: OptimizeSummary | undefined;
+ let mode: 'palette' | 'full' | undefined;
+ if (requested !== 'off') {
+ if (requested === 'auto') {
+ if (collectGlbMetrics(doc).uniqueMaterials >= PALETTE_MIN) mode = 'palette';
+ } else {
+ mode = requested;
+ }
}
- const summary = await consolidateMaterials(doc, mode);
+ if (mode) summary = await consolidateMaterials(doc, mode);
+ if (!summary && !instancing) return undefined;
const outBytes = await io.writeBinary(doc);
let report: InstanceabilityReport | undefined;
try {
@@ -815,7 +968,12 @@ export async function optimizeGlbBytes(
} catch {
report = undefined;
}
- return { bytes: outBytes, ...(report ? { report } : {}), summary };
+ return {
+ bytes: outBytes,
+ ...(report ? { report } : {}),
+ ...(summary ? { summary } : {}),
+ ...(instancing ? { instancing } : {}),
+ };
} catch {
return undefined;
}
@@ -871,7 +1029,7 @@ export async function snapGlbToPalette(
): Promise<SnapGlbResult | undefined> {
if (slots.length === 0) return undefined;
try {
- const io = new WebIO();
+ const io = engineIO();
const doc = await io.readBinary(bytes);
const before = collectGlbMetrics(doc);
const idx = buildSlotIndex(slots as readonly SnapSlot[]);
@@ -1007,7 +1165,9 @@ export async function composeSceneGLB(
opts: SceneComposeOptions = {},
): Promise<SceneComposeResult> {
const warnings: string[] = [];
- const io = new WebIO();
+ // engineIO so a part that carries EXT_mesh_gpu_instancing keeps its batches
+ // through the merge (mergeDocuments copies the extension onto the master).
+ const io = engineIO();
const master = new Document();
const masterScene = master.createScene(opts.sceneName ?? 'Scene');
let composed = 0;