Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/pcb/padstacks/
resolve.rs

1//! Borrowed effective copper-shape facts, following KiCad 10.0.6 PAD/PADSTACK.
2//!
3//! This is source interpretation, not land membership, geometry realization,
4//! connectivity, board-side reflection, or downstream model construction.
5
6use super::*;
7
8/// Effective source-local shape and layer-local policy for one copper selector.
9/// Distances remain millimetres and angles remain KiCad degrees. A drill offset
10/// moves the copper shape, not the hole. No policy is inherited from a footprint
11/// or a design rule here; absence remains absence.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct PcbResolvedPadCopperLayer<'a> {
14    pub shape: &'a str,
15    pub size: PcbPoint,
16    pub offset: PcbPoint,
17    pub rect_delta: PcbPoint,
18    pub roundrect_rratio: f64,
19    pub chamfer_ratio: f64,
20    pub chamfer_corners: &'a [String],
21    pub anchor: &'a str,
22    pub custom_options: Option<&'a PcbPadCustomOptions>,
23    pub custom_primitives: &'a [PcbPadCustomPrimitive],
24    pub clearance: Option<f64>,
25    pub thermal_bridge_width: Option<f64>,
26    pub thermal_bridge_angle: f64,
27    pub thermal_gap: Option<f64>,
28    pub zone_connect: Option<i64>,
29}
30
31/// Resolve a copper shape without deciding whether copper is present there.
32///
33/// Accepts `F.Cu`, `B.Cu`, `InN.Cu`, and the front/inner/back selector `Inner`.
34/// Normal pads use their root shape everywhere. Explicit non-front stack rows
35/// start with KiCad's empty layer defaults, not copies of the root. Missing
36/// custom rows fall back to the root; missing front/inner/back rows follow
37/// KiCad's const lookup (inner row when available, otherwise root).
38///
39/// The sparse source DTO cannot recover arbitrary mutation order. Explicit
40/// front rows, duplicate rows, nonstandard front/inner/back aliases, missing
41/// modes, and unsupported selectors are rejected instead of guessed. Row-level
42/// thermal angles stay authored facts; the released reader does not apply them
43/// to their rows (see `explicit_row`).
44/// This helper targets modern, conventionally ordered source. It is not proof
45/// of pre-7 file migration or arbitrary reordered-field parity; those need a
46/// version-aware, ordered source interpretation beyond this sparse DTO.
47pub fn resolve_pad_copper_layer<'a>(
48    pad: &'a PcbPad,
49    layer: &str,
50) -> Result<PcbResolvedPadCopperLayer<'a>, Error> {
51    if !copper_selector(layer) {
52        return Err(unsupported(
53            "Expected a concrete copper layer or Inner selector",
54        ));
55    }
56    let Some(stack) = &pad.padstack else {
57        return Ok(root(pad));
58    };
59    let mode = stack
60        .mode
61        .as_deref()
62        .ok_or_else(|| unsupported("Padstack mode is absent"))?;
63    if !matches!(mode, "front_inner_back" | "custom") {
64        return Err(unsupported("Unsupported padstack mode"));
65    }
66    let mut seen = std::collections::HashSet::new();
67    for row in &stack.layers {
68        if !seen.insert(row.layer.as_str()) {
69            return Err(unsupported(
70                "Duplicate padstack rows require ordered source interpretation",
71            ));
72        }
73        if row.layer == "F.Cu" {
74            return Err(unsupported(
75                "Explicit F.Cu padstack rows require ordered source interpretation",
76            ));
77        }
78        let valid = if mode == "front_inner_back" {
79            matches!(row.layer.as_str(), "Inner" | "B.Cu")
80        } else {
81            row.layer != "Inner" && copper_selector(&row.layer)
82        };
83        if !valid {
84            return Err(unsupported(
85                "Unsupported padstack row selector for this mode",
86            ));
87        }
88    }
89    if layer == "F.Cu" {
90        return Ok(root(pad));
91    }
92    if mode == "custom" && layer == "Inner" {
93        return Err(unsupported(
94            "Custom padstacks require a concrete inner layer",
95        ));
96    }
97    let selector = if mode == "front_inner_back" && layer != "B.Cu" {
98        "Inner"
99    } else {
100        layer
101    };
102    let selected = stack
103        .layers
104        .iter()
105        .find(|row| row.layer == selector)
106        .or_else(|| {
107            (mode == "front_inner_back")
108                .then(|| stack.layers.iter().find(|row| row.layer == "Inner"))
109                .flatten()
110        });
111    Ok(selected.map_or_else(|| root(pad), explicit_row))
112}
113
114fn root(pad: &PcbPad) -> PcbResolvedPadCopperLayer<'_> {
115    let anchor = pad
116        .custom_options
117        .as_ref()
118        .and_then(|options| options.anchor.as_deref())
119        .unwrap_or("circle");
120    PcbResolvedPadCopperLayer {
121        shape: &pad.shape,
122        size: PcbPoint {
123            x: pad.size_x,
124            y: pad.size_y,
125        },
126        offset: pad.offset,
127        rect_delta: PcbPoint {
128            x: pad.rect_delta_x.unwrap_or(0.0),
129            y: pad.rect_delta_y.unwrap_or(0.0),
130        },
131        roundrect_rratio: pad.roundrect_rratio.unwrap_or(0.25),
132        chamfer_ratio: pad.chamfer_ratio.unwrap_or(0.2),
133        chamfer_corners: &pad.chamfer_corners,
134        anchor,
135        custom_options: pad.custom_options.as_ref(),
136        custom_primitives: &pad.custom_primitives,
137        clearance: pad.clearance,
138        thermal_bridge_width: pad.thermal_bridge_width,
139        thermal_bridge_angle: pad.thermal_bridge_angle.unwrap_or(
140            if pad.shape == "circle" || (pad.shape == "custom" && anchor == "circle") {
141                45.0
142            } else {
143                90.0
144            },
145        ),
146        thermal_gap: pad.thermal_gap,
147        zone_connect: pad.zone_connect.or(Some(-1)),
148    }
149}
150
151fn explicit_row(row: &PcbPadstackLayer) -> PcbResolvedPadCopperLayer<'_> {
152    let shape = row.shape.as_deref().unwrap_or("circle");
153    PcbResolvedPadCopperLayer {
154        shape,
155        size: row.size.unwrap_or(PcbPoint { x: 0.0, y: 0.0 }),
156        offset: row.offset.unwrap_or(PcbPoint { x: 0.0, y: 0.0 }),
157        rect_delta: row.rect_delta.unwrap_or(PcbPoint { x: 0.0, y: 0.0 }),
158        roundrect_rratio: row.roundrect_rratio.unwrap_or(0.0),
159        chamfer_ratio: row.chamfer_ratio.unwrap_or(0.0),
160        chamfer_corners: &row.chamfer_corners,
161        anchor: row
162            .custom_options
163            .as_ref()
164            .and_then(|options| options.anchor.as_deref())
165            .unwrap_or("rect"),
166        custom_options: row.custom_options.as_ref(),
167        custom_primitives: &row.custom_primitives,
168        clearance: row.clearance,
169        thermal_bridge_width: row.thermal_bridge_width,
170        // KiCad 10.0.6 parsePadstack calls SetThermalSpokeAngle without curLayer,
171        // temporarily writing F.Cu. parsePAD then assigns the root angle/default
172        // after reading the stack, overwriting that write. Non-front rows retain
173        // their shape defaults, not the authored row thermal_bridge_angle token.
174        thermal_bridge_angle: if matches!(shape, "oval" | "rect" | "roundrect")
175            || row.chamfer_ratio.is_some_and(|ratio| ratio > 0.0)
176            || !row.chamfer_corners.is_empty()
177        {
178            90.0
179        } else {
180            45.0
181        },
182        thermal_gap: row.thermal_gap,
183        zone_connect: row.zone_connect,
184    }
185}
186
187fn copper_selector(layer: &str) -> bool {
188    matches!(layer, "F.Cu" | "B.Cu" | "Inner")
189        || layer
190            .strip_prefix("In")
191            .and_then(|suffix| suffix.strip_suffix(".Cu"))
192            .and_then(|number| number.parse::<u8>().ok())
193            .is_some_and(|number| (1..=62).contains(&number))
194}
195
196fn unsupported(message: &'static str) -> Error {
197    Error::build(ErrorKind::InvalidBuildValue, message)
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    fn pad(stack: &str) -> PcbPad {
205        let source = format!(
206            r#"(kicad_pcb (version 20260206)
207          (footprint "test" (layer "F.Cu") (at 0 0)
208            (pad "1" thru_hole rect (at 0 0) (size 2 3)
209              (drill 0.8 (offset 0.2 -0.3)) (layers "*.Cu")
210              (clearance 0.4) (thermal_bridge_angle 90) {stack})))"#
211        );
212        let view = PcbView::parse(&source, PcbLimits::default()).expect("source");
213        view.pads().next().expect("pad").expect("typed pad")
214    }
215
216    #[test]
217    fn copper_layer_defaults_fallbacks_and_sparse_rows_are_source_owned() {
218        let normal = pad("");
219        let root = resolve_pad_copper_layer(&normal, "B.Cu").unwrap();
220        assert_eq!(root.size, PcbPoint { x: 2.0, y: 3.0 });
221        assert_eq!(root.offset, PcbPoint { x: 0.2, y: -0.3 });
222        assert_eq!(
223            (root.anchor, root.roundrect_rratio, root.chamfer_ratio),
224            ("circle", 0.25, 0.2)
225        );
226        let tib = pad(r#"(padstack (mode front_inner_back)
227            (layer "Inner" (shape oval) (size 1 2))
228            (layer "B.Cu" (size 0.6 0.6) (zone_connect -1)))"#);
229        let inner = resolve_pad_copper_layer(&tib, "In3.Cu").unwrap();
230        assert_eq!((inner.shape, inner.thermal_bridge_angle), ("oval", 90.0));
231        assert_eq!(inner.offset, PcbPoint { x: 0.0, y: 0.0 });
232        assert_eq!(inner.clearance, None);
233        assert_eq!(inner.zone_connect, None);
234        assert_eq!(inner.anchor, "rect");
235        assert_eq!(inner.roundrect_rratio, 0.0);
236        let back = resolve_pad_copper_layer(&tib, "B.Cu").unwrap();
237        assert_eq!(
238            (back.shape, back.thermal_bridge_angle, back.zone_connect),
239            ("circle", 45.0, Some(-1))
240        );
241        let missing_back = pad(r#"(padstack (mode front_inner_back) (layer "Inner" (size 1 1)))"#);
242        assert_eq!(
243            resolve_pad_copper_layer(&missing_back, "B.Cu")
244                .unwrap()
245                .size
246                .x,
247            1.0
248        );
249        let custom = pad(r#"(padstack (mode custom) (layer "In2.Cu" (shape rect)))"#);
250        assert_eq!(
251            resolve_pad_copper_layer(&custom, "In1.Cu").unwrap().size.x,
252            2.0
253        );
254        assert_eq!(
255            resolve_pad_copper_layer(&custom, "In2.Cu").unwrap().size.x,
256            0.0
257        );
258        assert_ambiguous_stacks_are_rejected();
259        assert_authored_row_angles_follow_released_reader();
260    }
261
262    fn assert_authored_row_angles_follow_released_reader() {
263        for (mode, inner) in [("custom", "In1.Cu"), ("front_inner_back", "Inner")] {
264            let mut source = pad(&format!(
265                r#"(padstack (mode {mode})
266                    (layer "{inner}" (shape circle) (size 1 1) (thermal_bridge_angle 13))
267                    (layer "B.Cu" (shape rect) (size 1 2) (thermal_bridge_angle 27)))"#
268            ));
269            source.shape = "circle".into();
270            source.thermal_bridge_angle = Some(61.0);
271            for (root_override, expected_front) in [(Some(61.0), 61.0), (None, 45.0)] {
272                source.thermal_bridge_angle = root_override;
273                for (layer, expected) in
274                    [("F.Cu", expected_front), ("In1.Cu", 45.0), ("B.Cu", 90.0)]
275                {
276                    assert_eq!(
277                        resolve_pad_copper_layer(&source, layer)
278                            .unwrap()
279                            .thermal_bridge_angle,
280                        expected
281                    );
282                }
283            }
284            let rows = &source.padstack.as_ref().unwrap().layers;
285            assert_eq!(rows[0].thermal_bridge_angle, Some(13.0));
286            assert_eq!(rows[1].thermal_bridge_angle, Some(27.0));
287        }
288    }
289
290    fn assert_ambiguous_stacks_are_rejected() {
291        for stack in [
292            r#"(padstack (mode custom) (layer "F.Cu" (size 1 1)))"#,
293            r#"(padstack (mode custom) (layer "B.Cu") (layer "B.Cu"))"#,
294        ] {
295            assert!(resolve_pad_copper_layer(&pad(stack), "F.Cu").is_err());
296        }
297    }
298}