Files
snapcad-studio/apps/web/src/lib/dxfExport.ts
T

80 lines
2.6 KiB
TypeScript
Raw Normal View History

import Drawing from "dxf-writer";
import type { ObjExportMesh } from "@/lib/objExport";
import type { SvgProjectionLayer } from "@/lib/svgExport";
/**
* Exports 3D meshes and 2D projected cutting contours to AutoCAD DXF format.
* Generates standards-compliant DXF with 3D_MESH and CUT_CONTOURS layers,
* fully compatible with AutoCAD, SolidWorks, Fusion 360, FreeCAD, and CNC laser cutters.
*/
export function exportMeshesToDxf(
meshes: readonly ObjExportMesh[],
projectedLayers?: ReadonlyArray<SvgProjectionLayer>,
title = "SnapCAD Studio Model",
): string {
const dxf = new Drawing();
dxf.setUnits("Millimeters");
// Layers
dxf.addLayer("3D_GEOMETRY", Drawing.ACI.CYAN, "CONTINUOUS");
dxf.addLayer("CUT_OUTLINE", Drawing.ACI.WHITE, "CONTINUOUS");
dxf.addLayer("CUT_HOLES", Drawing.ACI.RED, "CONTINUOUS");
// 1. Export 3D Mesh Faces (3DFACE entities)
dxf.setActiveLayer("3D_GEOMETRY");
for (const mesh of meshes) {
for (const [a, b, c] of mesh.faces) {
const v1 = mesh.vertices[a];
const v2 = mesh.vertices[b];
const v3 = mesh.vertices[c];
if (!v1 || !v2 || !v3) continue;
// In DXF 3DFACE, a triangle repeats vertex 3 as vertex 4
dxf.drawFace(
Number(v1[0].toFixed(5)),
Number(v1[1].toFixed(5)),
Number(v1[2].toFixed(5)),
Number(v2[0].toFixed(5)),
Number(v2[1].toFixed(5)),
Number(v2[2].toFixed(5)),
Number(v3[0].toFixed(5)),
Number(v3[1].toFixed(5)),
Number(v3[2].toFixed(5)),
Number(v3[0].toFixed(5)),
Number(v3[1].toFixed(5)),
Number(v3[2].toFixed(5)),
);
}
}
// 2. Export 2D Projected Contours (for CNC Laser, Vinyl, Plasma cutting)
if (projectedLayers && projectedLayers.length > 0) {
for (const layer of projectedLayers) {
for (const polygon of layer.polygons) {
if (!polygon || polygon.length < 2) continue;
// Calculate signed polygon area to differentiate outer cut from inner hole
let area = 0;
for (let i = 0; i < polygon.length; i++) {
const curr = polygon[i];
const next = polygon[(i + 1) % polygon.length];
area += (next[0] - curr[0]) * (next[1] + curr[1]);
}
if (area >= 0) {
dxf.setActiveLayer("CUT_OUTLINE");
} else {
dxf.setActiveLayer("CUT_HOLES");
}
const points: Array<[number, number]> = polygon.map(([x, y]) => [
Number(x.toFixed(4)),
Number(y.toFixed(4)),
]);
dxf.drawPolyline(points, true);
}
}
}
return dxf.toDxfString();
}