Skip to main content

brep_ecad_core/
fabrication.rs

1//! Manufacturing outputs: Gerber X2 layers, Excellon drill files, and a zip bundle.
2//!
3//! Every file shares one origin, the lower-left corner of the board outline, with
4//! positive Y up as both formats expect. Board coordinates are Y down, so Y is
5//! flipped here and nowhere else. All layers are viewed from the top, as Gerber
6//! requires; bottom-side footprints are already mirrored by their placement.
7use crate::csv_field;
8use crate::board::{Board, Placement, Shape};
9use crate::graphic::GraphicLayer;
10use crate::{Document, Point};
11use std::collections::{BTreeMap, BTreeSet};
12use std::fmt::Write as _;
13
14/// Silkscreen stroke width.
15pub const SILK_WIDTH: i32 = 150;
16/// Stroke width used to draw the board outline.
17pub const OUTLINE_WIDTH: i32 = 100;
18/// Height of reference designators on the silkscreen.
19pub const TEXT_HEIGHT: i32 = 1000;
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct FabricationFile {
23    pub name: String,
24    pub contents: String,
25}
26
27#[derive(Clone, Debug, Default, PartialEq, Eq)]
28pub struct Fabrication {
29    pub files: Vec<FabricationFile>,
30    /// Problems worth fixing before ordering boards; the files are still complete.
31    pub warnings: Vec<String>,
32}
33impl Fabrication {
34    /// All files in one uncompressed zip archive, as most board houses accept.
35    pub fn zip(&self) -> Vec<u8> {
36        zip(self
37            .files
38            .iter()
39            .map(|f| (f.name.as_str(), f.contents.as_bytes())))
40    }
41}
42
43impl Document {
44    /// Gerber and drill files for the board. `name` prefixes every file name.
45    pub fn fabrication(&self, name: &str) -> Result<Fabrication, String> {
46        self.validate()?;
47        // A one-layer board has no bottom copper to put a back-side pad on, and
48        // drawing it on the top would make a board that is not the design. The
49        // design rule check names it; the export refuses it. (Storing the
50        // document does not: a refusal there would block every other edit.)
51        if self.board.layer_count == 1 {
52            if let Some(p) = self.board.placements.iter().find(|p| p.has_back_copper_pad()) {
53                let reference = self
54                    .components
55                    .iter()
56                    .find(|c| c.id == p.component)
57                    .map_or("A part", |c| c.reference.as_str());
58                return Err(format!(
59                    "{reference} has pads on the back copper, which a one-layer board does not have: add a second copper layer or move those pads to the front."
60                ));
61            }
62            if let Some(p) = self.board.placements.iter().find(|p| p.footprint.pads.iter().any(|pad| pad.vias.is_some())) {
63                let reference = self
64                    .components
65                    .iter()
66                    .find(|c| c.id == p.component)
67                    .map_or("A part", |c| c.reference.as_str());
68                return Err(format!(
69                    "{reference} has vias in its pads, which a one-layer board cannot carry: add a second copper layer or take the vias out of its pads."
70                ));
71            }
72        }
73        // The zones are refilled on a copy first: what is sent to be made is the
74        // fill the copper as it stands asks for, never a stale one the user forgot
75        // to refill.
76        let netlist = self.netlist();
77        let refilled;
78        let board = if self.board.zones.is_empty() {
79            &self.board
80        } else {
81            let mut copy = self.board.clone();
82            copy.fill_zones(&netlist);
83            refilled = copy;
84            &refilled
85        };
86        let base: String = name
87            .trim()
88            .chars()
89            .map(|c| {
90                if c.is_ascii_alphanumeric() || "-_.".contains(c) {
91                    c
92                } else {
93                    '_'
94                }
95            })
96            .collect();
97        let base = if base.is_empty() {
98            "board".into()
99        } else {
100            base
101        };
102        let origin = Origin::new(board);
103        let last = board.layer_count - 1;
104        let mut files = vec![];
105        let mut add = |suffix: &str, contents: String| {
106            files.push(FabricationFile {
107                name: format!("{base}-{suffix}"),
108                contents,
109            })
110        };
111
112        for layer in 0..board.layer_count {
113            let (name, extension, function) = if layer == 0 {
114                ("F_Cu".to_owned(), "gtl".to_owned(), "Copper,L1,Top")
115            } else if layer == last {
116                ("B_Cu".into(), "gbl".into(), "Copper,L{},Bot")
117            } else {
118                (
119                    format!("In{layer}_Cu"),
120                    format!("g{}", layer + 1),
121                    "Copper,L{},Inr",
122                )
123            };
124            let function = function.replace("{}", &(u32::from(layer) + 1).to_string());
125            add(
126                &format!("{name}.{extension}"),
127                copper(board, &origin, layer).finish(&function, "Positive"),
128            );
129        }
130        for (top, side) in [(true, "F"), (false, "B")] {
131            let (letter, position) = if top { ('t', "Top") } else { ('b', "Bot") };
132            add(
133                &format!("{side}_Mask.g{letter}s"),
134                mask(board, &origin, top).finish(&format!("Soldermask,{position}"), "Negative"),
135            );
136            add(
137                &format!("{side}_Paste.g{letter}p"),
138                paste(board, &origin, top).finish(&format!("Paste,{position}"), "Positive"),
139            );
140        }
141        let mut unsupported = BTreeSet::new();
142        for (top, side) in [(true, "F"), (false, "B")] {
143            let (letter, position) = if top { ('t', "Top") } else { ('b', "Bot") };
144            let layer = legend(self, &origin, top, &mut unsupported);
145            add(
146                &format!("{side}_Silkscreen.g{letter}o"),
147                layer.finish(&format!("Legend,{position}"), "Positive"),
148            );
149        }
150        let mut profile = Gerber::default();
151        profile.select(Aperture::Circle(OUTLINE_WIDTH), Some("Profile"));
152        // The outline, then each cutout, each its own closed loop of the profile.
153        for ring in std::iter::once(&board.outline).chain(board.cutouts.iter().map(|c| &c.points)) {
154            profile.stroke(ring.iter().chain(&ring[..1]).map(|p| origin.point(*p)));
155        }
156        add("Edge_Cuts.gm1", profile.finish("Profile,NP", "Positive"));
157
158        let (plated, unplated, spans) = drills(board, &origin);
159        let layers = board.layer_count;
160        // Blind and buried vias, one drill file per layer pair, numbered from 1
161        // at the top as Gerber X2 numbers copper.
162        for ((from, to), holes) in &spans {
163            let kind = if *from == 0 || *to + 1 == layers { "Blind" } else { "Buried" };
164            let (a, b) = (from + 1, to + 1);
165            add(
166                &format!("{kind}_{a}_{b}.drl"),
167                excellon(holes, &format!("Plated,{a},{b},{kind}"), &format!("Plated,{kind}")),
168            );
169        }
170        add(
171            "PTH.drl",
172            excellon(&plated, &format!("Plated,1,{layers},PTH"), "Plated,PTH"),
173        );
174        if !unplated.is_empty() {
175            add(
176                "NPTH.drl",
177                excellon(
178                    &unplated,
179                    &format!("NonPlated,1,{layers},NPTH"),
180                    "NonPlated,NPTH",
181                ),
182            );
183        }
184
185        let mut warnings = vec![];
186        if board.zones != self.board.zones {
187            warnings.push(
188                "The zones' fill was out of date, so these files carry a fresh fill: \
189                 fill the zones on the board to see what was sent."
190                    .to_owned(),
191            );
192        }
193        let findings = board.drc(&netlist);
194        if !findings.is_empty() {
195            let unrouted = findings
196                .iter()
197                .filter(|v| v.kind == crate::board::ViolationKind::Unrouted)
198                .count();
199            warnings.push(format!(
200                "The design rule check has {} finding(s), {unrouted} of them unrouted connections. \
201                 Fix them before ordering boards.",
202                findings.len()
203            ));
204        }
205        if !unsupported.is_empty() {
206            warnings.push(format!(
207                "Silkscreen text shows these characters as '?': {}",
208                unsupported.iter().collect::<String>()
209            ));
210        }
211        add("pos.csv", self.pick_and_place_csv());
212        add("bom.csv", self.electronics_bom_csv());
213        let readme = readme(self, &files, &warnings);
214        files.push(FabricationFile {
215            name: format!("{base}-README.txt"),
216            contents: readme,
217        });
218        Ok(Fabrication { files, warnings })
219    }
220
221    /// The pick-and-place (centroid) file, one row per placed part, in the
222    /// column convention of JLCPCB's CPL template, which KiCad's own position
223    /// export and most assembly houses also accept:
224    /// `Designator,Val,Package,Mid X,Mid Y,Rotation,Layer`.
225    ///
226    /// * Mid X / Mid Y are the footprint's anchor (its origin, where KiCad puts a
227    ///   part's position), in millimetres with a `mm` suffix, from the Gerbers'
228    ///   own origin: the outline's lower-left corner, Y up.
229    /// * Rotation is in degrees, counter-clockwise as seen from the top, 0 to 270.
230    ///   A bottom part is reported the same way: the angle of its mirrored
231    ///   footprint seen from the top. No assembler-specific bottom-side
232    ///   correction is applied.
233    /// * Layer is `Top` or `Bottom`.
234    ///
235    /// Rows are in reference order (`R2` before `R10`). Power symbols have no
236    /// part to place and do not appear.
237    pub fn pick_and_place_csv(&self) -> String {
238        let origin = Origin::new(&self.board);
239        let mut rows: Vec<(&str, String)> = vec![];
240        for placement in &self.board.placements {
241            let Some(component) = self.placed_part(placement) else {
242                continue;
243            };
244            let (x, y) = origin.point(placement.at);
245            let rotation = (4 - u32::from(placement.rotation % 4)) % 4 * 90;
246            rows.push((
247                &component.reference,
248                [
249                    csv_field(&component.reference),
250                    csv_field(&component.value),
251                    csv_field(&placement.footprint.name),
252                    format!("{}mm", millimetres(x / 1000)),
253                    format!("{}mm", millimetres(y / 1000)),
254                    rotation.to_string(),
255                    if placement.bottom { "Bottom" } else { "Top" }.into(),
256                ]
257                .join(","),
258            ));
259        }
260        rows.sort_by(|a, b| natural(a.0).cmp(&natural(b.0)));
261        let mut out = String::from("Designator,Val,Package,Mid X,Mid Y,Rotation,Layer\n");
262        for (_, row) in rows {
263            out.push_str(&row);
264            out.push('\n');
265        }
266        out
267    }
268
269    /// The electronics bill of materials: one line per value and footprint,
270    /// with every reference that uses it, in the column convention of JLCPCB's
271    /// BOM template: `Comment,Designator,Footprint,Quantity`. `Comment` is the
272    /// part's value, as JLCPCB names it; `Designator` lists the references in
273    /// order (`R1,R2,R10`), quoted because it holds commas.
274    ///
275    /// Every component on the schematic is listed, placed on the board or not:
276    /// a part not yet on the board still has to be bought. Its footprint is the
277    /// one it would be placed with. Power symbols are not parts and are left out.
278    /// Lines are in the order of their first reference.
279    pub fn electronics_bom_csv(&self) -> String {
280        let mut groups: BTreeMap<(String, String), Vec<&str>> = BTreeMap::new();
281        // The board's parts: a sheet's parts off the board are on the assembly BOM.
282        for component in self.components.iter().filter(|c| self.on_board(c)) {
283            if component.symbol.power_net.is_some() {
284                continue;
285            }
286            let footprint = self
287                .board
288                .placements
289                .iter()
290                .find(|p| p.component == component.id)
291                .map(|p| p.footprint.name.clone())
292                .or_else(|| component.pads.as_ref().map(|f| f.name.clone()))
293                .or_else(|| component.symbol.properties.get("Footprint").cloned())
294                .unwrap_or_default();
295            groups
296                .entry((component.value.clone(), footprint))
297                .or_default()
298                .push(&component.reference);
299        }
300        let mut lines: Vec<_> = groups
301            .into_iter()
302            .map(|((value, footprint), mut references)| {
303                references.sort_by(|a, b| natural(a).cmp(&natural(b)));
304                (value, footprint, references)
305            })
306            .collect();
307        lines.sort_by(|a, b| natural(a.2[0]).cmp(&natural(b.2[0])));
308        let mut out = String::from("Comment,Designator,Footprint,Quantity\n");
309        for (value, footprint, references) in lines {
310            let _ = writeln!(
311                out,
312                "{},{},{},{}",
313                csv_field(&value),
314                csv_field(&references.join(",")),
315                csv_field(&footprint),
316                references.len()
317            );
318        }
319        out
320    }
321
322    /// The component a board placement mounts, unless it is a power symbol.
323    fn placed_part(&self, placement: &Placement) -> Option<&crate::Component> {
324        self.components
325            .iter()
326            .find(|c| c.id == placement.component && c.symbol.power_net.is_none())
327    }
328}
329
330/// What a bundle's files hold, counted by reading the files themselves: pad
331/// flashes on the outer copper, drill hits, the outline's extent and the CSV
332/// rows. A host reports these beside an export so a caller can compare them
333/// with the board without trusting the writer.
334#[derive(Clone, Debug, Default, PartialEq)]
335pub struct ReadBack {
336    /// `D03` flashes in the top and bottom copper files.
337    pub top_flashes: usize,
338    pub bottom_flashes: usize,
339    /// Hits in the plated and non-plated drill files.
340    pub plated_holes: usize,
341    pub unplated_holes: usize,
342    /// Width and height of the Edge_Cuts drawing in millimetres, measured to
343    /// the centre of its stroke.
344    pub outline_mm: (f64, f64),
345    /// Data rows (not the header) of the pick-and-place and BOM files.
346    pub placements: usize,
347    pub bom_lines: usize,
348}
349
350impl Fabrication {
351    /// Count what the files hold; see [`ReadBack`].
352    pub fn read_back(&self) -> ReadBack {
353        let text = |suffix: &str| {
354            self.files
355                .iter()
356                .find(|f| f.name.ends_with(suffix))
357                .map_or("", |f| f.contents.as_str())
358        };
359        let flashes = |t: &str| t.lines().filter(|l| l.starts_with('X') && l.ends_with("D03*")).count();
360        let holes = |t: &str| t.lines().filter(|l| l.starts_with('X')).count();
361        let rows = |t: &str| t.lines().count().saturating_sub(1);
362        let mut min = (i64::MAX, i64::MAX);
363        let mut max = (i64::MIN, i64::MIN);
364        for line in text("-Edge_Cuts.gm1").lines() {
365            let Some((x, rest)) = line.strip_prefix('X').and_then(|l| l.split_once('Y')) else {
366                continue;
367            };
368            let y = rest.split('D').next().unwrap_or("");
369            if let (Ok(x), Ok(y)) = (x.parse::<i64>(), y.parse::<i64>()) {
370                min = (min.0.min(x), min.1.min(y));
371                max = (max.0.max(x), max.1.max(y));
372            }
373        }
374        let outline_mm = if min.0 <= max.0 {
375            ((max.0 - min.0) as f64 / 1e6, (max.1 - min.1) as f64 / 1e6)
376        } else {
377            (0., 0.)
378        };
379        ReadBack {
380            top_flashes: flashes(text("-F_Cu.gtl")),
381            bottom_flashes: flashes(text("-B_Cu.gbl")),
382            plated_holes: holes(text("-PTH.drl")),
383            unplated_holes: holes(text("-NPTH.drl")),
384            outline_mm,
385            placements: rows(text("-pos.csv")),
386            bom_lines: rows(text("-bom.csv")),
387        }
388    }
389}
390
391/// A sort key that orders the digits in a reference by value: `R2` before `R10`.
392fn natural(text: &str) -> Vec<(String, u64)> {
393    let mut key = vec![];
394    let mut letters = String::new();
395    let mut digits = String::new();
396    for c in text.chars() {
397        if c.is_ascii_digit() {
398            digits.push(c);
399        } else {
400            if !digits.is_empty() {
401                key.push((std::mem::take(&mut letters), digits.parse().unwrap_or(u64::MAX)));
402                digits.clear();
403            }
404            letters.push(c);
405        }
406    }
407    key.push((letters, digits.parse().unwrap_or(0)));
408    key
409}
410
411/// What each file in the bundle is, for the person placing the order.
412fn readme(document: &Document, files: &[FabricationFile], warnings: &[String]) -> String {
413    let board = &document.board;
414    let (min, max) = board.outline_bounds();
415    let mut out = String::from("Fabrication files\n=================\n\n");
416    let _ = writeln!(
417        out,
418        "Board: {} copper layer(s), outline {} x {} mm.",
419        board.layer_count,
420        millimetres(i64::from(max.x) - i64::from(min.x)),
421        millimetres(i64::from(max.y) - i64::from(min.y)),
422    );
423    out.push_str(
424        "Units are millimetres. Every file shares one origin, the lower-left corner of the\n\
425         board outline, with Y up. All layers are viewed from the top.\n\n",
426    );
427    for file in files {
428        let (_, suffix) = file.name.rsplit_once('-').unwrap_or(("", &file.name));
429        let what = match suffix.split('.').next().unwrap_or("") {
430            "F_Cu" => "Gerber X2, top copper".to_owned(),
431            "B_Cu" => "Gerber X2, bottom copper".to_owned(),
432            inner if inner.starts_with("In") && inner.ends_with("_Cu") => {
433                format!("Gerber X2, inner copper layer {}", &inner[2..inner.len() - 3])
434            }
435            "F_Mask" => "Gerber X2, top solder mask (negative: flashes are openings)".into(),
436            "B_Mask" => "Gerber X2, bottom solder mask (negative: flashes are openings)".into(),
437            "F_Paste" => "Gerber X2, top paste stencil".into(),
438            "B_Paste" => "Gerber X2, bottom paste stencil".into(),
439            "F_Silkscreen" => "Gerber X2, top silkscreen (legend)".into(),
440            "B_Silkscreen" => "Gerber X2, bottom silkscreen (legend)".into(),
441            "Edge_Cuts" => "Gerber X2, board outline (profile)".into(),
442            "PTH" => "Excellon, plated holes (vias and component holes)".into(),
443            span if span.starts_with("Blind_") || span.starts_with("Buried_") => {
444                let mut parts = span.split('_');
445                let kind = parts.next().unwrap_or("").to_lowercase();
446                let (a, b) = (parts.next().unwrap_or("?"), parts.next().unwrap_or("?"));
447                format!("Excellon, {kind} vias drilled between copper layers {a} and {b}")
448            }
449            "NPTH" => "Excellon, non-plated holes".into(),
450            "pos" => "pick and place (centroid), JLCPCB CPL columns".into(),
451            "bom" => "bill of materials, JLCPCB BOM columns, grouped by value and footprint".into(),
452            _ => continue,
453        };
454        let _ = writeln!(out, "{:<32} {what}", file.name);
455    }
456    out.push_str(
457        "\nPick and place: Mid X / Mid Y are each footprint's origin. Rotation is degrees\n\
458         counter-clockwise seen from the top; a bottom part's is its mirrored footprint's,\n\
459         also seen from the top, with no assembler-specific correction.\n",
460    );
461    if !warnings.is_empty() {
462        out.push_str("\nWarnings:\n");
463        for warning in warnings {
464            let _ = writeln!(out, "- {warning}");
465        }
466    }
467    out
468}
469
470/// Maps board micrometres (Y down) to output nanometres (Y up) from the outline's
471/// lower-left corner. Nanometres keep half-micrometre pad centres exact.
472struct Origin {
473    left: i64,
474    bottom: i64,
475}
476impl Origin {
477    fn new(board: &Board) -> Self {
478        let (min, max) = board.outline_bounds();
479        Self {
480            left: i64::from(min.x),
481            bottom: i64::from(max.y),
482        }
483    }
484    fn point(&self, p: Point) -> (i64, i64) {
485        (
486            (i64::from(p.x) - self.left) * 1000,
487            (self.bottom - i64::from(p.y)) * 1000,
488        )
489    }
490    /// Midpoint of two board points.
491    fn middle(&self, a: Point, b: Point) -> (i64, i64) {
492        (
493            (i64::from(a.x) + i64::from(b.x) - 2 * self.left) * 500,
494            (2 * self.bottom - i64::from(a.y) - i64::from(b.y)) * 500,
495        )
496    }
497}
498
499#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
500enum Aperture {
501    Circle(i32),
502    Rect(i32, i32),
503    Obround(i32, i32),
504}
505
506/// One Gerber image. Apertures are collected while drawing and written ahead of
507/// the drawing commands when the file is finished.
508#[derive(Default)]
509struct Gerber {
510    apertures: Vec<(Aperture, Option<&'static str>)>,
511    current: Option<usize>,
512    body: String,
513}
514impl Gerber {
515    fn select(&mut self, aperture: Aperture, function: Option<&'static str>) {
516        let key = (aperture, function);
517        let index = match self.apertures.iter().position(|a| *a == key) {
518            Some(index) => index,
519            None => {
520                self.apertures.push(key);
521                self.apertures.len() - 1
522            }
523        };
524        if self.current != Some(index) {
525            self.current = Some(index);
526            let _ = writeln!(self.body, "D{}*", index + 10);
527        }
528    }
529    fn flash(&mut self, (x, y): (i64, i64)) {
530        let _ = writeln!(self.body, "X{x}Y{y}D03*");
531    }
532    fn stroke(&mut self, points: impl IntoIterator<Item = (i64, i64)>) {
533        for (i, (x, y)) in points.into_iter().enumerate() {
534            let operation = if i == 0 { "D02" } else { "D01" };
535            let _ = writeln!(self.body, "X{x}Y{y}{operation}*");
536        }
537    }
538    /// Draw a copper-style shape grown by `grow` on every side.
539    fn shape(&mut self, origin: &Origin, shape: Shape, grow: i32, function: Option<&'static str>) {
540        // Grown first, so a negative margin shrinks the shape to at least a
541        // point instead of writing a negative aperture.
542        let (shape, grow) = (shape.grown(grow), 0);
543        match shape {
544            // A polygon is a region; its rounding, the polygon swept by a disc,
545            // is that region with every edge stroked by a round aperture of the
546            // disc, which the film draws exactly.
547            Shape::Polygon { points, radius } => {
548                if let Some(function) = function {
549                    let _ = writeln!(self.body, "%TA.AperFunction,{function}*%");
550                }
551                self.body.push_str("G36*\n");
552                self.stroke(points.iter().chain(points.first()).map(|p| origin.point(*p)));
553                self.body.push_str("G37*\n");
554                if function.is_some() {
555                    self.body.push_str("%TD*%\n");
556                }
557                if radius > 0 {
558                    self.select(Aperture::Circle(2 * radius), function);
559                    self.stroke(points.iter().chain(points.first()).map(|p| origin.point(*p)));
560                }
561            }
562            // No standard aperture is a rounded rectangle: drawn as a region of
563            // four straights and four EXACT quarter arcs (G02, multi-quadrant
564            // G75 is set in the header), so the film carries the copper the
565            // clearance and connectivity checks measured, not a facetted inside.
566            Shape::RoundRect { min, max, radius } => {
567                if let Some(function) = function {
568                    let _ = writeln!(self.body, "%TA.AperFunction,{function}*%");
569                }
570                let (lo, hi) = (
571                    Point::new(min.x + radius, min.y + radius),
572                    Point::new(max.x - radius, max.y - radius),
573                );
574                // Board y points down, so this walk (down the right side, then
575                // left along the bottom) is clockwise on the film.
576                let walk = [
577                    (Point::new(max.x, hi.y), Point::new(hi.x, max.y), hi),
578                    (Point::new(lo.x, max.y), Point::new(min.x, hi.y), Point::new(lo.x, hi.y)),
579                    (Point::new(min.x, lo.y), Point::new(lo.x, min.y), lo),
580                    (Point::new(hi.x, min.y), Point::new(max.x, lo.y), Point::new(hi.x, lo.y)),
581                ];
582                let (x, y) = origin.point(Point::new(max.x, lo.y));
583                let _ = writeln!(self.body, "G36*\nX{x}Y{y}D02*");
584                for (line_end, arc_end, centre) in walk {
585                    let (x, y) = origin.point(line_end);
586                    let _ = writeln!(self.body, "X{x}Y{y}D01*");
587                    let (cx, cy) = origin.point(centre);
588                    let (ex, ey) = origin.point(arc_end);
589                    let _ = writeln!(self.body, "G02*\nX{ex}Y{ey}I{}J{}D01*\nG01*", cx - x, cy - y);
590                }
591                self.body.push_str("G37*\n");
592                if function.is_some() {
593                    self.body.push_str("%TD*%\n");
594                }
595            }
596            Shape::Rect { min, max } => {
597                self.select(
598                    Aperture::Rect(max.x - min.x + 2 * grow, max.y - min.y + 2 * grow),
599                    function,
600                );
601                self.flash(origin.middle(min, max));
602            }
603            Shape::Capsule { a, b, radius } => {
604                let diameter = 2 * (radius + grow);
605                if a == b {
606                    self.select(Aperture::Circle(diameter), function);
607                    self.flash(origin.point(a));
608                } else if a.x == b.x || a.y == b.y {
609                    let (dx, dy) = (a.x.abs_diff(b.x) as i32, a.y.abs_diff(b.y) as i32);
610                    self.select(Aperture::Obround(dx + diameter, dy + diameter), function);
611                    self.flash(origin.middle(a, b));
612                } else {
613                    self.select(Aperture::Circle(diameter), function);
614                    self.stroke([origin.point(a), origin.point(b)]);
615                }
616            }
617        }
618    }
619    fn finish(self, file_function: &str, polarity: &str) -> String {
620        let mut out = String::new();
621        let _ = writeln!(
622            out,
623            "%TF.GenerationSoftware,eCAD,Schematic and PCB Studio,{}*%",
624            env!("CARGO_PKG_VERSION")
625        );
626        out.push_str("%TF.SameCoordinates,Original*%\n");
627        let _ = writeln!(out, "%TF.FileFunction,{file_function}*%");
628        let _ = writeln!(out, "%TF.FilePolarity,{polarity}*%");
629        out.push_str("%FSLAX46Y46*%\n%MOMM*%\n%LPD*%\nG01*\nG75*\n");
630        for (index, (aperture, function)) in self.apertures.iter().enumerate() {
631            if let Some(function) = function {
632                let _ = writeln!(out, "%TA.AperFunction,{function}*%");
633            }
634            let template = match *aperture {
635                Aperture::Circle(d) => format!("C,{}", millimetres(d)),
636                Aperture::Rect(w, h) => format!("R,{}X{}", millimetres(w), millimetres(h)),
637                Aperture::Obround(w, h) => format!("O,{}X{}", millimetres(w), millimetres(h)),
638            };
639            let _ = writeln!(out, "%ADD{}{template}*%", index + 10);
640            if function.is_some() {
641                out.push_str("%TD*%\n");
642            }
643        }
644        out.push_str(&self.body);
645        out.push_str("M02*\n");
646        out
647    }
648}
649
650fn millimetres(um: impl Into<i64>) -> String {
651    let um = um.into();
652    let sign = if um < 0 { "-" } else { "" };
653    format!("{sign}{}.{:03}", um.abs() / 1000, um.abs() % 1000)
654}
655
656/// A drilled pad with copper around the hole, or a plated one of any size.
657fn pad_has_copper(placement: &Placement, index: usize) -> bool {
658    let pad = &placement.footprint.pads[index];
659    match pad.hole_size() {
660        Some(hole) if !pad.plated => pad.size.x > hole.x && pad.size.y > hole.y,
661        _ => true,
662    }
663}
664
665fn copper(board: &Board, origin: &Origin, layer: u8) -> Gerber {
666    let last = board.layer_count - 1;
667    let mut gerber = Gerber::default();
668    // Zones first, as G36/G37 regions, each piece's holes joined to its outside by
669    // cut-ins (`zones::fractured`): the layer stays all dark polarity, so nothing
670    // drawn after a zone can be cleared by it. Each region carries the X2 function
671    // and net of its zone.
672    for zone in board.zones.iter().filter(|z| z.layer == layer && !z.fill.is_empty()) {
673        let _ = writeln!(gerber.body, "%TA.AperFunction,Conductor*%");
674        let _ = writeln!(gerber.body, "%TO.N,{}*%", zone.net.replace(['*', '%', ','], "_"));
675        for piece in &zone.fill {
676            let ring = crate::board::zones::fractured(piece);
677            gerber.body.push_str("G36*\n");
678            gerber.stroke(ring.iter().chain(ring.first()).map(|p| origin.point(*p)));
679            gerber.body.push_str("G37*\n");
680        }
681        gerber.body.push_str("%TD*%\n");
682    }
683    for placement in &board.placements {
684        for (index, pad) in placement.footprint.pads.iter().enumerate() {
685            let (from, to) = placement.pad_layers(pad, board.layer_count);
686            if !(from..=to).contains(&layer) || !pad_has_copper(placement, index) {
687                continue;
688            }
689            let function = match (pad.drill, pad.plated) {
690                (None, _) => "SMDPad,CuDef",
691                (Some(_), true) => "ComponentPad",
692                (Some(_), false) if layer == 0 || layer == last => "WasherPad",
693                (Some(_), false) => continue,
694            };
695            gerber.shape(origin, placement.pad_shape(pad), 0, Some(function));
696        }
697    }
698    for track in board.tracks.iter().filter(|t| t.layer == layer) {
699        gerber.select(Aperture::Circle(track.width), Some("Conductor"));
700        gerber.stroke(track.points.iter().map(|p| origin.point(*p)));
701    }
702    // A via's pad is on every layer it joins, and only those; a pad's own
703    // vias are through vias.
704    for via in board.all_vias().iter().filter(|v| {
705        let (from, to) = v.layers(board.layer_count);
706        (from..=to).contains(&layer)
707    }) {
708        gerber.shape(
709            origin,
710            Shape::circle(via.at, via.diameter / 2),
711            0,
712            Some("ViaPad"),
713        );
714    }
715    gerber
716}
717
718/// Openings over pads on one side: every pad whose copper reaches that side,
719/// unless the pad is set to stay covered there, grown by the pad's own mask
720/// margin or else the board's. Vias stay covered (tented) unless the board's
721/// rules say otherwise, when each via's ring opens on both sides.
722fn mask(board: &Board, origin: &Origin, top: bool) -> Gerber {
723    let mut gerber = Gerber::default();
724    if !board.rules.tent_vias {
725        // Only on a side the via reaches: a blind via opens on its outer side,
726        // a buried one on neither.
727        let last = board.layer_count - 1;
728        for via in board.vias.iter().filter(|v| {
729            let (from, to) = v.layers(board.layer_count);
730            if top { from == 0 } else { to == last }
731        }) {
732            gerber.shape(origin, Shape::circle(via.at, via.diameter / 2), board.rules.mask_expansion, None);
733        }
734    }
735    // A pad's vias open on the side away from the pad unless tented there; on
736    // the pad's own side its opening exposes them.
737    for (via, tented, far_is_bottom) in board.pad_vias() {
738        if !tented && far_is_bottom != top {
739            gerber.shape(origin, Shape::circle(via.at, via.diameter / 2), board.rules.mask_expansion, None);
740        }
741    }
742    for placement in &board.placements {
743        for pad in &placement.footprint.pads {
744            if pad_mask_open(board, placement, pad, top) {
745                gerber.shape(
746                    origin,
747                    placement.pad_shape(pad),
748                    pad.layers.mask_margin.unwrap_or(board.rules.mask_expansion),
749                    None,
750                );
751            }
752        }
753    }
754    gerber
755}
756
757/// Whether `pad` of `placement` gets a solder mask opening on the board's top
758/// (`top`) or bottom: its copper faces that side and it is not covered there.
759pub fn pad_mask_open(board: &Board, placement: &Placement, pad: &crate::board::Pad, top: bool) -> bool {
760    let side = if top { 0 } else { board.layer_count - 1 };
761    let (from, to) = placement.pad_layers(pad, board.layer_count);
762    // A one-layer board's bottom is layer 0 too: only a drilled pad reaches it.
763    let reaches = ((from..=to).contains(&side) && (top || side != 0)) || (!top && pad.drill.is_some());
764    reaches && !covered(pad, placement.front_faces(top))
765}
766fn covered(pad: &crate::board::Pad, front: bool) -> bool {
767    if front { pad.layers.cover_front } else { pad.layers.cover_back }
768}
769
770/// Stencil apertures for surface-mount pads on one side, grown by each pad's
771/// paste margin (0 unless set; negative shrinks the aperture).
772fn paste(board: &Board, origin: &Origin, top: bool) -> Gerber {
773    let last = board.layer_count - 1;
774    let mut gerber = Gerber::default();
775    for placement in &board.placements {
776        for pad in placement
777            .footprint
778            .pads
779            .iter()
780            .filter(|p| p.drill.is_none() && !p.layers.no_paste)
781        {
782            let (layer, _) = placement.pad_layers(pad, board.layer_count);
783            if (top && layer == 0) || (!top && last != 0 && layer == last) {
784                for shape in placement.pad_paste(pad) {
785                    gerber.shape(origin, shape, 0, None);
786                }
787            }
788        }
789    }
790    gerber
791}
792
793/// Footprint outlines and reference designators for parts on one side.
794fn legend(
795    document: &Document,
796    origin: &Origin,
797    top: bool,
798    unsupported: &mut BTreeSet<char>,
799) -> Gerber {
800    let mut gerber = Gerber::default();
801    let layer = if top { GraphicLayer::FrontSilk } else { GraphicLayer::BackSilk };
802    // What is drawn on the board itself, then each part's own.
803    for (width, filled, strokes) in document.board.drawing_on(layer) {
804        ink(&mut gerber, origin, width, filled, &strokes);
805    }
806    for placement in &document.board.placements {
807        // Every drawn item on this side's silkscreen, the part's own `silk`
808        // lines among them: a filled shape is a region, outlined by its pen.
809        for (width, filled, strokes) in placement.drawing_on(layer) {
810            ink(&mut gerber, origin, width, filled, &strokes);
811        }
812        if placement.bottom == top {
813            continue;
814        }
815        let Some(component) = document
816            .components
817            .iter()
818            .find(|c| c.id == placement.component)
819        else {
820            continue;
821        };
822        let (min, max) = placement.courtyard();
823        let anchor = Point::new(
824            ((i64::from(min.x) + i64::from(max.x)) / 2) as i32,
825            min.y - SILK_WIDTH,
826        );
827        for stroke in crate::font::text_strokes(&component.reference, anchor, TEXT_HEIGHT, !top, unsupported) {
828            gerber.select(Aperture::Circle(SILK_WIDTH), None);
829            gerber.stroke(stroke.iter().map(|p| origin.point(*p)));
830        }
831    }
832    gerber
833}
834
835/// One drawn item's centre lines on a legend film: a filled shape is a region
836/// (with no pen, the region alone), outlined by its pen.
837fn ink(gerber: &mut Gerber, origin: &Origin, width: i32, filled: bool, strokes: &[Vec<Point>]) {
838    for line in strokes {
839        gerber.select(Aperture::Circle(width.max(1)), None);
840        if filled && line.len() >= 4 {
841            gerber.body.push_str("G36*\n");
842            gerber.stroke(line.iter().map(|p| origin.point(*p)));
843            gerber.body.push_str("G37*\n");
844        }
845        if width > 0 {
846            gerber.stroke(line.iter().map(|p| origin.point(*p)));
847        }
848    }
849}
850
851#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
852enum Hole {
853    Via,
854    Component,
855}
856/// Drill hits grouped by (diameter, kind), in output coordinates.
857/// Holes by (tool diameter, kind): each a hit, or a slot routed from its first
858/// point to its second (equal for a round hole).
859type Drills = BTreeMap<(i32, Hole), Vec<((i64, i64), (i64, i64))>>;
860
861/// Plated through holes, unplated holes, and the blind and buried vias by
862/// their (top, bottom) copper layers.
863fn drills(board: &Board, origin: &Origin) -> (Drills, Drills, BTreeMap<(u8, u8), Drills>) {
864    let (mut plated, mut unplated) = (Drills::new(), Drills::new());
865    let mut spans: BTreeMap<(u8, u8), Drills> = BTreeMap::new();
866    for via in &board.all_vias() {
867        let at = origin.point(via.at);
868        let target = match via.kind(board.layer_count) {
869            crate::board::ViaKind::Through => &mut plated,
870            _ => spans.entry(via.layers(board.layer_count)).or_default(),
871        };
872        target.entry((via.drill, Hole::Via)).or_default().push((at, at));
873    }
874    for placement in &board.placements {
875        for pad in &placement.footprint.pads {
876            // A round hole is a capsule with its two centres together; a slot's
877            // tool is its width, routed between the two.
878            if let (Some(Shape::Capsule { a, b, radius }), Some(hole)) = (placement.pad_hole(pad), pad.hole_size()) {
879                let target = if pad.plated { &mut plated } else { &mut unplated };
880                // A round hole's tool is its drill, as always; a slot's is the width
881                // of the capsule every other check measures, so the drill file, the
882                // STEP and the ring agree to the micrometre.
883                let tool = if a == b { hole.x.min(hole.y) } else { 2 * radius };
884                target
885                    .entry((tool, Hole::Component))
886                    .or_default()
887                    .push((origin.point(a), origin.point(b)));
888            }
889        }
890    }
891    (plated, unplated, spans)
892}
893
894/// Excellon drill file in the XNC subset, with decimal millimetre coordinates.
895fn excellon(holes: &Drills, file_function: &str, plating: &str) -> String {
896    let mut out = String::from("M48\n");
897    let _ = writeln!(out, "; DRILL file {{eCAD {}}}", env!("CARGO_PKG_VERSION"));
898    out.push_str("; FORMAT={-:-/ absolute / metric / decimal}\n");
899    let _ = writeln!(
900        out,
901        "; #@! TF.GenerationSoftware,eCAD,Schematic and PCB Studio,{}",
902        env!("CARGO_PKG_VERSION")
903    );
904    let _ = writeln!(out, "; #@! TF.FileFunction,{file_function}");
905    out.push_str("FMAT,2\nMETRIC\n");
906    for (tool, (diameter, kind)) in holes.keys().enumerate() {
907        let kind = match kind {
908            Hole::Via => "ViaDrill",
909            Hole::Component => "ComponentDrill",
910        };
911        let _ = writeln!(out, "; #@! TA.AperFunction,{plating},{kind}");
912        let _ = writeln!(out, "T{}C{}", tool + 1, millimetres(*diameter));
913    }
914    // Absolute coordinates are the XNC default; readers reject G90 after the header.
915    out.push_str("%\nG05\n");
916    for (tool, hits) in holes.values().enumerate() {
917        let _ = writeln!(out, "T{}", tool + 1);
918        // Output coordinates are nanometres; drill files use micrometre precision.
919        let at = |(x, y): (i64, i64)| {
920            format!("X{}Y{}", millimetres(x.div_euclid(1000)), millimetres(y.div_euclid(1000)))
921        };
922        for (a, b) in hits {
923            if a == b {
924                let _ = writeln!(out, "{}", at(*a));
925            } else {
926                // A slot: the tool routed from one end centre to the other.
927                let _ = writeln!(out, "{}G85{}", at(*a), at(*b));
928            }
929        }
930    }
931    out.push_str("M30\n");
932    out
933}
934
935/// Bitwise CRC-32 (IEEE), as used by zip.
936pub fn crc32(bytes: &[u8]) -> u32 {
937    let mut crc = u32::MAX;
938    for &byte in bytes {
939        crc ^= u32::from(byte);
940        for _ in 0..8 {
941            crc = if crc & 1 == 1 {
942                (crc >> 1) ^ 0xEDB8_8320
943            } else {
944                crc >> 1
945            };
946        }
947    }
948    !crc
949}
950
951/// A zip archive with stored (uncompressed) entries and a fixed 1980-01-01
952/// timestamp, so identical inputs give identical archives.
953pub fn zip<'a>(entries: impl IntoIterator<Item = (&'a str, &'a [u8])>) -> Vec<u8> {
954    const DOS_DATE: u16 = (1 << 5) | 1;
955    let mut out = vec![];
956    let mut directory = vec![];
957    let mut count: u16 = 0;
958    let push16 = |v: &mut Vec<u8>, x: u16| v.extend_from_slice(&x.to_le_bytes());
959    let push32 = |v: &mut Vec<u8>, x: u32| v.extend_from_slice(&x.to_le_bytes());
960    for (name, data) in entries {
961        let offset = out.len() as u32;
962        let (crc, size, name_len) = (crc32(data), data.len() as u32, name.len() as u16);
963        for (record, signature) in [(&mut out, 0x0403_4b50), (&mut directory, 0x0201_4b50)] {
964            push32(record, signature);
965            if signature == 0x0201_4b50 {
966                push16(record, 20); // made by
967            }
968            push16(record, 10); // needed to extract
969            push16(record, 0); // flags
970            push16(record, 0); // stored
971            push16(record, 0); // time
972            push16(record, DOS_DATE);
973            push32(record, crc);
974            push32(record, size);
975            push32(record, size);
976            push16(record, name_len);
977            push16(record, 0); // extra
978            if signature == 0x0201_4b50 {
979                push16(record, 0); // comment
980                push16(record, 0); // disk
981                push16(record, 0); // internal attributes
982                push32(record, 0); // external attributes
983                push32(record, offset);
984            }
985            record.extend_from_slice(name.as_bytes());
986        }
987        out.extend_from_slice(data);
988        count += 1;
989    }
990    let (start, length) = (out.len() as u32, directory.len() as u32);
991    out.extend_from_slice(&directory);
992    push32(&mut out, 0x0605_4b50);
993    push16(&mut out, 0);
994    push16(&mut out, 0);
995    push16(&mut out, count);
996    push16(&mut out, count);
997    push32(&mut out, length);
998    push32(&mut out, start);
999    push16(&mut out, 0);
1000    out
1001}
1002
1003/// The entries of a zip archive, name and stored size, read from its central
1004/// directory in archive order. Empty when `archive` is not a zip this module
1005/// could have written (no end record, or a directory that runs off the end).
1006pub fn zip_entries(archive: &[u8]) -> Vec<(String, usize)> {
1007    let u16_at = |i: usize| -> Option<usize> {
1008        Some(u16::from_le_bytes(archive.get(i..i + 2)?.try_into().ok()?) as usize)
1009    };
1010    let u32_at = |i: usize| -> Option<usize> {
1011        Some(u32::from_le_bytes(archive.get(i..i + 4)?.try_into().ok()?) as usize)
1012    };
1013    let read = || -> Option<Vec<(String, usize)>> {
1014        let end = archive.len().checked_sub(22)?;
1015        if u32_at(end)? != 0x0605_4b50 {
1016            return None;
1017        }
1018        let mut entry = u32_at(end + 16)?;
1019        let mut out = vec![];
1020        for _ in 0..u16_at(end + 10)? {
1021            if u32_at(entry)? != 0x0201_4b50 {
1022                return None;
1023            }
1024            let name_len = u16_at(entry + 28)?;
1025            let name = archive.get(entry + 46..entry + 46 + name_len)?;
1026            out.push((String::from_utf8_lossy(name).into_owned(), u32_at(entry + 24)?));
1027            entry += 46 + name_len + u16_at(entry + 30)? + u16_at(entry + 32)?;
1028        }
1029        Some(out)
1030    };
1031    read().unwrap_or_default()
1032}