export mesh as .STL file? #1160
-
i'm sure this is super easy with GLTF-transform, but i'm not smart enough to figure it out. (and the AI that i just trained on https://gltf-transform.dev/ isn't smart enough to do it either ;) ) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
i guess i could pass the mesh to https://threejs.org/docs/#examples/en/exporters/STLExporter ? does this look right? (written by https://cursor.sh )
|
Beta Was this translation helpful? Give feedback.
-
glTF Transform doesn't read or write any other formats, but you could use it to obtain the vertex positions and normals you'd need to serialize an STL file with other libraries. I used import { NodeIO } from '@gltf-transform/core';
import { KHRONOS_EXTENSIONS } from '@gltf-transform/extensions';
import { normals, unweld } from '@gltf-transform/functions';
import stl from 'stl';
import { writeFile } from 'node:fs/promises';
const io = new NodeIO().registerExtensions(KHRONOS_EXTENSIONS);
const document = await io.read('./assets/input.glb');
await document.transform(normals({ overwrite: true }), unweld());
let nextIndex = 1;
for (const mesh of document.getRoot().listMeshes()) {
const name = mesh.getName() || `Mesh_${nextIndex++}`;
const object = { description: name, facets: [] };
for (const prim of mesh.listPrimitives()) {
const position = prim.getAttribute('POSITION');
const normal = prim.getAttribute('NORMAL');
for (let i = 0, il = position.getCount(); i < il; i += 3) {
object.facets.push({
normal: normal.getElement(i, []),
verts: [
position.getElement(i, []),
position.getElement(i + 1, []),
position.getElement(i + 2, []),
],
});
}
}
await writeFile(`./assets/${name}.stl`, stl.fromObject(object, /* binary */ false));
} Note that if you're trying to turn the entire GLB file into a single STL, rather than exporting meshes individually, you'll also need to consider the node transforms at which the meshes are instantiated. |
Beta Was this translation helpful? Give feedback.
glTF Transform doesn't read or write any other formats, but you could use it to obtain the vertex positions and normals you'd need to serialize an STL file with other libraries. I used
stl
for this example, but you could do the same with three.js by constructing BufferGeometries.