use super::{copper_and_nets, cutout_rings, mm, oriented_outline, xy, BOARD_SOLID_PREFIX, SUBSTRATE_SOLID, VIAS_SOLID};
use brep_ecad_core::board::{self, Board, CopperRef, Shape};
use brep_ecad_core::Netlist;
use brep_kernel::{
boolean_operation, extrude_profile_brep, make_arc, make_cylinder_brep, make_line, revolve_profile_brep,
BooleanOperation, BooleanOptions, BrepSolid, NurbsCurve, Vec3,
};
pub(crate) const SUBSTRATE_RGB: [u8; 3] = [0x1c, 0x5e, 0x38];
pub(crate) const COPPER_RGB: [u8; 3] = [0xc0, 0x7b, 0x38];
#[derive(Default)]
pub(crate) struct BoardStepSolids {
pub bodies: Vec<(String, BrepSolid)>,
pub colors: Vec<(String, [u8; 3])>,
pub skipped: Vec<String>,
pub notices: Vec<String>,
}
#[derive(Clone, Copy)]
struct Hole {
at: [f64; 2],
to: [f64; 2],
diameter: f64,
depth: Option<(f64, f64)>,
}
impl Hole {
fn round(at: [f64; 2], diameter: f64) -> Self {
Self { at, to: at, diameter, depth: None }
}
fn is_round(&self) -> bool {
(self.to[0] - self.at[0]).hypot(self.to[1] - self.at[1]) <= 1e-9
}
}
fn point(p: [f64; 2], z: f64) -> Vec3 {
Vec3::new(p[0], p[1], z)
}
fn polygon_curves(loop_xy: &[[f64; 2]], z: f64) -> Result<Vec<NurbsCurve>, String> {
(0..loop_xy.len())
.map(|i| make_line(point(loop_xy[i], z), point(loop_xy[(i + 1) % loop_xy.len()], z)))
.collect()
}
fn half_arc(centre: [f64; 2], radius: f64, start: f64, z: f64) -> Result<NurbsCurve, String> {
make_arc(
point(centre, z),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
radius,
start,
start + std::f64::consts::PI,
)
}
fn shape_curves(shape: &Shape, z: f64) -> Result<Vec<NurbsCurve>, String> {
match shape.clone() {
Shape::Polygon { .. } if shape.swept_corners().is_some() => {
let corners = shape.swept_corners().unwrap_or_default();
let n = corners.len();
let mmxy = |(x, y): (f64, f64)| [x / 1000., -y / 1000.];
let mut curves = vec![];
for i in (0..n).rev() {
let (start, _) = corners[i].ends();
if let board::SweptCorner::Arc { centre, radius, from, sweep } = corners[i] {
curves.push(make_arc(
point(xy(centre), z),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
mm(radius),
-(from + sweep),
-from,
)?);
}
let (to, from_pt) = (mmxy(corners[(i + n - 1) % n].ends().1), mmxy(start));
if (to[0] - from_pt[0]).hypot(to[1] - from_pt[1]) > 1e-6 {
curves.push(make_line(point(from_pt, z), point(to, z))?);
}
}
Ok(curves)
}
Shape::Polygon { .. } => {
let mut ring: Vec<[f64; 2]> = shape.outline(8).into_iter().map(xy).collect();
ring.reverse();
if ring.len() < 3 {
return Err("degenerate polygon".into());
}
polygon_curves(&ring, z)
}
Shape::RoundRect { min, max, radius } => {
let r = mm(radius);
let (a, b) = (xy(min), xy(max));
let (x0, x1) = (a[0].min(b[0]) + r, a[0].max(b[0]) - r);
let (y0, y1) = (a[1].min(b[1]) + r, a[1].max(b[1]) - r);
if r <= 1e-6 || x1 < x0 - 1e-9 || y1 < y0 - 1e-9 {
return Err("degenerate rounded rectangle".into());
}
let half = std::f64::consts::FRAC_PI_2;
let at = |c: [f64; 2], t: f64| [c[0] + r * t.cos(), c[1] + r * t.sin()];
let mut curves = vec![];
for (k, c) in [[x1, y0], [x1, y1], [x0, y1], [x0, y0]].into_iter().enumerate() {
let start = half * (k as f64 - 1.);
curves.push(make_arc(
point(c, z),
Vec3::new(1., 0., 0.),
Vec3::new(0., 1., 0.),
r,
start,
start + half,
)?);
let next = [[x1, y1], [x0, y1], [x0, y0], [x1, y0]][k];
let (from, to) = (at(c, start + half), at(next, start + half));
if (from[0] - to[0]).hypot(from[1] - to[1]) > 1e-6 {
curves.push(make_line(point(from, z), point(to, z))?);
}
}
Ok(curves)
}
Shape::Rect { min, max } => {
let (a, b) = (xy(min), xy(max));
let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0]));
let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1]));
if x1 - x0 <= 1e-6 || y1 - y0 <= 1e-6 {
return Err("degenerate rectangle".into());
}
polygon_curves(&[[x0, y0], [x1, y0], [x1, y1], [x0, y1]], z)
}
Shape::Capsule { a, b, radius } => {
let (a, b, r) = (xy(a), xy(b), mm(radius));
if r <= 1e-6 {
return Err("zero-radius capsule".into());
}
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
if (dx * dx + dy * dy).sqrt() <= 1e-6 {
return Ok(vec![half_arc(a, r, 0., z)?, half_arc(a, r, std::f64::consts::PI, z)?]);
}
let base = dy.atan2(dx) - std::f64::consts::FRAC_PI_2;
let at = |c: [f64; 2], t: f64| [c[0] + r * t.cos(), c[1] + r * t.sin()];
let (pi, far) = (std::f64::consts::PI, base + std::f64::consts::PI);
Ok(vec![
half_arc(b, r, base, z)?,
make_line(point(at(b, base + pi), z), point(at(a, far), z))?,
half_arc(a, r, far, z)?,
make_line(point(at(a, far + pi), z), point(at(b, base), z))?,
])
}
}
}
fn prism(curves: &[NurbsCurve], lo: f64, hi: f64) -> Result<BrepSolid, String> {
extrude_profile_brep(curves, Vec3::new(0., 0., 1.), hi - lo).map_err(String::from)
}
fn ring(centre: [f64; 2], r_in: f64, r_out: f64, lo: f64, hi: f64) -> Result<BrepSolid, String> {
if !(r_in > 1e-6 && r_out > r_in + 1e-6 && hi > lo) {
return Err(format!("degenerate ring r {r_in}..{r_out}"));
}
let at = |r: f64, z: f64| Vec3::new(centre[0] + r, centre[1], z);
let profile = [
make_line(at(r_in, lo), at(r_out, lo))?,
make_line(at(r_out, lo), at(r_out, hi))?,
make_line(at(r_out, hi), at(r_in, hi))?,
make_line(at(r_in, hi), at(r_in, lo))?,
];
revolve_profile_brep(&profile, point(centre, lo), Vec3::new(0., 0., 1.), std::f64::consts::TAU)
}
fn drilled(shape: &Shape, hole: Hole, lo: f64, hi: f64) -> Result<BrepSolid, String> {
if let Shape::Capsule { a, b, radius } = *shape {
let centred = (xy(a)[0] - hole.at[0]).hypot(xy(a)[1] - hole.at[1]) <= 1e-6;
if a == b && centred && hole.is_round() {
return ring(hole.at, hole.diameter / 2., mm(radius), lo, hi);
}
}
let body = prism(&shape_curves(shape, lo)?, lo, hi)?;
drill(body, &[hole], lo, hi)
}
fn cutter(hole: &Hole, lo: f64, hi: f64) -> Result<BrepSolid, String> {
let margin = 1.0;
let (lo, hi, margin_lo, margin_hi) = match hole.depth {
Some((d_lo, d_hi)) => (d_lo.max(lo), d_hi.min(hi), if d_lo <= lo { margin } else { 0. }, if d_hi >= hi { margin } else { 0. }),
None => (lo, hi, margin, margin),
};
if hole.depth.is_some() {
return make_cylinder_brep(
point(hole.at, lo - margin_lo),
Vec3::new(0., 0., 1.),
hole.diameter / 2.,
hi - lo + margin_lo + margin_hi,
);
}
if !hole.is_round() {
let (z0, z1) = (lo - margin, hi + margin);
let um = |v: f64| (v * 1000.).round() as i32;
let end = |p: [f64; 2]| brep_ecad_core::Point::new(um(p[0]), -um(p[1]));
let slot = Shape::Capsule { a: end(hole.at), b: end(hole.to), radius: um(hole.diameter / 2.) };
return prism(&shape_curves(&slot, z0)?, z0, z1);
}
make_cylinder_brep(
point(hole.at, lo - margin),
Vec3::new(0., 0., 1.),
hole.diameter / 2.,
hi - lo + 2. * margin,
)
}
fn drill(body: BrepSolid, holes: &[Hole], lo: f64, hi: f64) -> Result<BrepSolid, String> {
if holes.is_empty() {
return Ok(body);
}
let mut operands = Vec::with_capacity(holes.len() + 1);
operands.push(body.clone());
for hole in holes {
operands.push(cutter(hole, lo, hi)?);
}
if let Ok(drilled) = brep_kernel::boolean_operation_nary(&operands, BooleanOperation::Subtract) {
return Ok(drilled);
}
let options = BooleanOptions::default();
let mut body = body;
for hole in holes {
body = boolean_operation(&body, &cutter(hole, lo, hi)?, BooleanOperation::Subtract, &options)
.map_err(|refusal| format!("hole at ({:.3}, {:.3}): {refusal}", hole.at[0], hole.at[1]))?;
}
Ok(body)
}
fn cut_out(body: BrepSolid, board: &Board, lo: f64, hi: f64) -> Result<BrepSolid, String> {
if board.cutouts.is_empty() {
return Ok(body);
}
let (z0, z1) = (lo - 1., hi + 1.);
let cutters = cutout_rings(board)
.into_iter()
.map(|mut ring| {
ring.reverse();
prism(&polygon_curves(&ring, z0)?, z0, z1)
})
.collect::<Result<Vec<_>, String>>()?;
let operands: Vec<BrepSolid> = std::iter::once(body.clone()).chain(cutters.iter().cloned()).collect();
if let Ok(cut) = brep_kernel::boolean_operation_nary(&operands, BooleanOperation::Subtract) {
return Ok(cut);
}
let options = BooleanOptions::default();
let mut body = body;
for (k, cutter) in cutters.iter().enumerate() {
body = boolean_operation(&body, cutter, BooleanOperation::Subtract, &options)
.map_err(|refusal| format!("cutout {}: {refusal}", k + 1))?;
}
Ok(body)
}
fn fill_solid(piece: &board::FillPiece, lo: f64, hi: f64) -> Result<BrepSolid, String> {
let ring = |points: &[brep_ecad_core::Point], outward: bool| {
let mut ring: Vec<[f64; 2]> = points.iter().copied().map(xy).collect();
if (super::signed_area2(&ring) > 0.) != outward {
ring.reverse();
}
ring
};
let body = prism(&polygon_curves(&ring(&piece.outer, true), lo)?, lo, hi)?;
if piece.holes.is_empty() {
return Ok(body);
}
let margin = 1.0;
let cutters = piece
.holes
.iter()
.map(|hole| {
let curves = polygon_curves(&ring(hole, true), lo - margin)?;
prism(&curves, lo - margin, hi + margin)
})
.collect::<Result<Vec<_>, String>>()?;
let mut operands = Vec::with_capacity(cutters.len() + 1);
operands.push(body.clone());
operands.extend(cutters.iter().cloned());
if let Ok(cut) = brep_kernel::boolean_operation_nary(&operands, BooleanOperation::Subtract) {
return Ok(cut);
}
let options = BooleanOptions::default();
let mut body = body;
for (k, cutter) in cutters.iter().enumerate() {
body = boolean_operation(&body, cutter, BooleanOperation::Subtract, &options)
.map_err(|refusal| format!("fill hole {k}: {refusal}"))?;
}
Ok(body)
}
fn item_hole(board: &Board, vias: &[board::Via], owner: &CopperRef) -> Option<Hole> {
match *owner {
CopperRef::Via(index) => vias.get(index).map(|via| Hole::round(xy(via.at), mm(via.drill))),
CopperRef::Pad { placement, pad } => {
let placement = board.placements.get(placement)?;
let pad = placement.footprint.pads.get(pad)?;
let hole = pad.hole_size()?;
match placement.pad_hole(pad)? {
Shape::Capsule { a, b, radius } if a != b => Some(Hole { at: xy(a), to: xy(b), diameter: mm(2 * radius), depth: None }),
_ => Some(Hole::round(xy(placement.transform(pad.at)), mm(hole.x.min(hole.y)))),
}
}
CopperRef::Track { .. } => None,
}
}
fn bores_in(holes: &[Hole], covers: impl Fn(brep_ecad_core::Point) -> bool, own: Option<[f64; 2]>, lo: f64, hi: f64) -> Vec<Hole> {
holes
.iter()
.filter(|h| own.is_none_or(|at| (at[0] - h.at[0]).hypot(at[1] - h.at[1]) > 1e-6))
.filter(|h| h.depth.is_none_or(|(a, b)| a.min(b) < hi && lo < a.max(b)))
.filter(|h| covers(brep_ecad_core::Point::new((h.at[0] * 1000.).round() as i32, (-h.at[1] * 1000.).round() as i32)))
.cloned()
.collect()
}
fn board_holes(board: &Board) -> Vec<Hole> {
let count = board.layer_count;
let blind: Vec<Hole> = board
.vias
.iter()
.filter(|via| via.kind(count) == board::ViaKind::Blind)
.map(|via| {
let (from, to) = via.layers(count);
let depth = (mm(board::layer_z(to, count)), mm(board::layer_z(from, count)));
Hole { depth: Some(depth), ..Hole::round(xy(via.at), mm(via.drill)) }
})
.collect();
let all = board.all_vias();
let vias = (0..all.len()).filter(|&v| all[v].kind(count) == board::ViaKind::Through).map(CopperRef::Via);
let pads = board.placements.iter().enumerate().flat_map(|(placement, p)| {
(0..p.footprint.pads.len()).map(move |pad| CopperRef::Pad { placement, pad })
});
vias.chain(pads)
.filter_map(|owner| item_hole(board, &all, &owner))
.chain(blind)
.filter(|hole| hole.diameter > 1e-6)
.collect()
}
fn net_part(net: Option<&str>) -> String {
net.map(|net| net.replace('/', "_")).unwrap_or_else(|| "no-net".to_string())
}
pub(crate) fn board_step_solids(board: &Board, netlist: Option<&Netlist>) -> Option<BoardStepSolids> {
let outline = oriented_outline(board)?;
let mut out = BoardStepSolids::default();
let refilled;
let board = if board.zones.is_empty() {
board
} else {
let mut copy = board.clone();
let empty = Netlist { version: 1, nets: vec![], diagnostics: vec![] };
copy.fill_zones(netlist.unwrap_or(&empty));
if copy.zones != board.zones {
out.notices.push(
"STEP export: the zones' fill was out of date, so the file carries a fresh fill, as the fabrication \
export does. Fill zones (B) on the board to see the copper that was written."
.to_owned(),
);
}
refilled = copy;
&refilled
};
let holes = board_holes(board);
let (board_lo, board_hi) = (mm(-board::SUBSTRATE_THICKNESS), 0.);
let substrate = polygon_curves(&outline, board_lo)
.and_then(|curves| prism(&curves, board_lo, board_hi))
.and_then(|body| drill(body, &holes, board_lo, board_hi))
.and_then(|body| cut_out(body, board, board_lo, board_hi));
match substrate {
Ok(body) => {
out.bodies.push((SUBSTRATE_SOLID.to_string(), body));
out.colors.push((SUBSTRATE_SOLID.to_string(), SUBSTRATE_RGB));
}
Err(error) => out.skipped.push(format!("{SUBSTRATE_SOLID}: {error}")),
}
let all_vias = board.all_vias();
let (copper, nets) = copper_and_nets(board, netlist);
for layer in 0..board.layer_count.max(1) {
let (lo, hi) = super::copper_span(layer, board.layer_count);
let layer_name = format!("{BOARD_SOLID_PREFIX}{}", board::layer_name(layer, board.layer_count));
let mut count = 0usize;
for (item, net) in copper.iter().zip(&nets) {
if !(item.layers.0 <= layer && layer <= item.layers.1) {
continue;
}
count += 1;
let name = format!("{layer_name}/{}#{count}", net_part(net.as_deref()));
let own = item_hole(board, &all_vias, &item.owner);
let bores = bores_in(&holes, |p| item.shape.contains(p), own.as_ref().map(|h| h.at), lo, hi);
let solid = match own {
Some(hole) => drilled(&item.shape, hole, lo, hi).and_then(|body| drill(body, &bores, lo, hi)),
None => shape_curves(&item.shape, lo)
.and_then(|curves| prism(&curves, lo, hi))
.and_then(|body| drill(body, &bores, lo, hi)),
};
match solid {
Ok(body) => {
out.colors.push((name.clone(), COPPER_RGB));
out.bodies.push((name, body));
}
Err(error) => out.skipped.push(format!("{name}: {error}")),
}
}
for zone in board.zones.iter().filter(|z| z.layer == layer) {
for piece in &zone.fill {
count += 1;
let name = format!("{layer_name}/{}#{count}", net_part(Some(&zone.net)));
let bores = bores_in(&holes, |p| piece.contains(p), None, lo, hi);
match fill_solid(piece, lo, hi).and_then(|body| drill(body, &bores, lo, hi)) {
Ok(body) => {
out.colors.push((name.clone(), COPPER_RGB));
out.bodies.push((name, body));
}
Err(error) => out.skipped.push(format!("{name}: {error}")),
}
}
}
}
for (index, via) in board.all_vias().iter().enumerate() {
let name = format!("{VIAS_SOLID}#{}", index + 1);
let inner = mm(via.drill) / 2.;
let outer = inner + mm(board::COPPER_THICKNESS);
let (from, to) = via.layers(board.layer_count);
let (lo, hi) = (
mm(board::layer_z(to, board.layer_count)),
mm(board::layer_z(from, board.layer_count)),
);
let barrel = ring(xy(via.at), inner, outer, lo, hi);
match barrel {
Ok(body) => {
out.colors.push((name.clone(), COPPER_RGB));
out.bodies.push((name, body));
}
Err(error) => out.skipped.push(format!("{name}: {error}")),
}
}
Some(out)
}