3D engine that AI agents drive
Add OBJ with MTL and binary STL export as an addon (part of #747)
Nguyen Xuan An9dcf3971a8da
diff --git a/changes/747.md b/changes/747.mdnew file mode 100644index 00000000..6c9ca0e1--- /dev/null+++ b/changes/747.md@@ -0,0 +1 @@+- `exportObj` (OBJ with MTL text) and `exportStl` (binary STL) in the new `addons/export-mesh` entry write the same parts as `exportGlb`, in world space, with deterministic bytes (#747)diff --git a/docs/export-glb.md b/docs/export-glb.mdindex 40534791..13790054 100644--- a/docs/export-glb.md+++ b/docs/export-glb.md@@ -134,6 +134,35 @@ Without `clip` it writes the current pose: pattern and imported textures, skins,With `clip` (imported assets) it writes that source clip, translation, rotation, scale and weights, on the source skeleton, so the scene must carry no animation, node overrides or motion.`node scripts/smoke-glb-export.mjs cpu` runs a patterned recipe, the robot with IK and its Walking clip through the real server and leaves the files in `artifacts/`.+## OBJ and STL++`exportObj(parts, { mtlFilename })` returns `{ obj, mtl }` as text, and `exportStl(parts)` returns a binary STL `ArrayBuffer`.+Both take the same `parts` as `exportGlb`, apply each part matrix so every vertex is in world space, and write the same bytes for the same input.+Save the OBJ and MTL side by side; the OBJ names the MTL by `mtlFilename` (default `model.mtl`, a plain file name ending in `.mtl`).++They live in the `@codepawlhq/67js/addons/export-mesh` addon, so the core bundle does not grow.++```js+import { exportObj, exportStl } from '@codepawlhq/67js/addons/export-mesh';++const { obj, mtl } = exportObj(parts);+const stl = exportStl(parts);+```++| Format | Written | Not written |+| --- | --- | --- |+| OBJ | One `o` object per part, positions, UVs and normals when the geometry has them, faces as triangles | Textures, lights, cameras, animation, skins, morph weights |+| MTL | One material per distinct base color, emission, roughness and metallic: `Kd`, `Ke` (when emission is positive), `Pr`, `Pm` | Texture maps, layers, patterns |+| STL | Triangles with face normals, 80 byte header, no color | Everything but shape |++Y stays up and units stay as authored (67js uses meters); set the axis and unit in the importer or slicer.+A mirrored part (negative scale) has its winding swapped so faces still point outward.+A skinned part exports its bind shape.+Export stops with an error past `MAX_MESH_EXPORT_TRIANGLES` (1,000,000), and names the field it rejected: positions, indices or `part.matrix`.+Colors in the MTL are the linear base colors of the parts.+Blender 5.2 imports both files with the same triangle count (`File > Import > Wavefront (.obj)` and `STL (.stl)`).+These two functions are library calls; the `scene_export_glb` tool still writes GLB only.+## LimitsRecipe motion tracks are not converted to clips, and an imported clip cannot be combined with IK or node overrides in the MCP tool.diff --git a/package.json b/package.jsonindex 3a073c50..d6306f96 100644--- a/package.json+++ b/package.json@@ -80,6 +80,7 @@"./addons/vegetation": "./build/vegetation.js","./addons/terrain": "./build/terrain.js","./addons/heightfield": "./build/heightfield.js",+ "./addons/export-mesh": "./build/export-mesh.js","./addons/navmesh": "./build/navmesh.js","./addons/grass": "./build/grass.js","./addons/clutter": "./build/clutter.js",diff --git a/src/export-mesh.js b/src/export-mesh.jsnew file mode 100644index 00000000..dec59b70--- /dev/null+++ b/src/export-mesh.js@@ -0,0 +1,210 @@+// OBJ (with MTL) and binary STL export of the same parts `exportGlb` takes, with world transforms applied.+// Both formats carry triangles only: no lights, cameras, animation, skins, morph weights or textures.++export const MAX_MESH_EXPORT_TRIANGLES = 1_000_000;+const MAX_NAME_LENGTH = 64;+const STL_HEADER_TEXT = '67js binary STL';+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];++function checkParts(parts, format) {+ if (!Array.isArray(parts) || parts.length === 0) throw new TypeError(`${format} export requires a nonempty parts array.`);+ let triangleCount = 0;+ for (const part of parts) {+ const { positions, indices } = part?.geometry ?? {};+ if (!positions || positions.length < 9 || positions.length % 3 !== 0) {+ throw new TypeError(`${format} export requires geometry.positions with XYZ vertices on every part.`);+ }+ for (const value of positions) {+ if (!Number.isFinite(value)) throw new RangeError(`${format} export requires finite positions.`);+ }+ if (!(indices instanceof Uint32Array) || indices.length === 0 || indices.length % 3 !== 0) {+ throw new TypeError(`${format} export requires geometry.indices as a nonempty Uint32Array of triangles.`);+ }+ const vertexCount = positions.length / 3;+ for (const index of indices) {+ if (index >= vertexCount) throw new RangeError(`${format} export found an index past the ${vertexCount} vertices.`);+ }+ if (part.matrix !== undefined && (part.matrix.length !== 16 || Array.from(part.matrix).some(value => !Number.isFinite(value)))) {+ throw new RangeError(`${format} export requires part.matrix with 16 finite components.`);+ }+ triangleCount += indices.length / 3;+ if (triangleCount > MAX_MESH_EXPORT_TRIANGLES) {+ throw new RangeError(`${format} export is limited to ${MAX_MESH_EXPORT_TRIANGLES} triangles. Simplify the scene or export fewer parts.`);+ }+ }+}++function worldTriangles(part) {+ const matrix = part.matrix ?? IDENTITY;+ const { positions, indices } = part.geometry;+ const vertexCount = positions.length / 3;+ const world = new Float64Array(vertexCount * 3);+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ const x = positions[vertex * 3];+ const y = positions[vertex * 3 + 1];+ const z = positions[vertex * 3 + 2];+ for (let axis = 0; axis < 3; axis++) {+ world[vertex * 3 + axis] = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];+ }+ }+ const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[9] * matrix[6])+ - matrix[4] * (matrix[1] * matrix[10] - matrix[9] * matrix[2])+ + matrix[8] * (matrix[1] * matrix[6] - matrix[5] * matrix[2]);+ // A mirrored transform reverses winding, so swap two corners to keep faces pointing outward.+ const mirrored = determinant < 0;+ const triangles = new Uint32Array(indices);+ if (mirrored) {+ for (let corner = 0; corner < triangles.length; corner += 3) {+ const swapped = triangles[corner + 1];+ triangles[corner + 1] = triangles[corner + 2];+ triangles[corner + 2] = swapped;+ }+ }+ return { world, triangles, matrix };+}++function faceNormal(world, first, second, third) {+ const edgeA = [0, 1, 2].map(axis => world[second * 3 + axis] - world[first * 3 + axis]);+ const edgeB = [0, 1, 2].map(axis => world[third * 3 + axis] - world[first * 3 + axis]);+ const cross = [edgeA[1] * edgeB[2] - edgeA[2] * edgeB[1], edgeA[2] * edgeB[0] - edgeA[0] * edgeB[2], edgeA[0] * edgeB[1] - edgeA[1] * edgeB[0]];+ const length = Math.hypot(...cross);+ return length === 0 ? [0, 0, 0] : cross.map(value => value / length);+}++/** Returns a binary STL `ArrayBuffer` of every part's triangles in world space. Y stays up, units stay as authored. */+export function exportStl(parts) {+ checkParts(parts, 'STL');+ const prepared = parts.map(worldTriangles);+ const triangleCount = prepared.reduce((total, entry) => total + entry.triangles.length / 3, 0);+ const buffer = new ArrayBuffer(84 + triangleCount * 50);+ const view = new DataView(buffer);+ new Uint8Array(buffer, 0, 80).set(new TextEncoder().encode(STL_HEADER_TEXT));+ view.setUint32(80, triangleCount, true);+ let offset = 84;+ for (const { world, triangles } of prepared) {+ for (let corner = 0; corner < triangles.length; corner += 3) {+ const first = triangles[corner];+ const second = triangles[corner + 1];+ const third = triangles[corner + 2];+ for (const value of faceNormal(world, first, second, third)) {+ view.setFloat32(offset, value, true);+ offset += 4;+ }+ for (const vertex of [first, second, third]) {+ for (let axis = 0; axis < 3; axis++) {+ view.setFloat32(offset, world[vertex * 3 + axis], true);+ offset += 4;+ }+ }+ offset += 2;+ }+ }+ return buffer;+}++function formatNumber(value) {+ // Nine significant digits (more than Float32 holds), shortest text, no "-0": the same input always gives the same bytes.+ const rounded = Number(value.toPrecision(9));+ return String(rounded === 0 ? 0 : rounded);+}++function safeName(name, fallback) {+ const cleaned = String(name ?? '').replace(/[^A-Za-z0-9_.-]+/g, '_').slice(0, MAX_NAME_LENGTH);+ return cleaned || fallback;+}++function materialKey(material) {+ return JSON.stringify([material?.color, material?.emissiveColor, material?.emission, material?.metallic, material?.roughness]);+}++function mtlBlock(name, material) {+ const color = material?.color ?? [0.8, 0.8, 0.8];+ const lines = [`newmtl ${name}`, `Kd ${color.map(formatNumber).join(' ')}`];+ if ((material?.emission ?? 0) > 0) {+ const emissive = (material.emissiveColor ?? color).map(value => value * Math.min(material.emission, 1));+ lines.push(`Ke ${emissive.map(formatNumber).join(' ')}`);+ }+ lines.push(`Pr ${formatNumber(material?.roughness ?? 0.5)}`, `Pm ${formatNumber(material?.metallic ?? 0)}`, 'd 1');+ return lines.join('\n');+}++/**+ * Returns `{ obj, mtl }` as text. The OBJ names the MTL by `mtlFilename` (default `model.mtl`); save both files side by side.+ * Colors in the MTL are the linear base colors of the parts, with roughness and metallic as `Pr` and `Pm`.+ */+export function exportObj(parts, options = {}) {+ checkParts(parts, 'OBJ');+ const mtlFilename = options.mtlFilename ?? 'model.mtl';+ if (typeof mtlFilename !== 'string' || !/^[A-Za-z0-9_.-]{1,64}\.mtl$/.test(mtlFilename)) {+ throw new TypeError('OBJ export mtlFilename must be a plain file name ending in .mtl, such as "model.mtl".');+ }+ const materialNames = new Map();+ const materialBlocks = [];+ const lines = [`67js OBJ export`, `mtllib ${mtlFilename}`];+ let vertexBase = 1;+ let uvBase = 1;+ let normalBase = 1;+ parts.forEach((part, partIndex) => {+ const { world, triangles, matrix } = worldTriangles(part);+ const key = materialKey(part.material);+ if (!materialNames.has(key)) {+ const name = `material_${materialNames.size}`;+ materialNames.set(key, name);+ materialBlocks.push(mtlBlock(name, part.material));+ }+ lines.push(`o ${safeName(part.name, `part_${partIndex}`)}`, `usemtl ${materialNames.get(key)}`);+ const vertexCount = world.length / 3;+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ lines.push(`v ${formatNumber(world[vertex * 3])} ${formatNumber(world[vertex * 3 + 1])} ${formatNumber(world[vertex * 3 + 2])}`);+ }+ const uvs = part.geometry.uvs?.length === vertexCount * 2 ? part.geometry.uvs : null;+ if (uvs) {+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ lines.push(`vt ${formatNumber(uvs[vertex * 2])} ${formatNumber(uvs[vertex * 2 + 1])}`);+ }+ }+ const normals = part.geometry.normals?.length === vertexCount * 3 ? worldNormals(part.geometry.normals, matrix) : null;+ if (normals) {+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ lines.push(`vn ${formatNumber(normals[vertex * 3])} ${formatNumber(normals[vertex * 3 + 1])} ${formatNumber(normals[vertex * 3 + 2])}`);+ }+ }+ for (let corner = 0; corner < triangles.length; corner += 3) {+ const face = [0, 1, 2].map(offset => {+ const vertex = triangles[corner + offset];+ const position = vertex + vertexBase;+ const normal = vertex + normalBase;+ if (uvs && normals) return `${position}/${vertex + uvBase}/${normal}`;+ if (uvs) return `${position}/${vertex + uvBase}`;+ return normals ? `${position}//${normal}` : `${position}`;+ });+ lines.push(`f ${face.join(' ')}`);+ }+ vertexBase += vertexCount;+ if (uvs) uvBase += vertexCount;+ if (normals) normalBase += vertexCount;+ });+ return { obj: `${lines.join('\n')}\n`, mtl: `# 67js MTL export\n${materialBlocks.join('\n\n')}\n` };+}++// Normals use the inverse transpose of the upper 3x3 so non-uniform scale keeps them perpendicular to the surface.+function worldNormals(normals, matrix) {+ const [a, b, c, , d, e, f, , g, h, i] = matrix;+ const cofactor = [+ e * i - f * h, f * g - d * i, d * h - e * g,+ c * h - b * i, a * i - c * g, b * g - a * h,+ b * f - c * e, c * d - a * f, a * e - b * d,+ ];+ // Column-major matrix: the cofactor matrix is the inverse transpose up to the determinant's sign and size, which normalizing removes.+ const result = new Float64Array(normals.length);+ const sign = (a * cofactor[0] + b * cofactor[1] + c * cofactor[2]) < 0 ? -1 : 1;+ for (let vertex = 0; vertex < normals.length; vertex += 3) {+ const x = normals[vertex];+ const y = normals[vertex + 1];+ const z = normals[vertex + 2];+ const transformed = [0, 1, 2].map(row => sign * (cofactor[row] * x + cofactor[3 + row] * y + cofactor[6 + row] * z));+ const length = Math.hypot(...transformed) || 1;+ for (let axis = 0; axis < 3; axis++) result[vertex + axis] = transformed[axis] / length;+ }+ return result;+}diff --git a/tests/export-mesh.test.js b/tests/export-mesh.test.jsnew file mode 100644index 00000000..c6686632--- /dev/null+++ b/tests/export-mesh.test.js@@ -0,0 +1,156 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { mat4 } from 'gl-matrix';+import { box, sphere } from '../src/geometry.js';+import { exportObj, exportStl, MAX_MESH_EXPORT_TRIANGLES } from '../src/export-mesh.js';+import { exportGlb } from '../src/export.js';+import { parseGltf } from '../src/gltf.js';++const redMaterial = { color: [0.8, 0.1, 0.1], metallic: 0, roughness: 0.4 };+const glowMaterial = { color: [0.1, 0.2, 0.9], emissiveColor: [1, 0.5, 0], emission: 0.5, metallic: 1, roughness: 0.2 };++function placed(geometry, translation, scale = [1, 1, 1], material = redMaterial) {+ const matrix = mat4.fromRotationTranslationScale(mat4.create(), [0, 0, 0, 1], translation, scale);+ return { name: 'Part one', geometry, matrix, material };+}++function sceneParts() {+ return [placed(box(), [2, 0, 0], [1, 2, 3]), placed(sphere(12, 8), [0, 5, 0], [1, 1, 1], glowMaterial)];+}++function expectedTriangleCount(parts) {+ return parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);+}++function worldBounds(parts) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (const part of parts) {+ const { positions } = part.geometry;+ for (let offset = 0; offset < positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ const value = part.matrix[axis] * positions[offset] + part.matrix[4 + axis] * positions[offset + 1]+ + part.matrix[8 + axis] * positions[offset + 2] + part.matrix[12 + axis];+ minimum[axis] = Math.min(minimum[axis], value);+ maximum[axis] = Math.max(maximum[axis], value);+ }+ }+ }+ return { minimum, maximum };+}++function readStl(buffer) {+ const view = new DataView(buffer);+ const count = view.getUint32(80, true);+ assert.equal(buffer.byteLength, 84 + count * 50);+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let triangle = 0; triangle < count; triangle++) {+ for (let vertex = 0; vertex < 3; vertex++) {+ for (let axis = 0; axis < 3; axis++) {+ const value = view.getFloat32(84 + triangle * 50 + 12 + vertex * 12 + axis * 4, true);+ minimum[axis] = Math.min(minimum[axis], value);+ maximum[axis] = Math.max(maximum[axis], value);+ }+ }+ }+ return { count, minimum, maximum };+}++function readObj(text) {+ const vertices = [];+ let faces = 0;+ for (const line of text.split('\n')) {+ const fields = line.split(' ');+ if (fields[0] === 'v') vertices.push(fields.slice(1).map(Number));+ if (fields[0] === 'f') {+ faces++;+ for (const corner of fields.slice(1)) assert.ok(Number(corner.split('/')[0]) <= vertices.length, 'face uses a vertex written earlier');+ }+ }+ const minimum = [0, 1, 2].map(axis => Math.min(...vertices.map(vertex => vertex[axis])));+ const maximum = [0, 1, 2].map(axis => Math.max(...vertices.map(vertex => vertex[axis])));+ return { faces, minimum, maximum };+}++function assertClose(actual, expected) {+ actual.forEach((value, axis) => assert.ok(Math.abs(value - expected[axis]) < 1e-5, `${actual} vs ${expected}`));+}++test('STL roundtrip keeps the triangle count and world bounds', () => {+ const parts = sceneParts();+ const read = readStl(exportStl(parts));+ const bounds = worldBounds(parts);+ assert.equal(read.count, expectedTriangleCount(parts));+ assertClose(read.minimum, bounds.minimum);+ assertClose(read.maximum, bounds.maximum);+});++test('OBJ roundtrip keeps the triangle count and world bounds, and the MTL names every material', () => {+ const parts = sceneParts();+ const { obj, mtl } = exportObj(parts);+ const read = readObj(obj);+ const bounds = worldBounds(parts);+ assert.equal(read.faces, expectedTriangleCount(parts));+ assertClose(read.minimum, bounds.minimum);+ assertClose(read.maximum, bounds.maximum);+ assert.match(obj, /^mtllib model\.mtl$/m);+ assert.equal(obj.match(/^o Part_one$/gm).length, 2);+ assert.match(mtl, /newmtl material_0\nKd 0\.8 0\.1 0\.1\nPr 0\.4\nPm 0\nd 1/);+ assert.match(mtl, /newmtl material_1\nKd 0\.1 0\.2 0\.9\nKe 0\.5 0\.25 0\nPr 0\.2\nPm 1/);+ assert.ok(obj.includes('usemtl material_1'));+});++test('exports have the same triangles as the GLB export of the same parts', async () => {+ const parts = sceneParts();+ const asset = await parseGltf(exportGlb(parts));+ const glbTriangles = asset.parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);+ assert.equal(readStl(exportStl(parts)).count, glbTriangles);+ assert.equal(readObj(exportObj(parts).obj).faces, glbTriangles);+});++test('output bytes are identical for the same input and parts sharing a material share one MTL entry', () => {+ const parts = [placed(box(), [0, 0, 0]), placed(box(), [3, 0, 0])];+ assert.deepEqual(Buffer.from(exportStl(parts)), Buffer.from(exportStl(parts)));+ assert.deepEqual(exportObj(parts), exportObj(parts));+ assert.equal(exportObj(parts).mtl.match(/newmtl/g).length, 1);+});++test('a mirrored part keeps outward winding and OBJ normals follow non-uniform scale', () => {+ const mirrored = placed(box(), [0, 0, 0], [-1, 1, 1]);+ const view = new DataView(exportStl([mirrored]));+ // The first face normal must point away from the box center.+ const normal = [0, 1, 2].map(axis => view.getFloat32(84 + axis * 4, true));+ const corner = [0, 1, 2].map(axis => view.getFloat32(84 + 12 + axis * 4, true));+ assert.ok(normal[0] * corner[0] + normal[1] * corner[1] + normal[2] * corner[2] > 0);+ const stretched = placed({ ...box(), normals: Float32Array.from([...box().normals].map((_, index) => index % 3 === 0 ? 1 : 0)) }, [0, 0, 0], [1, 4, 1]);+ const firstNormal = exportObj([stretched]).obj.split('\n').find(line => line.startsWith('vn ')).split(' ').slice(1).map(Number);+ assertClose(firstNormal, [1, 0, 0]);+});++test('a part without a matrix exports at its own coordinates', () => {+ const geometry = box();+ const read = readStl(exportStl([{ name: 'bare', geometry, material: redMaterial }]));+ assert.equal(read.count, geometry.indices.length / 3);+});++test('invalid input names the field and what to pass', () => {+ const parts = sceneParts();+ assert.throws(() => exportStl([]), /nonempty parts array/);+ assert.throws(() => exportObj('parts'), /nonempty parts array/);+ assert.throws(() => exportStl([{ geometry: { positions: new Float32Array(3) } }]), /geometry\.positions/);+ assert.throws(() => exportStl([{ geometry: { positions: Float32Array.of(0, 0, 0, 1, 0, 0, NaN, 1, 0), indices: Uint32Array.of(0, 1, 2) } }]), /finite positions/);+ assert.throws(() => exportStl([{ geometry: { positions: new Float32Array(9), indices: [0, 1, 2] } }]), /Uint32Array/);+ assert.throws(() => exportStl([{ geometry: { positions: new Float32Array(9), indices: Uint32Array.of(0, 1, 3) } }]), /index past/);+ assert.throws(() => exportStl([{ ...parts[0], matrix: new Float32Array(15) }]), /part\.matrix/);+ for (const mtlFilename of ['model.txt', '../model.mtl', 'a b.mtl', 7]) {+ assert.throws(() => exportObj(parts, { mtlFilename }), /mtlFilename/);+ }+ assert.equal(exportObj(parts, { mtlFilename: 'scene.mtl' }).obj.includes('mtllib scene.mtl'), true);+});++test('the triangle limit is enforced before any output is built', () => {+ const geometry = { positions: new Float32Array(9), indices: new Uint32Array(MAX_MESH_EXPORT_TRIANGLES * 3 + 3) };+ assert.throws(() => exportStl([{ geometry }]), /limited to 1000000 triangles/);+ assert.throws(() => exportObj([{ geometry }]), /limited to 1000000 triangles/);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 80d48ff3..ddf3d7df 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -66,6 +66,7 @@ export default defineConfig({vegetation: 'src/vegetation.js',terrain: 'src/terrain.js',heightfield: 'src/heightfield.js',+ 'export-mesh': 'src/export-mesh.js',navmesh: 'src/navmesh.js',grass: 'src/grass.js',clutter: 'src/clutter.js',