feat: stl_cad merge(삼각형 병합+베드 배치)·stl_paths 일괄 info/transform·미터 단위 경고, scad import 경로 자동 보정, 대소문자 경로, 3D 모델 사이트 403 안내

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-09-29 12:43:55 +09:00
1 parent cb34baf755
commit 2fa1d1d541
5 files changed
+382 -11

No files matched your search

+7 -3
View File
@@ -1386,9 +1386,13 @@ async function webFetch(url: string): Promise<string> {
if (!response.ok) {
const needsBrowser = response.status === 401 || response.status === 403 || response.status === 429;
const hint = needsBrowser
? ` This site requires authentication or blocks automated requests. Try browser_open("${url}") instead.`
: '';
// 3D 모델 저장소 페이지는 봇 차단(403)이 정상 — 페이지 대신 전용 도구가 API로 검색·다운로드한다.
const isModelSite = /(^|\.)(printables\.com|makerworld\.com|thingiverse\.com)$/i.test((() => { try { return new URL(url).hostname; } catch { return ''; } })());
const hint = isModelSite
? ' 이 사이트의 웹페이지는 자동 접근이 막혀 있습니다(정상). 페이지를 다시 열지 말고 model_search(검색)와 model_download(model_id로 STL 다운로드)를 사용하세요.'
: needsBrowser
? ` This site requires authentication or blocks automated requests. Try browser_open("${url}") instead.`
: '';
return `Fetch failed (${response.status} ${response.statusText}).${hint}`;
}
+13 -1
View File
@@ -7,6 +7,7 @@ import { getWorkspacePath } from '../config/paths.js';
import { isPathInsideDir } from './image.js';
import { findWorkshopProjectName } from './print3d.js';
import { saveDirs } from '../gateway/routes/workshop-layout.js';
import { analyzeStl } from './stl-cad-core.js';
// 3D 모델 저장소 검색+다운로드 (2026-09-23) — Printables / MakerWorld / Thingiverse.
// 세 곳 모두 공식 API가 없거나(Printables/MakerWorld) 응용토큰이 필요한(Thingiverse) 사이라
@@ -484,10 +485,21 @@ export const modelDownloadTool = {
console.log(`[model-download] ${site}:${id} → ${outPath} (${result.size} bytes)`);
const relPath = path.relative(workspacePath, outPath);
// 다운로드 직후 단위 점검 — URDF 메시처럼 미터 단위 STL이 그대로 저장되는 걸 모델이 놓치지 않게 한다.
let unitNote = '';
if (/\.stl$/i.test(outPath)) {
try {
const a = analyzeStl(outPath);
const ext = Math.max(a.max[0] - a.min[0], a.max[1] - a.min[1], a.max[2] - a.min[2]);
unitNote = `\n- 크기: ${(a.max[0] - a.min[0]).toFixed(1)} × ${(a.max[1] - a.min[1]).toFixed(1)} × ${(a.max[2] - a.min[2]).toFixed(1)}`;
if (ext < 0.5) unitNote += `\n- ⚠️ 미터(m) 단위로 보입니다 — 바로 stl_cad action="transform" stl_path="${relPath}" scale=1000 으로 mm 변환하세요(제자리 덮어씀).`;
else if (ext > 1000) unitNote += `\n- ⚠️ 크기가 1m를 넘습니다 — 단위를 확인하세요(stl_cad info).`;
} catch { /* ASCII STL 등 — 단위 점검 생략 */ }
}
const multiNote = dl.totalFiles > 1 ? `\n- 이 모델은 파일 ${dl.totalFiles}개 중 슬라이싱 가능한 가장 큰 STL/3MF 1개만 받았습니다. 나머지 부품이 필요하면 모델 페이지(${site === 'printables' ? `https://www.printables.com/model/${id}` : site === 'makerworld' ? `https://makerworld.com/en/models/${id}` : `https://www.thingiverse.com/thing:${id}`})에서 직접 받아 워크스페이스에 넣어주세요.` : '';
return {
success: true,
stdout: `다운로드 완료: **${relPath}** (${(result.size / 1024 / 1024).toFixed(1)}MB, ${dl.name})${multiNote}\n\n바로 슬라이싱하려면 print3d_model(action="prepare", stl_path="${relPath}")을 호출하세요.`,
stdout: `다운로드 완료: **${relPath}** (${(result.size / 1024 / 1024).toFixed(1)}MB, ${dl.name})${unitNote}${multiNote}\n\n바로 슬라이싱하려면 print3d_model(action="prepare", stl_path="${relPath}")을 호출하세요.`,
};
},
};
+111
View File
@@ -356,3 +356,114 @@ export function findStlFiles(workspacePath: string, maxDepth = 6): string[] {
walk(workspacePath, 0);
return results.sort();
}
// ── 여러 STL 병합(2026-09-29 "merge" 액션) ─────────────────────────────────────
// OpenSCAD 합집합(CGAL)은 닫히지 않은(non-manifold) 메시에서 실패한다 — duck 프로젝트 STL 35개 중
// 19개가 그런 파일이라 "부품 여러 개를 한 판에 묶기"가 반복 실패했다. 삼각형을 그대로 이어 붙이고
// 위치만 옮기는 방식이라 메시 품질과 무관하게 동작한다(불리언 아님 — 겹침은 해소하지 않는다).
export interface MergePlacement { path: string; size: [number, number, number]; plate: number; x: number; y: number }
export interface MergeResult { ok: true; outputs: { path: string; parts: number; size: [number, number, number] }[]; placements: MergePlacement[]; overflow: string[] }
function readStlTriangles(filePath: string): Float32Array {
const buf = fs.readFileSync(filePath);
if (buf.length < 84) throw new Error('STL 파일이 너무 작거나 손상되었습니다.');
const n = buf.readUInt32LE(80);
if (buf.length !== 84 + n * 50) throw new Error('ASCII STL이거나 손상된 바이너리 STL — 바이너리 STL만 지원합니다.');
const out = new Float32Array(n * 9);
let off = 84;
for (let i = 0; i < n; i++) {
off += 12;
for (let k = 0; k < 9; k++) { out[i * 9 + k] = buf.readFloatLE(off); off += 4; }
off += 2;
}
return out;
}
function writeStlTriangles(filePath: string, tris: Float32Array): void {
const n = tris.length / 9;
const buf = Buffer.alloc(84 + n * 50);
buf.writeUInt32LE(n, 80);
let off = 84;
for (let i = 0; i < n; i++) {
const a = [tris[i * 9], tris[i * 9 + 1], tris[i * 9 + 2]], b = [tris[i * 9 + 3], tris[i * 9 + 4], tris[i * 9 + 5]], c = [tris[i * 9 + 6], tris[i * 9 + 7], tris[i * 9 + 8]];
const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
const nx = u[1] * v[2] - u[2] * v[1], ny = u[2] * v[0] - u[0] * v[2], nz = u[0] * v[1] - u[1] * v[0];
const len = Math.hypot(nx, ny, nz) || 1;
buf.writeFloatLE(nx / len, off); buf.writeFloatLE(ny / len, off + 4); buf.writeFloatLE(nz / len, off + 8); off += 12;
for (let k = 0; k < 9; k++) { buf.writeFloatLE(tris[i * 9 + k], off); off += 4; }
buf.writeUInt16LE(0, off); off += 2;
}
const tmp = filePath + '.merge-tmp';
fs.writeFileSync(tmp, buf);
fs.renameSync(tmp, filePath);
}
function trisBBox(t: Float32Array): { min: number[]; max: number[] } {
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
for (let i = 0; i < t.length; i += 3) for (let a = 0; a < 3; a++) { const v = t[i + a]; if (v < min[a]) min[a] = v; if (v > max[a]) max[a] = v; }
return { min, max };
}
/**
* layout='grid': 각 부품을 z=0 바닥에 붙이고 베드(bedX×bedY) 안에 행 단위로 채운다. 한 판에 안 들어가면
* 새 판(outPath, name_2.stl, name_3.stl…)으로 넘긴다. 판마다 XY 중심이 (0,0).
* layout='keep': 위치를 그대로 두고 삼각형만 합친다(조립체 확인용, 한 파일).
*/
export function mergeStls(opts: {
paths: { abs: string; label: string }[]; outPath: string;
layout: 'grid' | 'keep'; bedX: number; bedY: number; gap: number;
}): MergeResult | { ok: false; detail: string } {
try {
const parts = opts.paths.map(p => {
const tris = readStlTriangles(p.abs);
if (!tris.length) throw new Error(`${p.label}: 삼각형이 없습니다.`);
return { label: p.label, tris, bb: trisBBox(tris) };
});
if (opts.layout === 'keep') {
const all = new Float32Array(parts.reduce((s, p) => s + p.tris.length, 0));
let o = 0; for (const p of parts) { all.set(p.tris, o); o += p.tris.length; }
fs.mkdirSync(path.dirname(opts.outPath), { recursive: true });
writeStlTriangles(opts.outPath, all);
const bb = trisBBox(all);
const size = [bb.max[0] - bb.min[0], bb.max[1] - bb.min[1], bb.max[2] - bb.min[2]] as [number, number, number];
return { ok: true, outputs: [{ path: opts.outPath, parts: parts.length, size }], placements: parts.map(p => ({ path: p.label, size: [p.bb.max[0] - p.bb.min[0], p.bb.max[1] - p.bb.min[1], p.bb.max[2] - p.bb.min[2]] as [number, number, number], plate: 1, x: p.bb.min[0], y: p.bb.min[1] })), overflow: [] };
}
// grid — 큰 부품(깊이 큰 순)부터 행에 채운다.
const items = parts.map(p => ({ ...p, w: p.bb.max[0] - p.bb.min[0], d: p.bb.max[1] - p.bb.min[1], h: p.bb.max[2] - p.bb.min[2] }))
.sort((a, b) => b.d - a.d);
const overflow: string[] = [];
const plates: { items: (typeof items[number] & { x: number; y: number })[] }[] = [];
const startPlate = () => { plates.push({ items: [] }); return { xCur: 0, yCur: 0, rowH: 0 }; };
let cur = startPlate();
for (const it of items) {
if (it.w > opts.bedX || it.d > opts.bedY) overflow.push(`${it.label} (${it.w.toFixed(0)}×${it.d.toFixed(0)}mm — 베드 ${opts.bedX}×${opts.bedY}보다 큼)`);
if (cur.xCur > 0 && cur.xCur + it.w > opts.bedX) { cur.yCur += cur.rowH + opts.gap; cur.xCur = 0; cur.rowH = 0; }
if (cur.yCur > 0 && cur.yCur + it.d > opts.bedY) cur = startPlate();
plates[plates.length - 1].items.push({ ...it, x: cur.xCur, y: cur.yCur });
cur.xCur += it.w + opts.gap; cur.rowH = Math.max(cur.rowH, it.d);
}
const ext = path.extname(opts.outPath), base = opts.outPath.slice(0, opts.outPath.length - ext.length);
fs.mkdirSync(path.dirname(opts.outPath), { recursive: true });
const outputs: MergeResult['outputs'] = [], placements: MergePlacement[] = [];
plates.forEach((pl, pi) => {
const total = pl.items.reduce((s, it) => s + it.tris.length, 0);
const all = new Float32Array(total);
let o = 0;
for (const it of pl.items) {
const dx = it.x - it.bb.min[0], dy = it.y - it.bb.min[1], dz = -it.bb.min[2];
for (let i = 0; i < it.tris.length; i += 3) { all[o + i] = it.tris[i] + dx; all[o + i + 1] = it.tris[i + 1] + dy; all[o + i + 2] = it.tris[i + 2] + dz; }
o += it.tris.length;
}
const bb = trisBBox(all);
const cx = (bb.min[0] + bb.max[0]) / 2, cy = (bb.min[1] + bb.max[1]) / 2;
for (let i = 0; i < all.length; i += 3) { all[i] -= cx; all[i + 1] -= cy; }
const file = pi === 0 ? opts.outPath : `${base}_${pi + 1}${ext}`;
writeStlTriangles(file, all);
outputs.push({ path: file, parts: pl.items.length, size: [bb.max[0] - bb.min[0], bb.max[1] - bb.min[1], bb.max[2] - bb.min[2]] });
for (const it of pl.items) placements.push({ path: it.label, size: [it.w, it.d, it.h], plate: pi + 1, x: it.x - cx + 0, y: it.y - cy + 0 });
});
return { ok: true, outputs, placements, overflow };
} catch (e: any) {
return { ok: false, detail: String(e?.message || e) };
}
}
+111 -7
View File
@@ -8,7 +8,7 @@ import { buildImageMarkdown, isPathInsideDir } from './image.js';
import { autoRenderForScad } from './workshop-assembly-render.js';
import { previewPngPath } from '../gateway/routes/workshop-layout.js';
import { SCAD_RULES_SHORT, normalizeWorkshopScadPath, lintScadAssembly, formatLint } from './scad-conventions.js';
import { OPENSCAD_BIN, readStlBBox, renderStlPng, addHoleToStl, runOpenscad, applyBooleanOp, analyzeStl, StlAnalysis, translateStlZInPlace, transformStl } from './stl-cad-core.js';
import { OPENSCAD_BIN, readStlBBox, renderStlPng, addHoleToStl, runOpenscad, applyBooleanOp, analyzeStl, StlAnalysis, translateStlZInPlace, transformStl, mergeStls } from './stl-cad-core.js';
import { renderThreeView, fmtMm } from './stl-three-view.js';
// STL 확인/미리보기/간단 수정(구멍 추가) 도구 — "작업실"에서 만든 파츠를 재출력 없이
@@ -97,6 +97,31 @@ function formatAnalysisFull(a: StlAnalysis): string {
return lines.join('\n');
}
// 워크스페이스 기준 상대경로 import 를 절대경로로 바꾼다 — .scad 옆에 없고 워크스페이스 기준으론 있는 파일만.
export function rewriteWorkspaceImports(source: string, scadDir: string, workspacePath: string): { source: string; count: number } {
let count = 0;
const out = source.replace(/\b(import|surface)\s*\(\s*(file\s*=\s*)?"([^"]+)"/g, (whole, fn, fileKw, rel) => {
if (path.isAbsolute(rel)) return whole;
if (fs.existsSync(path.resolve(scadDir, rel))) return whole;
const abs = path.resolve(workspacePath, rel);
if (!isPathInsideDir(workspacePath, abs) || !fs.existsSync(abs)) return whole;
count++;
return `${fn}(${fileKw || ''}"${abs.replace(/\\/g, '/')}"`;
});
return { source: out, count };
}
// OpenSCAD 실패 메시지를 모델이 바로 다음 수를 알 수 있게 풀어준다.
export function openscadFailureAdvice(detail: string): string {
if (/Can't open import file/i.test(detail)) {
return '\n→ import 경로를 못 찾았습니다. 경로는 .scad 파일 위치 기준 상대경로이거나 절대경로여야 합니다(워크스페이스 기준 "workshop/…" 상대경로는 자동 보정되지만 파일이 실제로 있어야 함). stl_cad action="info"로 파일 존재·이름 대소문자를 확인하세요.';
}
if (/not closed|Unable to convert to CGAL|CGAL error|applyUnion3D/i.test(detail)) {
return '\n→ 임포트한 STL 메시가 닫혀 있지 않아(non-manifold) OpenSCAD의 합집합/차집합(CGAL)이 실패했습니다. 문제 STL은 stl_cad action="info"의 "밀폐(manifold)" 항목으로 찾을 수 있고, 여러 부품을 그냥 나란히 배치만 하려면 합집합 없이 각각 다른 위치로 import 하거나 문제 부품을 제외하세요. 같은 방식으로 재시도를 반복하지 마세요.';
}
return '';
}
// scad_to_stl 와 stl_cad compile 이 공유하는 컴파일 로직 — part 퍼지매칭·defines(임의 변수
// 오버라이드)·빈 출력 감지·analyzeStl 보고까지 한 번에. preview=true 면 iso PNG도 렌더.
async function compileScadToStl(opts: {
@@ -121,16 +146,28 @@ async function compileScadToStl(opts: {
}
const defineArgs = buildDefineArgs(opts.defines);
// import("workshop/…/x.stl")처럼 워크스페이스 기준으로 쓴 상대경로는 OpenSCAD가 .scad 파일 위치 기준으로
// 풀어서 못 찾는다(09-29 실측: 같은 실패를 4번 반복하고서야 절대경로로 고침). 파일이 없는 상대경로가
// 워크스페이스 기준으론 존재하면 임시 사본에서 절대경로로 바꿔 컴파일한다(원본 .scad는 그대로).
const rewritten = rewriteWorkspaceImports(fs.readFileSync(scadPath, 'utf8'), path.dirname(scadPath), workspacePath);
let compileScad = scadPath;
let tmpScad: string | null = null;
if (rewritten.count > 0) {
tmpScad = path.join(path.dirname(scadPath), `.__tmp_${process.pid}_${Date.now()}.scad`);
fs.writeFileSync(tmpScad, rewritten.source);
compileScad = tmpScad;
}
const openscadArgs = [
...(part ? ['-D', `PART="${part.replace(/"/g, '\\"')}"`] : []),
...defineArgs,
'-o', outPath,
'--export-format=binstl',
scadPath,
compileScad,
];
fs.mkdirSync(path.dirname(outPath), { recursive: true });
const run = await runOpenscad(openscadArgs, 120_000);
if (!run.ok) return { ok: false, error: `OpenSCAD 컴파일 실패: ${run.detail}` };
if (tmpScad) { try { fs.unlinkSync(tmpScad); } catch { /* noop */ } }
if (!run.ok) return { ok: false, error: `OpenSCAD 컴파일 실패: ${run.detail}${openscadFailureAdvice(run.detail)}` };
if (!fs.existsSync(outPath) || fs.statSync(outPath).size < 84) {
// 빈 출력 — PART 분기가 있는데 part를 안 줘서 "all" 조립체가 빈 경우도 드물지만, 분기
// 매칭에 실패한 경우가 대부분. 후보가 있으면 알려준다.
@@ -171,14 +208,19 @@ async function compileScadToStl(opts: {
export const stlCadTool = {
name: 'stl_cad',
description: '이미 있는 STL 3D모델 파일을 확인(치수/체적/밀폐여부/삼각형수)하거나 여러 각도로 미리보기 렌더링하거나, 구멍·박스 컷·불리언 연산(합/차/교집합)으로 편집한다(OpenSCAD 기반 — FreeCAD 대신 이걸 씀). ⚠️ 입력 파일이 .scad(아직 STL이 아닌 소스)면 이 도구 말고 scad_to_stl 도구로 컴파일할 것. 워크스페이스 안의 파일만 다룬다. 물리적 동작이 없는 파일 편집이라 확인 없이 바로 실행해도 된다.',
description: '이미 있는 STL 3D모델 파일을 확인(치수/체적/밀폐여부/삼각형수)하거나 여러 각도로 미리보기 렌더링하거나, 구멍·박스 컷·불리언 연산(합/차/교집합)으로 편집한다(OpenSCAD 기반 — FreeCAD 대신 이걸 씀). ⚠️ 입력 파일이 .scad(아직 STL이 아닌 소스)면 이 도구 말고 scad_to_stl 도구로 컴파일할 것. 워크스페이스 안의 파일만 다룬다. 물리적 동작이 없는 파일 편집이라 확인 없이 바로 실행해도 된다. ⚠️ STL 단위 확인·변환도 python_eval로 직접 짜지 말고 이 도구로 한다: 단위 확인=info(크기가 0.5mm 미만이면 미터 단위 의심), 미터→mm 변환=transform scale=1000(cm→mm는 10, inch→mm는 25.4). 여러 파일은 stl_paths 배열로 한 번에 처리하고, 결과 bbox가 도구 출력에 나오니 그 값으로만 "완료"를 보고할 것(파일을 만들었다고 추측해서 말하지 말 것).',
schema: { action: 'string', stl_path: 'string' },
jsonSchema: {
type: 'object',
required: ['action'],
properties: {
action: { type: 'string', enum: ['info', 'render', 'three_view', 'add_hole', 'cut', 'boolean', 'transform'], description: 'info: 치수/바운딩박스/체적/밀폐(manifold)여부/삼각형수 조회(stl_path). render: 지정한 각도로 PNG 미리보기 생성(stl_path, 모델이 직접 봄). three_view: 제작용 3면도(정면/평면/우측면, 외곽 치수선 표기)를 흰 도면 시트 PNG로 생성(stl_path). add_hole: 지정 좌표에 원통형 구멍 뚫어 새 STL로 저장(stl_path). cut: 박스 모양으로 깎아냄(stl_path). boolean: 다른 STL과 합/차/교집합(stl_path + second_path). transform: 크기변경/회전/거울/이동(stl_path, output_path 생략 시 제자리 덮어씀).' },
action: { type: 'string', enum: ['info', 'render', 'three_view', 'add_hole', 'cut', 'boolean', 'transform', 'merge'], description: 'merge: 여러 STL(stl_paths)을 한 파일로 합침(output_path 필수) — 삼각형을 그대로 이어붙여서 닫히지 않은(non-manifold) 메시도 OK, OpenSCAD 합집합보다 안전. layout=grid(기본)면 각 부품을 바닥(z=0)에 붙여 베드(bed_x×bed_y, 기본 260×260, gap 5mm) 안에 배치하고 넘치면 output_path_2.stl…로 판을 나눔. layout=keep이면 현재 위치 그대로 합침(조립체 확인용). info: 치수/바운딩박스/체적/밀폐(manifold)여부/삼각형수 조회(stl_path). render: 지정한 각도로 PNG 미리보기 생성(stl_path, 모델이 직접 봄). three_view: 제작용 3면도(정면/평면/우측면, 외곽 치수선 표기)를 흰 도면 시트 PNG로 생성(stl_path). add_hole: 지정 좌표에 원통형 구멍 뚫어 새 STL로 저장(stl_path). cut: 박스 모양으로 깎아냄(stl_path). boolean: 다른 STL과 합/차/교집합(stl_path + second_path). transform: 크기변경/회전/거울/이동(stl_path, output_path 생략 시 제자리 덮어씀).' },
stl_path: { type: 'string', description: '(info/render/add_hole/cut/boolean 필수) 워크스페이스 기준 상대경로의 바이너리 STL 파일(예: "print3d/esp32_camera/esp32_top.stl"). ASCII STL은 지원 안 함.' },
stl_paths: { type: 'array', items: { type: 'string' }, description: '(info/transform 선택) 여러 STL을 한 번에 처리할 때 stl_path 대신 경로 배열. transform은 각 파일을 제자리 덮어쓴다(output_path 불가). 결과는 파일별로 나열된다.' },
layout: { type: 'string', enum: ['grid', 'keep'], description: '(merge, 선택) grid=베드에 자동 배치(기본), keep=위치 유지' },
bed_x: { type: 'number', description: '(merge grid, 선택) 베드 가로 mm. 기본 260(K2 Combo)' },
bed_y: { type: 'number', description: '(merge grid, 선택) 베드 세로 mm. 기본 260' },
gap: { type: 'number', description: '(merge grid, 선택) 부품 간격 mm. 기본 5' },
view: { type: 'string', enum: ['iso', 'top', 'bottom', 'front', 'back', 'left', 'right'], description: '(render, 선택) 단일 보는 각도. 기본 iso. views를 주면 view는 무시됨.' },
views: { type: 'array', items: { type: 'string', enum: ['iso', 'top', 'bottom', 'front', 'back', 'left', 'right'] }, description: '(render, 선택) 여러 각도를 한 번에 렌더 — ["iso","top","front"] 식으로 주면 각각 PNG를 만들어 모두 돌려줌(모델이 형상 전체를 파악하기 좋음). view 단일보다 이쪽이 권장.' },
x: { type: 'number', description: '(add_hole/cut 필수) 중심 X좌표(모델 원본 좌표계, info로 바운딩박스 확인 후 지정)' },
@@ -232,18 +274,80 @@ export const stlCadTool = {
return r.ok ? { success: true, stdout: r.stdout } : { success: false, error: r.error };
}
// 여러 파일 일괄(info/transform) — 파일별로 같은 execute를 돌려 결과를 이어붙인다.
if (Array.isArray(args?.stl_paths) && args.stl_paths.length && (action === 'info' || action === 'transform')) {
if (action === 'transform' && String(args?.output_path || '').trim()) {
return { success: false, error: 'stl_paths 일괄 transform은 제자리 덮어쓰기만 가능합니다(output_path 불가).' };
}
const paths: string[] = args.stl_paths.map((x: any) => String(x || '').trim()).filter(Boolean).slice(0, 50);
const parts: string[] = [];
let okCount = 0;
for (const sp of paths) {
const r1: ToolResult = await (stlCadTool as any).execute({ ...args, stl_paths: undefined, stl_path: sp });
if (r1.success) okCount++;
parts.push(r1.success ? `▶ ${sp}\n${r1.stdout}` : `▶ ${sp}\n❌ ${r1.error}`);
}
return { success: okCount > 0, stdout: `${okCount}/${paths.length}개 성공\n\n${parts.join('\n\n')}`, ...(okCount === 0 ? { error: '모든 파일 처리 실패' } : {}) };
}
if (action === 'merge') {
const list: string[] = (Array.isArray(args?.stl_paths) ? args.stl_paths : []).map((x: any) => String(x || '').trim()).filter(Boolean);
if (list.length < 2) return { success: false, error: 'merge는 stl_paths에 STL 경로를 2개 이상 배열로 넘겨야 합니다.' };
if (list.length > 60) return { success: false, error: 'merge는 한 번에 최대 60개까지입니다.' };
const outArg = String(args?.output_path || '').trim();
if (!outArg || !/\.stl$/i.test(outArg)) return { success: false, error: 'output_path(.stl로 끝나는 저장 경로)가 필요합니다.' };
let outAbs: string;
try { outAbs = resolveWorkspacePath(workspacePath, outArg); } catch (e: any) { return { success: false, error: String(e?.message || e) }; }
const paths: { abs: string; label: string }[] = [];
const missing: string[] = [];
for (const rel of list) {
let abs: string;
try { abs = resolveWorkspacePath(workspacePath, rel); } catch (e: any) { return { success: false, error: String(e?.message || e) }; }
if (!fs.existsSync(abs)) {
const dir = path.dirname(abs), base = path.basename(abs).toLowerCase();
const hit = fs.existsSync(dir) ? fs.readdirSync(dir).find((f) => f.toLowerCase() === base) : undefined;
if (hit) abs = path.join(dir, hit); else { missing.push(rel); continue; }
}
paths.push({ abs, label: rel });
}
if (missing.length) return { success: false, error: `파일을 찾을 수 없습니다: ${missing.join(', ')}` };
const layout = args?.layout === 'keep' ? 'keep' : 'grid';
const pos = (v: any, d: number) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : d);
const res = mergeStls({ paths, outPath: outAbs, layout, bedX: pos(args?.bed_x, 260), bedY: pos(args?.bed_y, 260), gap: layout === 'grid' && Number.isFinite(Number(args?.gap)) && Number(args.gap) >= 0 ? Number(args.gap) : 5 });
if (!res.ok) return { success: false, error: `병합 실패: ${res.detail}` };
const rel = (p: string) => path.relative(workspacePath, p);
const lines = [`병합 완료 (${layout === 'grid' ? `베드 ${pos(args?.bed_x, 260)}×${pos(args?.bed_y, 260)} 자동 배치` : '위치 유지'}) — ${res.outputs.length}개 파일`];
for (const o of res.outputs) lines.push(`- ${rel(o.path)}: 부품 ${o.parts}개, 크기 ${o.size.map(n => n.toFixed(1)).join(' × ')} mm`);
if (res.placements.length) lines.push('배치: ' + res.placements.map(p => `${path.basename(p.path)}(판${p.plate})`).join(', '));
if (res.overflow.length) lines.push(`⚠️ 베드보다 큰 부품: ${res.overflow.join('; ')} — 크기 그대로 배치했으니 슬라이서에서 분할·축소하세요.`);
lines.push('※ 삼각형을 그대로 합친 것이라 겹친 부분은 해소되지 않습니다(불리언 아님).');
return { success: true, stdout: lines.join('\n') };
}
let stlPath: string;
try {
stlPath = resolveWorkspacePath(workspacePath, String(args?.stl_path || ''));
} catch (e: any) {
return { success: false, error: String(e?.message || e) };
}
if (!fs.existsSync(stlPath)) return { success: false, error: `파일을 찾을 수 없습니다: ${args?.stl_path}` };
if (!fs.existsSync(stlPath)) {
// 확장자/이름 대소문자만 다른 경우(L1.stl ↔ L1.STL — 09-29 실측 6회 연속 실패) 자동으로 맞춘다.
const dir = path.dirname(stlPath), base = path.basename(stlPath).toLowerCase();
const hit = fs.existsSync(dir) ? fs.readdirSync(dir).find((f) => f.toLowerCase() === base) : undefined;
if (hit) stlPath = path.join(dir, hit);
else return { success: false, error: `파일을 찾을 수 없습니다: ${args?.stl_path}` };
}
if (action === 'info') {
let analysis: StlAnalysis;
try { analysis = analyzeStl(stlPath); } catch (e: any) { return { success: false, error: String(e?.message || e) }; }
return { success: true, stdout: `**${path.basename(stlPath)}**\n${formatAnalysisFull(analysis)}` };
const maxExt = Math.max(analysis.max[0] - analysis.min[0], analysis.max[1] - analysis.min[1], analysis.max[2] - analysis.min[2]);
const unitAdvice = maxExt < 0.5
? `\n⚠️ 미터(m) 단위로 보입니다(최대 ${maxExt.toFixed(3)}) — mm로 쓰려면 stl_cad action="transform" stl_path="${args?.stl_path}" scale=1000 (제자리 덮어씀).`
: maxExt > 1000
? `\n⚠️ 크기가 1m를 넘습니다 — 마이크로미터/잘못된 단위일 수 있습니다. 실제 크기를 확인하고 필요하면 transform scale=<배율>로 조정하세요.`
: '';
return { success: true, stdout: `**${path.basename(stlPath)}**\n${formatAnalysisFull(analysis)}${unitAdvice}` };
}
if (action === 'render') {
+140
View File
@@ -0,0 +1,140 @@
// stl_cad 단위 점검/일괄 변환 (2026-09-29) — 미터 단위 STL 경고, stl_paths 일괄 transform.
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawnSync } from 'child_process';
import { OPENSCAD_BIN, readStlBBox } from '../src/tools/stl-cad-core';
import { stlCadTool } from '../src/tools/stl-cad';
describe('stl_cad — 미터 단위 경고 + 일괄 변환', () => {
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'stl-unit-'));
const mk = (name: string, scad: string) => {
const f = path.join(ws, name + '.scad');
fs.writeFileSync(f, scad);
const r = spawnSync(OPENSCAD_BIN, ['-o', path.join(ws, name + '.stl'), '--export-format=binstl', f], { timeout: 60_000 });
assert.equal(r.status, 0, `fixture 실패: ${r.stderr}`);
};
test.before(() => {
mk('m1', 'cube([0.1,0.2,0.05]);'); // 미터 단위 부품(최대 0.2)
mk('m2', 'cube([0.08,0.04,0.02]);');
mk('ok', 'cube([40,20,10]);'); // mm 정상
});
test('info — 미터 단위면 변환 명령을 안내', { timeout: 60_000 }, async () => {
const r: any = await stlCadTool.execute({ action: 'info', stl_path: 'm1.stl', _workspacePath: ws });
assert.ok(r.success);
assert.match(r.stdout, /미터\(m\) 단위/);
assert.match(r.stdout, /scale=1000/);
});
test('info — mm 정상이면 경고 없음', { timeout: 60_000 }, async () => {
const r: any = await stlCadTool.execute({ action: 'info', stl_path: 'ok.stl', _workspacePath: ws });
assert.ok(r.success);
assert.doesNotMatch(r.stdout, /미터\(m\) 단위/);
});
test('transform stl_paths — 여러 파일 ×1000 제자리 변환, 실제 bbox로 검증', { timeout: 180_000 }, async () => {
const r: any = await stlCadTool.execute({ action: 'transform', stl_paths: ['m1.stl', 'm2.stl', 'nope.stl'], scale: 1000, _workspacePath: ws });
assert.ok(r.success);
assert.match(r.stdout, /2\/3개 성공/);
assert.match(r.stdout, /nope\.stl[\s\S]*❌/);
const b1 = readStlBBox(path.join(ws, 'm1.stl'));
assert.ok(Math.abs((b1.max[1] - b1.min[1]) - 200) < 0.5, `m1 Y 크기 200mm 아님: ${b1.max[1] - b1.min[1]}`);
const b2 = readStlBBox(path.join(ws, 'm2.stl'));
assert.ok(Math.abs((b2.max[0] - b2.min[0]) - 80) < 0.5, `m2 X 크기 80mm 아님`);
});
test('stl_paths + output_path 조합은 거부', async () => {
const r: any = await stlCadTool.execute({ action: 'transform', stl_paths: ['ok.stl'], scale: 2, output_path: 'x.stl', _workspacePath: ws });
assert.equal(r.success, false);
});
});
describe('stl_cad — 대소문자만 다른 경로', () => {
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'stl-case-'));
test('L1.stl 로 요청해도 L1.STL 을 찾는다', { timeout: 60_000 }, async () => {
const f = path.join(ws, 'L1.scad');
fs.writeFileSync(f, 'cube([10,10,10]);');
const r0 = spawnSync(OPENSCAD_BIN, ['-o', path.join(ws, 'L1.STL'), '--export-format=binstl', f], { timeout: 60_000 });
assert.equal(r0.status, 0);
const r: any = await stlCadTool.execute({ action: 'info', stl_path: 'L1.stl', _workspacePath: ws });
assert.ok(r.success, r.error);
});
});
describe('scad import 경로 — 워크스페이스 기준 상대경로 자동 보정', () => {
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'stl-import-'));
test.before(() => {
fs.mkdirSync(path.join(ws, 'CAD', 'groups'), { recursive: true });
const f = path.join(ws, 'CAD', 'src.scad');
fs.writeFileSync(f, 'cube([10,10,10]);');
const r = spawnSync(OPENSCAD_BIN, ['-o', path.join(ws, 'CAD', 'part.stl'), '--export-format=binstl', f], { timeout: 60_000 });
assert.equal(r.status, 0);
});
test('import("CAD/part.stl")(워크스페이스 기준)이 .scad가 다른 폴더에 있어도 컴파일된다', { timeout: 120_000 }, async () => {
fs.writeFileSync(path.join(ws, 'CAD', 'groups', 'g.scad'), 'import("CAD/part.stl");\ntranslate([20,0,0]) import("CAD/part.stl");\n');
const r: any = await stlCadTool.execute({ action: 'compile', scad_path: 'CAD/groups/g.scad', output_path: 'CAD/groups/g.stl', _workspacePath: ws });
assert.ok(r.success, r.error);
const b = readStlBBox(path.join(ws, 'CAD', 'groups', 'g.stl'));
assert.ok(Math.abs((b.max[0] - b.min[0]) - 30) < 0.5, '두 큐브(10+간격20+10=30) 아님');
assert.equal(fs.readdirSync(path.join(ws, 'CAD', 'groups')).filter((f) => f.startsWith('.__tmp_')).length, 0, '임시 scad가 남음');
assert.match(fs.readFileSync(path.join(ws, 'CAD', 'groups', 'g.scad'), 'utf8'), /import\("CAD\/part\.stl"\)/, '원본 scad가 바뀜');
});
test('실제로 없는 파일이면 실패 + 안내 문구', { timeout: 120_000 }, async () => {
fs.writeFileSync(path.join(ws, 'CAD', 'groups', 'bad.scad'), 'import("CAD/nope.stl");\n');
const r: any = await stlCadTool.execute({ action: 'compile', scad_path: 'CAD/groups/bad.scad', output_path: 'CAD/groups/bad.stl', _workspacePath: ws });
assert.equal(r.success, false);
});
});
describe('stl_cad merge — 삼각형 병합 + 베드 배치', () => {
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'stl-merge-'));
const mk = (name: string, scad: string) => {
const f = path.join(ws, name + '.scad');
fs.writeFileSync(f, scad);
const r = spawnSync(OPENSCAD_BIN, ['-o', path.join(ws, name + '.stl'), '--export-format=binstl', f], { timeout: 60_000 });
assert.equal(r.status, 0, `fixture 실패: ${r.stderr}`);
};
test.before(() => {
mk('a', 'translate([100,100,50]) cube([40,20,10]);'); // 원점에서 멀리 떠 있는 부품
mk('b', 'cube([30,30,5]);');
mk('c', 'cube([50,50,8]);');
});
test('grid — 바닥 z=0, 중심 (0,0), 베드 안에 배치, 삼각형 수 합계 보존', { timeout: 60_000 }, async () => {
const r: any = await stlCadTool.execute({ action: 'merge', stl_paths: ['a.stl', 'b.stl', 'c.stl'], output_path: 'out/plate.stl', _workspacePath: ws });
assert.ok(r.success, r.error);
const bb = readStlBBox(path.join(ws, 'out', 'plate.stl'));
assert.ok(Math.abs(bb.min[2]) < 1e-3, '바닥이 z=0이 아님');
assert.ok(Math.abs(bb.min[0] + bb.max[0]) < 0.1 && Math.abs(bb.min[1] + bb.max[1]) < 0.1, 'XY 중심이 (0,0)이 아님');
assert.ok(bb.max[0] - bb.min[0] <= 260 && bb.max[1] - bb.min[1] <= 260, '베드 초과');
const tris = (f: string) => fs.readFileSync(path.join(ws, f)).readUInt32LE(80);
assert.equal(tris('out/plate.stl'), tris('a.stl') + tris('b.stl') + tris('c.stl'), '삼각형 수가 안 맞음');
});
test('grid — 베드가 작으면 판을 나눔(plate_2.stl)', { timeout: 60_000 }, async () => {
const r: any = await stlCadTool.execute({ action: 'merge', stl_paths: ['a.stl', 'b.stl', 'c.stl'], output_path: 'out2/p.stl', bed_x: 60, bed_y: 60, gap: 5, _workspacePath: ws });
assert.ok(r.success, r.error);
assert.ok(fs.existsSync(path.join(ws, 'out2', 'p.stl')) && fs.existsSync(path.join(ws, 'out2', 'p_2.stl')), '판이 나뉘지 않음');
assert.match(r.stdout, /\d개 파일/);
});
test('keep — 위치 그대로 합침', { timeout: 60_000 }, async () => {
const r: any = await stlCadTool.execute({ action: 'merge', stl_paths: ['a.stl', 'b.stl'], output_path: 'keep.stl', layout: 'keep', _workspacePath: ws });
assert.ok(r.success, r.error);
const bb = readStlBBox(path.join(ws, 'keep.stl'));
assert.ok(bb.max[0] >= 139.9, '원래 위치(x=140)가 유지되지 않음');
});
test('입력 검증 — 1개/없는 파일/output_path 없음', async () => {
const one: any = await stlCadTool.execute({ action: 'merge', stl_paths: ['a.stl'], output_path: 'x.stl', _workspacePath: ws });
assert.equal(one.success, false);
const miss: any = await stlCadTool.execute({ action: 'merge', stl_paths: ['a.stl', 'zz.stl'], output_path: 'x.stl', _workspacePath: ws });
assert.equal(miss.success, false);
assert.match(miss.error, /zz\.stl/);
const noOut: any = await stlCadTool.execute({ action: 'merge', stl_paths: ['a.stl', 'b.stl'], _workspacePath: ws });
assert.equal(noOut.success, false);
});
});