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