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.

Fix final GLB texture lineage (#38)

Matthew Kissinger8358800bb4dd
diff --git a/src/__tests__/final-texture-lineage.test.ts b/src/__tests__/final-texture-lineage.test.ts
new file mode 100644
index 00000000..4475e03b
--- /dev/null
+++ b/src/__tests__/final-texture-lineage.test.ts
@@ -0,0 +1,65 @@
+import { createHash } from 'node:crypto';
+import { expect, test } from 'bun:test';
+import { WebIO } from '@gltf-transform/core';
+import { KHRTextureBasisu } from '@gltf-transform/extensions';
+
+import { bindBakedTextureProvenanceToFinalGlb, renderGLBInProcess } from '../render';
+
+const SOURCE = `
+const meta = { name: 'MaterialLineage', category: 'prop' };
+async function build() {
+ const root = createRoot('MaterialLineage');
+ const albedo = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'albedo', name: 'Albedo', layers: [{ op: 'noise', colorA: 0x102030, colorB: 0x8090a0, scale: 2 }] });
+ const normal = normalMapFromHeight(albedo, { name: 'Normal' });
+ const mr = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'metallicRoughness', name: 'MetallicRoughness', layers: [{ op: 'checker', colorA: 0x0040c0, colorB: 0x00c040, squares: 2 }] });
+ const ao = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'occlusion', name: 'Occlusion', layers: [{ op: 'solid', color: 0x808080 }] });
+ const emissive = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'emissive', name: 'Emissive', layers: [{ op: 'stripes', colorA: 0x00ffff, colorB: 0x000000, count: 2 }] });
+ root.add(createPart('Body', boxUnwrap(boxGeo(1, 1, 1)), pbrMaterial({ albedo, normal, metallicRoughness: mr, aoMap: ao, emissive }), {}));
+ return root;
+}
+`;
+
+test('rebinds every baked material slot to exact final embedded image and GLB bytes', async () => {
+ const source = await renderGLBInProcess(SOURCE);
+ expect(source.bakedTextures?.map((texture) => texture.usage).sort()).toEqual([
+ 'albedo',
+ 'emissive',
+ 'metallicRoughness',
+ 'normal',
+ 'occlusion',
+ ]);
+
+ const io = new WebIO().registerExtensions([KHRTextureBasisu]);
+ const doc = await io.readBinary(source.glb);
+ const material = doc.getRoot().listMaterials()[0]!;
+ const packedMr = material.getMetallicRoughnessTexture()!;
+ const originalAo = material.getOcclusionTexture()!;
+ material.setOcclusionTexture(packedMr);
+ originalAo.dispose();
+ for (const [index, texture] of doc.getRoot().listTextures().entries()) {
+ texture.setImage(Uint8Array.from([0xab, 0x4b, 0x54, 0x58, index])).setMimeType('image/ktx2');
+ }
+ doc.createExtension(KHRTextureBasisu).setRequired(true);
+ const finalGlb = await io.writeBinary(doc);
+ const finalGlbSha256 = `sha256:${createHash('sha256').update(finalGlb).digest('hex')}` as const;
+
+ const rebound = await bindBakedTextureProvenanceToFinalGlb(source.bakedTextures ?? [], finalGlb);
+
+ expect(rebound).toHaveLength(5);
+ expect(rebound.map((texture) => texture.slot).sort()).toEqual([
+ 'aoMap',
+ 'emissiveMap',
+ 'map',
+ 'normalMap',
+ 'roughnessMap',
+ ]);
+ for (const texture of rebound) {
+ expect(texture.artifactGlbSha256).toBe(finalGlbSha256);
+ expect(texture.finalMime).toBe('image/ktx2');
+ expect(texture.finalImageSha256).toMatch(/^sha256:[0-9a-f]{64}$/);
+ }
+ expect(new Set(rebound.map((texture) => texture.finalImageSha256)).size).toBe(4);
+ expect(rebound.find(({ usage }) => usage === 'occlusion')?.finalImageSha256).toBe(
+ rebound.find(({ usage }) => usage === 'metallicRoughness')?.finalImageSha256,
+ );
+});
diff --git a/src/render.ts b/src/render.ts
index 0795527f..8806903b 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -11,6 +11,7 @@
*/
import * as THREE from 'three';
+import { createHash } from 'node:crypto';
import { Document, WebIO, getBounds } from '@gltf-transform/core';
import {
EXTMeshGPUInstancing,
@@ -993,6 +994,104 @@ export interface RenderSceneOptions {
role?: AssetRole;
}
+function finalTextureForSlot(material: GtMaterial, slot: string): GtTexture | null {
+ switch (slot) {
+ case 'map':
+ return material.getBaseColorTexture();
+ case 'normalMap':
+ return material.getNormalTexture();
+ case 'roughnessMap':
+ case 'metalnessMap':
+ return material.getMetallicRoughnessTexture();
+ case 'emissiveMap':
+ return material.getEmissiveTexture();
+ case 'aoMap':
+ return material.getOcclusionTexture();
+ default:
+ return null;
+ }
+}
+
+/**
+ * Rebind engine-authored texture lineage to a downstream final GLB.
+ *
+ * Studio may legally rewrite the first engine export through instancing, ORM
+ * packing, and KTX2 transcoding before persistence. The authored recipe and
+ * source PNG identity remain useful, but their original artifact hash is not a
+ * claim about those final bytes. Resolve each recorded material slot against
+ * the final document and attach the exact embedded image and GLB identities.
+ * No generated source is executed.
+ */
+export async function bindBakedTextureProvenanceToFinalGlb(
+ baked: readonly BakedTextureProvenanceV1[],
+ finalGlb: Uint8Array,
+): Promise<BakedTextureProvenanceV1[]> {
+ if (baked.length === 0) return [];
+ const doc = await engineIO().readBinary(finalGlb);
+ const root = doc.getRoot();
+ const byMaterialName = new Map<string, GtMaterial[]>();
+ for (const material of root.listMaterials()) {
+ const name = material.getName() || '(unnamed material)';
+ const list = byMaterialName.get(name) ?? [];
+ list.push(material);
+ byMaterialName.set(name, list);
+ }
+ const nodesByName = new Map<string, GtNode[]>();
+ for (const node of root.listNodes()) {
+ const list = nodesByName.get(node.getName()) ?? [];
+ list.push(node);
+ nodesByName.set(node.getName(), list);
+ }
+ const artifactGlbSha256 = `sha256:${await sha256Hex(finalGlb)}` as const;
+
+ return baked.flatMap((entry) => {
+ const resolved = new Set<GtTexture>();
+ for (const binding of entry.bindings) {
+ const nodeMaterials = (nodesByName.get(binding.node) ?? []).flatMap(
+ (node) =>
+ node
+ .getMesh()
+ ?.listPrimitives()
+ .flatMap((primitive) => {
+ const material = primitive.getMaterial();
+ return material ? [material] : [];
+ }) ?? [],
+ );
+ const materials = nodeMaterials.filter(
+ (material) => (material.getName() || '(unnamed material)') === binding.material,
+ );
+ const candidates = materials.length
+ ? materials
+ : (byMaterialName.get(binding.material) ?? []);
+ for (const material of candidates) {
+ const texture = finalTextureForSlot(material, binding.slot);
+ if (texture) resolved.add(texture);
+ }
+ }
+ // Texture names survive ordinary transforms and are a safe disambiguator
+ // when instancing replaced the authored node. Do not use the name alone if
+ // it is empty: unnamed textures are common and not identities.
+ if (resolved.size === 0 && entry.texture !== '(unnamed texture)') {
+ for (const texture of root.listTextures()) {
+ if (texture.getName() === entry.texture) resolved.add(texture);
+ }
+ }
+ if (resolved.size !== 1) return [];
+ const texture = [...resolved][0]!;
+ const image = texture.getImage();
+ const mime = texture.getMimeType();
+ if (!image || !mime) return [];
+ return [
+ {
+ ...entry,
+ artifactGlbSha256,
+ finalMime: mime,
+ finalImageSha256: `sha256:${createHash('sha256').update(image).digest('hex')}` as const,
+ },
+ ];
+ });
+}
+
/** 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).
* Aligned with the instanceability rubric: grade B tops out at 3 materials, so
diff --git a/src/texture-bake.ts b/src/texture-bake.ts
index 96d89fb0..e227e2e5 100644
--- a/src/texture-bake.ts
+++ b/src/texture-bake.ts
@@ -76,6 +76,14 @@ export interface BakedTextureProvenanceV1 {
imageSha256: `sha256:${string}`;
/** SHA-256 identity of the final GLB containing this binding. Filled after export. */
artifactGlbSha256?: `sha256:${string}`;
+ /**
+ * Encoding of the image actually bound by the final GLB after downstream
+ * packing/transcoding. Absent only while this record still describes the
+ * first engine export.
+ */
+ finalMime?: string;
+ /** SHA-256 identity of those exact final embedded image bytes. */
+ finalImageSha256?: `sha256:${string}`;
/** SHA-1 of the PNG bytes — the handle a determinism test compares. */
sha1: string;
/**
@@ -287,10 +295,18 @@ export async function bakeSceneTextures(
// against `texture.colorSpace`, and reporting the slot's expectation here
// would make a mismatched color space pass by asserting itself.
const colorSpace = entry.texture.colorSpace === THREE.SRGBColorSpace ? 'srgb' : 'linear';
- // A shared texture can legally occupy several bindings. Its own declared
- // usage is taken from the first deterministic traversal binding; every
- // binding remains present in provenance below.
- const primaryUsage = entry.bindings[0]?.usage ?? 'albedo';
+ const recipe = (entry.texture.userData as Record<string, unknown>)['kilnProcedural'] as
+ | ProceduralRecipeRecord
+ | undefined;
+ // Prefer the authored portable usage over incidental slot order. A packed
+ // metallic-roughness map occupies both Three.js slots, where choosing the
+ // first (`roughnessMap`) loses the authored combined-channel meaning.
+ const primaryUsage =
+ recipe?.usage ??
+ (entry.bindings.some(({ slot }) => slot === 'roughnessMap') &&
+ entry.bindings.some(({ slot }) => slot === 'metalnessMap')
+ ? 'metallicRoughness'
+ : (entry.bindings[0]?.usage ?? 'albedo'));
(entry.texture.userData as Record<string, unknown>)['kilnTexture'] = {
usage: primaryUsage,
colorSpace,
@@ -299,10 +315,6 @@ export async function bakeSceneTextures(
hasAlpha: hasTranslucentPixel(raw),
} satisfies KilnTextureMetadata;
- const recipe = (entry.texture.userData as Record<string, unknown>)['kilnProcedural'] as
- | ProceduralRecipeRecord
- | undefined;
-
const sha1 = createHash('sha1').update(bytes).digest('hex');
const imageSha256 = `sha256:${createHash('sha256').update(bytes).digest('hex')}` as const;
baked.push({
@@ -311,7 +323,7 @@ export async function bakeSceneTextures(
node: firstBinding.node,
material: firstBinding.material,
slot: firstBinding.slot,
- usage: firstBinding.usage,
+ usage: primaryUsage,
bindings: entry.bindings,
width: raw.width,
height: raw.height,