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(kiln/lod): meshopt-backed LOD chain generator

Matt Kissinger01de34c4775f
diff --git a/index.ts b/index.ts
index 07c2e39e..86b2a2cb 100644
--- a/index.ts
+++ b/index.ts
@@ -122,6 +122,19 @@ export type { GearOptions, BladeOptions } from './gears';
export { loadTexture, pbrMaterial } from './textures';
export type { PbrMaterialOptions, TextureSource, EncodedTextureData } from './textures';
+// -----------------------------------------------------------------------------
+// LOD chain generator (kiln/lod)
+// -----------------------------------------------------------------------------
+// Note: `countTriangles` is intentionally NOT re-exported from the kiln
+// namespace — primitives.ts already exports a THREE.Object3D variant under
+// the same name. Reach into `./lod/generate` if you need the Document variant.
+export { generateLODChain } from './lod';
+export type {
+ GenerateLODChainOptions,
+ GenerateLODChainResult,
+ LODLevel,
+} from './lod';
+
// -----------------------------------------------------------------------------
// Imposter baker (kiln/imposter)
// -----------------------------------------------------------------------------
diff --git a/lod/__tests__/generate.test.ts b/lod/__tests__/generate.test.ts
new file mode 100644
index 00000000..c866b87f
--- /dev/null
+++ b/lod/__tests__/generate.test.ts
@@ -0,0 +1,66 @@
+/**
+ * LOD chain generator tests — uses a trivial procedural mesh so the suite
+ * stays fast and offline.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+
+import { renderSceneToGLB } from '../../render';
+import { generateLODChain } from '../generate';
+
+// Build a small GLB fixture with ~1000 triangles — enough for meshopt to bite.
+async function makeFixture(segments = 32): Promise<Buffer> {
+ const root = new THREE.Group();
+ root.name = 'Fixture';
+ const geom = new THREE.SphereGeometry(1, segments, segments);
+ const mat = new THREE.MeshStandardMaterial({ color: 0x00aa66 });
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Sphere';
+ root.add(mesh);
+
+ const { bytes } = await renderSceneToGLB(root, {});
+ return Buffer.from(bytes);
+}
+
+describe('generateLODChain', () => {
+ test('default ratios produce 4 levels with descending tri counts', async () => {
+ const fixture = await makeFixture(32);
+ const result = await generateLODChain(fixture);
+
+ expect(result.lods).toHaveLength(4);
+ expect(result.source.triangles).toBeGreaterThan(1000);
+
+ // LOD0 preserves the source exactly (ratio = 1.0).
+ expect(result.lods[0]!.ratio).toBe(1.0);
+ expect(result.lods[0]!.triangles).toBe(result.source.triangles);
+
+ // Each subsequent LOD has strictly fewer triangles.
+ for (let i = 1; i < result.lods.length; i++) {
+ expect(result.lods[i]!.triangles).toBeLessThan(result.lods[i - 1]!.triangles);
+ }
+
+ // All level GLBs are valid binary (glTF magic = 0x46546C67 "glTF").
+ for (const lod of result.lods) {
+ expect(lod.glb.readUInt32LE(0)).toBe(0x46546c67);
+ expect(lod.bytes).toBe(lod.glb.byteLength);
+ }
+ }, 60_000);
+
+ test('custom ratios honored', async () => {
+ const fixture = await makeFixture(24);
+ const result = await generateLODChain(fixture, { ratios: [1.0, 0.2] });
+ expect(result.lods).toHaveLength(2);
+ expect(result.lods[0]!.ratio).toBe(1.0);
+ expect(result.lods[1]!.ratio).toBe(0.2);
+ // 20% target should leave far fewer than the source tris.
+ expect(result.lods[1]!.triangles).toBeLessThan(result.source.triangles * 0.6);
+ }, 60_000);
+
+ test('ratio = 1.0 is a pass-through (no simplification)', async () => {
+ const fixture = await makeFixture(16);
+ const result = await generateLODChain(fixture, { ratios: [1.0] });
+ expect(result.lods).toHaveLength(1);
+ expect(result.lods[0]!.triangles).toBe(result.source.triangles);
+ }, 30_000);
+});
diff --git a/lod/generate.ts b/lod/generate.ts
new file mode 100644
index 00000000..02fa9a66
--- /dev/null
+++ b/lod/generate.ts
@@ -0,0 +1,125 @@
+/**
+ * LOD chain generator — meshoptimizer-backed decimation.
+ *
+ * Produces N simplified copies of a source GLB at descending tri ratios.
+ * Each level is returned as its own Buffer so the caller can write them as
+ * `lod0.glb`, `lod1.glb`, ... per the TIJ pipeline's directory contract.
+ *
+ * Pipeline per level:
+ * 1. Re-read source GLB (fresh Document — transforms are destructive).
+ * 2. weld() — collapse duplicate verts so simplify has something to collapse.
+ * 3. simplify() with the requested ratio + error threshold.
+ * 4. prune() — remove unused accessors/textures the simplifier orphaned.
+ * 5. dedup() — merge identical materials, textures, accessors.
+ *
+ * Skinned (rigged) meshes: simplify preserves JOINTS_0 / WEIGHTS_0 vertex
+ * attributes, so bone animation continues to work. Animations are unchanged
+ * because the skeleton node graph is untouched. Quality at ratios ≤ 0.1 on
+ * characters can degrade silhouette — the gallery is the final arbiter.
+ */
+
+import { readFileSync } from 'node:fs';
+import { Buffer } from 'node:buffer';
+
+import { NodeIO, type Document } from '@gltf-transform/core';
+import { simplify, weld, prune, dedup } from '@gltf-transform/functions';
+import { MeshoptSimplifier } from 'meshoptimizer';
+
+export interface GenerateLODChainOptions {
+ /** Target ratios of vertices to keep, one per LOD level. Default [1.0, 0.5, 0.25, 0.1]. */
+ ratios?: number[];
+ /** Max permitted error as a fraction of mesh radius. Default 0.01. */
+ errorThreshold?: number;
+ /** Lock topological borders — use for tiled terrain. Default false. */
+ lockBorder?: boolean;
+}
+
+export interface LODLevel {
+ /** Index in the chain (0 = highest detail, N-1 = lowest). */
+ level: number;
+ /** Target ratio passed to meshopt. */
+ ratio: number;
+ /** Serialized GLB bytes for this level. */
+ glb: Buffer;
+ /** Total triangle count in this level (post-decimation). */
+ triangles: number;
+ /** Byte length of the GLB. */
+ bytes: number;
+}
+
+export interface GenerateLODChainResult {
+ lods: LODLevel[];
+ source: {
+ triangles: number;
+ bytes: number;
+ };
+}
+
+export async function generateLODChain(
+ input: Buffer | string,
+ opts: GenerateLODChainOptions = {},
+): Promise<GenerateLODChainResult> {
+ const ratios = opts.ratios ?? [1.0, 0.5, 0.25, 0.1];
+ const errorThreshold = opts.errorThreshold ?? 0.01;
+ const lockBorder = opts.lockBorder ?? false;
+
+ // meshoptimizer ships WASM — gate on ready before first use.
+ await MeshoptSimplifier.ready;
+
+ const io = new NodeIO();
+ const srcBuf = typeof input === 'string' ? readFileSync(input) : input;
+ const srcDoc = await io.readBinary(srcBuf);
+ const srcTris = countTriangles(srcDoc);
+
+ const lods: LODLevel[] = [];
+ for (let level = 0; level < ratios.length; level++) {
+ const ratio = ratios[level]!;
+ // Fresh Document per level — @gltf-transform transforms mutate in place.
+ const doc = await io.readBinary(srcBuf);
+
+ if (ratio < 1.0) {
+ await doc.transform(
+ weld(),
+ simplify({
+ simplifier: MeshoptSimplifier,
+ ratio,
+ error: errorThreshold,
+ lockBorder,
+ }),
+ prune(),
+ dedup(),
+ );
+ }
+
+ const bytes = await io.writeBinary(doc);
+ const glb = Buffer.from(bytes);
+ lods.push({
+ level,
+ ratio,
+ glb,
+ triangles: countTriangles(doc),
+ bytes: glb.byteLength,
+ });
+ }
+
+ return {
+ lods,
+ source: { triangles: srcTris, bytes: srcBuf.byteLength },
+ };
+}
+
+export function countTriangles(doc: Document): number {
+ let tris = 0;
+ for (const mesh of doc.getRoot().listMeshes()) {
+ for (const prim of mesh.listPrimitives()) {
+ const index = prim.getIndices();
+ if (index) {
+ tris += index.getCount() / 3;
+ } else {
+ const pos = prim.getAttribute('POSITION');
+ if (pos) tris += pos.getCount() / 3;
+ }
+ }
+ }
+ return Math.round(tris);
+}
diff --git a/lod/index.ts b/lod/index.ts
new file mode 100644
index 00000000..9b305bb2
--- /dev/null
+++ b/lod/index.ts
@@ -0,0 +1,16 @@
+/**
+ * kiln/lod — meshopt-backed LOD chain generator.
+ *
+ * import { kiln } from '@pixel-forge/core';
+ * const { lods, source } = await kiln.generateLODChain(glb, {
+ * ratios: [1.0, 0.5, 0.25, 0.1],
+ * });
+ * for (const lod of lods) writeFileSync(`lod${lod.level}.glb`, lod.glb);
+ */
+
+export { generateLODChain, countTriangles } from './generate';
+export type {
+ GenerateLODChainOptions,
+ GenerateLODChainResult,
+ LODLevel,
+} from './generate';