feat(stl): 3면도에 원형 구멍·원통 지름(Ø) 표기 — 단면에서 닫힌 원형 윤곽을 찾아 잰다(stl-circles). 동심 원은 겹치지 않게 쌓고, 원뿔은 Ø최소~최대 테이퍼로 요약, 한쪽이 열린 C자 홈은 표기하지 않음
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
31313319b1
commit
f5e23118bf
4 files changed
+347
-6
No files matched your search
@@ -426,7 +426,7 @@ export function findStlFiles(workspacePath: string, maxDepth = 6): string[] {
|
||||
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 {
|
||||
export function readStlTriangles(filePath: string): Float32Array {
|
||||
const buf = fs.readFileSync(filePath);
|
||||
if (buf.length < 84) throw new Error('STL 파일이 너무 작거나 손상되었습니다.');
|
||||
const n = buf.readUInt32LE(80);
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* stl-circles.ts — STL 단면에서 원형 구멍·원통의 지름을 찾는다.
|
||||
*
|
||||
* 용도: 3면도(stl-three-view.ts)에 지름(Ø) 표기를 넣는다(2026-09-30, "지름 있으면 좋을텐데").
|
||||
*
|
||||
* 방법. 축(x/y/z)에 수직인 평면으로 모델을 여러 높이에서 잘라 단면 윤곽선(닫힌 고리)을 만들고,
|
||||
* 각 고리에 원을 맞춘다. 고리 전체가 원에 잘 맞으면(잔차 작음) 원형 구멍/원통으로 본다.
|
||||
* - 한쪽이 열린 C자 홈처럼 "닫힌 고리가 아닌" 것은 검출하지 않는다 — 다른 형상과 이어진 호는
|
||||
* 지름을 단정할 수 없어서다.
|
||||
* - 여러 높이에서 같은 원이 반복되면 하나로 묶고, 그 원이 존재하는 높이 범위(lo~hi)를 기록한다.
|
||||
* - 다각형으로 근사된 원(STL은 삼각형)은 꼭짓점이 원 위에 있으므로 맞춘 지름이 설계 지름에 가깝다.
|
||||
*/
|
||||
|
||||
export type Axis = 'x' | 'y' | 'z';
|
||||
|
||||
export interface Circle {
|
||||
/** 단면 평면 안의 중심 좌표. z축이면 (x,y), y축이면 (x,z), x축이면 (y,z). */
|
||||
u: number;
|
||||
v: number;
|
||||
dia: number;
|
||||
/** 이 원이 보이는 축 방향 범위(mm) — 관통 구멍인지 얕은 홈인지 판단용. */
|
||||
lo: number;
|
||||
hi: number;
|
||||
/** 몇 개 높이에서 검출됐는가. */
|
||||
levels: number;
|
||||
/** 테이퍼(원뿔·깔때기)면 지름이 dia(최소)~diaMax(최대)로 변한다. */
|
||||
diaMax?: number;
|
||||
taper?: boolean;
|
||||
}
|
||||
|
||||
const AXES: Record<Axis, [number, number, number]> = { z: [0, 1, 2], y: [0, 2, 1], x: [1, 2, 0] }; // [u, v, 축]
|
||||
|
||||
export function detectCircles(tri: Float32Array, axis: Axis, opts: { levels?: number; minDia?: number } = {}): Circle[] {
|
||||
const [iu, iv, ia] = AXES[axis];
|
||||
const n = tri.length / 9;
|
||||
if (n === 0) return [];
|
||||
let amin = Infinity, amax = -Infinity;
|
||||
for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) { const a = tri[i * 9 + k * 3 + ia]; if (a < amin) amin = a; if (a > amax) amax = a; }
|
||||
const span = amax - amin;
|
||||
if (!(span > 0)) return [];
|
||||
// 2.5mm 두께 판의 구멍도 2개 이상 높이에서 잡히도록 촘촘히(0.85mm 간격 수준) 자른다.
|
||||
const levelCount = opts.levels ?? 64;
|
||||
const minDia = opts.minDia ?? 3;
|
||||
|
||||
const found: Circle[] = [];
|
||||
for (let li = 0; li < levelCount; li++) {
|
||||
// 면이 딱 그 높이에 있는 수평면(바닥·윗면)을 피하려고 약간 어긋난 높이로 자른다.
|
||||
const a = amin + span * ((li + 0.5) / levelCount) + span * 1e-4;
|
||||
const loops = sliceLoops(tri, n, iu, iv, ia, a);
|
||||
for (const pts of loops) {
|
||||
const c = fitClosedCircle(pts);
|
||||
if (c && c.dia >= minDia) found.push({ u: c.u, v: c.v, dia: c.dia, lo: a, hi: a, levels: 1 });
|
||||
}
|
||||
}
|
||||
return mergeCircles(found);
|
||||
}
|
||||
|
||||
/** 평면 a=const 와 삼각형의 교선을 이어 닫힌 고리들의 점열로 만든다. */
|
||||
function sliceLoops(tri: Float32Array, n: number, iu: number, iv: number, ia: number, a: number): Array<Array<[number, number]>> {
|
||||
const segs: Array<[number, number, number, number]> = [];
|
||||
for (let t = 0; t < n; t++) {
|
||||
const b = t * 9;
|
||||
const A = [tri[b + ia], tri[b + 3 + ia], tri[b + 6 + ia]];
|
||||
if (Math.min(A[0], A[1], A[2]) > a || Math.max(A[0], A[1], A[2]) < a) continue;
|
||||
const pts: Array<[number, number]> = [];
|
||||
for (let e = 0; e < 3; e++) {
|
||||
const p = e, q = (e + 1) % 3;
|
||||
if ((A[p] - a) * (A[q] - a) < 0) {
|
||||
const s = (a - A[p]) / (A[q] - A[p]);
|
||||
pts.push([tri[b + p * 3 + iu] + s * (tri[b + q * 3 + iu] - tri[b + p * 3 + iu]), tri[b + p * 3 + iv] + s * (tri[b + q * 3 + iv] - tri[b + p * 3 + iv])]);
|
||||
}
|
||||
}
|
||||
if (pts.length === 2) segs.push([pts[0][0], pts[0][1], pts[1][0], pts[1][1]]);
|
||||
}
|
||||
// 끝점을 0.001mm로 양자화해 이웃 연결(공유 정점이라 정확히 일치한다).
|
||||
const key = (x: number, y: number) => `${Math.round(x * 1000)},${Math.round(y * 1000)}`;
|
||||
const adj = new Map<string, Array<{ to: string; x: number; y: number }>>();
|
||||
const add = (k: string, to: string, x: number, y: number) => { (adj.get(k) || adj.set(k, []).get(k)!).push({ to, x, y }); };
|
||||
for (const [x0, y0, x1, y1] of segs) {
|
||||
const k0 = key(x0, y0), k1 = key(x1, y1);
|
||||
if (k0 === k1) continue;
|
||||
add(k0, k1, x1, y1); add(k1, k0, x0, y0);
|
||||
}
|
||||
const visited = new Set<string>();
|
||||
const loops: Array<Array<[number, number]>> = [];
|
||||
for (const [start, nb] of adj) {
|
||||
if (visited.has(start)) continue;
|
||||
// 고리 판정: 모든 점의 차수가 2인 연결 성분만(분기·열린 끝이 있으면 닫힌 원형 윤곽이 아니다).
|
||||
const comp: string[] = [];
|
||||
const stack = [start];
|
||||
let closed = true;
|
||||
const seen = new Set<string>([start]);
|
||||
while (stack.length) {
|
||||
const k = stack.pop()!;
|
||||
comp.push(k);
|
||||
const nbs = adj.get(k)!;
|
||||
if (nbs.length !== 2) closed = false;
|
||||
for (const o of nbs) if (!seen.has(o.to)) { seen.add(o.to); stack.push(o.to); }
|
||||
}
|
||||
for (const k of comp) visited.add(k);
|
||||
void nb;
|
||||
if (!closed || comp.length < 12) continue;
|
||||
// 차수 2 성분이라 한 바퀴 순회로 순서 있는 점열을 얻는다.
|
||||
const pts: Array<[number, number]> = [];
|
||||
let prev = '', cur = start;
|
||||
for (let guard = 0; guard <= comp.length + 1; guard++) {
|
||||
const nbs = adj.get(cur)!;
|
||||
const me = nbs.find((o) => o.to !== prev) || nbs[0];
|
||||
const [cx, cy] = cur.split(',').map(Number);
|
||||
pts.push([cx / 1000, cy / 1000]);
|
||||
prev = cur; cur = me.to;
|
||||
if (cur === start) break;
|
||||
}
|
||||
loops.push(pts);
|
||||
}
|
||||
return loops;
|
||||
}
|
||||
|
||||
/** 고리 전체가 원에 맞는지 본다(대수적 최소제곱 + 잔차·각도 커버리지 검사). */
|
||||
function fitClosedCircle(pts: Array<[number, number]>): { u: number; v: number; dia: number } | null {
|
||||
const m = pts.length;
|
||||
let sx = 0, sy = 0;
|
||||
for (const [x, y] of pts) { sx += x; sy += y; }
|
||||
const mx = sx / m, my = sy / m;
|
||||
// Kasa 피팅: x²+y² + D x + E y + F = 0
|
||||
let suu = 0, suv = 0, svv = 0, suuu = 0, svvv = 0, suvv = 0, svuu = 0;
|
||||
for (const [x, y] of pts) {
|
||||
const u = x - mx, v = y - my;
|
||||
suu += u * u; suv += u * v; svv += v * v;
|
||||
suuu += u * u * u; svvv += v * v * v; suvv += u * v * v; svuu += v * u * u;
|
||||
}
|
||||
const det = suu * svv - suv * suv;
|
||||
if (Math.abs(det) < 1e-9) return null;
|
||||
const uc = (0.5 * (suuu + suvv) * svv - 0.5 * (svvv + svuu) * suv) / det;
|
||||
const vc = (0.5 * (svvv + svuu) * suu - 0.5 * (suuu + suvv) * suv) / det;
|
||||
const cx = uc + mx, cy = vc + my;
|
||||
let rs = 0;
|
||||
for (const [x, y] of pts) rs += Math.hypot(x - cx, y - cy);
|
||||
const r = rs / m;
|
||||
if (!(r > 0.5) || r > 500) return null;
|
||||
let maxRes = 0;
|
||||
for (const [x, y] of pts) maxRes = Math.max(maxRes, Math.abs(Math.hypot(x - cx, y - cy) - r));
|
||||
if (maxRes > Math.max(0.03 * r, 0.06)) return null;
|
||||
// 각도 커버리지 — 점이 원 둘레 전체에 퍼져 있어야 한다(한쪽 호만 있는 조각 배제).
|
||||
const angs = pts.map(([x, y]) => Math.atan2(y - cy, x - cx)).sort((a, b) => a - b);
|
||||
let gap = angs[0] + 2 * Math.PI - angs[angs.length - 1];
|
||||
for (let i = 1; i < angs.length; i++) gap = Math.max(gap, angs[i] - angs[i - 1]);
|
||||
if (gap > Math.PI / 6) return null;
|
||||
return { u: cx, v: cy, dia: 2 * r };
|
||||
}
|
||||
|
||||
/** 같은 중심·지름의 원을 하나로 묶고, 지름이 연속으로 변하는 동심 원 무리는 테이퍼 하나로 요약한다. */
|
||||
function mergeCircles(list: Circle[]): Circle[] {
|
||||
const groups: Circle[] = [];
|
||||
for (const c of list) {
|
||||
const hit = groups.find((o) => Math.hypot(o.u - c.u, o.v - c.v) < 0.4 && Math.abs(o.dia - c.dia) < Math.max(0.5, c.dia * 0.02));
|
||||
if (hit) {
|
||||
hit.lo = Math.min(hit.lo, c.lo); hit.hi = Math.max(hit.hi, c.hi);
|
||||
hit.dia = (hit.dia * hit.levels + c.dia) / (hit.levels + 1);
|
||||
hit.u = (hit.u * hit.levels + c.u) / (hit.levels + 1);
|
||||
hit.v = (hit.v * hit.levels + c.v) / (hit.levels + 1);
|
||||
hit.levels++;
|
||||
} else groups.push({ ...c });
|
||||
}
|
||||
const kept = groups.filter((c) => c.levels >= 2);
|
||||
return summarizeTapers(kept).sort((a, b) => (b.hi - b.lo) - (a.hi - a.lo) || b.dia - a.dia);
|
||||
}
|
||||
|
||||
/** 같은 중심의 원이 지름 4mm 이내 간격으로 3개 이상 이어지면 원뿔/깔때기 — 하나의 테이퍼로 묶는다. */
|
||||
function summarizeTapers(cs: Circle[]): Circle[] {
|
||||
const used = new Set<Circle>();
|
||||
const out: Circle[] = [];
|
||||
for (const base of cs) {
|
||||
if (used.has(base)) continue;
|
||||
const family = cs.filter((o) => Math.hypot(o.u - base.u, o.v - base.v) < 0.6).sort((a, b) => a.dia - b.dia);
|
||||
// 지름 순으로 정렬한 뒤, 이웃과의 지름 차가 4mm 이하이고 높이 범위가 이어지는 연속 구간을 찾는다.
|
||||
let run: Circle[] = [];
|
||||
const flush = () => {
|
||||
if (run.length >= 3) {
|
||||
out.push({ u: base.u, v: base.v, dia: run[0].dia, diaMax: run[run.length - 1].dia, taper: true,
|
||||
lo: Math.min(...run.map((r) => r.lo)), hi: Math.max(...run.map((r) => r.hi)), levels: run.reduce((a, r) => a + r.levels, 0) });
|
||||
for (const r of run) used.add(r);
|
||||
}
|
||||
run = [];
|
||||
};
|
||||
for (const f of family) {
|
||||
if (used.has(f)) continue;
|
||||
const last = run[run.length - 1];
|
||||
// 테이퍼는 높이가 올라가며 지름이 바뀌므로 이웃 원의 높이 범위가 거의 겹치지 않는다. 안쪽 벽과 바깥 벽처럼
|
||||
// 같은 높이에 동시에 있는 동심 원(예: 계단 원통의 Ø29.3·Ø32.1·Ø37.8)은 겹침이 크다 — 테이퍼로 묶지 않는다.
|
||||
const adjacent = !!last && f.dia - last.dia <= 4 && f.lo <= last.hi + 3 && f.hi >= last.lo - 3
|
||||
&& Math.max(0, Math.min(f.hi, last.hi) - Math.max(f.lo, last.lo)) <= 0.5 * Math.min(f.hi - f.lo, last.hi - last.lo) + 1;
|
||||
if (!last || adjacent) run.push(f);
|
||||
else { flush(); run = [f]; }
|
||||
}
|
||||
flush();
|
||||
}
|
||||
for (const c of cs) if (!used.has(c)) out.push(c);
|
||||
return out;
|
||||
}
|
||||
@@ -2,9 +2,10 @@
|
||||
* STL 3면도(제3각법: 평면도 위, 정면도 아래, 우측면도 오른쪽) + 바운딩 치수선 자동 생성
|
||||
* (2026-09-25, "C안" — FreeCAD 전환 대신 OpenSCAD 체계 안에서 제작용 도면 최소치를 뽑는다).
|
||||
*
|
||||
* 범위(사용자 합의): 외곽 치수(가로/깊이/높이)만. 구멍 지름·공차는 제외 — 그건 FreeCAD
|
||||
* (TechDraw) 영역. 체계는 workshop-assembly-render.ts와 동일: OpenSCAD ortho 렌더 후
|
||||
* python3+PIL+numpy 로 합성한다.
|
||||
* 범위: 외곽 치수(가로/깊이/높이) + 원형 구멍·원통의 지름(Ø). 지름은 2026-09-30에 추가했다("지름 있으면
|
||||
* 좋을텐데") — stl-circles.ts가 단면에서 닫힌 원형 윤곽을 찾아 잰다. 공차·나사·C자 홈처럼 닫힌 원이
|
||||
* 아닌 형상은 표기하지 않는다(그건 FreeCAD TechDraw 영역). 체계는 workshop-assembly-render.ts와 동일:
|
||||
* OpenSCAD ortho 렌더 후 python3+PIL+numpy 로 합성한다.
|
||||
*
|
||||
* 동치축 보증: 세 뷰를 같은 ortho 카메라로 렌더하고, 실루엣을 크롭한 뒤 공통 축척
|
||||
* S(px/mm)로 통일해 리샘플한다 — OpenSCAD 카메라 산식을 코드에 복제하지 않아도 치수선이
|
||||
@@ -13,8 +14,9 @@
|
||||
*/
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { detectCircles, Circle } from './stl-circles.js';
|
||||
import { spawn } from 'child_process';
|
||||
import { readStlBBox, renderStlPng } from './stl-cad-core.js';
|
||||
import { readStlBBox, renderStlPng, readStlTriangles } from './stl-cad-core.js';
|
||||
|
||||
export interface ThreeViewDims {
|
||||
w: number; // X(mm)
|
||||
@@ -155,6 +157,59 @@ x_h = fx - O
|
||||
hext(fy, x_h - 6, fx); hext(fy + fh, x_h - 6, fx)
|
||||
vdim(x_h, fy, fy + fh, labels['h'])
|
||||
|
||||
# ── 지름(Ø) 표기(2026-09-30) ──────────────────────────────────────────────
|
||||
# job['circles'][뷰] = [{u,v,dia,diaMax?,taper?}] : 평면도는 (x,y), 정면도는 (x,z), 우측면도는 (y,z) 좌표.
|
||||
# 뷰 이미지는 실루엣 bbox로 크롭한 뒤 공통 축척 S로 리샘플했으므로 mm→px는 bbox로 바로 환산된다.
|
||||
# 우측면도는 오른쪽에서 본 것이라 가로축이 Y의 반대 방향(왼쪽이 +Y)이다.
|
||||
bbmin = job['bbox']['min']; bbmax = job['bbox']['max']
|
||||
def px_top(u, v): return (tx + (u - bbmin[0]) * S, ty + (bbmax[1] - v) * S)
|
||||
def px_front(u, v): return (fx + (u - bbmin[0]) * S, fy + (bbmax[2] - v) * S)
|
||||
def px_right(u, v): return (rx + (bbmax[1] - u) * S, ry + (bbmax[2] - v) * S)
|
||||
f_dia = font(17)
|
||||
BLUE = (0, 84, 166)
|
||||
|
||||
def dia_label(cx, cy, dia, text, taper):
|
||||
r = dia * S / 2
|
||||
if not taper and r >= 10:
|
||||
# 지름 치수선: 원의 가로 지름 위에 화살표 양끝
|
||||
draw.line([(cx - r, cy), (cx + r, cy)], fill=BLUE, width=2)
|
||||
for sgn, x in ((1, cx - r), (-1, cx + r)):
|
||||
draw.polygon([(x, cy), (x + sgn * 9, cy - 4), (x + sgn * 9, cy + 4)], fill=BLUE)
|
||||
bb = draw.textbbox((0, 0), text, font=f_dia)
|
||||
tw_, th_ = bb[2] - bb[0], bb[3] - bb[1]
|
||||
x0, y0 = cx - tw_ / 2 - 4, cy - th_ - 12 if (not taper and r >= 10) else cy - th_ / 2 - 3
|
||||
draw.rectangle([x0, y0 - 2, x0 + tw_ + 8, y0 + th_ + 4], fill=(255, 255, 255))
|
||||
draw.text((x0 + 4 - bb[0], y0 - bb[1]), text, fill=BLUE, font=f_dia)
|
||||
|
||||
def draw_circles(items, mapper, view_w_mm, view_h_mm, limit):
|
||||
shown = 0
|
||||
used = []
|
||||
for c in items:
|
||||
if shown >= limit: break
|
||||
dmax = c.get('diaMax') or c['dia']
|
||||
# 외곽 윤곽 자체(뷰 폭/높이와 거의 같은 원)는 외곽 치수가 이미 말해 준다.
|
||||
if dmax >= 0.97 * min(view_w_mm, view_h_mm) and not c.get('taper'): continue
|
||||
cx, cy = mapper(c['u'], c['v'])
|
||||
# 같은 자리에 겹치는 라벨(동심 원)은 세로로 어긋나게 쌓는다.
|
||||
k = sum(1 for (ux, uy) in used if abs(ux - cx) < 30 and abs(uy - cy) < 34 * (1 + len(used)))
|
||||
cy_l = cy + 26 * k * (1 if k % 2 else -1) * ((k + 1) // 2 if k else 0)
|
||||
used.append((cx, cy))
|
||||
if c.get('taper'):
|
||||
text = 'Ø%s~%s' % (fmt(c['dia']), fmt(c['diaMax']))
|
||||
else:
|
||||
text = 'Ø' + fmt(c['dia'])
|
||||
dia_label(cx, cy_l, c['dia'], text, bool(c.get('taper')))
|
||||
shown += 1
|
||||
|
||||
def fmt(n):
|
||||
r = round(n, 1)
|
||||
return str(int(r)) if r == int(r) else ('%.1f' % r)
|
||||
|
||||
circ = job.get('circles') or {}
|
||||
draw_circles(circ.get('top', []), px_top, W, D, 10)
|
||||
draw_circles(circ.get('front', []), px_front, W, H, 6)
|
||||
draw_circles(circ.get('right', []), px_right, D, H, 6)
|
||||
|
||||
def caption(cx, y, text):
|
||||
bb = draw.textbbox((0, 0), text, font=f_cap)
|
||||
draw.text((cx - (bb[2] - bb[0]) / 2, y), text, fill=CAP, font=f_cap)
|
||||
@@ -215,9 +270,11 @@ export function renderThreeView(stlPath: string, outPngPath: string): Promise<Th
|
||||
async function doRender(stlPath: string, outPngPath: string): Promise<ThreeViewResult | { ok: false; error: string }> {
|
||||
const t0 = Date.now();
|
||||
let dims: ThreeViewDims;
|
||||
let bboxAll: { min: number[]; max: number[] };
|
||||
try {
|
||||
const bb = readStlBBox(stlPath);
|
||||
dims = { w: bb.max[0] - bb.min[0], d: bb.max[1] - bb.min[1], h: bb.max[2] - bb.min[2] };
|
||||
bboxAll = { min: bb.min, max: bb.max };
|
||||
} catch (e: any) {
|
||||
return { ok: false, error: String(e?.message || e) };
|
||||
}
|
||||
@@ -235,14 +292,23 @@ async function doRender(stlPath: string, outPngPath: string): Promise<ThreeViewR
|
||||
views[v] = p;
|
||||
}
|
||||
|
||||
// 원형 구멍·원통 지름 — 실패해도 도면은 지름 없이 만든다(부가 정보).
|
||||
let circles: Record<string, Circle[]> = { top: [], front: [], right: [] };
|
||||
try {
|
||||
const tri = readStlTriangles(stlPath);
|
||||
circles = { top: detectCircles(tri, 'z'), front: detectCircles(tri, 'y'), right: detectCircles(tri, 'x') };
|
||||
} catch { /* 지름 표기 생략 */ }
|
||||
|
||||
const jobPath = path.join(tmpDir, 'job.json');
|
||||
fs.writeFileSync(jobPath, JSON.stringify({
|
||||
out: outPngPath,
|
||||
dims,
|
||||
bbox: bboxAll!,
|
||||
circles,
|
||||
views,
|
||||
labels: { w: fmtMm(dims.w), d: fmtMm(dims.d), h: fmtMm(dims.h) },
|
||||
title: `3면도 — ${path.basename(stlPath)}`,
|
||||
subtitle: `가로 ${fmtMm(dims.w)} × 깊이 ${fmtMm(dims.d)} × 높이 ${fmtMm(dims.h)} mm · 치수는 외곽 기준`,
|
||||
subtitle: `가로 ${fmtMm(dims.w)} × 깊이 ${fmtMm(dims.d)} × 높이 ${fmtMm(dims.h)} mm · 치수는 외곽 기준 · Ø는 원형 구멍/원통 지름`,
|
||||
}));
|
||||
const compose = await runCompose(jobPath);
|
||||
if (!compose.ok) return { ok: false, error: `도면 합성 실패: ${compose.detail}` };
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* detectCircles — STL 단면에서 원형 구멍·원통 지름 검출
|
||||
*
|
||||
* 합성 부품은 OpenSCAD로 만든다(없으면 건너뜀). 검출값이 설계 지름에 근접해야 하고,
|
||||
* 한쪽이 열린 C자 홈처럼 닫힌 원이 아닌 것은 검출하지 않아야 한다.
|
||||
*/
|
||||
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 { OPENSCAD_BIN, runOpenscad, readStlTriangles } from '../src/tools/stl-cad-core';
|
||||
import { detectCircles } from '../src/tools/stl-circles';
|
||||
|
||||
const HAS = fs.existsSync(OPENSCAD_BIN);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'circ-'));
|
||||
async function makeStl(name: string, scad: string): Promise<Float32Array> {
|
||||
const s = path.join(dir, `${name}.scad`), o = path.join(dir, `${name}.stl`);
|
||||
fs.writeFileSync(s, scad);
|
||||
const r = await runOpenscad(['-o', o, '--export-format=binstl', s], 60_000);
|
||||
assert.equal(r.ok, true, r.ok ? '' : (r as any).detail);
|
||||
return readStlTriangles(o);
|
||||
}
|
||||
|
||||
describe('detectCircles', { skip: !HAS }, () => {
|
||||
test('판의 관통 원형 구멍: 위치와 지름을 잰다(z축)', async () => {
|
||||
const tri = await makeStl('plate', 'difference(){ cube([60,40,6]); translate([15,25,-1]) cylinder(d=12,h=8,$fn=96); }');
|
||||
const cs = detectCircles(tri, 'z');
|
||||
assert.equal(cs.length, 1);
|
||||
assert.ok(Math.abs(cs[0].dia - 12) < 0.15, `지름 ${cs[0].dia}`);
|
||||
assert.ok(Math.abs(cs[0].u - 15) < 0.1 && Math.abs(cs[0].v - 25) < 0.1, `중심 (${cs[0].u}, ${cs[0].v})`);
|
||||
assert.ok(cs[0].hi - cs[0].lo > 4, '관통 구멍은 넓은 높이 범위에서 보인다');
|
||||
});
|
||||
|
||||
test('서로 다른 지름 두 개(동심 계단 구멍)를 각각 잰다', async () => {
|
||||
const tri = await makeStl('step', 'difference(){ cube([50,50,10]); translate([25,25,-1]) cylinder(d=8,h=12,$fn=96); translate([25,25,5]) cylinder(d=20,h=6,$fn=96); }');
|
||||
const cs = detectCircles(tri, 'z').map((c) => Math.round(c.dia)).sort((a, b) => a - b);
|
||||
assert.deepEqual(cs, [8, 20]);
|
||||
});
|
||||
|
||||
test('옆면 구멍(y축으로 뚫린 구멍)은 y축 단면에서 (x,z) 좌표로 나온다', async () => {
|
||||
const tri = await makeStl('side', 'difference(){ cube([40,30,20]); translate([10,-1,14]) rotate([-90,0,0]) cylinder(d=6,h=32,$fn=96); }');
|
||||
const cs = detectCircles(tri, 'y');
|
||||
assert.equal(cs.length, 1);
|
||||
assert.ok(Math.abs(cs[0].dia - 6) < 0.1);
|
||||
assert.ok(Math.abs(cs[0].u - 10) < 0.1 && Math.abs(cs[0].v - 14) < 0.1, `(x,z)=(${cs[0].u}, ${cs[0].v})`);
|
||||
});
|
||||
|
||||
test('원뿔(지름이 높이에 따라 변함)은 원 여러 개가 아니라 테이퍼 하나로 요약한다', async () => {
|
||||
const tri = await makeStl('cone', 'difference(){ cube([50,50,30]); translate([25,25,-1]) cylinder(d1=10,d2=34,h=32,$fn=96); }');
|
||||
const cs = detectCircles(tri, 'z');
|
||||
assert.equal(cs.length, 1);
|
||||
assert.equal(cs[0].taper, true);
|
||||
assert.ok(cs[0].dia >= 9 && cs[0].dia < 16 && cs[0].diaMax! > 28 && cs[0].diaMax! <= 34.5, `Ø${cs[0].dia}~${cs[0].diaMax}`);
|
||||
});
|
||||
|
||||
test('계단 원통(같은 높이에 안쪽·바깥 벽이 함께 있음)은 테이퍼로 묶지 않고 각각 잰다', async () => {
|
||||
const tri = await makeStl('tube', 'difference(){ union(){ cylinder(d=32,h=50,$fn=96); translate([0,0,25]) cylinder(d=38,h=25,$fn=96); } translate([0,0,-1]) cylinder(d=29,h=52,$fn=96); }');
|
||||
const cs = detectCircles(tri, 'z');
|
||||
const dias = cs.map((c) => Math.round(c.dia)).sort((a, b) => a - b);
|
||||
assert.ok(cs.every((c) => !c.taper), '테이퍼로 오인');
|
||||
assert.ok(dias.includes(29) && dias.includes(32) && dias.includes(38), `검출: ${dias.join(',')}`);
|
||||
});
|
||||
|
||||
test('한쪽이 열린 C자 홈은 원으로 검출하지 않는다', async () => {
|
||||
const tri = await makeStl('cshape', 'difference(){ cube([50,50,8]); translate([25,25,-1]) cylinder(d=20,h=10,$fn=96); translate([25,-1,-1]) cube([12,30,10]); }');
|
||||
assert.equal(detectCircles(tri, 'z').length, 0);
|
||||
});
|
||||
|
||||
test('구멍이 없는 단순 블록은 아무것도 검출하지 않는다', async () => {
|
||||
const tri = await makeStl('block', 'cube([30,20,10]);');
|
||||
assert.equal(detectCircles(tri, 'z').length, 0);
|
||||
assert.equal(detectCircles(new Float32Array(0), 'z').length, 0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user