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

kicad_monkey_core/pcb/
pads.rs

1//! Detailed embedded-footprint pad inputs for native readers and plotters.
2
3use super::*;
4mod custom;
5pub use custom::{PcbPadPolygonPoint, PcbPadPrimitiveGeometry};
6
7/// Custom-pad clearance and anchor policy.
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct PcbPadCustomOptions {
10    pub clearance: Option<String>,
11    pub anchor: Option<String>,
12    pub source_range: Range<usize>,
13}
14
15/// One source-local custom-pad primitive, with policy declaration evidence.
16#[derive(Clone, Debug, PartialEq)]
17pub struct PcbPadCustomPrimitive {
18    pub kind: String,
19    /// Compatibility XY projection of `pts`; use geometry for complete polygons
20    /// containing arcs and for non-polygon primitives.
21    pub points: Vec<PcbPoint>,
22    /// None marks an unsupported or incomplete geometry, not an empty shape.
23    pub geometry: Option<PcbPadPrimitiveGeometry>,
24    pub width: Option<f64>,
25    pub fill: Option<String>,
26    pub source_range: Range<usize>,
27}
28
29/// One typed footprint pad in board source order.
30#[derive(Clone, Debug, PartialEq)]
31pub struct PcbPad {
32    pub owner: PcbFootprintMemberOwner,
33    /// Compatibility index for board consumers; zero for standalone records.
34    /// Prefer `owner` when distinguishing document scope.
35    pub footprint_index: usize,
36    pub number: String,
37    pub kind: String,
38    pub shape: String,
39    pub at_x: f64,
40    pub at_y: f64,
41    pub angle: f64,
42    pub size_x: f64,
43    pub size_y: f64,
44    pub drill: Option<PcbPadDrill>,
45    /// The pad shape's offset from its position (`(drill (offset x y))`),
46    /// stated with or without a drill size; zero when absent.
47    pub offset: PcbPoint,
48    /// Drill plating when a drill is authored; `None` for undrilled pads.
49    pub plated: Option<bool>,
50    /// Whether a direct `(layers ...)` declaration is present, including an
51    /// explicitly empty `(layers)`. This is source evidence, not an effective
52    /// layer mask: absent declarations do not synthesize entries in `layers`.
53    pub has_layers: bool,
54    pub layers: Vec<String>,
55    pub net: PcbNetRef,
56    pub uuid: Option<String>,
57    pub pin_function: Option<String>,
58    pub pin_type: Option<String>,
59    pub die_length: Option<f64>,
60    pub rect_delta_x: Option<f64>,
61    pub rect_delta_y: Option<f64>,
62    pub roundrect_rratio: Option<f64>,
63    pub chamfer_ratio: Option<f64>,
64    pub chamfer_corners: Vec<String>,
65    pub solder_mask_margin: Option<f64>,
66    pub solder_paste_margin: Option<f64>,
67    pub solder_paste_margin_ratio: Option<f64>,
68    pub clearance: Option<f64>,
69    pub thermal_bridge_width: Option<f64>,
70    pub thermal_bridge_angle: Option<f64>,
71    pub thermal_gap: Option<f64>,
72    pub zone_connect: Option<i64>,
73    pub remove_unused_layers: Option<bool>,
74    pub keep_end_layers: Option<bool>,
75    pub teardrops: Option<PcbTeardropParameters>,
76    pub backdrill: Option<PcbDrillProperties>,
77    pub tertiary_drill: Option<PcbDrillProperties>,
78    pub front_post_machining: Option<PcbPostMachiningProperties>,
79    pub back_post_machining: Option<PcbPostMachiningProperties>,
80    pub zone_layer_connections: Option<PcbZoneLayerConnections>,
81    pub custom_options: Option<PcbPadCustomOptions>,
82    pub custom_primitives: Vec<PcbPadCustomPrimitive>,
83    pub padstack: Option<PcbPadstack>,
84    pub source_range: Range<usize>,
85}
86
87impl PcbPad {
88    /// Whether pcbnew plots no copper for this NPTH pad because its hole
89    /// covers it: a circle on a round hole at least as wide or an oval on an
90    /// oblong hole at least as large, centred on the hole, or a circle or
91    /// oval exactly the hole's size. Its mask and hole are still drawn.
92    pub fn npth_hole_covers_copper(&self) -> bool {
93        let hole = self
94            .drill
95            .as_ref()
96            .map(|drill| crate::plotter_ir::NpthHole {
97                oblong: drill.shape == PcbHoleShape::Oval,
98                size_mm: [drill.width, drill.height.unwrap_or(drill.width)],
99                pad_offset_mm: [self.offset.x, self.offset.y],
100            });
101        crate::plotter_ir::npth_flash_is_suppressed(
102            &self.kind,
103            &self.shape,
104            [self.size_x, self.size_y],
105            hole,
106        )
107    }
108}
109
110pub(super) fn pad_from_span(
111    source: &str,
112    indexed: &IndexedNestedForm,
113    limits: PcbLimits,
114) -> Result<PcbPad, Error> {
115    let header = bounded_scalar_values(source, &indexed.span, limits.max_pad_header_scalars)?;
116    let children = direct_children(source, &indexed.span, limits.max_pad_children, limits)?;
117    let (at, size) = pad_placement(source, &children, limits)?;
118    let (rect_delta_x, rect_delta_y) = optional_complete_pair(source, &children, "rect_delta")?;
119    let kind = required_string(header.get(1), "Expected pad kind", &indexed.span)?;
120    let (drill, plated) = pad_drill_and_plating(source, &children, &kind, limits)?;
121    let custom = custom_pad_fields(source, &children, limits)?;
122    Ok(PcbPad {
123        owner: PcbFootprintMemberOwner::EmbeddedFootprint {
124            footprint_index: indexed.parent_index,
125        },
126        footprint_index: indexed.parent_index,
127        number: required_string(header.first(), "Expected pad number", &indexed.span)?,
128        kind,
129        shape: required_string(header.get(2), "Expected pad shape", &indexed.span)?,
130        at_x: at[0],
131        at_y: at[1],
132        angle: at[2],
133        size_x: size[0],
134        size_y: size[1],
135        drill,
136        offset: physical::pad_offset_from_children(source, &children, limits)?,
137        plated,
138        has_layers: child(&children, "layers").is_some(),
139        layers: child_strings(source, &children, "layers", limits.max_layers)?,
140        net: bounded_child_net_ref(source, &children, limits.max_pad_header_scalars)?,
141        uuid: optional_uuid(source, &children)?,
142        pin_function: optional_child_string(source, &children, "pinfunction")?,
143        pin_type: optional_child_string(source, &children, "pintype")?,
144        die_length: optional_child_f64(source, &children, "die_length")?,
145        rect_delta_x,
146        rect_delta_y,
147        roundrect_rratio: optional_child_f64(source, &children, "roundrect_rratio")?,
148        chamfer_ratio: optional_child_f64(source, &children, "chamfer_ratio")?,
149        chamfer_corners: child_strings(
150            source,
151            &children,
152            "chamfer",
153            limits.max_pad_chamfer_corners,
154        )?,
155        solder_mask_margin: optional_child_f64(source, &children, "solder_mask_margin")?,
156        solder_paste_margin: optional_child_f64(source, &children, "solder_paste_margin")?,
157        solder_paste_margin_ratio: optional_child_f64(
158            source,
159            &children,
160            "solder_paste_margin_ratio",
161        )?,
162        clearance: tolerant_optional_child_f64(source, &children, "clearance")?,
163        thermal_bridge_width: optional_child_f64(source, &children, "thermal_bridge_width")?,
164        thermal_bridge_angle: optional_child_f64(source, &children, "thermal_bridge_angle")?,
165        thermal_gap: optional_child_f64(source, &children, "thermal_gap")?,
166        zone_connect: optional_child_i64(source, &children, "zone_connect")?,
167        remove_unused_layers: manufacturing::optional_presence_bool(
168            source,
169            &children,
170            "remove_unused_layers",
171        )?,
172        keep_end_layers: manufacturing::optional_presence_bool(
173            source,
174            &children,
175            "keep_end_layers",
176        )?,
177        teardrops: manufacturing::teardrop_parameters_from_children(source, &children, limits)?,
178        backdrill: manufacturing::drill_properties_from_children(
179            source,
180            &children,
181            "backdrill",
182            limits,
183        )?,
184        tertiary_drill: manufacturing::drill_properties_from_children(
185            source,
186            &children,
187            "tertiary_drill",
188            limits,
189        )?,
190        front_post_machining: manufacturing::post_machining_from_children(
191            source,
192            &children,
193            "front_post_machining",
194            limits,
195        )?,
196        back_post_machining: manufacturing::post_machining_from_children(
197            source,
198            &children,
199            "back_post_machining",
200            limits,
201        )?,
202        zone_layer_connections: manufacturing::zone_layer_connections_from_children(
203            source, &children, limits,
204        )?,
205        custom_options: custom.options,
206        custom_primitives: custom.primitives,
207        padstack: custom.stack,
208        source_range: indexed.span.range.clone(),
209    })
210}
211
212struct CustomPadFields {
213    options: Option<PcbPadCustomOptions>,
214    primitives: Vec<PcbPadCustomPrimitive>,
215    stack: Option<PcbPadstack>,
216}
217
218fn pad_placement(
219    source: &str,
220    children: &[FormSpan],
221    limits: PcbLimits,
222) -> Result<([f64; 3], [f64; 2]), Error> {
223    Ok((
224        optional_vector(
225            source,
226            children,
227            "at",
228            [0.0, 0.0, 0.0],
229            limits.max_pad_header_scalars,
230        )?,
231        optional_pair(source, children, "size", [0.0, 0.0])?,
232    ))
233}
234
235#[derive(Default)]
236pub(super) struct CustomPadBudget {
237    points: usize,
238    primitives: usize,
239}
240
241fn custom_pad_fields(
242    source: &str,
243    children: &[FormSpan],
244    limits: PcbLimits,
245) -> Result<CustomPadFields, Error> {
246    let mut budget = CustomPadBudget::default();
247    Ok(CustomPadFields {
248        options: custom_options_from_children(source, children, limits)?,
249        primitives: custom_primitives_from_children(source, children, limits, &mut budget)?,
250        stack: padstacks::padstack(source, children, limits, &mut budget)?,
251    })
252}
253
254fn pad_drill_and_plating(
255    source: &str,
256    children: &[FormSpan],
257    kind: &str,
258    limits: PcbLimits,
259) -> Result<(Option<PcbPadDrill>, Option<bool>), Error> {
260    let drill = physical::pad_drill_from_children(source, children, limits)?;
261    let plated = drill.as_ref().map(|_| kind != "np_thru_hole");
262    Ok((drill, plated))
263}
264
265fn optional_complete_pair(
266    source: &str,
267    children: &[FormSpan],
268    head: &str,
269) -> Result<(Option<f64>, Option<f64>), Error> {
270    let Some(span) = child(children, head) else {
271        return Ok((None, None));
272    };
273    let values = first_two_scalar_values(source, span)?;
274    let [x, y] = values.as_slice() else {
275        return Ok((None, None));
276    };
277    Ok((Some(parse_f64(x, span)?), Some(parse_f64(y, span)?)))
278}
279
280fn tolerant_optional_child_f64(
281    source: &str,
282    children: &[FormSpan],
283    head: &str,
284) -> Result<Option<f64>, Error> {
285    let Some(span) = child(children, head) else {
286        return Ok(None);
287    };
288    Ok(first_string(source, span)?.and_then(|value| value.parse().ok()))
289}
290
291pub(super) fn custom_options_from_children(
292    source: &str,
293    children: &[FormSpan],
294    limits: PcbLimits,
295) -> Result<Option<PcbPadCustomOptions>, Error> {
296    let Some(options) = child(children, "options") else {
297        return Ok(None);
298    };
299    let fields = direct_children(source, options, limits.max_pad_children, limits)?;
300    Ok(Some(PcbPadCustomOptions {
301        clearance: optional_child_string(source, &fields, "clearance")?
302            .filter(|value| !value.is_empty()),
303        anchor: optional_child_string(source, &fields, "anchor")?.filter(|value| !value.is_empty()),
304        source_range: options.range.clone(),
305    }))
306}
307
308pub(super) fn custom_primitives_from_children(
309    source: &str,
310    children: &[FormSpan],
311    limits: PcbLimits,
312    budget: &mut CustomPadBudget,
313) -> Result<Vec<PcbPadCustomPrimitive>, Error> {
314    let Some(primitives) = child(children, "primitives") else {
315        return Ok(Vec::new());
316    };
317    let forms = direct_children(
318        source,
319        primitives,
320        limits
321            .max_pad_custom_primitives
322            .saturating_sub(budget.primitives),
323        limits,
324    )?;
325    budget.primitives += forms.len();
326    forms
327        .into_iter()
328        .map(|primitive| custom_primitive_from_span(source, primitive, limits, &mut budget.points))
329        .collect()
330}
331
332fn custom_primitive_from_span(
333    source: &str,
334    primitive: FormSpan,
335    limits: PcbLimits,
336    point_count: &mut usize,
337) -> Result<PcbPadCustomPrimitive, Error> {
338    let fields = direct_children(source, &primitive, limits.max_pad_children, limits)?;
339    let (points, geometry) =
340        custom::primitive_geometry(source, &primitive, &fields, limits, point_count)?;
341    Ok(PcbPadCustomPrimitive {
342        kind: primitive.head.clone().unwrap_or_default(),
343        points,
344        geometry,
345        width: custom_primitive_width(source, &fields, limits)?,
346        fill: optional_child_string(source, &fields, "fill")?,
347        source_range: primitive.range,
348    })
349}
350
351fn custom_primitive_width(
352    source: &str,
353    fields: &[FormSpan],
354    limits: PcbLimits,
355) -> Result<Option<f64>, Error> {
356    // Custom primitives use KiCad's PCB_SHAPE grammar: both legacy width and
357    // modern nested stroke are accepted. Only a width token updates the running
358    // stroke; a later style-only block does not reset a previous width.
359    let mut width = None;
360    for field in fields {
361        match field.head.as_deref() {
362            Some("width") => {
363                width = optional_child_f64(source, std::slice::from_ref(field), "width")?;
364            }
365            Some("stroke") => {
366                for child in direct_children(source, field, limits.max_object_children, limits)? {
367                    if child.head.as_deref() == Some("width") {
368                        width = optional_child_f64(source, std::slice::from_ref(&child), "width")?;
369                    }
370                }
371            }
372            _ => {}
373        }
374    }
375    Ok(width)
376}