feat(pcb): 미배선은 점퍼선으로 해결 — 구리 도형 연결성을 직접 분석해 끊어진 구리 섬을 윗면 점퍼선(기존 관통 구멍 사이)으로 연결, 화면 표시·jumpers.txt 출력
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8c4d60f5a2
commit
ee8fe7f2cb
5 files changed
+114
-10
No files matched your search
@@ -3,6 +3,7 @@ import { FOOTPRINTS } from '../../tools/pcb/footprints';
|
||||
import { buildDsn, parseSes, validateProject } from '../../tools/pcb/dsn';
|
||||
import { freeroutingStatus, runFreerouting } from '../../tools/pcb/freerouting';
|
||||
import { buildGcode } from '../../tools/pcb/gcode';
|
||||
import { findJumpers, jumperList } from '../../tools/pcb/jumpers';
|
||||
import { DEFAULT_RULES, type PcbProject, type Routed } from '../../tools/pcb/types';
|
||||
|
||||
function normalize(raw: any): PcbProject {
|
||||
@@ -36,7 +37,11 @@ export function registerPcbRoutes(app: express.Application, requireGatewayAuth:
|
||||
timeoutSec: Number(req.body?.timeoutSec) || 120,
|
||||
});
|
||||
const routed = parseSes(run.ses, project);
|
||||
res.json({ ...routed, stats: { unrouted: run.unrouted, violations: run.violations, seconds: run.seconds }, log: run.log });
|
||||
// 단면 보드: 구리로 못 이은 곳은 윗면 점퍼선으로 잇는다(양면은 비아로 풀리므로 대상 아님).
|
||||
const useJumpers = project.rules.layers === 1 && req.body?.jumpers !== false;
|
||||
const jr = useJumpers ? findJumpers(project, routed) : { jumpers: [], unresolved: [] };
|
||||
routed.jumpers = jr.jumpers;
|
||||
res.json({ ...routed, stats: { unrouted: run.unrouted, violations: run.violations, seconds: run.seconds, jumpers: jr.jumpers.length }, log: run.log });
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ error: String(err?.message || err) });
|
||||
}
|
||||
@@ -54,7 +59,11 @@ export function registerPcbRoutes(app: express.Application, requireGatewayAuth:
|
||||
vias: Array.isArray(rr.vias) ? rr.vias : [],
|
||||
};
|
||||
if (!routed.traces.length) { res.status(400).json({ error: '배선 결과가 없습니다. 먼저 자동 배선을 실행하세요.' }); return; }
|
||||
res.json(buildGcode(project, routed));
|
||||
const jumpers = Array.isArray(rr.jumpers) ? rr.jumpers : [];
|
||||
routed.jumpers = jumpers;
|
||||
const g = buildGcode(project, routed);
|
||||
if (jumpers.length) g.files['jumpers.txt'] = jumperList(project, jumpers);
|
||||
res.json(g);
|
||||
} catch (err: any) {
|
||||
res.status(500).json({ error: String(err?.message || err) });
|
||||
}
|
||||
|
||||
@@ -55,6 +55,11 @@ const toMm = (p: IP): Pt => [p.X / S, p.Y / S];
|
||||
|
||||
/** 한 층의 동박(패드+비아+트레이스) 합집합. */
|
||||
function copperUnion(p: PcbProject, routed: Routed, layer: string): IP[][] {
|
||||
return union(copperPolys(p, routed, layer));
|
||||
}
|
||||
|
||||
/** 합치기 전의 동박 도형들(패드·비아·트레이스 각각). 연결성 분석에도 쓴다. */
|
||||
export function copperPolys(p: PcbProject, routed: Routed, layer: string): IP[][] {
|
||||
const polys: IP[][] = [];
|
||||
for (const pad of placedPads(p.parts)) {
|
||||
if (pad.smd && layer !== 'F.Cu') continue;
|
||||
@@ -67,7 +72,7 @@ function copperUnion(p: PcbProject, routed: Routed, layer: string): IP[][] {
|
||||
if (t.layer !== layer || t.pts.length < 2) continue;
|
||||
polys.push(...offsetOpen(t.pts.map(([x, y]) => ip(x, y)), t.w / 2));
|
||||
}
|
||||
return union(polys);
|
||||
return polys;
|
||||
}
|
||||
|
||||
/** 가장 가까운 경로 순서로 재배열(이동 거리 단축). */
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// 미배선 보완: 자동 배선 뒤에도 구리로 이어지지 않은 곳(구리 섬이 나뉜 넷)을 윗면 점퍼선으로 잇는다.
|
||||
// 점퍼선은 부품면(윗면)에서 기존 관통 구멍 두 곳을 잇는 전선이라, 아랫면 배선을 가로질러도 단락되지 않는다.
|
||||
// 연결성은 Freerouting 의 말을 믿지 않고 실제 구리 도형(트레이스+패드)의 합집합으로 직접 판정한다.
|
||||
import { placedPads } from './footprints';
|
||||
import type { PcbProject, Routed } from './types';
|
||||
import { copperPolys } from './gcode';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const ClipperLib: any = require('clipper-lib');
|
||||
const S = 1000;
|
||||
|
||||
export interface Jumper { net: string; a: string; b: string; len: number; smd: boolean }
|
||||
|
||||
interface Island { outer: { X: number; Y: number }[]; holes: { X: number; Y: number }[][] }
|
||||
|
||||
function islandsOf(polys: { X: number; Y: number }[][]): Island[] {
|
||||
const c = new ClipperLib.Clipper();
|
||||
c.AddPaths(polys, ClipperLib.PolyType.ptSubject, true);
|
||||
const tree = new ClipperLib.PolyTree();
|
||||
c.Execute(ClipperLib.ClipType.ctUnion, tree, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);
|
||||
const out: Island[] = [];
|
||||
const walk = (node: any) => {
|
||||
for (const ch of node.Childs()) {
|
||||
if (!ch.IsHole()) out.push({ outer: ch.Contour(), holes: ch.Childs().filter((h: any) => h.IsHole()).map((h: any) => h.Contour()) });
|
||||
walk(ch);
|
||||
}
|
||||
};
|
||||
walk(tree);
|
||||
return out;
|
||||
}
|
||||
const inside = (pt: { X: number; Y: number }, path: { X: number; Y: number }[]) => ClipperLib.Clipper.PointInPolygon(pt, path) !== 0;
|
||||
|
||||
export interface JumperResult { jumpers: Jumper[]; unresolved: string[] }
|
||||
|
||||
export function findJumpers(p: PcbProject, routed: Routed): JumperResult {
|
||||
const layer = p.rules.copper;
|
||||
const pads = placedPads(p.parts);
|
||||
const byId = new Map(pads.map(x => [x.id, x]));
|
||||
const islands = islandsOf(copperPolys(p, routed, layer));
|
||||
const padIsland = (id: string): number => {
|
||||
const pad = byId.get(id)!;
|
||||
const pt = { X: Math.round(pad.x * S), Y: Math.round(pad.y * S) };
|
||||
return islands.findIndex(is => inside(pt, is.outer) && !is.holes.some(h => ClipperLib.Clipper.PointInPolygon(pt, h) === 1));
|
||||
};
|
||||
const jumpers: Jumper[] = [];
|
||||
const unresolved: string[] = [];
|
||||
for (const net of p.nets) {
|
||||
const ids = net.pins.filter(id => byId.has(id) && (!byId.get(id)!.smd || layer === 'F.Cu'));
|
||||
if (ids.length < 2) continue;
|
||||
const isl = new Map<number, string[]>();
|
||||
ids.forEach((id, k) => { const i = padIsland(id); const key = i >= 0 ? i : -1 - k; (isl.get(key) || isl.set(key, []).get(key)!).push(id); });
|
||||
const groups = [...isl.values()];
|
||||
if (groups.length < 2) continue;
|
||||
// 섬들 사이 최소 신장 트리(Prim): 두 섬 사이 거리 = 서로 가장 가까운 핀 쌍(관통 구멍 우선)
|
||||
const best = (A: string[], B: string[]) => {
|
||||
let r: { a: string; b: string; d: number; smd: boolean } | null = null;
|
||||
for (const a of A) for (const b of B) {
|
||||
const pa = byId.get(a)!, pb = byId.get(b)!, smd = pa.smd || pb.smd;
|
||||
const d = Math.hypot(pa.x - pb.x, pa.y - pb.y) + (smd ? 1000 : 0); // SMD 끝점은 마지막 수단
|
||||
if (!r || d < r.d) r = { a, b, d, smd };
|
||||
}
|
||||
return r!;
|
||||
};
|
||||
const used = [0], rest = groups.map((_, i) => i).slice(1);
|
||||
while (rest.length) {
|
||||
let pick: { a: string; b: string; d: number; smd: boolean } | null = null, pj = -1;
|
||||
for (const i of used) for (const j of rest) { const c = best(groups[i], groups[j]); if (!pick || c.d < pick.d) { pick = c; pj = j; } }
|
||||
jumpers.push({ net: net.name, a: pick!.a, b: pick!.b, len: Math.round(Math.hypot(byId.get(pick!.a)!.x - byId.get(pick!.b)!.x, byId.get(pick!.a)!.y - byId.get(pick!.b)!.y) * 10) / 10, smd: pick!.smd });
|
||||
used.push(pj); rest.splice(rest.indexOf(pj), 1);
|
||||
}
|
||||
}
|
||||
return { jumpers, unresolved };
|
||||
}
|
||||
|
||||
export function jumperList(p: PcbProject, jumpers: Jumper[]): string {
|
||||
if (!jumpers.length) return '점퍼선 없음\n';
|
||||
return ['점퍼선 목록 (부품면=윗면에서 연결, 단위 mm)', ...jumpers.map((j, i) => `J${i + 1}: ${j.a} ↔ ${j.b} (넷 ${j.net}, 길이 약 ${j.len}${j.smd ? ', SMD 패드 포함 — 납땜 주의' : ''})`)].join('\n') + '\n';
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export interface PcbProject {
|
||||
}
|
||||
export interface Trace { net: string; layer: string; w: number; pts: [number, number][] } // mm, 에디터 좌표
|
||||
export interface Via { net: string; x: number; y: number }
|
||||
export interface Routed { traces: Trace[]; vias: Via[] }
|
||||
export interface Routed { traces: Trace[]; vias: Via[]; jumpers?: { net: string; a: string; b: string; len: number; smd: boolean }[] }
|
||||
|
||||
export const DEFAULT_RULES: PcbRules = { trace: 0.4, clearance: 0.3, layers: 1, copper: 'B.Cu', viaDia: 0.9, viaDrill: 0.5 };
|
||||
export const DEFAULT_MILL: MillSettings = {
|
||||
|
||||
@@ -105,6 +105,7 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
|
||||
<details open><summary>자동 배선 (Freerouting)</summary>
|
||||
<div class="grid2"><div><label>최대 패스</label><input type="number" id="passes" value="30" min="1" max="100"></div><div><label>제한 시간(초)</label><input type="number" id="tmo" value="120" min="10" max="600"></div></div>
|
||||
<label style="display:block;margin-top:8px;font-size:12px"><input type="checkbox" id="jmp" checked style="width:auto"> 못 이은 곳은 점퍼선으로 연결 (단면)</label>
|
||||
<button class="btn pri" id="rbtn" style="width:100%;margin-top:8px" onclick="doRoute()">🧭 자동 배선</button>
|
||||
<div id="rres" class="note"></div>
|
||||
</details>
|
||||
@@ -225,6 +226,15 @@ function draw(){
|
||||
ctx.globalAlpha=1;
|
||||
for(const v of routed.vias){ctx.fillStyle='#cfd8dc';ctx.beginPath();ctx.arc(sx(v.x),sy(v.y),P.rules.viaDia/2*view.s,0,7);ctx.fill();ctx.fillStyle='#000';ctx.beginPath();ctx.arc(sx(v.x),sy(v.y),P.rules.viaDrill/2*view.s,0,7);ctx.fill();}
|
||||
}
|
||||
// 점퍼선(윗면 전선)
|
||||
if(routed&&routed.jumpers&&routed.jumpers.length){
|
||||
const pm0=Object.fromEntries(allPads().map(p=>[p.id,p]));
|
||||
ctx.save();ctx.strokeStyle='#ffa726';ctx.fillStyle='#ffa726';ctx.lineWidth=Math.max(2,0.7*view.s);ctx.lineCap='round';ctx.setLineDash([view.s*1.2,view.s*0.7]);
|
||||
routed.jumpers.forEach((j,i)=>{const a=pm0[j.a],b=pm0[j.b];if(!a||!b)return;ctx.beginPath();ctx.moveTo(sx(a.x),sy(a.y));ctx.lineTo(sx(b.x),sy(b.y));ctx.stroke();});
|
||||
ctx.setLineDash([]);ctx.font='bold 11px sans-serif';
|
||||
routed.jumpers.forEach((j,i)=>{const a=pm0[j.a],b=pm0[j.b];if(!a||!b)return;ctx.fillText('J'+(i+1),sx((a.x+b.x)/2)+4,sy((a.y+b.y)/2)-4);});
|
||||
ctx.restore();
|
||||
}
|
||||
// 부품
|
||||
for(const part of P.parts){
|
||||
const b=bboxOf(part); if(!b) continue;
|
||||
@@ -352,11 +362,13 @@ function applyMill(){
|
||||
async function doRoute(){
|
||||
const b=$('rbtn');b.disabled=true;$('rres').innerHTML='Freerouting 실행 중… (보드에 따라 수 초~수 분)';
|
||||
try{
|
||||
const d=await api('/api/pcb/route',{project:P,maxPasses:+$('passes').value||30,timeoutSec:+$('tmo').value||120});
|
||||
routed={traces:d.traces,vias:d.vias};gres=null;$('res').innerHTML='';$('dl').innerHTML='';
|
||||
const un=d.stats.unrouted;
|
||||
$('rres').innerHTML=un===0?`<span class="ok">✔ 배선 완료</span> · ${d.traces.length}구간 · 비아 ${d.vias.length}개 · ${d.stats.seconds}초`
|
||||
:`<span class="bad">✖ 미배선 ${un<0?'?':un}건</span> (${d.traces.length}구간 배선됨, ${d.stats.seconds}초)<br>단면 보드는 배선이 교차하면 풀 수 없습니다. 부품을 옮기거나 회전해 교차를 줄이거나, 양면/점퍼를 쓰세요.`;
|
||||
const d=await api('/api/pcb/route',{project:P,maxPasses:+$('passes').value||30,timeoutSec:+$('tmo').value||120,jumpers:$('jmp').checked});
|
||||
routed={traces:d.traces,vias:d.vias,jumpers:d.jumpers||[]};gres=null;$('res').innerHTML='';$('dl').innerHTML='';
|
||||
const un=d.stats.unrouted, jn=routed.jumpers.length;
|
||||
const jl=jn?`<div class="note" style="margin-top:4px">점퍼선(윗면, 부품 구멍 사이 전선):<br>`+routed.jumpers.map((j,i)=>`J${i+1}: ${esc(j.a)} ↔ ${esc(j.b)} · ${j.len}mm${j.smd?' ⚠SMD':''}`).join('<br>')+'</div>':'';
|
||||
$('rres').innerHTML=(un===0?`<span class="ok">✔ 구리 배선 완료</span> · ${d.traces.length}구간 · 비아 ${d.vias.length}개 · ${d.stats.seconds}초`
|
||||
:jn?`<span class="ok">✔ 구리 + 점퍼선 ${jn}개로 모두 연결</span> · ${d.traces.length}구간 · ${d.stats.seconds}초`
|
||||
:`<span class="bad">✖ 미배선 ${un<0?'?':un}건</span> (${d.traces.length}구간 배선됨, ${d.stats.seconds}초)<br>부품을 옮기거나 회전해 교차를 줄이거나, '점퍼선' 옵션을 켜 보세요.`)+jl;
|
||||
save();draw();
|
||||
}catch(e){$('rres').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
|
||||
finally{b.disabled=false;}
|
||||
@@ -368,7 +380,7 @@ async function doGcode(){
|
||||
gres=await api('/api/pcb/gcode',{project:P,routed});
|
||||
const s=gres.stats;
|
||||
$('res').innerHTML=`구멍 ${s.holes}개(드릴 ${s.drillSizes.join(', ')||'-'}mm) · 격리 경로 ${s.isolationLengthMm}mm · 예상 약 ${s.estMinutes}분`+gres.warnings.map(w=>`<div class="warn">⚠ ${esc(w)}</div>`).join('');
|
||||
$('dl').innerHTML=Object.keys(gres.files).map(n=>`<a href="#" onclick="dlFile('${esc(n)}');return false">⬇ ${esc(n)}</a>`).join('')+'<div class="note">순서: 격리(copper) → 드릴(공구 교체 시 M0 일시정지) → 외곽. 가공 전 Z 영점·고정을 확인하세요.</div>';
|
||||
$('dl').innerHTML=Object.keys(gres.files).map(n=>`<a href="#" onclick="dlFile('${esc(n)}');return false">⬇ ${esc(n)}</a>`).join('')+'<div class="note">순서: 격리(copper) → 드릴(공구 교체 시 M0 일시정지) → 외곽. jumpers.txt 는 조립 시 윗면에 납땜할 점퍼선 목록입니다. 가공 전 Z 영점·고정을 확인하세요.</div>';
|
||||
draw();
|
||||
}catch(e){$('res').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
|
||||
finally{b.disabled=false;}
|
||||
|
||||
Reference in new issue
Block a user