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): normalise non-unit normals with a note naming the part (#217) (#231)

Matthew Kissingerd19c84d20206
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aefcbac7..e7e6efea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,6 +76,13 @@ does not publish a package.
largest radius so the seam stays continuous. Calls without it are unchanged. The contract
and geometry docs say to weld the non-indexed output with `mergeVertices` where the
projection is continuous.
+- Normalise non-unit normals on export ([#217](https://github.com/instruktlabs/kiln/issues/217)).
+ A raw `THREE.LatheGeometry` whose profile nears the axis left pole normals of length
+ 0.02 to 0.13, and export stopped with repeated `GLTF_ACCESSOR_VECTOR3_NON_UNIT` lines naming
+ an accessor. Export now writes those normals at unit length with one `NORMALS_NORMALISED`
+ note naming the part and count, leaving the authored geometry and unit normals untouched.
+ A zero-length normal fails naming the part and vertex, with `lathe`, `revolveGeo` or
+ `creaseNormals` as the remedy.
## 1.3.1 (2026-10-17)
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 160cb8b1..7f38e767 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -25589,6 +25589,28 @@ function geometryAttributeValues(attribute) {
}
return values;
}
+function unitNormalValues(attribute) {
+ const values = geometryAttributeValues(attribute);
+ for (let i = 0;i < values.length; i += 3) {
+ const length = Math.hypot(values[i], values[i + 1], values[i + 2]);
+ if (Math.abs(length - 1) <= UNIT_NORMAL_TOLERANCE || length === 0)
+ continue;
+ for (let component = 0;component < 3; component++)
+ values[i + component] /= length;
+ }
+ return values;
+}
+function offUnitNormals(normal, name) {
+ let count = 0;
+ for (let vertex = 0;vertex < normal.count; vertex++) {
+ const length = Math.hypot(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
+ if (length < 0.000001)
+ throw new TypeError(`${name}: normal at vertex ${vertex} has zero length, so it has no direction to export. Build revolved profiles with lathe or revolveGeo, or recompute the normals with creaseNormals.`);
+ if (Math.abs(length - 1) > UNIT_NORMAL_TOLERANCE)
+ count++;
+ }
+ return count;
+}
function noteMeshList(names) {
const counts = new Map;
for (const name of names)
@@ -25659,6 +25681,10 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
}
}
}
+ const normal = geometry.getAttribute("normal");
+ const offUnit = normal?.itemSize === 3 ? offUnitNormals(normal, name) : 0;
+ if (offUnit > 0)
+ addNote(mesh, name, "NORMALS_NORMALISED", `${offUnit} non-unit normals were scaled to unit length on export.`);
const index = geometry.getIndex();
if ((index?.count ?? position.count) % 3 !== 0)
throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
@@ -25704,7 +25730,7 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-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 EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, UNIT_NORMAL_TOLERANCE = 0.0005, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
@@ -36745,7 +36771,7 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
}
const normAttr = geometry.getAttribute("normal");
if (normAttr) {
- prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
+ prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(unitNormalValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
}
const uvAttr = geometry.getAttribute("uv");
if (uvAttr) {
diff --git a/dist/build.json b/dist/build.json
index 05b2596a..371581f8 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:30d934d80e37799159bb656bc76edcbabb256fb903af065833cad20ba09ee7a2",
+ "identity": "sha256:87db6a4bebbd23ff45c63007ed94737db002c806798867672bc36a3932d705e5",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "cc66db80ad8d09fd170de4896b49ab1bba756ef982d4b76085759951340f82dc",
+ "sourceHash": "933586256ec90971162f278942bc4e5ccb37de7b4eedad01b3631a505d70cf28",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -37,13 +37,13 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:f467cfb2d687775eaac65fc713d5deb92b912844e6e418467ca345d7dfaf3244"
+ "bundleHash": "sha256:eb4c421782d3d96e7f4ba04072ecdca10af471d17299bc42a1e0e2fc4c54c421"
},
"agent-run": {
- "identity": "sha256:30d934d80e37799159bb656bc76edcbabb256fb903af065833cad20ba09ee7a2",
+ "identity": "sha256:87db6a4bebbd23ff45c63007ed94737db002c806798867672bc36a3932d705e5",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "cc66db80ad8d09fd170de4896b49ab1bba756ef982d4b76085759951340f82dc",
+ "sourceHash": "933586256ec90971162f278942bc4e5ccb37de7b4eedad01b3631a505d70cf28",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -75,13 +75,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:6077d9e31e214dc97a6383eb591f95e9dd88aff36ee5466486533a163162e07f"
+ "bundleHash": "sha256:463f1803f3cf6cbe1c33e0eba1651b012dc5b39d7afa762a7ef155780a0b31f4"
},
"agent-providers": {
- "identity": "sha256:30d934d80e37799159bb656bc76edcbabb256fb903af065833cad20ba09ee7a2",
+ "identity": "sha256:87db6a4bebbd23ff45c63007ed94737db002c806798867672bc36a3932d705e5",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "cc66db80ad8d09fd170de4896b49ab1bba756ef982d4b76085759951340f82dc",
+ "sourceHash": "933586256ec90971162f278942bc4e5ccb37de7b4eedad01b3631a505d70cf28",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -116,10 +116,10 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:30d934d80e37799159bb656bc76edcbabb256fb903af065833cad20ba09ee7a2",
+ "identity": "sha256:87db6a4bebbd23ff45c63007ed94737db002c806798867672bc36a3932d705e5",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "cc66db80ad8d09fd170de4896b49ab1bba756ef982d4b76085759951340f82dc",
+ "sourceHash": "933586256ec90971162f278942bc4e5ccb37de7b4eedad01b3631a505d70cf28",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -154,10 +154,10 @@
"bundleHash": "sha256:a246b2c79d629a332cef4430dbe742b0c4a0d2f04f0281e673c3c60ff22706da"
},
"cli": {
- "identity": "sha256:30d934d80e37799159bb656bc76edcbabb256fb903af065833cad20ba09ee7a2",
+ "identity": "sha256:87db6a4bebbd23ff45c63007ed94737db002c806798867672bc36a3932d705e5",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "cc66db80ad8d09fd170de4896b49ab1bba756ef982d4b76085759951340f82dc",
+ "sourceHash": "933586256ec90971162f278942bc4e5ccb37de7b4eedad01b3631a505d70cf28",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -189,13 +189,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:2d905a68e31ee6aa97f0c303d51246aa4f8f4414b28f907335f7acac91a5a01b"
+ "bundleHash": "sha256:75e9b3dae1ad7bfcb0bc9ce07d18d005e6720d0ee2f3fc5bbffe2bb4d364981c"
},
"engine": {
- "identity": "sha256:30d934d80e37799159bb656bc76edcbabb256fb903af065833cad20ba09ee7a2",
+ "identity": "sha256:87db6a4bebbd23ff45c63007ed94737db002c806798867672bc36a3932d705e5",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "cc66db80ad8d09fd170de4896b49ab1bba756ef982d4b76085759951340f82dc",
+ "sourceHash": "933586256ec90971162f278942bc4e5ccb37de7b4eedad01b3631a505d70cf28",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "20b5b45a138ab83d340e78729d1a427bdc9b8aeadc47c5f7acf907eab43377f3",
"dependencies": {
@@ -227,7 +227,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:970aad4330d6b90fb28441312f9add1784d7c8f96ac0cbdee9666d925c6f2832"
+ "bundleHash": "sha256:00469f2fe9953b0dfb942f62d27cab9a2c0e2a5363456592ba0d1f849fd1214c"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 894904ad..d2a632f0 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -23259,6 +23259,28 @@ function geometryAttributeValues(attribute) {
}
return values;
}
+function unitNormalValues(attribute) {
+ const values = geometryAttributeValues(attribute);
+ for (let i = 0;i < values.length; i += 3) {
+ const length = Math.hypot(values[i], values[i + 1], values[i + 2]);
+ if (Math.abs(length - 1) <= UNIT_NORMAL_TOLERANCE || length === 0)
+ continue;
+ for (let component = 0;component < 3; component++)
+ values[i + component] /= length;
+ }
+ return values;
+}
+function offUnitNormals(normal, name) {
+ let count = 0;
+ for (let vertex = 0;vertex < normal.count; vertex++) {
+ const length = Math.hypot(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
+ if (length < 0.000001)
+ throw new TypeError(`${name}: normal at vertex ${vertex} has zero length, so it has no direction to export. Build revolved profiles with lathe or revolveGeo, or recompute the normals with creaseNormals.`);
+ if (Math.abs(length - 1) > UNIT_NORMAL_TOLERANCE)
+ count++;
+ }
+ return count;
+}
function noteMeshList(names) {
const counts = new Map;
for (const name of names)
@@ -23329,6 +23351,10 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
}
}
}
+ const normal = geometry.getAttribute("normal");
+ const offUnit = normal?.itemSize === 3 ? offUnitNormals(normal, name) : 0;
+ if (offUnit > 0)
+ addNote(mesh, name, "NORMALS_NORMALISED", `${offUnit} non-unit normals were scaled to unit length on export.`);
const index = geometry.getIndex();
if ((index?.count ?? position.count) % 3 !== 0)
throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
@@ -23374,7 +23400,7 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-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 EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, UNIT_NORMAL_TOLERANCE = 0.0005, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
@@ -37850,7 +37876,7 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
}
const normAttr = geometry.getAttribute("normal");
if (normAttr) {
- prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
+ prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(unitNormalValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
}
const uvAttr = geometry.getAttribute("uv");
if (uvAttr) {
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index e276d7a7..57dbceb8 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -16855,6 +16855,28 @@ function geometryAttributeValues(attribute) {
}
return values;
}
+function unitNormalValues(attribute) {
+ const values = geometryAttributeValues(attribute);
+ for (let i = 0;i < values.length; i += 3) {
+ const length = Math.hypot(values[i], values[i + 1], values[i + 2]);
+ if (Math.abs(length - 1) <= UNIT_NORMAL_TOLERANCE || length === 0)
+ continue;
+ for (let component = 0;component < 3; component++)
+ values[i + component] /= length;
+ }
+ return values;
+}
+function offUnitNormals(normal, name) {
+ let count = 0;
+ for (let vertex = 0;vertex < normal.count; vertex++) {
+ const length = Math.hypot(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
+ if (length < 0.000001)
+ throw new TypeError(`${name}: normal at vertex ${vertex} has zero length, so it has no direction to export. Build revolved profiles with lathe or revolveGeo, or recompute the normals with creaseNormals.`);
+ if (Math.abs(length - 1) > UNIT_NORMAL_TOLERANCE)
+ count++;
+ }
+ return count;
+}
function noteMeshList(names) {
const counts = new Map;
for (const name of names)
@@ -16925,6 +16947,10 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
}
}
}
+ const normal = geometry.getAttribute("normal");
+ const offUnit = normal?.itemSize === 3 ? offUnitNormals(normal, name) : 0;
+ if (offUnit > 0)
+ addNote(mesh, name, "NORMALS_NORMALISED", `${offUnit} non-unit normals were scaled to unit length on export.`);
const index = geometry.getIndex();
if ((index?.count ?? position.count) % 3 !== 0)
throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
@@ -16970,7 +16996,7 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-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 EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, UNIT_NORMAL_TOLERANCE = 0.0005, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
@@ -33197,7 +33223,7 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
}
const normAttr = geometry.getAttribute("normal");
if (normAttr) {
- prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
+ prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(unitNormalValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
}
const uvAttr = geometry.getAttribute("uv");
if (uvAttr) {
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 79502dda..be34a5c3 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -22823,6 +22823,28 @@ function geometryAttributeValues(attribute) {
}
return values;
}
+function unitNormalValues(attribute) {
+ const values = geometryAttributeValues(attribute);
+ for (let i = 0;i < values.length; i += 3) {
+ const length = Math.hypot(values[i], values[i + 1], values[i + 2]);
+ if (Math.abs(length - 1) <= UNIT_NORMAL_TOLERANCE || length === 0)
+ continue;
+ for (let component = 0;component < 3; component++)
+ values[i + component] /= length;
+ }
+ return values;
+}
+function offUnitNormals(normal, name) {
+ let count = 0;
+ for (let vertex = 0;vertex < normal.count; vertex++) {
+ const length = Math.hypot(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
+ if (length < 0.000001)
+ throw new TypeError(`${name}: normal at vertex ${vertex} has zero length, so it has no direction to export. Build revolved profiles with lathe or revolveGeo, or recompute the normals with creaseNormals.`);
+ if (Math.abs(length - 1) > UNIT_NORMAL_TOLERANCE)
+ count++;
+ }
+ return count;
+}
function noteMeshList(names) {
const counts = new Map;
for (const name of names)
@@ -22893,6 +22915,10 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
}
}
}
+ const normal = geometry.getAttribute("normal");
+ const offUnit = normal?.itemSize === 3 ? offUnitNormals(normal, name) : 0;
+ if (offUnit > 0)
+ addNote(mesh, name, "NORMALS_NORMALISED", `${offUnit} non-unit normals were scaled to unit length on export.`);
const index = geometry.getIndex();
if ((index?.count ?? position.count) % 3 !== 0)
throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
@@ -22938,7 +22964,7 @@ function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
});
return warnings.map((warning) => typeof warning === "string" ? warning : formatNoteGroup(warning));
}
-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 EXPORTED_GEOMETRY_ATTRIBUTES, CUSTOM_EXPORT_ATTRIBUTES, AUTHOR_ATTRIBUTE_PATTERN, AUTHOR_ATTRIBUTE_COMPONENTS, AUTHOR_ATTRIBUTE_MAX_NAME = 64, TEXTURE_SLOTS, THREE_GEOMETRY_ATTRIBUTES, UNIT_NORMAL_TOLERANCE = 0.0005, NOTE_NAMES_SHOWN = 3;
var init_geometry_export = __esm(() => {
EXPORTED_GEOMETRY_ATTRIBUTES = {
position: 3,
@@ -37387,7 +37413,7 @@ function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {
}
const normAttr = geometry.getAttribute("normal");
if (normAttr) {
- prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
+ prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(unitNormalValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));
}
const uvAttr = geometry.getAttribute("uv");
if (uvAttr) {
diff --git a/docs/geometry.md b/docs/geometry.md
index 1ddac364..16807fc3 100644
--- a/docs/geometry.md
+++ b/docs/geometry.md
@@ -252,6 +252,7 @@ const report = geometryDiagnostics(shaded);
- `subdivide(..., { preserveUV: true })` keeps per-corner UV charts while smoothing positions. The default position-only weld reports UV loss with `SUBDIVIDE_UV_DROPPED`; losses of other attributes, groups and morphs are also explicit.
- `mergeVertices` normally keeps separate vertices where normals or UVs differ. `{ positionOnly: true }` explicitly drops other attributes to weld geometric topology.
- `creaseNormals` preserves UV corners, averages neighboring face normals within the degree threshold, and invalidates tangents. Its position tolerance defaults to `1e-8` times the bounding-box diagonal, with no world-unit floor. An explicit positive `tolerance` overrides that distance.
+- Export writes unit normals. A non-unit normal, such as a pole ring from raw `THREE.LatheGeometry`, is scaled to unit length in the written file with one `NORMALS_NORMALISED` note naming the part and count; your geometry is not changed and shading is identical. A zero-length normal has no direction, so export fails naming the part and vertex; build revolved profiles with `lathe` or `revolveGeo`, or recompute with `creaseNormals`.
- `geometryDiagnostics` reports boundary edges, non-manifold edges, inconsistent edge orientation, degenerate triangles, invalid indices, and nonfinite vertices. Default seam tolerance is `1e-6` times the finite-position bounding-box diagonal. A supplied positive tolerance remains an absolute geometry-local distance. The result exposes `tolerance`, `toleranceMode`, and `positionScale`. Open boundaries are expected for sheets; the counts do not certify a valid solid or detect general self-intersections.
- `collapsedByToleranceTriangles` reports faces whose vertices merge in that diagnostic grid. Those faces are excluded from edge counts so their remaining edges are not counted twice. This is separate from the area-based `degenerateTriangles` count. A nonzero value means topology detail was lost at the chosen tolerance; inspect at a finer deliberate tolerance before interpreting the edge counts. The helper does not weld, remove or repair geometry.
diff --git a/src/__tests__/geometry-export-contract.test.ts b/src/__tests__/geometry-export-contract.test.ts
index 959d55e9..ac97e69b 100644
--- a/src/__tests__/geometry-export-contract.test.ts
+++ b/src/__tests__/geometry-export-contract.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from 'bun:test';
import * as THREE from 'three';
import { WebIO } from '@gltf-transform/core';
import { inspectGeometryExport } from '../geometry-export';
+import { mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js';
import { renderSceneToGLB } from '../render';
+import { validateFinalGlbBytes } from '../qa/gltf';
function fixture() {
const root = new THREE.Group();
@@ -27,7 +29,11 @@ function fixture() {
describe('custom mesh export contract', () => {
it('round trips supported indexed attributes', async () => {
const { root, geometry } = fixture();
- const result = await renderSceneToGLB(root, { dedup: false, optimize: 'off', instance: 'off' });
+ const result = await renderSceneToGLB(root, {
+ dedup: false,
+ optimize: 'off',
+ instance: 'off',
+ });
const doc = await new WebIO().readBinary(result.bytes);
const primitive = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
for (const [attribute, semantic] of [
@@ -145,7 +151,11 @@ describe('custom mesh export contract', () => {
4,
);
geometry.setAttribute('position', new THREE.InterleavedBufferAttribute(data, 3, 0));
- const result = await renderSceneToGLB(root, { dedup: false, optimize: 'off', instance: 'off' });
+ const result = await renderSceneToGLB(root, {
+ dedup: false,
+ optimize: 'off',
+ instance: 'off',
+ });
const doc = await new WebIO().readBinary(result.bytes);
expect(
Array.from(
@@ -165,7 +175,10 @@ describe('geometry notes', () => {
}
it('reports a note repeated across meshes once, naming a few of them', () => {
- const loft = { code: 'LOFT_SELF_INTERSECTION_UNCHECKED', message: 'Loft advisory.' };
+ const loft = {
+ code: 'LOFT_SELF_INTERSECTION_UNCHECKED',
+ message: 'Loft advisory.',
+ };
const root = new THREE.Group();
root.add(noted('Rib_0', [loft]));
root.add(noted('Turn_A', [{ code: 'SWEEP_TIGHT_TURN', message: 'Station 3 turns.' }]));
@@ -206,3 +219,79 @@ describe('geometry notes', () => {
]);
});
});
+
+describe('non-unit normals on export', () => {
+ // A cup whose profile starts and ends a millimetre from the axis, as in the Cove pass.
+ const cup = () => {
+ const points = [
+ [0.001, 0],
+ [0.04, 0],
+ [0.045, 0.06],
+ [0.03, 0.09],
+ [0.001, 0.09],
+ ].map(([x, y]) => new THREE.Vector2(x, y));
+ return mergeVertices(new THREE.LatheGeometry(points, 24));
+ };
+ const lengths = (values: ArrayLike<number>) =>
+ Array.from({ length: values.length / 3 }, (_, i) =>
+ Math.hypot(values[i * 3]!, values[i * 3 + 1]!, values[i * 3 + 2]!),
+ );
+
+ for (const exporter of ['legacy', 'three'] as const) {
+ it(`normalises raw LatheGeometry normals with one note naming the part (${exporter})`, async () => {
+ const geometry = cup();
+ const before = Array.from(geometry.getAttribute('normal').array);
+ const bad = lengths(before).filter((length) => Math.abs(length - 1) > 0.0005).length;
+ expect(bad).toBeGreaterThan(0);
+ const root = new THREE.Group();
+ const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
+ mesh.name = 'LampBase';
+ root.add(mesh);
+ const result = await renderSceneToGLB(root, {
+ dedup: false,
+ optimize: 'off',
+ instance: 'off',
+ gltfExporter: exporter,
+ });
+ const notes = result.warnings.filter((warning) => warning.includes('normal'));
+ expect(notes).toEqual([
+ `LampBase: NORMALS_NORMALISED ${bad} non-unit normals were scaled to unit length on export.`,
+ ]);
+ const doc = await new WebIO().readBinary(result.bytes);
+ const written = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!.getAttribute('NORMAL')!;
+ for (const length of lengths(written.getArray()!))
+ expect(Math.abs(length - 1)).toBeLessThan(0.0005);
+ expect(Array.from(geometry.getAttribute('normal').array)).toEqual(before);
+ const report = await validateFinalGlbBytes(result.bytes);
+ expect(report.issues.messages.map((issue) => issue.code)).not.toContain(
+ 'ACCESSOR_VECTOR3_NON_UNIT',
+ );
+ });
+ }
+
+ it('fails on a zero-length normal, naming the part and a remedy', async () => {
+ const { root, geometry } = fixture();
+ geometry.getAttribute('normal').setXYZ(1, 0, 0, 0);
+ await expect(renderSceneToGLB(root)).rejects.toThrow(
+ 'CustomPanel: normal at vertex 1 has zero length',
+ );
+ await expect(renderSceneToGLB(root)).rejects.toThrow('revolveGeo');
+ });
+
+ it('writes unit normals byte for byte', async () => {
+ const { root, geometry } = fixture();
+ const result = await renderSceneToGLB(root, {
+ dedup: false,
+ optimize: 'off',
+ instance: 'off',
+ });
+ expect(result.warnings.filter((warning) => warning.includes('NORMALS_NORMALISED'))).toEqual([]);
+ const doc = await new WebIO().readBinary(result.bytes);
+ const written = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!.getAttribute('NORMAL')!;
+ const bytes = (array: ArrayLike<number> & ArrayBufferView) =>
+ Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength));
+ expect(bytes(written.getArray()!)).toEqual(
+ bytes(geometry.getAttribute('normal').array as Float32Array),
+ );
+ });
+});
diff --git a/src/geometry-export.ts b/src/geometry-export.ts
index d2227fd9..38675d2c 100644
--- a/src/geometry-export.ts
+++ b/src/geometry-export.ts
@@ -105,6 +105,43 @@ export function geometryAttributeValues(
return values;
}
+/** The glTF validator's tolerance for unit-length NORMAL vectors. */
+const UNIT_NORMAL_TOLERANCE = 0.0005;
+
+/**
+ * Written NORMAL values, each off-unit vector scaled to unit length. A shader normalises before
+ * it lights, so the image is unchanged; the validator rejects the file without this. Vectors
+ * within tolerance keep their exact bytes. Inspection has already refused zero-length vectors.
+ */
+export function unitNormalValues(
+ attribute: THREE.BufferAttribute | THREE.InterleavedBufferAttribute,
+): Float32Array<ArrayBuffer> {
+ const values = geometryAttributeValues(attribute);
+ for (let i = 0; i < values.length; i += 3) {
+ const length = Math.hypot(values[i]!, values[i + 1]!, values[i + 2]!);
+ if (Math.abs(length - 1) <= UNIT_NORMAL_TOLERANCE || length === 0) continue;
+ for (let component = 0; component < 3; component++) values[i + component]! /= length;
+ }
+ return values;
+}
+
+/** Count off-unit normals; a zero-length normal has no direction to keep, so it fails. */
+function offUnitNormals(
+ normal: THREE.BufferAttribute | THREE.InterleavedBufferAttribute,
+ name: string,
+): number {
+ let count = 0;
+ for (let vertex = 0; vertex < normal.count; vertex++) {
+ const length = Math.hypot(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
+ if (length < 1e-6)
+ throw new TypeError(
+ `${name}: normal at vertex ${vertex} has zero length, so it has no direction to export. Build revolved profiles with lathe or revolveGeo, or recompute the normals with creaseNormals.`,
+ );
+ if (Math.abs(length - 1) > UNIT_NORMAL_TOLERANCE) count++;
+ }
+ return count;
+}
+
/** One helper note (a code and message, or a legacy string) and the meshes that carry it. */
type GeometryNoteGroup = {
code?: string;
@@ -196,6 +233,15 @@ export function inspectGeometryExport(
}
}
}
+ const normal = geometry.getAttribute('normal');
+ const offUnit = normal?.itemSize === 3 ? offUnitNormals(normal, name) : 0;
+ if (offUnit > 0)
+ addNote(
+ mesh,
+ name,
+ 'NORMALS_NORMALISED',
+ `${offUnit} non-unit normals were scaled to unit length on export.`,
+ );
const index = geometry.getIndex();
if ((index?.count ?? position.count) % 3 !== 0)
throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
diff --git a/src/render.ts b/src/render.ts
index 4f04f0e1..b589bb81 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -59,6 +59,7 @@ import {
CUSTOM_EXPORT_ATTRIBUTES,
customAttributeSemantic,
geometryAttributeValues,
+ unitNormalValues,
inspectGeometryExport,
validateMaterialGroups,
type GeometryExportPolicy,
@@ -802,7 +803,7 @@ function bridgeGeometry(
'NORMAL',
doc
.createAccessor(`${meshName}_norm`)
- .setArray(geometryAttributeValues(normAttr))
+ .setArray(unitNormalValues(normAttr))
.setType(TYPE_VEC3)
.setBuffer(buf),
);