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(export): keep vertex colours, author attributes and a second UV set on the default converter (#195) (#226)

Matthew Kissingerb15e3301973f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb75150c..e24a0634 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,6 +41,15 @@ does not publish a package.
usages such as `normal`, so a height recipe can emboss the albedo's stamped pits; palettes
stay colour-only. V2 derivation identities and existing V3 recipe hashes are unchanged
(#205).
+- Export vertex colours (`COLOR_0`) and lowercase underscore author attributes such as
+- Export vertex colours (`COLOR_0`), a second UV set (`uv1` as `TEXCOORD_1`) and lowercase
+ underscore author attributes such as
+ `_wet` (as float `_WET`, 1 to 4 components) through the default `legacy` converter as
+ well as `three`; the runtime three target lists them in `customAttributes` in the same
+ order as delivery inspection. A `color` attribute now tints the exported surface in glTF
+ 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).
## 1.3.1 (2026-10-17)
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 3ef49841..75041012 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -25397,6 +25397,11 @@ function collectAuthorExtras(root) {
var MAX_USER_DATA_BYTES_PER_OBJECT = 4096, MAX_USER_DATA_BYTES_TOTAL = 65536, RESERVED_USER_DATA_PREFIX = "kiln", isReservedUserDataKey = (key) => key.startsWith(RESERVED_USER_DATA_PREFIX), MAX_LISTED = 8, utf8Bytes = (text) => new TextEncoder().encode(text).length, listed = (items) => items.length > MAX_LISTED ? `${items.slice(0, MAX_LISTED).join(", ")}, and ${items.length - MAX_LISTED} more` : items.join(", "), plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
// src/geometry-export.ts
+function customAttributeSemantic(key) {
+ if (key.length > AUTHOR_ATTRIBUTE_MAX_NAME || !AUTHOR_ATTRIBUTE_PATTERN.test(key))
+ return null;
+ return CUSTOM_EXPORT_ATTRIBUTES[key] ?? key.toUpperCase();
+}
function geometryExportAttributes(exporter) {
return exporter === "three" ? THREE_GEOMETRY_ATTRIBUTES : EXPORTED_GEOMETRY_ATTRIBUTES;
}
@@ -25466,8 +25471,8 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
return;
const geometry = mesh.geometry;
const name = mesh.name || "<unnamed mesh>";
- const unsupported = (feature) => {
- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
+ const unsupported = (feature, hint = "") => {
+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.${hint}`;
if (policy === "strict")
throw new TypeError(message);
warnings.push(message);
@@ -25476,9 +25481,9 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = attributes[key];
+ const expected = attributes[key] ?? (customAttributeSemantic(key) ? AUTHOR_ATTRIBUTE_COMPONENTS : undefined);
if (expected === undefined) {
- unsupported(key);
+ unsupported(key, key.startsWith("_") ? " Author attributes use a lowercase name such as _wet (exported as _WET) with 1 to 4 float components." : "");
continue;
}
const sizes = typeof expected === "number" ? [expected] : expected;
@@ -25503,6 +25508,19 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ for (const slot of TEXTURE_SLOTS) {
+ const texture = material[slot];
+ const channel = texture?.isTexture ? texture.channel ?? 0 : 0;
+ if (channel === 0)
+ continue;
+ const uv = `uv${channel}`;
+ if (attributes[uv] === undefined)
+ unsupported(`${slot} UV channel ${channel}`);
+ else if (!geometry.getAttribute(uv))
+ throw new TypeError(`${name}: ${slot} samples ${uv}, which the geometry lacks.`);
+ }
+ }
if (exporter === "three" && Array.isArray(mesh.material))
validateMaterialGroups(geometry, mesh.material.length, name);
if (exporter === "legacy") {
@@ -25525,13 +25543,15 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
+var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
normal: 3,
uv: 2,
+ uv1: 2,
tangent: 4,
+ color: [3, 4],
_edge: 1,
_cavity: 1
};
@@ -25539,10 +25559,18 @@ var init_geometry_export = __esm(() => {
_edge: "_EDGE",
_cavity: "_CAVITY"
};
+ AUTHOR_ATTRIBUTE_PATTERN = /^_[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
+ AUTHOR_ATTRIBUTE_COMPONENTS = [1, 2, 3, 4];
+ TEXTURE_SLOTS = [
+ "map",
+ "normalMap",
+ "roughnessMap",
+ "metalnessMap",
+ "aoMap",
+ "emissiveMap"
+ ];
THREE_GEOMETRY_ATTRIBUTES = {
...EXPORTED_GEOMETRY_ATTRIBUTES,
- color: [3, 4],
- uv1: 2,
uv2: 2,
uv3: 2,
skinIndex: 4,
@@ -36407,6 +36435,8 @@ function bridgeTextureSampler(source, target, atlas) {
}
}
target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);
+ if (source.channel === 1)
+ target.setTexCoord(1);
const ref = atlas?.texture(source);
if (ref)
target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });
@@ -36551,15 +36581,28 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
if (uvAttr) {
prim.setAttribute("TEXCOORD_0", doc.createAccessor(`${meshName}_uv`).setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));
}
+ const uv1Attr = geometry.getAttribute("uv1");
+ if (uv1Attr) {
+ prim.setAttribute("TEXCOORD_1", doc.createAccessor(`${meshName}_uv1`).setArray(geometryAttributeValues(uv1Attr)).setType(TYPE_VEC2).setBuffer(buf));
+ }
const tangentAttr = geometry.getAttribute("tangent");
if (tangentAttr?.itemSize === 4) {
prim.setAttribute("TANGENT", doc.createAccessor(`${meshName}_tangent`).setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));
}
- for (const [key, gltfName] of Object.entries(CUSTOM_EXPORT_ATTRIBUTES)) {
+ const colorAttr = geometry.getAttribute("color");
+ if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {
+ prim.setAttribute("COLOR_0", doc.createAccessor(`${meshName}_color`).setArray(geometryAttributeValues(colorAttr)).setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3).setBuffer(buf));
+ }
+ const customKeys = [
+ ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),
+ ...Object.keys(geometry.attributes).filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES)).sort()
+ ];
+ for (const key of customKeys) {
+ const gltfName = customAttributeSemantic(key);
const custom = geometry.getAttribute(key);
- if (custom?.itemSize !== 1)
+ if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4)
continue;
- prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(TYPE_SCALAR).setBuffer(buf));
+ prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(ACCESSOR_TYPES[custom.itemSize - 1]).setBuffer(buf));
}
const indexAttr = geometry.getIndex();
if (indexAttr) {
@@ -37351,7 +37394,7 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", ACCESSOR_TYPES, GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
var init_render = __esm(() => {
init_requirements_context();
init_requirements_run();
@@ -37391,6 +37434,7 @@ var init_render = __esm(() => {
init_kit();
init_texture_bake();
engineIO = createGltfIO;
+ ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];
GLTF_MIN_FILTER = {
[THREE54.NearestFilter]: 9728,
[THREE54.LinearFilter]: 9729,
@@ -37710,7 +37754,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}) {
collider: pathOf(collider),
proxy: pathOf(proxy)
})),
- customAttributes: [...customAttributes].sort(([a], [b]) => a === "_EDGE" ? -1 : b === "_EDGE" ? 1 : a < b ? -1 : a > b ? 1 : 0).map(([name, meshes]) => ({
+ customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({
name,
meshes: meshes.size,
componentType: "FLOAT",
@@ -37729,7 +37773,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}) {
};
return { glb, delivery };
}
-var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));
+var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));
var init_runtime_three = __esm(() => {
init_semantic();
init_gltf_io();
@@ -42033,7 +42077,6 @@ define2("repeatAlongCurve", {
],
limitations: [
"Tangents come from the polyline segments; sample curves densely for smooth turns.",
- "The default legacy GLB converter does not export the _along attribute.",
"Merged copies are one part: they are not separately named or addressable."
],
related: [
@@ -44525,7 +44568,8 @@ async function currentCapabilities(context, presentation) {
materialGroups: true,
skinning: exporter === undefined ? null : exporter === "three",
morphAttributes: exporter === undefined ? null : exporter === "three" ? ["position", "normal"] : [],
- unsupported: exporter === undefined ? null : exporter === "three" ? ["custom attributes", "UV4+", "morph attributes other than position/normal"] : ["vertex colors", "UV1+", "skinning", "morphs", "custom attributes"],
+ unsupported: exporter === undefined ? null : exporter === "three" ? ["UV4+", "morph attributes other than position/normal"] : ["UV2+", "skinning", "morphs"],
+ customAttributes: exporter === undefined ? null : "Lowercase underscore names such as _wet with 1 to 4 float components export as _WET; GLTFLoader reads them back as _wet.",
strictExport: "geometryPolicy:strict on GLB export or host context; local KILN_GEOMETRY_POLICY=strict",
implicitSurfaces: "experimental"
},
diff --git a/dist/build.json b/dist/build.json
index 7dfd2385..09b08bb8 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:65bbde8a0f4fb6bbe5d2fb453a7bf06ee53816e24a065327378cc435eab7cacd",
+ "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "9fd570a2fb356da9c98850bfdbec20794e41a56842a44a6118ea5c7f605dd23b",
+ "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -37,13 +37,13 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:bbf2cb6546fb3b154fb1fa1c4fd84f5829494e8729286746dff1c17eac076343"
+ "bundleHash": "sha256:190519c2ee31122dd7593fad43b2a91dfe877a6c117386aabda3d772926000b6"
},
"agent-run": {
- "identity": "sha256:65bbde8a0f4fb6bbe5d2fb453a7bf06ee53816e24a065327378cc435eab7cacd",
+ "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "9fd570a2fb356da9c98850bfdbec20794e41a56842a44a6118ea5c7f605dd23b",
+ "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -75,13 +75,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:88a47ef5bf4cced9a46e776e2bdf7b5f47f446a3fd26e47164e49402c7721d8b"
+ "bundleHash": "sha256:050e39186329fcae99c4221c1d22049a82862761cacad0f08ede45e07076b328"
},
"agent-providers": {
- "identity": "sha256:65bbde8a0f4fb6bbe5d2fb453a7bf06ee53816e24a065327378cc435eab7cacd",
+ "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "9fd570a2fb356da9c98850bfdbec20794e41a56842a44a6118ea5c7f605dd23b",
+ "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -116,10 +116,10 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:65bbde8a0f4fb6bbe5d2fb453a7bf06ee53816e24a065327378cc435eab7cacd",
+ "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "9fd570a2fb356da9c98850bfdbec20794e41a56842a44a6118ea5c7f605dd23b",
+ "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -154,10 +154,10 @@
"bundleHash": "sha256:a246b2c79d629a332cef4430dbe742b0c4a0d2f04f0281e673c3c60ff22706da"
},
"cli": {
- "identity": "sha256:65bbde8a0f4fb6bbe5d2fb453a7bf06ee53816e24a065327378cc435eab7cacd",
+ "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "9fd570a2fb356da9c98850bfdbec20794e41a56842a44a6118ea5c7f605dd23b",
+ "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -189,13 +189,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:63f82be14be5a505b9d06fda197e4e5d6fe8b478c196f653981fcdce960a60c3"
+ "bundleHash": "sha256:43403843350f974ff6a3c2b849b1ad794f52cb29c35087a758a2d543ed1134d0"
},
"engine": {
- "identity": "sha256:65bbde8a0f4fb6bbe5d2fb453a7bf06ee53816e24a065327378cc435eab7cacd",
+ "identity": "sha256:62a5b4fde531be50253bc7aebebe2b2fb198f1406d32d84f6f308e0fecdbd5b0",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "9fd570a2fb356da9c98850bfdbec20794e41a56842a44a6118ea5c7f605dd23b",
+ "sourceHash": "dcade89e6d874f98bf3c70c09ccdc95b6cda532c8858a2054d3eab440cbc1b36",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -227,7 +227,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:c41e776bf0a57d83a82221f2a90465bd82d4743768fa09ecd6d1f2b7055dc25e"
+ "bundleHash": "sha256:e04d326d5205496189eabc5fe947cd1b7669f1b3ea871c754c1b91d3cc63a7c2"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index c9da3cc0..1574cce7 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -23067,6 +23067,11 @@ function collectAuthorExtras(root) {
var MAX_USER_DATA_BYTES_PER_OBJECT = 4096, MAX_USER_DATA_BYTES_TOTAL = 65536, RESERVED_USER_DATA_PREFIX = "kiln", isReservedUserDataKey = (key) => key.startsWith(RESERVED_USER_DATA_PREFIX), MAX_LISTED = 8, utf8Bytes = (text) => new TextEncoder().encode(text).length, listed = (items) => items.length > MAX_LISTED ? `${items.slice(0, MAX_LISTED).join(", ")}, and ${items.length - MAX_LISTED} more` : items.join(", "), plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
// src/geometry-export.ts
+function customAttributeSemantic(key) {
+ if (key.length > AUTHOR_ATTRIBUTE_MAX_NAME || !AUTHOR_ATTRIBUTE_PATTERN.test(key))
+ return null;
+ return CUSTOM_EXPORT_ATTRIBUTES[key] ?? key.toUpperCase();
+}
function geometryExportAttributes(exporter) {
return exporter === "three" ? THREE_GEOMETRY_ATTRIBUTES : EXPORTED_GEOMETRY_ATTRIBUTES;
}
@@ -23136,8 +23141,8 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
return;
const geometry = mesh.geometry;
const name = mesh.name || "<unnamed mesh>";
- const unsupported = (feature) => {
- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
+ const unsupported = (feature, hint = "") => {
+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.${hint}`;
if (policy === "strict")
throw new TypeError(message);
warnings.push(message);
@@ -23146,9 +23151,9 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = attributes[key];
+ const expected = attributes[key] ?? (customAttributeSemantic(key) ? AUTHOR_ATTRIBUTE_COMPONENTS : undefined);
if (expected === undefined) {
- unsupported(key);
+ unsupported(key, key.startsWith("_") ? " Author attributes use a lowercase name such as _wet (exported as _WET) with 1 to 4 float components." : "");
continue;
}
const sizes = typeof expected === "number" ? [expected] : expected;
@@ -23173,6 +23178,19 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ for (const slot of TEXTURE_SLOTS) {
+ const texture = material[slot];
+ const channel = texture?.isTexture ? texture.channel ?? 0 : 0;
+ if (channel === 0)
+ continue;
+ const uv = `uv${channel}`;
+ if (attributes[uv] === undefined)
+ unsupported(`${slot} UV channel ${channel}`);
+ else if (!geometry.getAttribute(uv))
+ throw new TypeError(`${name}: ${slot} samples ${uv}, which the geometry lacks.`);
+ }
+ }
if (exporter === "three" && Array.isArray(mesh.material))
validateMaterialGroups(geometry, mesh.material.length, name);
if (exporter === "legacy") {
@@ -23195,13 +23213,15 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
+var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
normal: 3,
uv: 2,
+ uv1: 2,
tangent: 4,
+ color: [3, 4],
_edge: 1,
_cavity: 1
};
@@ -23209,10 +23229,18 @@ var init_geometry_export = __esm(() => {
_edge: "_EDGE",
_cavity: "_CAVITY"
};
+ AUTHOR_ATTRIBUTE_PATTERN = /^_[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
+ AUTHOR_ATTRIBUTE_COMPONENTS = [1, 2, 3, 4];
+ TEXTURE_SLOTS = [
+ "map",
+ "normalMap",
+ "roughnessMap",
+ "metalnessMap",
+ "aoMap",
+ "emissiveMap"
+ ];
THREE_GEOMETRY_ATTRIBUTES = {
...EXPORTED_GEOMETRY_ATTRIBUTES,
- color: [3, 4],
- uv1: 2,
uv2: 2,
uv3: 2,
skinIndex: 4,
@@ -37512,6 +37540,8 @@ function bridgeTextureSampler(source, target, atlas) {
}
}
target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);
+ if (source.channel === 1)
+ target.setTexCoord(1);
const ref = atlas?.texture(source);
if (ref)
target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });
@@ -37656,15 +37686,28 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
if (uvAttr) {
prim.setAttribute("TEXCOORD_0", doc.createAccessor(`${meshName}_uv`).setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));
}
+ const uv1Attr = geometry.getAttribute("uv1");
+ if (uv1Attr) {
+ prim.setAttribute("TEXCOORD_1", doc.createAccessor(`${meshName}_uv1`).setArray(geometryAttributeValues(uv1Attr)).setType(TYPE_VEC2).setBuffer(buf));
+ }
const tangentAttr = geometry.getAttribute("tangent");
if (tangentAttr?.itemSize === 4) {
prim.setAttribute("TANGENT", doc.createAccessor(`${meshName}_tangent`).setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));
}
- for (const [key, gltfName] of Object.entries(CUSTOM_EXPORT_ATTRIBUTES)) {
+ const colorAttr = geometry.getAttribute("color");
+ if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {
+ prim.setAttribute("COLOR_0", doc.createAccessor(`${meshName}_color`).setArray(geometryAttributeValues(colorAttr)).setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3).setBuffer(buf));
+ }
+ const customKeys = [
+ ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),
+ ...Object.keys(geometry.attributes).filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES)).sort()
+ ];
+ for (const key of customKeys) {
+ const gltfName = customAttributeSemantic(key);
const custom = geometry.getAttribute(key);
- if (custom?.itemSize !== 1)
+ if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4)
continue;
- prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(TYPE_SCALAR).setBuffer(buf));
+ prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(ACCESSOR_TYPES[custom.itemSize - 1]).setBuffer(buf));
}
const indexAttr = geometry.getIndex();
if (indexAttr) {
@@ -38466,7 +38509,7 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", ACCESSOR_TYPES, GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
var init_render = __esm(() => {
init_requirements_context();
init_requirements_run();
@@ -38506,6 +38549,7 @@ var init_render = __esm(() => {
init_kit();
init_texture_bake();
engineIO = createGltfIO;
+ ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];
GLTF_MIN_FILTER = {
[THREE54.NearestFilter]: 9728,
[THREE54.LinearFilter]: 9729,
@@ -41823,7 +41867,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}) {
collider: pathOf(collider),
proxy: pathOf(proxy)
})),
- customAttributes: [...customAttributes].sort(([a], [b]) => a === "_EDGE" ? -1 : b === "_EDGE" ? 1 : a < b ? -1 : a > b ? 1 : 0).map(([name, meshes]) => ({
+ customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({
name,
meshes: meshes.size,
componentType: "FLOAT",
@@ -41842,7 +41886,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}) {
};
return { glb, delivery };
}
-var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));
+var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));
var init_runtime_three = __esm(() => {
init_semantic();
init_gltf_io();
@@ -45362,7 +45406,6 @@ var init_helper_contracts = __esm(() => {
],
limitations: [
"Tangents come from the polyline segments; sample curves densely for smooth turns.",
- "The default legacy GLB converter does not export the _along attribute.",
"Merged copies are one part: they are not separately named or addressable."
],
related: [
@@ -47893,7 +47936,8 @@ async function currentCapabilities(context, presentation) {
materialGroups: true,
skinning: exporter === undefined ? null : exporter === "three",
morphAttributes: exporter === undefined ? null : exporter === "three" ? ["position", "normal"] : [],
- unsupported: exporter === undefined ? null : exporter === "three" ? ["custom attributes", "UV4+", "morph attributes other than position/normal"] : ["vertex colors", "UV1+", "skinning", "morphs", "custom attributes"],
+ unsupported: exporter === undefined ? null : exporter === "three" ? ["UV4+", "morph attributes other than position/normal"] : ["UV2+", "skinning", "morphs"],
+ customAttributes: exporter === undefined ? null : "Lowercase underscore names such as _wet with 1 to 4 float components export as _WET; GLTFLoader reads them back as _wet.",
strictExport: "geometryPolicy:strict on GLB export or host context; local KILN_GEOMETRY_POLICY=strict",
implicitSurfaces: "experimental"
},
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index afa07572..437d63ab 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -16663,6 +16663,11 @@ function collectAuthorExtras(root) {
var MAX_USER_DATA_BYTES_PER_OBJECT = 4096, MAX_USER_DATA_BYTES_TOTAL = 65536, RESERVED_USER_DATA_PREFIX = "kiln", isReservedUserDataKey = (key) => key.startsWith(RESERVED_USER_DATA_PREFIX), MAX_LISTED = 8, utf8Bytes = (text) => new TextEncoder().encode(text).length, listed = (items) => items.length > MAX_LISTED ? `${items.slice(0, MAX_LISTED).join(", ")}, and ${items.length - MAX_LISTED} more` : items.join(", "), plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
// src/geometry-export.ts
+function customAttributeSemantic(key) {
+ if (key.length > AUTHOR_ATTRIBUTE_MAX_NAME || !AUTHOR_ATTRIBUTE_PATTERN.test(key))
+ return null;
+ return CUSTOM_EXPORT_ATTRIBUTES[key] ?? key.toUpperCase();
+}
function geometryExportAttributes(exporter) {
return exporter === "three" ? THREE_GEOMETRY_ATTRIBUTES : EXPORTED_GEOMETRY_ATTRIBUTES;
}
@@ -16732,8 +16737,8 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
return;
const geometry = mesh.geometry;
const name = mesh.name || "<unnamed mesh>";
- const unsupported = (feature) => {
- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
+ const unsupported = (feature, hint = "") => {
+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.${hint}`;
if (policy === "strict")
throw new TypeError(message);
warnings.push(message);
@@ -16742,9 +16747,9 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = attributes[key];
+ const expected = attributes[key] ?? (customAttributeSemantic(key) ? AUTHOR_ATTRIBUTE_COMPONENTS : undefined);
if (expected === undefined) {
- unsupported(key);
+ unsupported(key, key.startsWith("_") ? " Author attributes use a lowercase name such as _wet (exported as _WET) with 1 to 4 float components." : "");
continue;
}
const sizes = typeof expected === "number" ? [expected] : expected;
@@ -16769,6 +16774,19 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ for (const slot of TEXTURE_SLOTS) {
+ const texture = material[slot];
+ const channel = texture?.isTexture ? texture.channel ?? 0 : 0;
+ if (channel === 0)
+ continue;
+ const uv = `uv${channel}`;
+ if (attributes[uv] === undefined)
+ unsupported(`${slot} UV channel ${channel}`);
+ else if (!geometry.getAttribute(uv))
+ throw new TypeError(`${name}: ${slot} samples ${uv}, which the geometry lacks.`);
+ }
+ }
if (exporter === "three" && Array.isArray(mesh.material))
validateMaterialGroups(geometry, mesh.material.length, name);
if (exporter === "legacy") {
@@ -16791,13 +16809,15 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
+var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
normal: 3,
uv: 2,
+ uv1: 2,
tangent: 4,
+ color: [3, 4],
_edge: 1,
_cavity: 1
};
@@ -16805,10 +16825,18 @@ var init_geometry_export = __esm(() => {
_edge: "_EDGE",
_cavity: "_CAVITY"
};
+ AUTHOR_ATTRIBUTE_PATTERN = /^_[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
+ AUTHOR_ATTRIBUTE_COMPONENTS = [1, 2, 3, 4];
+ TEXTURE_SLOTS = [
+ "map",
+ "normalMap",
+ "roughnessMap",
+ "metalnessMap",
+ "aoMap",
+ "emissiveMap"
+ ];
THREE_GEOMETRY_ATTRIBUTES = {
...EXPORTED_GEOMETRY_ATTRIBUTES,
- color: [3, 4],
- uv1: 2,
uv2: 2,
uv3: 2,
skinIndex: 4,
@@ -32859,6 +32887,8 @@ function bridgeTextureSampler(source, target, atlas) {
}
}
target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);
+ if (source.channel === 1)
+ target.setTexCoord(1);
const ref = atlas?.texture(source);
if (ref)
target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });
@@ -33003,15 +33033,28 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
if (uvAttr) {
prim.setAttribute("TEXCOORD_0", doc.createAccessor(`${meshName}_uv`).setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));
}
+ const uv1Attr = geometry.getAttribute("uv1");
+ if (uv1Attr) {
+ prim.setAttribute("TEXCOORD_1", doc.createAccessor(`${meshName}_uv1`).setArray(geometryAttributeValues(uv1Attr)).setType(TYPE_VEC2).setBuffer(buf));
+ }
const tangentAttr = geometry.getAttribute("tangent");
if (tangentAttr?.itemSize === 4) {
prim.setAttribute("TANGENT", doc.createAccessor(`${meshName}_tangent`).setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));
}
- for (const [key, gltfName] of Object.entries(CUSTOM_EXPORT_ATTRIBUTES)) {
+ const colorAttr = geometry.getAttribute("color");
+ if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {
+ prim.setAttribute("COLOR_0", doc.createAccessor(`${meshName}_color`).setArray(geometryAttributeValues(colorAttr)).setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3).setBuffer(buf));
+ }
+ const customKeys = [
+ ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),
+ ...Object.keys(geometry.attributes).filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES)).sort()
+ ];
+ for (const key of customKeys) {
+ const gltfName = customAttributeSemantic(key);
const custom = geometry.getAttribute(key);
- if (custom?.itemSize !== 1)
+ if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4)
continue;
- prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(TYPE_SCALAR).setBuffer(buf));
+ prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(ACCESSOR_TYPES[custom.itemSize - 1]).setBuffer(buf));
}
const indexAttr = geometry.getIndex();
if (indexAttr) {
@@ -33803,7 +33846,7 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", ACCESSOR_TYPES, GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
var init_render = __esm(() => {
init_requirements_context();
init_requirements_run();
@@ -33843,6 +33886,7 @@ var init_render = __esm(() => {
init_kit();
init_texture_bake();
engineIO = createGltfIO;
+ ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];
GLTF_MIN_FILTER = {
[THREE54.NearestFilter]: 9728,
[THREE54.LinearFilter]: 9729,
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 93577341..2dd83d96 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -8914,7 +8914,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}) {
collider: pathOf(collider),
proxy: pathOf(proxy)
})),
- customAttributes: [...customAttributes].sort(([a], [b]) => a === "_EDGE" ? -1 : b === "_EDGE" ? 1 : a < b ? -1 : a > b ? 1 : 0).map(([name, meshes]) => ({
+ customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({
name,
meshes: meshes.size,
componentType: "FLOAT",
@@ -8933,7 +8933,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}) {
};
return { glb, delivery };
}
-var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, rolesOf = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));
+var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));
var init_runtime_three = __esm(() => {
init_semantic();
init_gltf_io();
@@ -22631,6 +22631,11 @@ function collectAuthorExtras(root) {
var MAX_USER_DATA_BYTES_PER_OBJECT = 4096, MAX_USER_DATA_BYTES_TOTAL = 65536, RESERVED_USER_DATA_PREFIX = "kiln", isReservedUserDataKey = (key) => key.startsWith(RESERVED_USER_DATA_PREFIX), MAX_LISTED = 8, utf8Bytes = (text) => new TextEncoder().encode(text).length, listed = (items) => items.length > MAX_LISTED ? `${items.slice(0, MAX_LISTED).join(", ")}, and ${items.length - MAX_LISTED} more` : items.join(", "), plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
// src/geometry-export.ts
+function customAttributeSemantic(key) {
+ if (key.length > AUTHOR_ATTRIBUTE_MAX_NAME || !AUTHOR_ATTRIBUTE_PATTERN.test(key))
+ return null;
+ return CUSTOM_EXPORT_ATTRIBUTES[key] ?? key.toUpperCase();
+}
function geometryExportAttributes(exporter) {
return exporter === "three" ? THREE_GEOMETRY_ATTRIBUTES : EXPORTED_GEOMETRY_ATTRIBUTES;
}
@@ -22700,8 +22705,8 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
return;
const geometry = mesh.geometry;
const name = mesh.name || "<unnamed mesh>";
- const unsupported = (feature) => {
- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
+ const unsupported = (feature, hint = "") => {
+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.${hint}`;
if (policy === "strict")
throw new TypeError(message);
warnings.push(message);
@@ -22710,9 +22715,9 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = attributes[key];
+ const expected = attributes[key] ?? (customAttributeSemantic(key) ? AUTHOR_ATTRIBUTE_COMPONENTS : undefined);
if (expected === undefined) {
- unsupported(key);
+ unsupported(key, key.startsWith("_") ? " Author attributes use a lowercase name such as _wet (exported as _WET) with 1 to 4 float components." : "");
continue;
}
const sizes = typeof expected === "number" ? [expected] : expected;
@@ -22737,6 +22742,19 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ for (const slot of TEXTURE_SLOTS) {
+ const texture = material[slot];
+ const channel = texture?.isTexture ? texture.channel ?? 0 : 0;
+ if (channel === 0)
+ continue;
+ const uv = `uv${channel}`;
+ if (attributes[uv] === undefined)
+ unsupported(`${slot} UV channel ${channel}`);
+ else if (!geometry.getAttribute(uv))
+ throw new TypeError(`${name}: ${slot} samples ${uv}, which the geometry lacks.`);
+ }
+ }
if (exporter === "three" && Array.isArray(mesh.material))
validateMaterialGroups(geometry, mesh.material.length, name);
if (exporter === "legacy") {
@@ -22759,13 +22777,15 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
+var EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
normal: 3,
uv: 2,
+ uv1: 2,
tangent: 4,
+ color: [3, 4],
_edge: 1,
_cavity: 1
};
@@ -22773,10 +22793,18 @@ var init_geometry_export = __esm(() => {
_edge: "_EDGE",
_cavity: "_CAVITY"
};
+ AUTHOR_ATTRIBUTE_PATTERN = /^_[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
+ AUTHOR_ATTRIBUTE_COMPONENTS = [1, 2, 3, 4];
+ TEXTURE_SLOTS = [
+ "map",
+ "normalMap",
+ "roughnessMap",
+ "metalnessMap",
+ "aoMap",
+ "emissiveMap"
+ ];
THREE_GEOMETRY_ATTRIBUTES = {
...EXPORTED_GEOMETRY_ATTRIBUTES,
- color: [3, 4],
- uv1: 2,
uv2: 2,
uv3: 2,
skinIndex: 4,
@@ -37049,6 +37077,8 @@ function bridgeTextureSampler(source, target, atlas) {
}
}
target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);
+ if (source.channel === 1)
+ target.setTexCoord(1);
const ref = atlas?.texture(source);
if (ref)
target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });
@@ -37193,15 +37223,28 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
if (uvAttr) {
prim.setAttribute("TEXCOORD_0", doc.createAccessor(`${meshName}_uv`).setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));
}
+ const uv1Attr = geometry.getAttribute("uv1");
+ if (uv1Attr) {
+ prim.setAttribute("TEXCOORD_1", doc.createAccessor(`${meshName}_uv1`).setArray(geometryAttributeValues(uv1Attr)).setType(TYPE_VEC2).setBuffer(buf));
+ }
const tangentAttr = geometry.getAttribute("tangent");
if (tangentAttr?.itemSize === 4) {
prim.setAttribute("TANGENT", doc.createAccessor(`${meshName}_tangent`).setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));
}
- for (const [key, gltfName] of Object.entries(CUSTOM_EXPORT_ATTRIBUTES)) {
+ const colorAttr = geometry.getAttribute("color");
+ if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {
+ prim.setAttribute("COLOR_0", doc.createAccessor(`${meshName}_color`).setArray(geometryAttributeValues(colorAttr)).setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3).setBuffer(buf));
+ }
+ const customKeys = [
+ ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),
+ ...Object.keys(geometry.attributes).filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES)).sort()
+ ];
+ for (const key of customKeys) {
+ const gltfName = customAttributeSemantic(key);
const custom = geometry.getAttribute(key);
- if (custom?.itemSize !== 1)
+ if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4)
continue;
- prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(TYPE_SCALAR).setBuffer(buf));
+ prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(ACCESSOR_TYPES[custom.itemSize - 1]).setBuffer(buf));
}
const indexAttr = geometry.getIndex();
if (indexAttr) {
@@ -38003,7 +38046,7 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", ACCESSOR_TYPES, GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;
var init_render = __esm(() => {
init_requirements_context();
init_requirements_run();
@@ -38043,6 +38086,7 @@ var init_render = __esm(() => {
init_kit();
init_texture_bake();
engineIO = createGltfIO;
+ ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];
GLTF_MIN_FILTER = {
[THREE55.NearestFilter]: 9728,
[THREE55.LinearFilter]: 9729,
@@ -46148,7 +46192,6 @@ define2("repeatAlongCurve", {
],
limitations: [
"Tangents come from the polyline segments; sample curves densely for smooth turns.",
- "The default legacy GLB converter does not export the _along attribute.",
"Merged copies are one part: they are not separately named or addressable."
],
related: [
@@ -48640,7 +48683,8 @@ async function currentCapabilities(context, presentation) {
materialGroups: true,
skinning: exporter === undefined ? null : exporter === "three",
morphAttributes: exporter === undefined ? null : exporter === "three" ? ["position", "normal"] : [],
- unsupported: exporter === undefined ? null : exporter === "three" ? ["custom attributes", "UV4+", "morph attributes other than position/normal"] : ["vertex colors", "UV1+", "skinning", "morphs", "custom attributes"],
+ unsupported: exporter === undefined ? null : exporter === "three" ? ["UV4+", "morph attributes other than position/normal"] : ["UV2+", "skinning", "morphs"],
+ customAttributes: exporter === undefined ? null : "Lowercase underscore names such as _wet with 1 to 4 float components export as _WET; GLTFLoader reads them back as _wet.",
strictExport: "geometryPolicy:strict on GLB export or host context; local KILN_GEOMETRY_POLICY=strict",
implicitSurfaces: "experimental"
},
diff --git a/docs/export-profiles.md b/docs/export-profiles.md
index b380ec18..0621aa57 100644
--- a/docs/export-profiles.md
+++ b/docs/export-profiles.md
@@ -28,7 +28,7 @@ is available: a runtime sidecar is **not** a replacement for it.
| Setting | When it applies | Default | Optional choice | Why it exists |
| --- | --- | --- | --- | --- |
-| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, vertex colors, extra UV sets and material extensions |
+| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, extra UV sets and material extensions |
| Export profile | Delivery of an already-saved revision | `editable` | `runtime` | Keep exact authoring artifacts or externalize duplicate review data for application loading |
The converter is selected through the host's `KILN_GLTF_EXPORTER` environment or the
diff --git a/docs/extending.md b/docs/extending.md
index 5a45e3ce..3f402753 100644
--- a/docs/extending.md
+++ b/docs/extending.md
@@ -14,7 +14,7 @@ Copy shared primitive geometry with `copyGeometry` before modifying its buffers.
## Check what survives export
-Kiln exports triangle positions, normals, UV0, tangents, indices and material groups. Vertex colors, additional UV sets, skinning and morph targets are not supported by this bridge. The default policy reports unsupported data; `geometryPolicy: 'strict'` rejects it. Local CLI/MCP hosts can enforce the same policy with `KILN_GEOMETRY_POLICY=strict`.
+Kiln exports triangle positions, normals, UV0, a second UV set (`uv1`), tangents, vertex colors, lowercase underscore author attributes (such as `_wet`), indices and material groups; [geometry](geometry.md#carry-vertex-colours-and-author-masks) lists each converter's attributes. Further UV sets, skinning and morph targets are not supported by the default bridge. The default policy reports unsupported data; `geometryPolicy: 'strict'` rejects it. Local CLI/MCP hosts can enforce the same policy with `KILN_GEOMETRY_POLICY=strict`.
Inspect the exported GLB as well as the authored scene. Topology diagnostics do not prove that a model has no self-intersections, and CPU views do not establish material fidelity. A reusable part should include a small example that exercises its parameter limits and shows its attachments clearly.
diff --git a/docs/geometry.md b/docs/geometry.md
index 4818c7e6..b5e6fb86 100644
--- a/docs/geometry.md
+++ b/docs/geometry.md
@@ -398,7 +398,7 @@ Output is experimental, has no UVs, and records resolution and evaluation counts
`arrayLinear` and `arrayRadial` require integer counts from 1 to 10,000, including the existing source; their return value contains `count - 1` new meshes. Count 1 returns no copies. Frames, offsets/centers, and all resulting positions must be finite, with rejection before attaching any copies. Resources remain shared and these helpers do not batch draw calls.
-`repeatAlongCurve(source, points, { count, ... })` places `count` copies along a sampled curve, evenly spaced by arc length between `start` and `end` (fractions of its length). Each copy's local +X follows the tangent of the segment it sits on (the outgoing segment at a sample point) and local +Y points toward `up`, default `[0,1,0]`, made perpendicular to the tangent. `scale` and `twist` are constant or interpolated from attachment to tip; `opposite: true` adds a copy twisted a further 180 degrees at each position. With the default `merge: true` it returns one BufferGeometry: every source attribute is copied per copy, UVs unchanged, positions, normals and tangents transformed, material groups and morph targets not copied, and `along: true` adds a float `_along` attribute from 0 on the first copy to 1 on the last (the default `legacy` GLB converter does not yet export author underscore attributes, so `_along` is available in source but not in the saved GLB; see [#195](https://github.com/instruktlabs/kiln/issues/195)). A merge larger than 262,144 vertices fails before allocating. With `merge: false` it returns shared-geometry mesh nodes, like `arrayLinear`, and does not move the source.
+`repeatAlongCurve(source, points, { count, ... })` places `count` copies along a sampled curve, evenly spaced by arc length between `start` and `end` (fractions of its length). Each copy's local +X follows the tangent of the segment it sits on (the outgoing segment at a sample point) and local +Y points toward `up`, default `[0,1,0]`, made perpendicular to the tangent. `scale` and `twist` are constant or interpolated from attachment to tip; `opposite: true` adds a copy twisted a further 180 degrees at each position. With the default `merge: true` it returns one BufferGeometry: every source attribute is copied per copy, UVs unchanged, positions, normals and tangents transformed, material groups and morph targets not copied, and `along: true` adds a float `_along` attribute from 0 on the first copy to 1 on the last, which both GLB converters export as `_ALONG`. A merge larger than 262,144 vertices fails before allocating. With `merge: false` it returns shared-geometry mesh nodes, like `arrayLinear`, and does not move the source.
These are per-operation compute limits for every asset. Choose a coarser sampling/subdivision or deliberately split large work; no asset category selects a different budget.
@@ -445,6 +445,37 @@ geometry copy, because cavity depends on placement. The bake is deterministic an
bounded by `GEOMETRY_ALLOCATION_LIMITS`; see the [delivery contract](delivery-contract.md#baked-vertex-attributes)
for the formulas.
+## Carry vertex colours and author masks
+
+Export keeps these vertex attributes; anything else is reported as
+`EXPORT_ATTRIBUTE_UNSUPPORTED` (or rejected under `geometryPolicy: 'strict'`):
+
+| three.js attribute | glTF attribute | `legacy` (default) | `three` |
+| --- | --- | --- | --- |
+| `position`, `normal`, `uv`, `tangent` | `POSITION`, `NORMAL`, `TEXCOORD_0`, `TANGENT` | yes | yes |
+| `color` (3 or 4 components) | `COLOR_0` | yes | yes |
+| `_edge`, `_cavity` (baked) | `_EDGE`, `_CAVITY` | yes | yes |
+| lowercase `_name`, 1 to 4 float components | `_NAME` | yes | yes |
+| `uv1` | `TEXCOORD_1` | yes | yes |
+| `uv2`, `uv3` | `TEXCOORD_2`, `TEXCOORD_3` | no | yes |
+| `skinIndex`, `skinWeight` | `JOINTS_0`, `WEIGHTS_0` | no | yes |
+
+A texture with `channel = 1` (for example a baked `aoMap`) samples `uv1` (`TEXCOORD_1`); export
+refuses it when the mesh has no `uv1`, and reports channels a converter does not write.
+
+An author attribute name is an underscore, a lowercase letter, then lowercase
+letters, digits or single underscores (at most 64 characters), such as `_wet` or
+`_flow_dir`. It is written as 32-bit floats under the uppercase name, and three.js
+`GLTFLoader` reads it back under the lowercase one. Use it for a per-vertex mask
+such as a wet line or wear instead of cutting triangles along the boundary.
+`runtime --target three` keeps author attributes as unquantized 32-bit floats and lists
+them in the sidecar `customAttributes`. Mixed-case names such as `_Wet` would not
+round-trip and stay unsupported.
+
+glTF multiplies base colour by `COLOR_0`, and loaders enable vertex colours when it
+is present, whether or not the authoring material set `vertexColors`. Remove a
+`color` attribute that is not meant to tint the surface.
+
## Declare a triangle budget
`defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 })` records the asset's
diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.md
index f384cb23..9fe0018f 100644
--- a/skills/kiln-author-asset/references/export-profiles.md
+++ b/skills/kiln-author-asset/references/export-profiles.md
@@ -29,7 +29,7 @@ is available: a runtime sidecar is **not** a replacement for it.
| Setting | When it applies | Default | Optional choice | Why it exists |
| --- | --- | --- | --- | --- |
-| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, vertex colors, extra UV sets and material extensions |
+| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, extra UV sets and material extensions |
| Export profile | Delivery of an already-saved revision | `editable` | `runtime` | Keep exact authoring artifacts or externalize duplicate review data for application loading |
The converter is selected through the host's `KILN_GLTF_EXPORTER` environment or the
diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.md
index f75b4dfe..a8a8b249 100644
--- a/skills/kiln-author-asset/references/geometry-recipes.md
+++ b/skills/kiln-author-asset/references/geometry-recipes.md
@@ -304,6 +304,12 @@ that convention when editing the path; arbitrary atlas rotations suit baked deta
but can disrupt directional tiling. Caps and physical texture scale need separate
decisions. Read the GPU image: CPU geometry feedback cannot establish texture direction.
+For a per-vertex mask such as a wet line, wear or moss, set a float attribute with a
+lowercase underscore name (`_wet`, 1 to 4 components) instead of cutting triangles
+along the boundary; both converters export it as `_WET` for the destination shader.
+A `color` attribute exports as `COLOR_0`, which glTF multiplies into base colour, and a
+second UV set `uv1` exports as `TEXCOORD_1` for baked occlusion or unique wear maps.
+
## Shape an existing mesh
```js
diff --git a/src/__tests__/discovery.test.ts b/src/__tests__/discovery.test.ts
index 94d6e2e7..a4c93b08 100644
--- a/src/__tests__/discovery.test.ts
+++ b/src/__tests__/discovery.test.ts
@@ -39,15 +39,15 @@ describe('progressive capability discovery', () => {
const bytes = Buffer.from(rendered.glb);
const document = JSON.parse(bytes.subarray(20, 20 + bytes.readUInt32LE(12)).toString());
const attributes = document.meshes[0].primitives[0].attributes;
- for (const [sourceKey, gltfKey] of [
- ['color', 'COLOR_0'],
- ['uv1', 'TEXCOORD_1'],
- ['uv2', 'TEXCOORD_2'],
- ['uv3', 'TEXCOORD_3'],
- ]) {
- const reported = result.capabilities.geometry.attributes.includes(sourceKey!);
- expect(reported).toBe(exporter === 'three');
- expect(gltfKey! in attributes).toBe(reported);
+ for (const [sourceKey, gltfKey, both] of [
+ ['color', 'COLOR_0', true],
+ ['uv1', 'TEXCOORD_1', true],
+ ['uv2', 'TEXCOORD_2', false],
+ ['uv3', 'TEXCOORD_3', false],
+ ] as const) {
+ const reported = result.capabilities.geometry.attributes.includes(sourceKey);
+ expect(reported).toBe(both || exporter === 'three');
+ expect(gltfKey in attributes).toBe(reported);
}
}
});
diff --git a/src/__tests__/geometry-export-contract.test.ts b/src/__tests__/geometry-export-contract.test.ts
index 9280eada..959d55e9 100644
--- a/src/__tests__/geometry-export-contract.test.ts
+++ b/src/__tests__/geometry-export-contract.test.ts
@@ -63,6 +63,75 @@ describe('custom mesh export contract', () => {
);
});
+ for (const gltfExporter of ['legacy', 'three'] as const)
+ it(`${gltfExporter} writes vertex colours and lowercase underscore author attributes`, async () => {
+ const { root, geometry } = fixture();
+ const color = [1, 0, 0, 1, 0, 1, 0, 0.5, 0, 0, 1, 0.25];
+ geometry.setAttribute('color', new THREE.Float32BufferAttribute(color, 4));
+ geometry.setAttribute('_wet', new THREE.Float32BufferAttribute([0, 1, 1], 1));
+ geometry.setAttribute('_flow_dir', new THREE.Float32BufferAttribute([1, 0, 0, 1, 1, 1], 2));
+ geometry.setAttribute('uv1', new THREE.Float32BufferAttribute([0.5, 0, 1, 0.5, 0, 1], 2));
+ const result = await renderSceneToGLB(root, {
+ dedup: false,
+ optimize: 'off',
+ instance: 'off',
+ gltfExporter,
+ });
+ expect(result.warnings.join('\n')).not.toContain('EXPORT_ATTRIBUTE_UNSUPPORTED');
+ const doc = await new WebIO().readBinary(result.bytes);
+ const primitive = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
+ const values = (semantic: string) => {
+ const accessor = primitive.getAttribute(semantic);
+ if (!accessor) throw new Error(`missing ${semantic}`);
+ return { type: accessor.getType(), values: Array.from(accessor.getArray()!) };
+ };
+ expect(values('COLOR_0')).toEqual({ type: 'VEC4', values: color });
+ expect(values('_WET')).toEqual({ type: 'SCALAR', values: [0, 1, 1] });
+ expect(values('_FLOW_DIR')).toEqual({ type: 'VEC2', values: [1, 0, 0, 1, 1, 1] });
+ expect(values('TEXCOORD_1')).toEqual({ type: 'VEC2', values: [0.5, 0, 1, 0.5, 0, 1] });
+ });
+
+ it('legacy samples a channel-1 occlusion map through TEXCOORD_1', async () => {
+ const { root, geometry } = fixture();
+ const mesh = root.children[0] as THREE.Mesh;
+ const ao = new THREE.DataTexture(new Uint8Array([200, 200, 200, 255]), 1, 1);
+ ao.needsUpdate = true;
+ ao.channel = 1;
+ (mesh.material as THREE.MeshStandardMaterial).aoMap = ao;
+ // Pinned: CI also runs the suite with KILN_GLTF_EXPORTER=three, which names the set uv2.
+ const legacy = { gltfExporter: 'legacy' } as const;
+ await expect(renderSceneToGLB(root, legacy)).rejects.toThrow(
+ 'CustomPanel: aoMap samples uv1, which the geometry lacks.',
+ );
+ geometry.setAttribute('uv1', new THREE.Float32BufferAttribute([0, 0, 1, 0, 0, 1], 2));
+ const result = await renderSceneToGLB(root, {
+ ...legacy,
+ dedup: false,
+ optimize: 'off',
+ instance: 'off',
+ });
+ const doc = await new WebIO().readBinary(result.bytes);
+ expect(doc.getRoot().listMaterials()[0]!.getOcclusionTextureInfo()!.getTexCoord()).toBe(1);
+ ao.channel = 2;
+ expect((await renderSceneToGLB(root, legacy)).warnings).toContain(
+ 'EXPORT_ATTRIBUTE_UNSUPPORTED CustomPanel: aoMap UV channel 2 is not preserved by the GLB bridge.',
+ );
+ });
+
+ it('names author attributes that cannot round-trip through GLTFLoader', async () => {
+ const { root, geometry } = fixture();
+ geometry.setAttribute('_Wet', new THREE.Float32BufferAttribute([0, 1, 1], 1));
+ const result = await renderSceneToGLB(root);
+ expect(result.warnings).toContain(
+ 'EXPORT_ATTRIBUTE_UNSUPPORTED CustomPanel: _Wet is not preserved by the GLB bridge. Author attributes use a lowercase name such as _wet (exported as _WET) with 1 to 4 float components.',
+ );
+ geometry.deleteAttribute('_Wet');
+ geometry.setAttribute('_wet', new THREE.Float32BufferAttribute(new Array(15).fill(0), 5));
+ await expect(renderSceneToGLB(root)).rejects.toThrow(
+ 'CustomPanel: _wet requires 3 vertices with 1 or 2 or 3 or 4 components each.',
+ );
+ });
+
it('rejects nonfinite positions before writing invalid bytes', async () => {
const { root, geometry } = fixture();
geometry.getAttribute('position').setX(0, Number.NaN);
diff --git a/src/__tests__/runtime-three-export.test.ts b/src/__tests__/runtime-three-export.test.ts
index 182c0e10..b88299b9 100644
--- a/src/__tests__/runtime-three-export.test.ts
+++ b/src/__tests__/runtime-three-export.test.ts
@@ -228,6 +228,58 @@ describe('three runtime target', () => {
expect((await deliverThreeRuntimeGlb(bytes)).glb).toEqual(skipped.glb);
});
+ test('an authored two-region mask survives save, editable export and the three runtime target', async () => {
+ const program = `const meta={name:'Wet Line'};
+function build(){
+ const root=createRoot('Root');
+ const geo=boxGeo(1,1,1);
+ const position=geo.getAttribute('position');
+ const wet=new Float32Array(position.count);
+ for(let i=0;i<position.count;i++) wet[i]=position.getY(i)<0?1:0;
+ geo.setAttribute('_wet',new THREE.BufferAttribute(wet,1));
+ geo.setAttribute('_aged',new THREE.BufferAttribute(new Float32Array(position.count).fill(0.5),1));
+ const rock=createPart('Rock',geo,gameMaterial('#888070'),{parent:root});
+ bakeSurfaceAttributes(rock,{cavity:{rays:8}});
+ return root;
+}`;
+ const rendered = await renderGLBInProcess(program);
+ expect(rendered.warnings.join('\n')).not.toContain('EXPORT_ATTRIBUTE_UNSUPPORTED');
+ const saved = new Uint8Array(rendered.glb);
+ const editable = await exportAssetGlb(assetRecord(saved), { profile: 'editable' });
+ const runtime = await exportAssetGlb(assetRecord(saved), {
+ profile: 'runtime',
+ target: 'three',
+ metadataFileName: 'rock.kiln-metadata.json',
+ });
+ if (runtime.profile !== 'runtime') throw new Error('expected runtime');
+ const delivery = JSON.parse(new TextDecoder().decode(runtime.metadata.bytes)).delivery;
+ expect(delivery.customAttributes.map((a: { name: string }) => a.name)).toEqual([
+ '_EDGE',
+ '_CAVITY',
+ '_AGED',
+ '_WET',
+ ]);
+ expect(delivery.customAttributes[3]).toEqual({
+ name: '_WET',
+ meshes: 1,
+ componentType: 'FLOAT',
+ normalized: false,
+ });
+ for (const bytes of [saved, editable.glb, runtime.glb]) {
+ const gltf = await loadWithGltfLoader(bytes);
+ let mesh: THREE.Mesh | undefined;
+ gltf.scene.traverse((node) => {
+ if ((node as THREE.Mesh).isMesh) mesh ??= node as THREE.Mesh;
+ });
+ if (!mesh) throw new Error('missing mesh');
+ const wet = mesh.geometry.getAttribute('_wet');
+ const position = mesh.geometry.getAttribute('position');
+ const regions = new Set<string>();
+ for (let i = 0; i < wet.count; i++) regions.add(`${position.getY(i) < 0}:${wet.getX(i)}`);
+ expect([...regions].sort()).toEqual(['false:0', 'true:1']);
+ }
+ });
+
test('target three requires the runtime profile', async () => {
const rendered = await renderGLBInProcess(RUNTIME_PROGRAM);
await expect(
diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.ts
index 89090820..9910ed95 100644
--- a/src/discovery/helper-contracts.ts
+++ b/src/discovery/helper-contracts.ts
@@ -2138,7 +2138,6 @@ define(
],
limitations: [
'Tangents come from the polyline segments; sample curves densely for smooth turns.',
- 'The default legacy GLB converter does not export the _along attribute.',
'Merged copies are one part: they are not separately named or addressable.',
],
related: [
diff --git a/src/geometry-export.ts b/src/geometry-export.ts
index d49801f6..d2227fd9 100644
--- a/src/geometry-export.ts
+++ b/src/geometry-export.ts
@@ -1,11 +1,13 @@
import type * as THREE from 'three';
export type GeometryExportPolicy = 'warn' | 'strict';
-export const EXPORTED_GEOMETRY_ATTRIBUTES: Readonly<Record<string, number>> = {
+export const EXPORTED_GEOMETRY_ATTRIBUTES: Readonly<Record<string, number | readonly number[]>> = {
position: 3,
normal: 3,
uv: 2,
+ uv1: 2,
tangent: 4,
+ color: [3, 4],
// Delivery contract custom attributes (bakeSurfaceAttributes), written as _EDGE/_CAVITY.
_edge: 1,
_cavity: 1,
@@ -17,10 +19,33 @@ export const CUSTOM_EXPORT_ATTRIBUTES: Readonly<Record<string, string>> = {
_cavity: '_CAVITY',
};
+/**
+ * Author attributes: a lowercase three.js name such as `_wet` is written by both converters as a
+ * float glTF attribute `_WET`, which GLTFLoader reads back as `_wet`. Other names would not
+ * round-trip, so they stay unsupported.
+ */
+export const AUTHOR_ATTRIBUTE_PATTERN = /^_[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
+export const AUTHOR_ATTRIBUTE_COMPONENTS: readonly number[] = [1, 2, 3, 4];
+const AUTHOR_ATTRIBUTE_MAX_NAME = 64;
+
+/** glTF semantic for a three.js custom attribute name, or null when it is not one. */
+export function customAttributeSemantic(key: string): string | null {
+ if (key.length > AUTHOR_ATTRIBUTE_MAX_NAME || !AUTHOR_ATTRIBUTE_PATTERN.test(key)) return null;
+ return CUSTOM_EXPORT_ATTRIBUTES[key] ?? key.toUpperCase();
+}
+
+/** Material texture slots whose UV channel export must preserve. */
+const TEXTURE_SLOTS = [
+ 'map',
+ 'normalMap',
+ 'roughnessMap',
+ 'metalnessMap',
+ 'aoMap',
+ 'emissiveMap',
+] as const;
+
const THREE_GEOMETRY_ATTRIBUTES = {
...EXPORTED_GEOMETRY_ATTRIBUTES,
- color: [3, 4],
- uv1: 2,
uv2: 2,
uv3: 2,
skinIndex: 4,
@@ -138,17 +163,23 @@ export function inspectGeometryExport(
if (!mesh.isMesh) return;
const geometry = mesh.geometry;
const name = mesh.name || '<unnamed mesh>';
- const unsupported = (feature: string) => {
- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
+ const unsupported = (feature: string, hint = '') => {
+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.${hint}`;
if (policy === 'strict') throw new TypeError(message);
warnings.push(message);
};
const position = geometry.getAttribute('position');
if (position?.itemSize !== 3) throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = attributes[key];
+ const expected =
+ attributes[key] ?? (customAttributeSemantic(key) ? AUTHOR_ATTRIBUTE_COMPONENTS : undefined);
if (expected === undefined) {
- unsupported(key);
+ unsupported(
+ key,
+ key.startsWith('_')
+ ? ' Author attributes use a lowercase name such as _wet (exported as _WET) with 1 to 4 float components.'
+ : '',
+ );
continue;
}
const sizes = typeof expected === 'number' ? [expected] : expected;
@@ -175,6 +206,20 @@ export function inspectGeometryExport(
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
+ // A texture's UV channel must reach the GLB, or it would silently sample UV0.
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ for (const slot of TEXTURE_SLOTS) {
+ const texture = (material as unknown as Record<string, THREE.Texture | null | undefined>)[
+ slot
+ ];
+ const channel = texture?.isTexture ? (texture.channel ?? 0) : 0;
+ if (channel === 0) continue;
+ const uv = `uv${channel}`;
+ if (attributes[uv] === undefined) unsupported(`${slot} UV channel ${channel}`);
+ else if (!geometry.getAttribute(uv))
+ throw new TypeError(`${name}: ${slot} samples ${uv}, which the geometry lacks.`);
+ }
+ }
if (exporter === 'three' && Array.isArray(mesh.material))
validateMaterialGroups(geometry, mesh.material.length, name);
if (exporter === 'legacy') {
diff --git a/src/render.ts b/src/render.ts
index ce516860..442bcf8f 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -57,6 +57,7 @@ import { rigExtrasForExport } from './rig-export';
import { type AuthorExtras, collectAuthorExtras } from './user-data-extras';
import {
CUSTOM_EXPORT_ATTRIBUTES,
+ customAttributeSemantic,
geometryAttributeValues,
inspectGeometryExport,
validateMaterialGroups,
@@ -236,6 +237,8 @@ const TYPE_SCALAR: AccessorTypeStr = 'SCALAR';
const TYPE_VEC2: AccessorTypeStr = 'VEC2';
const TYPE_VEC3: AccessorTypeStr = 'VEC3';
const TYPE_VEC4: AccessorTypeStr = 'VEC4';
+/** Accessor type by component count, 1 to 4. */
+const ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4] as const;
// =============================================================================
// Execution
@@ -584,6 +587,8 @@ function bridgeTextureSampler(
}
}
target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);
+ // Export inspection has already refused channels the geometry cannot supply.
+ if (source.channel === 1) target.setTexCoord(1);
const ref = atlas?.texture(source);
if (ref) target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });
}
@@ -814,6 +819,18 @@ function bridgeGeometry(
);
}
+ const uv1Attr = geometry.getAttribute('uv1') as THREE.BufferAttribute | undefined;
+ if (uv1Attr) {
+ prim.setAttribute(
+ 'TEXCOORD_1',
+ doc
+ .createAccessor(`${meshName}_uv1`)
+ .setArray(geometryAttributeValues(uv1Attr))
+ .setType(TYPE_VEC2)
+ .setBuffer(buf),
+ );
+ }
+
const tangentAttr = geometry.getAttribute('tangent') as THREE.BufferAttribute | undefined;
if (tangentAttr?.itemSize === 4) {
prim.setAttribute(
@@ -826,15 +843,35 @@ function bridgeGeometry(
);
}
- for (const [key, gltfName] of Object.entries(CUSTOM_EXPORT_ATTRIBUTES)) {
+ const colorAttr = geometry.getAttribute('color') as THREE.BufferAttribute | undefined;
+ if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {
+ prim.setAttribute(
+ 'COLOR_0',
+ doc
+ .createAccessor(`${meshName}_color`)
+ .setArray(geometryAttributeValues(colorAttr))
+ .setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3)
+ .setBuffer(buf),
+ );
+ }
+
+ // Baked attributes keep their established order; author attributes follow in name order.
+ const customKeys = [
+ ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),
+ ...Object.keys(geometry.attributes)
+ .filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES))
+ .sort(),
+ ];
+ for (const key of customKeys) {
+ const gltfName = customAttributeSemantic(key);
const custom = geometry.getAttribute(key) as THREE.BufferAttribute | undefined;
- if (custom?.itemSize !== 1) continue;
+ if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4) continue;
prim.setAttribute(
gltfName,
doc
.createAccessor(`${meshName}${gltfName.toLowerCase()}`)
.setArray(geometryAttributeValues(custom))
- .setType(TYPE_SCALAR)
+ .setType(ACCESSOR_TYPES[custom.itemSize - 1]!)
.setBuffer(buf),
);
}
diff --git a/src/runtime-three.ts b/src/runtime-three.ts
index efae96a4..2e670b16 100644
--- a/src/runtime-three.ts
+++ b/src/runtime-three.ts
@@ -8,7 +8,7 @@
* - KTX2 (`KHR_texture_basisu`) only when the host supplies an encoder, reported `skipped`
* otherwise.
*
- * Kept: `_EDGE`/`_CAVITY` and every other underscore attribute (as float32, never quantized),
+ * Kept: `_EDGE`/`_CAVITY` and author underscore attributes such as `_WET` (float32, never quantized),
* semantic roles and kit extras, hidden collider nodes, anchors, ports and `MSFT_lod` chains.
* A collider node keeps its authored transform: its proxy mesh moves to a child first, so the
* dequantization transform lands on that child instead of the collider's size. Static mesh
@@ -112,6 +112,7 @@ export interface RuntimeThreeDeliveryV1 {
};
}
+const customRank = (name: string) => (name === '_EDGE' ? 0 : name === '_CAVITY' ? 1 : 2);
const rolesOf = (node: Node): string[] =>
readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
const isCollider = (node: Node) =>
@@ -414,7 +415,8 @@ export async function deliverRuntimeThreeGlb(
proxy: pathOf(proxy),
})),
customAttributes: [...customAttributes]
- .sort(([a], [b]) => (a === '_EDGE' ? -1 : b === '_EDGE' ? 1 : a < b ? -1 : a > b ? 1 : 0))
+ // Same order as delivery inspection: _EDGE, _CAVITY, then author attributes by name.
+ .sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0))
.map(([name, meshes]) => ({
name,
meshes: meshes.size,
diff --git a/src/tools/discovery.ts b/src/tools/discovery.ts
index 1dfba112..f5ed082d 100644
--- a/src/tools/discovery.ts
+++ b/src/tools/discovery.ts
@@ -156,8 +156,12 @@ async function currentCapabilities(
exporter === undefined
? null
: exporter === 'three'
- ? ['custom attributes', 'UV4+', 'morph attributes other than position/normal']
- : ['vertex colors', 'UV1+', 'skinning', 'morphs', 'custom attributes'],
+ ? ['UV4+', 'morph attributes other than position/normal']
+ : ['UV2+', 'skinning', 'morphs'],
+ customAttributes:
+ exporter === undefined
+ ? null
+ : 'Lowercase underscore names such as _wet with 1 to 4 float components export as _WET; GLTFLoader reads them back as _wet.',
strictExport:
'geometryPolicy:strict on GLB export or host context; local KILN_GEOMETRY_POLICY=strict',
implicitSurfaces: 'experimental',
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 35c36742..0aeb0ad3 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -510,8 +510,8 @@ async function renderDerivativeCell(
// and adjudicated. Submitting it for judgement a second time fails on the
// round trip rather than on the asset: see `derivative` in render.ts.
derivative: true,
- // Review reconstruction preserves vertex colors and secondary UVs; the legacy
- // authored exporter does not carry those channels into the GPU derivative.
+ // Review reconstruction preserves UV2 and UV3; the legacy authored exporter
+ // does not carry them into the GPU derivative.
gltfExporter: 'three',
requirements: toolRequirements(context).binding,
});