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(metrics): suggest optional material merges (#209) (#227)

Matthew Kissinger1478cdfefc0e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e24a0634..41cca0ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,11 @@ does not publish a package.
viewers instead of being dropped with a warning. `docs/geometry.md` lists the attributes
each converter keeps. A texture with `channel = 1` exports with `texCoord: 1`, and a mesh it
samples must have `uv1` (#195).
+- Add optional material merge advice to the instanceability report: drawn materials that
+ share alpha, sidedness, texture bindings, extensions and extras but differ in factors are
+ listed with their parts, the differing factors, what a merge needs and the projected
+ material count and grade. The advice is labelled optional and never changes the grade or
+ any QA disposition (#209).
## 1.3.1 (2026-10-17)
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 75041012..1aaebedf 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -23335,9 +23335,151 @@ function collectGlbMetrics(doc, triangles) {
triangles: triangles ?? derivedTris
};
}
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
+}
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
+ ];
+}
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
+ ]);
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
+ continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
+ }
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
+ });
+}
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
+ };
+}
function gradeInstanceability(metrics, opts = {}) {
const m = metrics;
- const band = MATERIAL_GRADE_BANDS.find((b) => m.uniqueMaterials <= b.max);
+ const band = materialBand(m.uniqueMaterials);
let grade = band.grade;
const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
@@ -23375,9 +23517,18 @@ function gradeInstanceability(metrics, opts = {}) {
if (opts.category)
reasons.push(`category: ${opts.category}`);
const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- return { grade, summary, reasons, metrics: m };
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
var init_metrics = __esm(() => {
MATERIAL_GRADE_BANDS = [
{ grade: "A", max: 1, range: "0-1" },
@@ -23386,6 +23537,14 @@ var init_metrics = __esm(() => {
{ grade: "D", max: 12, range: "7-12" },
{ grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
});
// src/written-nodes.ts
@@ -37070,7 +37229,9 @@ async function renderSceneToGLB(root, opts = {}) {
let metricsError;
try {
const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);
- instanceability = gradeInstanceability(metrics);
+ instanceability = gradeInstanceability(metrics, {
+ mergeCandidates: materialMergeCandidates(doc)
+ });
} catch (err) {
metricsError = err instanceof Error ? err.message : String(err);
}
diff --git a/dist/build.json b/dist/build.json
index 09b08bb8..79d1fed3 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
+ "identity": "sha256:7ac7c7547ff2e4ab8ef3bbd87f3454091deec94a16e5951951cf688ccdf44609",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
+ "sourceHash": "a65c95852a179170b5a563e919fbbb44e3e68bc3855b82844d8508db3f3a6518",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -37,13 +37,13 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:190519c2ee31122dd7593fad43b2a91dfe877a6c117386aabda3d772926000b6"
+ "bundleHash": "sha256:520d921c096ae6886598aea30c98378cba2dd2ccf01984c0d4623bc16a661adb"
},
"agent-run": {
- "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
+ "identity": "sha256:7ac7c7547ff2e4ab8ef3bbd87f3454091deec94a16e5951951cf688ccdf44609",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
+ "sourceHash": "a65c95852a179170b5a563e919fbbb44e3e68bc3855b82844d8508db3f3a6518",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -75,13 +75,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:050e39186329fcae99c4221c1d22049a82862761cacad0f08ede45e07076b328"
+ "bundleHash": "sha256:82d23b6651688af117e951a6049dca4359e572639e3d14041f715d157cff2630"
},
"agent-providers": {
- "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
+ "identity": "sha256:7ac7c7547ff2e4ab8ef3bbd87f3454091deec94a16e5951951cf688ccdf44609",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
+ "sourceHash": "a65c95852a179170b5a563e919fbbb44e3e68bc3855b82844d8508db3f3a6518",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -116,10 +116,10 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
+ "identity": "sha256:7ac7c7547ff2e4ab8ef3bbd87f3454091deec94a16e5951951cf688ccdf44609",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
+ "sourceHash": "a65c95852a179170b5a563e919fbbb44e3e68bc3855b82844d8508db3f3a6518",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -154,10 +154,10 @@
"bundleHash": "sha256:a246b2c79d629a332cef4430dbe742b0c4a0d2f04f0281e673c3c60ff22706da"
},
"cli": {
- "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
+ "identity": "sha256:7ac7c7547ff2e4ab8ef3bbd87f3454091deec94a16e5951951cf688ccdf44609",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
+ "sourceHash": "a65c95852a179170b5a563e919fbbb44e3e68bc3855b82844d8508db3f3a6518",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -189,13 +189,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:43403843350f974ff6a3c2b849b1ad794f52cb29c35087a758a2d543ed1134d0"
+ "bundleHash": "sha256:ebd05f2ba4e429db70f7a48b4e67c8afbeaf49b63dfa0fb3804d130fe1deab4c"
},
"engine": {
- "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
+ "identity": "sha256:7ac7c7547ff2e4ab8ef3bbd87f3454091deec94a16e5951951cf688ccdf44609",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
+ "sourceHash": "a65c95852a179170b5a563e919fbbb44e3e68bc3855b82844d8508db3f3a6518",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -227,7 +227,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:e04d326d5205496189eabc5fe947cd1b7669f1b3ea871c754c1b91d3cc63a7c2"
+ "bundleHash": "sha256:91f4e7f1b401d03810c7e6b5aa8b322a0366246e3af55d8a4e7433cf5c3eeeee"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 1574cce7..684ae1a3 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -21005,9 +21005,151 @@ function collectGlbMetrics(doc, triangles) {
triangles: triangles ?? derivedTris
};
}
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
+}
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
+ ];
+}
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
+ ]);
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
+ continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
+ }
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
+ });
+}
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
+ };
+}
function gradeInstanceability(metrics, opts = {}) {
const m = metrics;
- const band = MATERIAL_GRADE_BANDS.find((b) => m.uniqueMaterials <= b.max);
+ const band = materialBand(m.uniqueMaterials);
let grade = band.grade;
const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
@@ -21045,9 +21187,18 @@ function gradeInstanceability(metrics, opts = {}) {
if (opts.category)
reasons.push(`category: ${opts.category}`);
const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- return { grade, summary, reasons, metrics: m };
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
var init_metrics = __esm(() => {
MATERIAL_GRADE_BANDS = [
{ grade: "A", max: 1, range: "0-1" },
@@ -21056,6 +21207,14 @@ var init_metrics = __esm(() => {
{ grade: "D", max: 12, range: "7-12" },
{ grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
});
// src/written-nodes.ts
@@ -38175,7 +38334,9 @@ async function renderSceneToGLB(root, opts = {}) {
let metricsError;
try {
const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);
- instanceability = gradeInstanceability(metrics);
+ instanceability = gradeInstanceability(metrics, {
+ mergeCandidates: materialMergeCandidates(doc)
+ });
} catch (err) {
metricsError = err instanceof Error ? err.message : String(err);
}
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index 437d63ab..739a3ce5 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -14620,9 +14620,151 @@ function collectGlbMetrics(doc, triangles) {
triangles: triangles ?? derivedTris
};
}
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
+}
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
+ ];
+}
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
+ ]);
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
+ continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
+ }
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
+ });
+}
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
+ };
+}
function gradeInstanceability(metrics, opts = {}) {
const m = metrics;
- const band = MATERIAL_GRADE_BANDS.find((b) => m.uniqueMaterials <= b.max);
+ const band = materialBand(m.uniqueMaterials);
let grade = band.grade;
const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
@@ -14660,9 +14802,18 @@ function gradeInstanceability(metrics, opts = {}) {
if (opts.category)
reasons.push(`category: ${opts.category}`);
const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- return { grade, summary, reasons, metrics: m };
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
var init_metrics = __esm(() => {
MATERIAL_GRADE_BANDS = [
{ grade: "A", max: 1, range: "0-1" },
@@ -14671,6 +14822,14 @@ var init_metrics = __esm(() => {
{ grade: "D", max: 12, range: "7-12" },
{ grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
});
// src/written-nodes.ts
@@ -33522,7 +33681,9 @@ async function renderSceneToGLB(root, opts = {}) {
let metricsError;
try {
const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);
- instanceability = gradeInstanceability(metrics);
+ instanceability = gradeInstanceability(metrics, {
+ mergeCandidates: materialMergeCandidates(doc)
+ });
} catch (err) {
metricsError = err instanceof Error ? err.message : String(err);
}
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 2dd83d96..54493000 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -8066,9 +8066,151 @@ function collectGlbMetrics(doc, triangles) {
triangles: triangles ?? derivedTris
};
}
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
+}
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
+ ];
+}
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
+ ]);
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
+ continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
+ }
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
+ });
+}
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
+ };
+}
function gradeInstanceability(metrics, opts = {}) {
const m = metrics;
- const band = MATERIAL_GRADE_BANDS.find((b) => m.uniqueMaterials <= b.max);
+ const band = materialBand(m.uniqueMaterials);
let grade = band.grade;
const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
@@ -8106,9 +8248,18 @@ function gradeInstanceability(metrics, opts = {}) {
if (opts.category)
reasons.push(`category: ${opts.category}`);
const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- return { grade, summary, reasons, metrics: m };
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
var init_metrics = __esm(() => {
MATERIAL_GRADE_BANDS = [
{ grade: "A", max: 1, range: "0-1" },
@@ -8117,6 +8268,14 @@ var init_metrics = __esm(() => {
{ grade: "D", max: 12, range: "7-12" },
{ grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
});
// src/written-nodes.ts
@@ -37712,7 +37871,9 @@ async function renderSceneToGLB(root, opts = {}) {
let metricsError;
try {
const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);
- instanceability = gradeInstanceability(metrics);
+ instanceability = gradeInstanceability(metrics, {
+ mergeCandidates: materialMergeCandidates(doc)
+ });
} catch (err) {
metricsError = err instanceof Error ? err.message : String(err);
}
diff --git a/docs/geometry.md b/docs/geometry.md
index b5e6fb86..ac9a9c89 100644
--- a/docs/geometry.md
+++ b/docs/geometry.md
@@ -510,6 +510,17 @@ which may differ from the source after optimization. The `instanceability` grade
informational, not a QA verdict: its summary names the metric that set the grade, and
a transparent material lowers only an A or B grade to C.
+When drawn materials share alpha mode and cutoff, sidedness, texture bindings and
+samplers, extensions and extras, and differ only in factors such as base colour or
+roughness, the report adds optional advice. The summary ends with "Optional advice,
+not a requirement", each reason names the members, differing factors, parts using them
+and what a merge needs, and `instanceability.advice` holds the groups with the
+projected material count and grade. The advice never changes the grade or a QA
+disposition. Merging differing base colours needs a shared texture, an atlas region or vertex
+colours (`COLOR_0`);
+the host's `KILN_BAKE_OPTIMIZE=palette` builds a palette texture for flat-colour
+materials. Byte-identical materials are already merged by deduplication.
+
Specialized factories also check finite dimensions and bounded counts. Cards accept
pivots outside their panel when the resulting coordinates remain finite. Wings
accept a zero tip chord; stairs accept signed rise/run for descending or reversed
diff --git a/src/__tests__/metrics.test.ts b/src/__tests__/metrics.test.ts
index 54cb1c8a..4d8089fc 100644
--- a/src/__tests__/metrics.test.ts
+++ b/src/__tests__/metrics.test.ts
@@ -17,7 +17,12 @@ import {
glassMaterial,
} from '../primitives';
import { renderSceneToGLB, renderGLB, gradeGlbBytes } from '../render';
-import { collectGlbMetrics, gradeInstanceability, type InstanceabilityMetrics } from '../metrics';
+import {
+ collectGlbMetrics,
+ gradeInstanceability,
+ materialMergeCandidates,
+ type InstanceabilityMetrics,
+} from '../metrics';
import { Document } from '@gltf-transform/core';
import { EXTMeshGPUInstancing } from '@gltf-transform/extensions';
import * as THREE from 'three';
@@ -209,6 +214,110 @@ describe('gradeInstanceability (advisory rubric)', () => {
});
});
+describe('material merge advice (optional)', () => {
+ /** One triangle per material, each on its own named node. */
+ function shadingDoc() {
+ const doc = new Document();
+ const position = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]));
+ const scene = doc.createScene();
+ const place = (name: string, material: ReturnType<Document['createMaterial']>) =>
+ scene.addChild(
+ doc
+ .createNode(name)
+ .setMesh(
+ doc
+ .createMesh(name)
+ .addPrimitive(
+ doc.createPrimitive().setAttribute('POSITION', position).setMaterial(material),
+ ),
+ ),
+ );
+ const red = [0.8, 0.1, 0.1, 1] as [number, number, number, number];
+ place('Frond_0', doc.createMaterial('FrondA').setBaseColorFactor(red));
+ place('Frond_1', doc.createMaterial('FrondB').setBaseColorFactor([0.1, 0.6, 0.1, 1]));
+ place('Leaf', doc.createMaterial('Cutout').setBaseColorFactor(red).setAlphaMode('MASK'));
+ place(
+ 'Bark',
+ doc.createMaterial('Bark').setBaseColorFactor(red).setBaseColorTexture(doc.createTexture()),
+ );
+ return doc;
+ }
+
+ it('groups factor-only differences and projects the material band without changing the grade', () => {
+ const doc = shadingDoc();
+ const candidates = materialMergeCandidates(doc);
+ expect(candidates).toEqual([
+ {
+ materials: ['FrondA', 'FrondB'],
+ parts: [['Frond_0'], ['Frond_1']],
+ alphaMode: 'OPAQUE',
+ differs: ['baseColorFactor'],
+ needs: 'colours in a shared texture, an atlas region or vertex colours',
+ },
+ ]);
+ const metrics = collectGlbMetrics(doc);
+ const plain = gradeInstanceability(metrics);
+ const advised = gradeInstanceability(metrics, { mergeCandidates: candidates });
+ expect(advised.grade).toBe(plain.grade);
+ expect(advised.grade).toBe('C');
+ expect(advised.reasons[0]).toBe(plain.reasons[0]);
+ expect(advised.advice).toEqual({
+ optional: true,
+ materialMerges: candidates,
+ projectedMaterials: 3,
+ projectedGrade: 'B',
+ });
+ expect(advised.summary).toStartWith(plain.summary);
+ expect(advised.summary).toEndWith(
+ ' Optional advice, not a requirement: merging FrondA + FrondB (differ in baseColorFactor) would leave 3 materials (B at 2-3).',
+ );
+ expect(advised.reasons).toContain(
+ 'optional advice: FrondA + FrondB share shading and differ in baseColorFactor; a merge needs colours in a shared texture, an atlas region or vertex colours; parts: Frond_0, Frond_1',
+ );
+ });
+
+ it('keeps alpha mode, texture bindings and extras apart and is silent without candidates', () => {
+ const doc = shadingDoc();
+ doc
+ .getRoot()
+ .listMaterials()
+ .find((m) => m.getName() === 'FrondB')!
+ .setExtras({ role: 'trim' });
+ expect(materialMergeCandidates(doc)).toEqual([]);
+ const report = gradeInstanceability(collectGlbMetrics(doc), { mergeCandidates: [] });
+ expect(report.advice).toBeUndefined();
+ expect(report.summary).not.toContain('Optional advice');
+ });
+
+ it('dedup keeps byte-identical materials merged, so they produce no candidate', async () => {
+ const root = createRoot('Palm');
+ for (let i = 0; i < 3; i++)
+ createPart(`Frond_${i}`, boxGeo(1, 0.1, 0.3), gameMaterial(0x2f7a2f), {
+ parent: root,
+ position: [i, 0, 0],
+ });
+ const same = await renderSceneToGLB(root, { optimize: 'off' });
+ expect(same.instanceability!.metrics.uniqueMaterials).toBe(1);
+ expect(same.instanceability!.advice).toBeUndefined();
+
+ createPart('Frond_3', boxGeo(1, 0.1, 0.3), gameMaterial(0x3f8a2f), { parent: root });
+ const varied = await renderSceneToGLB(root, { optimize: 'off' });
+ expect(varied.instanceability!.grade).toBe('B');
+ expect(varied.instanceability!.advice).toMatchObject({
+ projectedMaterials: 1,
+ projectedGrade: 'A',
+ });
+ expect(varied.instanceability!.advice!.materialMerges[0]!.materials).toEqual([
+ 'Mesh_Frond_0 material',
+ 'Mesh_Frond_3 material',
+ ]);
+ expect(varied.instanceability!.summary).toContain('Optional advice, not a requirement');
+ });
+});
+
describe('render.meta carries the instanceability report', () => {
it('renderGLB merges instanceability into meta', async () => {
const code = `
diff --git a/src/metrics.ts b/src/metrics.ts
index b24d6fdb..506ebee5 100644
--- a/src/metrics.ts
+++ b/src/metrics.ts
@@ -61,6 +61,31 @@ export interface InstanceabilityReport {
/** Why the grade landed where it did (advisory bullet points); the first names the driver. */
reasons: string[];
metrics: InstanceabilityMetrics;
+ /** Optional suggestions; present only when there is something to suggest. Never moves the grade. */
+ advice?: InstanceabilityAdvice;
+}
+
+/** Materials that share every shading-relevant setting and differ only in factor values. */
+export interface MaterialMergeCandidate {
+ /** Member material names (`<first part> material` when unnamed), in document order. */
+ materials: string[];
+ /** Per member, the drawn nodes whose primitives use it (at most eight each). */
+ parts: string[][];
+ alphaMode: 'OPAQUE' | 'MASK' | 'BLEND';
+ /** Factors or material extensions whose values differ between members. */
+ differs: string[];
+ /** What a merge needs so the differing values survive. */
+ needs: string;
+}
+
+export interface InstanceabilityAdvice {
+ /** Advice is optional: it never changes the grade or any QA disposition. */
+ optional: true;
+ materialMerges: MaterialMergeCandidate[];
+ /** Distinct materials if every candidate group became one material. */
+ projectedMaterials: number;
+ /** The rubric's grade at `projectedMaterials`, other inputs unchanged. */
+ projectedGrade: InstanceabilityGrade;
}
function primTris(prim: import('@gltf-transform/core').Primitive): number {
@@ -201,6 +226,195 @@ const MATERIAL_GRADE_BANDS: readonly {
const counted = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`;
+const materialBand = (materials: number) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max)!;
+const lowersToC = (m: InstanceabilityMetrics) => m.transparentMaterials > 0 || m.textureCount > 4;
+
+/** The rubric alone: the material band, with transparency or texture sprawl lowering A/B to C. */
+function rubricGrade(m: InstanceabilityMetrics): InstanceabilityGrade {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === 'A' || grade === 'B') && lowersToC(m) ? 'C' : grade;
+}
+
+type GltfMaterial = import('@gltf-transform/core').Material;
+type GltfTextureInfo = import('@gltf-transform/core').TextureInfo;
+
+const MERGE_PARTS_KEPT = 8;
+const MERGE_FACTORS: readonly [string, (m: GltfMaterial) => unknown][] = [
+ ['baseColorFactor', (m) => m.getBaseColorFactor()],
+ ['emissiveFactor', (m) => m.getEmissiveFactor()],
+ ['metallicFactor', (m) => m.getMetallicFactor()],
+ ['roughnessFactor', (m) => m.getRoughnessFactor()],
+ ['normalScale', (m) => m.getNormalScale()],
+ ['occlusionStrength', (m) => m.getOcclusionStrength()],
+];
+
+function textureSlots(m: GltfMaterial) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()],
+ ] as const;
+}
+
+const extensionNames = (property: { listExtensions(): { extensionName: string }[] }) =>
+ property
+ .listExtensions()
+ .map((extension) => extension.extensionName)
+ .sort();
+
+/** Everything a merge cannot reconcile by choosing factor values: alpha, sidedness, bindings, extras. */
+function shadingKey(m: GltfMaterial, textures: readonly object[]): string {
+ const binding = (info: GltfTextureInfo | null) =>
+ info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info),
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === 'MASK' ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras(),
+ ]);
+}
+
+function differingFactors(group: readonly GltfMaterial[]): string[] {
+ const [first, ...rest] = group as [GltfMaterial, ...GltfMaterial[]];
+ const differs = MERGE_FACTORS.filter(([, read]) =>
+ rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first))),
+ ).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (
+ rest.some(
+ (m) =>
+ !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension),
+ )
+ )
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+
+function mergeNeeds(differs: readonly string[]): string {
+ const needs: string[] = [];
+ if (differs.some((d) => d === 'baseColorFactor' || d === 'emissiveFactor'))
+ needs.push('colours in a shared texture, an atlas region or vertex colours');
+ if (differs.some((d) => d === 'metallicFactor' || d === 'roughnessFactor'))
+ needs.push('one metallic/roughness value or a shared metallicRoughness texture');
+ if (differs.some((d) => d === 'normalScale' || d === 'occlusionStrength'))
+ needs.push('one normal scale and occlusion strength');
+ if (differs.some((d) => d.startsWith('KHR_') || d.startsWith('EXT_')))
+ needs.push('one setting for each differing extension');
+ return needs.length ? needs.join('; ') : 'only reusing one material; the members already match';
+}
+
+/**
+ * Optional advice: drawn materials that share alpha mode and cutoff, sidedness, texture bindings and
+ * samplers, extensions and extras, so only factor values separate them. Call after dedup(), which
+ * already merges byte-identical materials.
+ */
+export function materialMergeCandidates(doc: Document): MaterialMergeCandidate[] {
+ const root = doc.getRoot();
+ const parts = new Map<GltfMaterial, string[]>();
+ const visit = (node: import('@gltf-transform/core').Node): void => {
+ if (isHiddenGltfNode(node)) return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material) continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name)) list.push(name);
+ parts.set(material, list);
+ }
+ for (const child of node.listChildren()) visit(child);
+ };
+ for (const scene of root.listScenes()) for (const node of scene.listChildren()) visit(node);
+
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map<string, GltfMaterial[]>();
+ for (const material of materials) {
+ if (!parts.has(material)) continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group) group.push(material);
+ else groups.set(key, [material]);
+ }
+ return [...groups.values()]
+ .filter((group) => group.length > 1)
+ .map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)![0]} material`),
+ parts: group.map((m) => parts.get(m)!.slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0]!.getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs),
+ };
+ });
+}
+
+/** First few names, then a count of the rest. */
+function shortList(names: readonly string[], shown: number, joiner: string): string {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+
+function mergeAdvice(
+ m: InstanceabilityMetrics,
+ candidates: readonly MaterialMergeCandidate[],
+): { advice: InstanceabilityAdvice; summary: string; reasons: string[] } {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates
+ .filter((c) => c.alphaMode === 'BLEND')
+ .reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected: InstanceabilityMetrics = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged),
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c: MaterialMergeCandidate) => shortList(c.materials, 4, ' + ');
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(', ')}` : 'identical shading';
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3) groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors =
+ projectedGrade === band.grade ? '' : `; other factors give ${projectedGrade}`;
+ const summary =
+ ` Optional advice, not a requirement: merging ${groups.join('; ')} would leave ` +
+ `${counted(projected.uniqueMaterials, 'material', 'materials')} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(', ')}` : '';
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ', ')}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade,
+ },
+ summary,
+ reasons,
+ };
+}
+
/**
* Grade instanceability A–F. Kiln-tuned, advisory only.
*
@@ -221,12 +435,12 @@ const counted = (n: number, one: string, many: string): string => `${n} ${n ===
*/
export function gradeInstanceability(
metrics: InstanceabilityMetrics,
- opts: { category?: string } = {},
+ opts: { category?: string; mergeCandidates?: readonly MaterialMergeCandidate[] } = {},
): InstanceabilityReport {
const m = metrics;
// Base grade from distinct-material cardinality (the collapsible axis).
- const band = MATERIAL_GRADE_BANDS.find((b) => m.uniqueMaterials <= b.max)!;
+ const band = materialBand(m.uniqueMaterials);
let grade = band.grade;
const materials = `${counted(m.uniqueMaterials, 'distinct material', 'distinct materials')} (${band.grade} at ${band.range})`;
@@ -273,5 +487,14 @@ export function gradeInstanceability(
if (opts.category) reasons.push(`category: ${opts.category}`);
const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join('; ')}.`;
- return { grade, summary, reasons, metrics: m };
+ if (!opts.mergeCandidates?.length) return { grade, summary, reasons, metrics: m };
+ // Advice follows the grade text and never feeds back into it.
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice,
+ };
}
diff --git a/src/render.ts b/src/render.ts
index 442bcf8f..4f04f0e1 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -93,6 +93,7 @@ import {
import {
collectGlbMetrics,
gradeInstanceability,
+ materialMergeCandidates,
type InstanceabilityGrade,
type InstanceabilityMetrics,
type InstanceabilityReport,
@@ -1964,7 +1965,9 @@ export async function renderSceneToGLB(
doc,
optimize || instancing ? undefined : tris,
);
- instanceability = gradeInstanceability(metrics);
+ instanceability = gradeInstanceability(metrics, {
+ mergeCandidates: materialMergeCandidates(doc),
+ });
} catch (err) {
metricsError = err instanceof Error ? err.message : String(err);
}
@@ -2249,7 +2252,10 @@ export async function gradeGlbBytes(
): Promise<InstanceabilityReport | undefined> {
try {
const doc = await engineIO().readBinary(bytes);
- return gradeInstanceability(collectGlbMetrics(doc), opts);
+ return gradeInstanceability(collectGlbMetrics(doc), {
+ ...opts,
+ mergeCandidates: materialMergeCandidates(doc),
+ });
} catch {
return undefined;
}
@@ -2321,7 +2327,10 @@ export async function optimizeGlbBytes(
const gltfValidation = await assertFinalGlbValid(outBytes);
let report: InstanceabilityReport | undefined;
try {
- report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });
+ report = gradeInstanceability(collectGlbMetrics(doc), {
+ category: opts.category,
+ mergeCandidates: materialMergeCandidates(doc),
+ });
} catch {
report = undefined;
}
@@ -2480,7 +2489,10 @@ export async function snapGlbToPalette(
const gltfValidation = await assertFinalGlbValid(outBytes);
let report: InstanceabilityReport | undefined;
try {
- report = gradeInstanceability(after, { category: opts.category });
+ report = gradeInstanceability(after, {
+ category: opts.category,
+ mergeCandidates: materialMergeCandidates(doc),
+ });
} catch {
report = undefined;
}