From 4552f51619687a35653873a51d47d7be40dc0e6e Mon Sep 17 00:00:00 2001 From: kim Date: Tue, 29 Sep 2026 13:11:16 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=AA=A8=EB=93=A0=20STL=20=EA=B8=B0?= =?UTF-8?q?=EB=B3=B8=20=EB=B0=94=EB=8B=A5(z=3D0)=20=EA=B7=9C=EC=B9=99=20?= =?UTF-8?q?=E2=80=94=20=EC=97=85=EB=A1=9C=EB=93=9C=C2=B7model=5Fdownload?= =?UTF-8?q?=C2=B7stl=5Fcad=20transform(=EA=B8=B0=EB=B3=B8=20align=5Fbottom?= =?UTF-8?q?)=EC=97=90=EC=84=9C=20z=20=ED=8F=89=ED=96=89=EC=9D=B4=EB=8F=99?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=A0=95=EB=A0=AC(dropStlToFloor)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/routes/routes-workshop.ts | 6 +++- src/tools/model-search.ts | 5 ++- src/tools/stl-cad-core.ts | 13 ++++++++ src/tools/stl-cad.ts | 8 ++--- tests/stl-transform.test.ts | 2 +- tests/stl-unit-batch.test.ts | 48 +++++++++++++++++++++++++++ 6 files changed, 75 insertions(+), 7 deletions(-) diff --git a/src/gateway/routes/routes-workshop.ts b/src/gateway/routes/routes-workshop.ts index 0754e78..ba48985 100644 --- a/src/gateway/routes/routes-workshop.ts +++ b/src/gateway/routes/routes-workshop.ts @@ -20,7 +20,7 @@ import { listDeletedProjects, restoreFromHistory, readHistory, duplicateProject, genWorkshopId, } from './workshop-storage'; import { searchDanawa } from '../../tools/danawa'; -import { renderStlPng } from '../../tools/stl-cad-core'; +import { renderStlPng, dropStlToFloor } from '../../tools/stl-cad-core'; import { scanScadModules, unassignedParts } from './workshop-assembly'; import { renderAssemblyManual, readManifest, resolveScadPath, currentAssemblyHash, assemblyOutDir, ASSEMBLY_DIR_NAME, draftAssembly } from '../../tools/workshop-assembly-render'; import { clearHistory } from '../session'; @@ -488,9 +488,13 @@ export function registerWorkshopRoutes( const targetName = folder ? `${folder}/${filename}` : filename; const { relPath, absPath } = resolveUploadPath(dir, targetName); fs.writeFileSync(absPath, fileData); + // 모든 STL은 기본적으로 바닥(z=0)에 붙인다(2026-09-29) — 업로드한 외부 STL도 z 평행이동만 적용. + let zShift = 0; + if (/\.stl$/i.test(absPath)) { const zr = dropStlToFloor(absPath); if (zr.ok) zShift = zr.shifted; } res.json({ success: true, + zAlignedMm: zShift ? Number(zShift.toFixed(3)) : 0, name: path.basename(relPath), relPath, size: fileData.length, diff --git a/src/tools/model-search.ts b/src/tools/model-search.ts index b1281c7..9fe4ce3 100644 --- a/src/tools/model-search.ts +++ b/src/tools/model-search.ts @@ -7,7 +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'; +import { analyzeStl, dropStlToFloor } from './stl-cad-core.js'; // 3D 모델 저장소 검색+다운로드 (2026-09-23) — Printables / MakerWorld / Thingiverse. // 세 곳 모두 공식 API가 없거나(Printables/MakerWorld) 응용토큰이 필요한(Thingiverse) 사이라 @@ -489,6 +489,9 @@ export const modelDownloadTool = { let unitNote = ''; if (/\.stl$/i.test(outPath)) { try { + // 기본 규칙: 모든 STL은 바닥(z=0)에 붙인다 — 미터 단위(<0.5)면 변환 뒤에 다시 맞춘다. + const zr = dropStlToFloor(outPath); + if (zr.ok && zr.shifted) unitNote += `\n- 바닥(z=0)에 맞춤: z ${zr.shifted > 0 ? '+' : ''}${zr.shifted.toFixed(2)}mm 이동`; 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)}`; diff --git a/src/tools/stl-cad-core.ts b/src/tools/stl-cad-core.ts index 1251ce2..3a31af5 100644 --- a/src/tools/stl-cad-core.ts +++ b/src/tools/stl-cad-core.ts @@ -180,6 +180,19 @@ export function translateStlZInPlace(stlPath: string, dz: number): { ok: true } } } +// "모든 STL은 바닥(z=0)에 붙인다"가 기본 규칙(2026-09-29) — 다운로드/업로드/변환 진입점이 공유하는 헬퍼. +// bbox 최저점이 z=0에서 tol(mm) 넘게 벗어나면 z 평행이동만 한다(모양·XY 불변). 바이너리 STL만 — ASCII/손상은 +// 건드리지 않고 { ok:false }로 돌려준다. shifted = 실제로 옮긴 z 양(0이면 이미 바닥). +export function dropStlToFloor(stlPath: string, tol = 0.05): { ok: true; shifted: number } | { ok: false; detail: string } { + let bb: StlBBox; + try { bb = readStlBBox(stlPath); } catch (e: any) { return { ok: false, detail: String(e?.message || e) }; } + const minZ = bb.min[2]; + if (!Number.isFinite(minZ)) return { ok: false, detail: '삼각형이 없습니다.' }; + if (Math.abs(minZ) <= tol) return { ok: true, shifted: 0 }; + const r = translateStlZInPlace(stlPath, -minZ); + return r.ok ? { ok: true, shifted: -minZ } : r; +} + // 기존 STL을 크기변경·회전·거울·이동해 재출력(2026-09-25 "transform" 액션) — 소스 없는 // 외부 STL(다운로드 파일)도 채팅에서 편집할 수 있게. 회전·거울·배율은 부품 bbox 중심 // 기준으로 먹힌다(원점 기준이 아님 — 모델이 화면 밖으로 흩어지지 않게). 법선·와인딩은 diff --git a/src/tools/stl-cad.ts b/src/tools/stl-cad.ts index cb05784..1c206f9 100644 --- a/src/tools/stl-cad.ts +++ b/src/tools/stl-cad.ts @@ -243,7 +243,7 @@ export const stlCadTool = { dx: { type: 'number', description: '(transform, 선택) X 이동(mm)' }, dy: { type: 'number', description: '(transform, 선택) Y 이동(mm)' }, dz: { type: 'number', description: '(transform, 선택) Z 이동(mm)' }, - align_bottom: { type: 'boolean', description: '(transform, 선택) true면 변환 후 바닥을 z=0에 붙인다' }, + align_bottom: { type: 'boolean', description: '(transform, 선택) 기본 true — 변환 후 바닥을 z=0에 붙인다(모든 STL 기본 규칙). false로 주면 끈다. 이것만 단독으로 주면(true) 이동 없이 바닥 정렬만 한다' }, output_path: { type: 'string', description: '(add_hole/cut/boolean 필수, transform 선택) 결과 STL을 저장할 워크스페이스 기준 상대경로(.stl로 끝나야 함). transform에서 생략하면 stl_path 파일을 제자리 덮어쓴다.' }, }, additionalProperties: false, @@ -387,8 +387,8 @@ export const stlCadTool = { const rx = Number(args?.rx) || 0, ry = Number(args?.ry) || 0, rz = Number(args?.rz) || 0; const mirror = (['x', 'y', 'z'].includes(args?.mirror) ? args.mirror : '') as '' | 'x' | 'y' | 'z'; const dx = Number(args?.dx) || 0, dy = Number(args?.dy) || 0, dz = Number(args?.dz) || 0; - const alignBottom = args?.align_bottom === true; - if (scale === 1 && !rx && !ry && !rz && !mirror && !dx && !dy && !dz && !alignBottom) { + const alignBottom = args?.align_bottom !== false; // 기본 true — 모든 STL은 바닥(z=0)에 붙인다(2026-09-29). false로 끄기 + if (scale === 1 && !rx && !ry && !rz && !mirror && !dx && !dy && !dz && args?.align_bottom !== true) { return { success: false, error: '변환 내용이 없습니다 — scale, rx/ry/rz(도), mirror(x/y/z), dx/dy/dz(mm), align_bottom 중 하나 이상 지정하세요.' }; } const outPathArg = String(args?.output_path || '').trim(); @@ -407,7 +407,7 @@ export const stlCadTool = { if (mirror) done.push(`거울 ${mirror}축`); if (dx || dy || dz) done.push(`이동 (${dx}, ${dy}, ${dz})`); let stdout = `변환 완료: ${done.join(', ')}\n결과 bbox: X[${fmtMm(result.bbox.min[0])}, ${fmtMm(result.bbox.max[0])}] Y[${fmtMm(result.bbox.min[1])}, ${fmtMm(result.bbox.max[1])}] Z[${fmtMm(result.bbox.min[2])}, ${fmtMm(result.bbox.max[2])}] mm`; - if (alignBottom && result.bbox.min[2] < -0.05) { + if (alignBottom && Math.abs(result.bbox.min[2]) > 0.05) { // 파묻힌 것(z<0)도 떠 있는 것(z>0)도 바닥에 붙인다 const sh = translateStlZInPlace(outPath, -result.bbox.min[2]); if (sh.ok) stdout += '\n바닥을 z=0에 붙였습니다.'; } diff --git a/tests/stl-transform.test.ts b/tests/stl-transform.test.ts index 129cb5e..7729d34 100644 --- a/tests/stl-transform.test.ts +++ b/tests/stl-transform.test.ts @@ -22,7 +22,7 @@ describe('stl_cad transform — 외부 STL 변형', () => { test('배율 ×2 — 크기 2배, 중심 유지', { timeout: 120_000 }, async () => { const before = readStlBBox(stl); - const r = await stlCadTool.execute({ action: 'transform', stl_path: 'part.stl', scale: 2, output_path: 'part_x2.stl', _workspacePath: ws }); + const r = await stlCadTool.execute({ action: 'transform', stl_path: 'part.stl', scale: 2, output_path: 'part_x2.stl', align_bottom: false, _workspacePath: ws }); // 기본은 바닥 정렬(09-29) — 중심 유지 검증이라 끔 assert.ok(r.success, `실패: ${'error' in r ? r.error : ''}`); const after = readStlBBox(path.join(ws, 'part_x2.stl')); const sc = [after.size?.[0] ?? 0]; diff --git a/tests/stl-unit-batch.test.ts b/tests/stl-unit-batch.test.ts index ef9e741..fd46ee8 100644 --- a/tests/stl-unit-batch.test.ts +++ b/tests/stl-unit-batch.test.ts @@ -138,3 +138,51 @@ describe('stl_cad merge — 삼각형 병합 + 베드 배치', () => { assert.equal(noOut.success, false); }); }); + +describe('모든 STL 바닥(z=0) 기본 규칙 — dropStlToFloor + transform 기본 align_bottom', () => { + const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'stl-floor-')); + 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('buried', 'translate([0,0,-20]) cube([10,10,10]);'); // z:[-20,-10] + mk('floating', 'translate([0,0,15]) cube([10,10,10]);'); // z:[15,25] + mk('floor', 'cube([10,10,10]);'); + }); + + test('파묻힌 STL(z<0)을 z=0으로', async () => { + const { dropStlToFloor } = await import('../src/tools/stl-cad-core'); + const r: any = dropStlToFloor(path.join(ws, 'buried.stl')); + assert.ok(r.ok && Math.abs(r.shifted - 20) < 0.01); + assert.ok(Math.abs(readStlBBox(path.join(ws, 'buried.stl')).min[2]) < 0.001); + }); + test('떠 있는 STL(z>0)도 z=0으로, XY는 불변', async () => { + const { dropStlToFloor } = await import('../src/tools/stl-cad-core'); + const before = readStlBBox(path.join(ws, 'floating.stl')); + const r: any = dropStlToFloor(path.join(ws, 'floating.stl')); + assert.ok(r.ok && Math.abs(r.shifted + 15) < 0.01); + const after = readStlBBox(path.join(ws, 'floating.stl')); + assert.ok(Math.abs(after.min[2]) < 0.001 && Math.abs(after.min[0] - before.min[0]) < 1e-3 && Math.abs(after.max[1] - before.max[1]) < 1e-3); + }); + test('이미 바닥이면 shifted 0, ASCII는 ok:false', async () => { + const { dropStlToFloor } = await import('../src/tools/stl-cad-core'); + const r: any = dropStlToFloor(path.join(ws, 'floor.stl')); + assert.ok(r.ok && r.shifted === 0); + fs.writeFileSync(path.join(ws, 'ascii.stl'), 'solid x\nfacet normal 0 0 1\nouter loop\nvertex 0 0 5\nvertex 1 0 5\nvertex 0 1 5\nendloop\nendfacet\nendsolid x\n'); + const a: any = dropStlToFloor(path.join(ws, 'ascii.stl')); + assert.equal(a.ok, false); + }); + test('transform은 기본으로 바닥에 붙인다(align_bottom 생략), false면 안 붙인다', { timeout: 120_000 }, async () => { + mk('t1', 'translate([0,0,30]) cube([10,10,10]);'); + const r: any = await stlCadTool.execute({ action: 'transform', stl_path: 't1.stl', rz: 90, _workspacePath: ws }); + assert.ok(r.success, r.error); + assert.ok(Math.abs(readStlBBox(path.join(ws, 't1.stl')).min[2]) < 0.05, '기본으로 바닥에 안 붙음'); + mk('t2', 'translate([0,0,30]) cube([10,10,10]);'); + const r2: any = await stlCadTool.execute({ action: 'transform', stl_path: 't2.stl', rz: 90, align_bottom: false, _workspacePath: ws }); + assert.ok(r2.success); + assert.ok(readStlBBox(path.join(ws, 't2.stl')).min[2] > 25, 'align_bottom=false인데 붙음'); + }); +});