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