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/retex): character diffuse-texture swap

Matt Kissinger43993e13125b
diff --git a/index.ts b/index.ts
index 6f09caee..2f9b27dd 100644
--- a/index.ts
+++ b/index.ts
@@ -158,6 +158,12 @@ export {
export { ingestFbx, openFbxIngestSession } from './fbx-ingest';
export type { IngestFbxOptions, IngestFbxResult, IngestFbxSession } from './fbx-ingest';
+// -----------------------------------------------------------------------------
+// Character retex (kiln/retex)
+// -----------------------------------------------------------------------------
+export { retexCharacter, FACTION_PRESETS } from './retex';
+export type { RetexCharacterOptions, RetexCharacterResult, FactionPreset } from './retex';
+
// -----------------------------------------------------------------------------
// Imposter baker (kiln/imposter)
// -----------------------------------------------------------------------------
diff --git a/retex/__tests__/retex.test.ts b/retex/__tests__/retex.test.ts
new file mode 100644
index 00000000..2a52da35
--- /dev/null
+++ b/retex/__tests__/retex.test.ts
@@ -0,0 +1,97 @@
+/**
+ * Retex tests — builds a procedural GLB with one textured material, swaps the
+ * diffuse, and verifies the output GLB carries the new bytes.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { Buffer } from 'node:buffer';
+import sharp from 'sharp';
+import * as THREE from 'three';
+
+import { NodeIO } from '@gltf-transform/core';
+
+import { renderSceneToGLB } from '../../render';
+import { retexCharacter } from '../retex';
+
+async function solid(w: number, h: number, rgb: [number, number, number]): Promise<Buffer> {
+ return sharp({
+ create: { width: w, height: h, channels: 4, background: { r: rgb[0], g: rgb[1], b: rgb[2], alpha: 1 } },
+ })
+ .png()
+ .toBuffer();
+}
+
+async function makeFixture(): Promise<Buffer> {
+ const root = new THREE.Group();
+ root.name = 'TexturedCube';
+ const geom = new THREE.BoxGeometry(1, 1, 1);
+ const mat = new THREE.MeshStandardMaterial({ color: 0xffffff });
+ mat.name = 'CharacterAtlas';
+ // DataTexture works headlessly — no HTMLImageElement needed.
+ const data = new Uint8Array(4 * 4 * 4);
+ for (let i = 0; i < data.length; i += 4) {
+ data[i] = 200;
+ data[i + 1] = 180;
+ data[i + 2] = 100;
+ data[i + 3] = 255;
+ }
+ const dataTex = new THREE.DataTexture(data, 4, 4, THREE.RGBAFormat);
+ dataTex.needsUpdate = true;
+ mat.map = dataTex;
+ const mesh = new THREE.Mesh(geom, mat);
+ root.add(mesh);
+
+ const { bytes } = await renderSceneToGLB(root, {});
+ return Buffer.from(bytes);
+}
+
+describe('retexCharacter', () => {
+ test('swaps the first material\'s base-color texture', async () => {
+ const fixture = await makeFixture();
+ const newDiffuse = await solid(32, 32, [50, 150, 50]); // OG-107-ish
+ const result = await retexCharacter(fixture, {
+ diffuse: newDiffuse,
+ presetName: 'OG-107-jungle',
+ });
+ expect(result.glb.readUInt32LE(0)).toBe(0x46546c67);
+ expect(result.meta.materialIndex).toBe(0);
+ expect(result.meta.presetName).toBe('OG-107-jungle');
+ expect(result.meta.sourceBytes).toBe(fixture.byteLength);
+
+ // Verify the new texture is in the output GLB by re-reading it.
+ const io = new NodeIO();
+ const doc = await io.readBinary(result.glb);
+ const textures = doc.getRoot().listTextures();
+ expect(textures.length).toBeGreaterThanOrEqual(1);
+ const diffuseImg = textures[0]!.getImage();
+ expect(diffuseImg).toBeTruthy();
+ // The embedded texture size should match the new diffuse, not the original 4x4.
+ expect(diffuseImg!.length).toBe(newDiffuse.length);
+ });
+
+ test('selects material by name', async () => {
+ const fixture = await makeFixture();
+ const newDiffuse = await solid(16, 16, [10, 10, 10]);
+ const result = await retexCharacter(fixture, {
+ diffuse: newDiffuse,
+ materialName: 'CharacterAtlas',
+ });
+ expect(result.meta.materialName).toBe('CharacterAtlas');
+ });
+
+ test('throws on unknown material name', async () => {
+ const fixture = await makeFixture();
+ const newDiffuse = await solid(16, 16, [10, 10, 10]);
+ await expect(
+ retexCharacter(fixture, { diffuse: newDiffuse, materialName: 'NoSuchMaterial' }),
+ ).rejects.toThrow(/no material named/);
+ });
+
+ test('throws on out-of-bounds materialIndex', async () => {
+ const fixture = await makeFixture();
+ const newDiffuse = await solid(16, 16, [10, 10, 10]);
+ await expect(
+ retexCharacter(fixture, { diffuse: newDiffuse, materialIndex: 99 }),
+ ).rejects.toThrow(/out of bounds/);
+ });
+});
diff --git a/retex/index.ts b/retex/index.ts
new file mode 100644
index 00000000..2e4d2cdd
--- /dev/null
+++ b/retex/index.ts
@@ -0,0 +1,12 @@
+/**
+ * kiln/retex — character diffuse-texture swap (faction retex).
+ *
+ * import { kiln } from '@pixel-forge/core';
+ * const { glb, meta } = await kiln.retexCharacter(sourceGlbBuffer, {
+ * diffuse: og107PngBuffer,
+ * presetName: 'OG-107-jungle',
+ * });
+ */
+
+export { retexCharacter, FACTION_PRESETS } from './retex';
+export type { RetexCharacterOptions, RetexCharacterResult, FactionPreset } from './retex';
diff --git a/retex/retex.ts b/retex/retex.ts
new file mode 100644
index 00000000..f623d124
--- /dev/null
+++ b/retex/retex.ts
@@ -0,0 +1,131 @@
+/**
+ * Character retex — swap a GLB material's base-color texture.
+ *
+ * First-pass implementation focuses on the 99% case: Quaternius-style
+ * characters bake their whole outfit into one diffuse atlas on a single
+ * material. Swap that texture and the character gets a new uniform without
+ * touching UVs or vertex data. Region-aware LUT retex (separate skin vs
+ * uniform zones) is a future enhancement — deferred per proposal §P5 scope.
+ *
+ * For batch faction retex (OG-107, ERDL, tiger-stripe, khaki, black-pajama),
+ * the caller generates five preset diffuse PNGs once per base character (via
+ * the sprite pipeline or hand-authored) and feeds them through this function
+ * as `diffuse` buffers.
+ */
+
+import { Buffer } from 'node:buffer';
+import { readFileSync } from 'node:fs';
+
+import { NodeIO, type Material } from '@gltf-transform/core';
+
+export interface RetexCharacterOptions {
+ /** New base-color PNG bytes (or path to a PNG on disk). */
+ diffuse: Buffer | string;
+ /** Target material by its glTF name. First match wins. */
+ materialName?: string;
+ /**
+ * Target material by 0-based index in doc.listMaterials(). Ignored if
+ * materialName is set.
+ */
+ materialIndex?: number;
+ /**
+ * Label stored in the output meta for provenance (e.g. 'OG-107-jungle').
+ * Does not affect the GLB itself.
+ */
+ presetName?: string;
+}
+
+export interface RetexCharacterResult {
+ glb: Buffer;
+ meta: {
+ materialName: string;
+ materialIndex: number;
+ bytes: number;
+ sourceBytes: number;
+ presetName?: string;
+ };
+}
+
+export async function retexCharacter(
+ input: Buffer | string,
+ opts: RetexCharacterOptions,
+): Promise<RetexCharacterResult> {
+ const srcBuf = typeof input === 'string' ? readFileSync(input) : input;
+ const diffuseBytes =
+ typeof opts.diffuse === 'string' ? readFileSync(opts.diffuse) : opts.diffuse;
+
+ const io = new NodeIO();
+ const doc = await io.readBinary(srcBuf);
+ const materials = doc.getRoot().listMaterials();
+ if (!materials.length) {
+ throw new Error('retexCharacter: GLB has no materials to retex');
+ }
+
+ const { material, index } = selectMaterial(materials, opts);
+
+ // Reuse the existing base-color texture if present; otherwise create one.
+ let texture = material.getBaseColorTexture();
+ if (!texture) {
+ texture = doc.createTexture(`${material.getName() || 'mat'}_baseColor`);
+ material.setBaseColorTexture(texture);
+ }
+ texture.setImage(new Uint8Array(diffuseBytes));
+ texture.setMimeType('image/png');
+
+ const outBytes = await io.writeBinary(doc);
+ const glb = Buffer.from(outBytes);
+
+ return {
+ glb,
+ meta: {
+ materialName: material.getName(),
+ materialIndex: index,
+ bytes: glb.byteLength,
+ sourceBytes: srcBuf.byteLength,
+ ...(opts.presetName ? { presetName: opts.presetName } : {}),
+ },
+ };
+}
+
+function selectMaterial(
+ materials: Material[],
+ opts: RetexCharacterOptions,
+): { material: Material; index: number } {
+ if (opts.materialName) {
+ const idx = materials.findIndex((m) => m.getName() === opts.materialName);
+ if (idx < 0) {
+ throw new Error(
+ `retexCharacter: no material named "${opts.materialName}" (available: ${materials
+ .map((m) => m.getName() || '(unnamed)')
+ .join(', ')})`,
+ );
+ }
+ return { material: materials[idx]!, index: idx };
+ }
+ if (typeof opts.materialIndex === 'number') {
+ const idx = opts.materialIndex;
+ if (idx < 0 || idx >= materials.length) {
+ throw new Error(
+ `retexCharacter: materialIndex ${idx} out of bounds (have ${materials.length})`,
+ );
+ }
+ return { material: materials[idx]!, index: idx };
+ }
+ // Default: first material (Quaternius pattern — one atlas per character).
+ return { material: materials[0]!, index: 0 };
+}
+
+/**
+ * Known faction preset names. These are labels for provenance — this module
+ * does NOT ship the baked diffuse PNGs; the caller provides them. Presets
+ * are expected to be generated by the sprite pipeline once per base model
+ * and cached alongside the source GLB.
+ */
+export const FACTION_PRESETS = [
+ 'OG-107-jungle',
+ 'ERDL-leaf',
+ 'tiger-stripe',
+ 'khaki-plain',
+ 'black-pajama',
+] as const;
+export type FactionPreset = (typeof FACTION_PRESETS)[number];