1use crate::FabViewData;
13use crate::diodes::{DiodeOptions, ResolvedDiode, resolve_diodes};
14use crate::geom::{
15 AreaKind, AreaShape, CoordNm, FabArea, FabComponent, FabLand, FabLayerItems, FabStroke,
16 LayerSide, Placement2D, StrokeKind, StrokePath, mm_to_nm,
17};
18use crate::passives::{
19 designator_prefix, is_suppress_token, match_pin_list_ci, pad_min_dim_nm, param_ci,
20 resolve_capacitor, resolve_inductor,
21};
22use crate::view::text::realize_stroke_label;
23use std::collections::{HashMap, HashSet};
24
25const MIN_DOT_FLOOR_NM: i64 = 10_000;
26const MIN_LABEL_HEIGHT_MM: f64 = 0.08;
27const MAX_LABEL_HEIGHT_MM: f64 = 2.00;
28const LABEL_FILL_RATIO: f64 = 0.62;
29
30#[derive(Clone, Debug, Default)]
32pub struct Pin1Override {
33 pub enabled: Option<bool>,
34 pub pad: Option<String>,
35}
36
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub enum Pin1Role {
40 Dot,
41 GridPad,
42 DiodeA,
43 DiodeK,
44 PolarityPos,
45 PolarityNeg,
46}
47
48#[derive(Clone, Debug)]
50pub struct Pin1Marker {
51 pub component_id: String,
52 pub designator: String,
53 pub pin: String,
54 pub role: Pin1Role,
55 pub dot_diameter_mm: Option<f64>,
56 pub items: FabLayerItems,
57}
58
59#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
61pub enum PadLabelOrientation {
62 #[default]
64 Pad,
65 Orthogonal,
67 Upright,
69}
70
71#[derive(Clone, Debug)]
73pub struct Pin1Options {
74 pub diode_ak_labels: bool,
75 pub cap_polarity_labels: bool,
76 pub inductor_polarity_markers: bool,
77 pub exclude_single_pin: bool,
78 pub exclude_prefixes: Vec<String>,
79 pub exclude_two_pin_prefixes: Vec<String>,
80 pub grid_pad_fill: bool,
81 pub fixed_dot_diameter_mm: Option<f64>,
82 pub min_dot_diameter_mm: f64,
83 pub max_dot_diameter_mm: f64,
84 pub label_orientation: PadLabelOrientation,
85 pub diode_options: DiodeOptions,
86 pub overrides: HashMap<String, Pin1Override>,
88}
89
90impl Default for Pin1Options {
91 fn default() -> Self {
92 Self {
93 diode_ak_labels: true,
94 cap_polarity_labels: true,
95 inductor_polarity_markers: true,
96 exclude_single_pin: true,
97 exclude_prefixes: vec![
98 "R".to_owned(),
99 "C".to_owned(),
100 "L".to_owned(),
101 "F".to_owned(),
102 "FB".to_owned(),
103 "FU".to_owned(),
104 "SW".to_owned(),
105 ],
106 exclude_two_pin_prefixes: vec!["X".to_owned(), "Y".to_owned()],
107 grid_pad_fill: true,
108 fixed_dot_diameter_mm: None,
109 min_dot_diameter_mm: 0.40,
110 max_dot_diameter_mm: 0.90,
111 label_orientation: PadLabelOrientation::Pad,
112 diode_options: DiodeOptions::default(),
113 overrides: HashMap::new(),
114 }
115 }
116}
117
118#[must_use]
120pub fn build_pin1_markers(
121 view: &FabViewData,
122 side: LayerSide,
123 opts: &Pin1Options,
124) -> Vec<Pin1Marker> {
125 let layer_key = if side == LayerSide::Bottom {
126 "BOTTOM"
127 } else {
128 "TOP"
129 };
130 let Some(layer_items) = view.layers_items.get(layer_key) else {
131 return Vec::new();
132 };
133 let mirrored = side == LayerSide::Bottom;
134 let lands_by_comp = index_lands(layer_items);
135 let holes_by_comp = index_holes(view);
136 let diodes_by_comp: HashMap<String, ResolvedDiode> = if opts.diode_ak_labels {
137 resolve_diodes(view, side, &opts.diode_options)
138 .into_iter()
139 .map(|d| (d.component_id.clone(), d))
140 .collect()
141 } else {
142 HashMap::new()
143 };
144
145 let mut markers = Vec::new();
146 for comp in &view.components {
147 if comp.side != side || !comp.fitted || comp.board_only {
148 continue;
149 }
150 let Some(comp_lands) = lands_by_comp.get(comp.id.as_str()) else {
151 continue;
152 };
153 let comp_holes = holes_by_comp.get(comp.id.as_str());
154 emit_component_pin1(
155 comp,
156 comp_lands,
157 comp_holes,
158 diodes_by_comp.get(&comp.id),
159 mirrored,
160 opts,
161 &mut markers,
162 );
163 }
164 markers
165}
166
167#[must_use]
169pub fn build_pin1_layer(view: &FabViewData, side: LayerSide, opts: &Pin1Options) -> FabLayerItems {
170 let mut out = FabLayerItems::default();
171 for marker in build_pin1_markers(view, side, opts) {
172 out.lands.extend(marker.items.lands);
173 out.strokes.extend(marker.items.strokes);
174 out.areas.extend(marker.items.areas);
175 }
176 out
177}
178
179fn emit_explicit_polarity_params(
180 comp: &FabComponent,
181 lands: &HashMap<String, Vec<&FabLand>>,
182 mirrored: bool,
183 opts: &Pin1Options,
184 out: &mut Vec<Pin1Marker>,
185) -> bool {
186 let pos_val = param_ci(comp, "POSITIVE_PAD").filter(|p| !is_suppress_token(p));
187 let neg_val = param_ci(comp, "NEGATIVE_PAD").filter(|n| !is_suppress_token(n));
188 if pos_val.is_none() && neg_val.is_none() {
189 return false;
190 }
191 let mut pos_pins = pos_val
192 .map(|p| match_pin_list_ci(&comp.pins, p))
193 .unwrap_or_default();
194 let mut neg_pins = neg_val
195 .map(|n| match_pin_list_ci(&comp.pins, n))
196 .unwrap_or_default();
197 if comp.pins.len() == 2 {
198 if pos_pins.is_empty() && !neg_pins.is_empty() {
199 pos_pins = comp
200 .pins
201 .iter()
202 .filter(|p| !neg_pins.iter().any(|n| n.eq_ignore_ascii_case(p)))
203 .cloned()
204 .collect();
205 } else if neg_pins.is_empty() && !pos_pins.is_empty() {
206 neg_pins = comp
207 .pins
208 .iter()
209 .filter(|p| !pos_pins.iter().any(|pp| pp.eq_ignore_ascii_case(p)))
210 .cloned()
211 .collect();
212 }
213 }
214 for p in &pos_pins {
215 emit_pad_label_marker(
216 comp,
217 lands,
218 p,
219 "+",
220 Pin1Role::PolarityPos,
221 mirrored,
222 opts.label_orientation,
223 out,
224 );
225 }
226 for n in &neg_pins {
227 emit_pad_label_marker(
228 comp,
229 lands,
230 n,
231 "-",
232 Pin1Role::PolarityNeg,
233 mirrored,
234 opts.label_orientation,
235 out,
236 );
237 }
238 true
239}
240
241fn emit_component_pin1(
242 comp: &FabComponent,
243 lands: &HashMap<String, Vec<&FabLand>>,
244 holes: Option<&HashMap<String, i64>>,
245 diode: Option<&ResolvedDiode>,
246 mirrored: bool,
247 opts: &Pin1Options,
248 out: &mut Vec<Pin1Marker>,
249) {
250 let override_entry = opts
251 .overrides
252 .get(&comp.designator.trim().to_ascii_uppercase())
253 .or_else(|| opts.overrides.get(comp.designator.trim()));
254 if override_entry.is_some_and(|ov| ov.enabled == Some(false)) {
255 return;
256 }
257 if let Some(ov_pad) = override_entry.and_then(|ov| ov.pad.as_deref()) {
258 if !is_suppress_token(ov_pad) {
259 emit_dot_or_pad_marker(comp, lands, holes, ov_pad, opts, out);
260 }
261 return;
262 }
263 let explicit_opt_in = override_entry.is_some_and(|ov| ov.enabled == Some(true));
264
265 if emit_explicit_polarity_params(comp, lands, mirrored, opts, out) {
267 return;
268 }
269
270 if let Some(p1) = param_ci(comp, "PIN1_PAD") {
272 if !is_suppress_token(p1) {
273 emit_dot_or_pad_marker(comp, lands, holes, p1, opts, out);
274 }
275 return;
276 }
277
278 if opts.inductor_polarity_markers
280 && let Some(ind) = resolve_inductor(comp)
281 && ind.polarized
282 && let Some(pin) = ind.polarity_pins.first()
283 {
284 emit_dot_or_pad_marker(comp, lands, holes, pin, opts, out);
285 return;
286 }
287
288 if let Some(d) = diode {
290 for pin in &d.anode_pins {
291 emit_pad_label_marker(
292 comp,
293 lands,
294 pin,
295 "A",
296 Pin1Role::DiodeA,
297 mirrored,
298 opts.label_orientation,
299 out,
300 );
301 }
302 for pin in &d.cathode_pins {
303 emit_pad_label_marker(
304 comp,
305 lands,
306 pin,
307 "K",
308 Pin1Role::DiodeK,
309 mirrored,
310 opts.label_orientation,
311 out,
312 );
313 }
314 return;
315 }
316
317 if opts.cap_polarity_labels
319 && let Some(cap) = resolve_capacitor(comp)
320 && cap.polarized
321 {
322 for pin in &cap.positive_pins {
323 emit_pad_label_marker(
324 comp,
325 lands,
326 pin,
327 "+",
328 Pin1Role::PolarityPos,
329 mirrored,
330 opts.label_orientation,
331 out,
332 );
333 }
334 for pin in &cap.negative_pins {
335 emit_pad_label_marker(
336 comp,
337 lands,
338 pin,
339 "-",
340 Pin1Role::PolarityNeg,
341 mirrored,
342 opts.label_orientation,
343 out,
344 );
345 }
346 return;
347 }
348
349 emit_generic_pin1(comp, lands, holes, explicit_opt_in, opts, out);
351}
352
353fn emit_generic_pin1(
354 comp: &FabComponent,
355 lands: &HashMap<String, Vec<&FabLand>>,
356 holes: Option<&HashMap<String, i64>>,
357 explicit_opt_in: bool,
358 opts: &Pin1Options,
359 out: &mut Vec<Pin1Marker>,
360) {
361 let prefix = designator_prefix(&comp.designator);
362 if !explicit_opt_in
363 && opts
364 .exclude_prefixes
365 .iter()
366 .any(|p| p.eq_ignore_ascii_case(&prefix))
367 {
368 return;
369 }
370 if opts.exclude_single_pin && comp.pins.len() < 2 && !explicit_opt_in {
371 return;
372 }
373 if !explicit_opt_in
374 && comp.pins.len() == 2
375 && opts
376 .exclude_two_pin_prefixes
377 .iter()
378 .any(|p| p.eq_ignore_ascii_case(&prefix))
379 {
380 return;
381 }
382 if let Some(pin) = choose_pin1_designator(&comp.pins, &prefix) {
383 emit_dot_or_pad_marker(comp, lands, holes, &pin, opts, out);
384 }
385}
386
387const PAD_ELONGATION_MIN_RATIO: f64 = 0.80;
388
389fn upright_angle_deg(angle_deg: f64) -> f64 {
390 let mut norm = (angle_deg + 90.0).rem_euclid(180.0) - 90.0;
391 if (norm + 90.0).abs() <= 1e-6 {
392 norm = 90.0;
393 }
394 if norm.abs() <= 1e-6 { 0.0 } else { norm }
395}
396
397fn nearly_square_primary_angle_deg(e0: f64, a0: f64, e1: f64, a1: f64) -> Option<f64> {
398 let best = if (a0.abs() - a1.abs()).abs() <= 1e-3 {
399 if (e0 - e1).abs() > 1.0 {
400 if e0 >= e1 { a0 } else { a1 }
401 } else if a0 >= a1 {
402 a0
403 } else {
404 a1
405 }
406 } else if a0.abs() <= a1.abs() {
407 a0
408 } else {
409 a1
410 };
411 (best.abs() > 1e-3).then_some(best)
412}
413
414fn component_oblique_angle_deg(comp: &FabComponent) -> Option<f64> {
415 let norm = upright_angle_deg(comp.rotation_deg);
416 if norm.abs() <= 1e-3 || (norm.abs() - 90.0).abs() <= 1e-3 {
417 None
418 } else {
419 Some(norm)
420 }
421}
422
423fn land_primary_angle_deg(land: &FabLand) -> Option<f64> {
424 let ang = land.placement.angle_deg;
425 match &land.shape {
426 AreaShape::Disk { .. } | AreaShape::Region { .. } => None,
427 AreaShape::Rect { width, height }
428 | AreaShape::RoundedRect { width, height, .. }
429 | AreaShape::ChamferedRect { width, height, .. }
430 | AreaShape::Trapezoid { width, height, .. } => {
431 let e0 = (*width).abs() as f64;
432 let e1 = (*height).abs() as f64;
433 let max_e = e0.max(e1);
434 if max_e <= 1.0 {
435 return None;
436 }
437 if e0.min(e1) / max_e >= PAD_ELONGATION_MIN_RATIO {
438 let a0 = upright_angle_deg(ang);
439 let a1 = upright_angle_deg(ang + 90.0);
440 return nearly_square_primary_angle_deg(e0, a0, e1, a1);
441 }
442 Some(upright_angle_deg(if e0 >= e1 { ang } else { ang + 90.0 }))
443 }
444 AreaShape::Capsule { length, width } => {
445 let span = (*length - *width).max(0) as f64;
446 if span <= 1.0 {
447 return None;
448 }
449 let r = (*width as f64) * 0.5;
450 let a = upright_angle_deg(ang);
451 if span <= 0.5 * r && (a.abs() <= 1e-3 || (a.abs() - 90.0).abs() <= 1e-3) {
452 None
453 } else {
454 Some(a)
455 }
456 }
457 }
458}
459
460fn polarity_label_angle_deg(
461 comp: &FabComponent,
462 land: &FabLand,
463 orientation: PadLabelOrientation,
464) -> f64 {
465 if orientation != PadLabelOrientation::Pad {
466 return 0.0;
467 }
468 if let Some(comp_ang) = component_oblique_angle_deg(comp) {
469 return comp_ang;
470 }
471 if let Some(pad_ang) = land_primary_angle_deg(land)
472 && pad_ang.abs() > 1e-3
473 && (pad_ang.abs() - 90.0).abs() > 1e-3
474 {
475 return pad_ang;
476 }
477 0.0
478}
479
480#[allow(
481 clippy::too_many_arguments,
482 reason = "pad-label marker helper takes explicit placement/orientation/output context"
483)]
484fn emit_pad_label_marker(
485 comp: &FabComponent,
486 lands: &HashMap<String, Vec<&FabLand>>,
487 pin: &str,
488 label: &str,
489 role: Pin1Role,
490 mirrored: bool,
491 orientation: PadLabelOrientation,
492 out: &mut Vec<Pin1Marker>,
493) {
494 let Some(pad_list) = lands.get(&pin.trim().to_ascii_uppercase()) else {
495 return;
496 };
497 for land in pad_list {
498 let min_dim_mm = pad_min_dim_nm(land) as f64 / 1e6;
499 let raw_height_mm = min_dim_mm * LABEL_FILL_RATIO;
500 if raw_height_mm < MIN_LABEL_HEIGHT_MM {
501 continue;
502 }
503 let height_mm = raw_height_mm.min(MAX_LABEL_HEIGHT_MM);
504 let center = CoordNm::new(land.placement.tx, land.placement.ty);
505 let stroke_w = (height_mm * 0.16).clamp(0.03, 0.16);
506 let angle_deg = polarity_label_angle_deg(comp, land, orientation);
507 let (polylines, width_nm) = realize_stroke_label(
508 label,
509 center,
510 height_mm,
511 angle_deg,
512 mirrored,
513 Some(stroke_w),
514 );
515 let mut items = FabLayerItems::default();
516 for pl in polylines {
517 for pair in pl.windows(2) {
518 items.strokes.push(FabStroke {
519 kind: StrokeKind::Virtual,
520 path: StrokePath::Line {
521 start: pair[0],
522 end: pair[1],
523 },
524 width: width_nm,
525 net: None,
526 component: Some(comp.id.clone()),
527 source: land.source.clone(),
528 });
529 }
530 }
531 if !items.is_empty() {
532 out.push(Pin1Marker {
533 component_id: comp.id.clone(),
534 designator: comp.designator.clone(),
535 pin: pin.to_owned(),
536 role,
537 dot_diameter_mm: None,
538 items,
539 });
540 }
541 }
542}
543
544fn emit_dot_or_pad_marker(
545 comp: &FabComponent,
546 lands: &HashMap<String, Vec<&FabLand>>,
547 holes: Option<&HashMap<String, i64>>,
548 pin: &str,
549 opts: &Pin1Options,
550 out: &mut Vec<Pin1Marker>,
551) {
552 let key = pin.trim().to_ascii_uppercase();
553 let Some(pad_list) = lands.get(&key) else {
554 return;
555 };
556 let min_r = mm_to_nm(opts.min_dot_diameter_mm / 2.0).max(MIN_DOT_FLOOR_NM);
557 let max_r = mm_to_nm(opts.max_dot_diameter_mm / 2.0).max(min_r);
558 let is_grid = is_grid_pad_designator(pin);
559
560 for land in pad_list {
561 let mut items = FabLayerItems::default();
562 let hole_r = holes.and_then(|h| h.get(&key).copied()).map(|dia| dia / 2);
563 let (role, dot_dia) = if hole_r.is_none() && is_grid && opts.grid_pad_fill {
564 items.areas.push(FabArea {
565 kind: AreaKind::Virtual,
566 shape: land.shape.clone(),
567 placement: land.placement,
568 net: None,
569 component: Some(comp.id.clone()),
570 source: land.source.clone(),
571 });
572 (Pin1Role::GridPad, None)
573 } else {
574 let radius = if let Some(fixed_d) = opts.fixed_dot_diameter_mm {
575 mm_to_nm(fixed_d / 2.0).max(MIN_DOT_FLOOR_NM)
576 } else if let Some(hr) = hole_r {
577 hr.max(min_r)
578 } else {
579 let scaled = ((pad_min_dim_nm(land) as f64) * 0.35).round() as i64;
580 scaled.clamp(min_r, max_r)
581 };
582 items.areas.push(FabArea {
583 kind: AreaKind::Virtual,
584 shape: AreaShape::Disk { radius },
585 placement: Placement2D::translate(land.placement.tx, land.placement.ty),
586 net: None,
587 component: Some(comp.id.clone()),
588 source: land.source.clone(),
589 });
590 (Pin1Role::Dot, Some(radius as f64 * 2.0 / 1e6))
591 };
592 out.push(Pin1Marker {
593 component_id: comp.id.clone(),
594 designator: comp.designator.clone(),
595 pin: pin.to_owned(),
596 role,
597 dot_diameter_mm: dot_dia,
598 items,
599 });
600 }
601}
602
603fn choose_pin1_designator(pins: &[String], prefix: &str) -> Option<String> {
604 if let Some(p) = pins.iter().find(|p| p.trim() == "1") {
605 return Some(p.clone());
606 }
607 if let Some(p) = pins.iter().find(|p| p.trim().eq_ignore_ascii_case("A1")) {
608 return Some(p.clone());
609 }
610 if matches!(prefix, "J" | "JP" | "P" | "CN" | "CON" | "HDR" | "USB") {
611 return None;
612 }
613 let parsed: Vec<(String, u32, &str)> = pins
614 .iter()
615 .filter_map(|pin| {
616 parse_grid_pin(pin).map(|(r, c)| (r.to_ascii_uppercase(), c, pin.as_str()))
617 })
618 .collect();
619 let other_rows: HashSet<&str> = parsed
620 .iter()
621 .map(|(r, _, _)| r.as_str())
622 .filter(|&r| r != "M")
623 .collect();
624 let mut best: Option<((u32, usize, String), &str)> = None;
625 for (row, col, raw_pin) in &parsed {
626 if row == "M" && other_rows.len() < 4 {
628 continue;
629 }
630 let key = (*col, grid_row_index(row), raw_pin.to_ascii_uppercase());
631 if best.as_ref().is_none_or(|(bk, _)| key < *bk) {
632 best = Some((key, *raw_pin));
633 }
634 }
635 best.map(|(_, p)| p.to_owned())
636}
637
638#[must_use]
641pub fn is_grid_pad_designator(pin: &str) -> bool {
642 parse_grid_pin(pin).is_some()
643}
644
645fn parse_grid_pin(pin: &str) -> Option<(&str, u32)> {
646 let trimmed = pin.trim();
647 let split = trimmed.find(|c: char| !c.is_ascii_alphabetic())?;
648 if split == 0 {
649 return None;
650 }
651 let (letters, digits) = trimmed.split_at(split);
652 if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
653 return None;
654 }
655 let upper = letters.to_ascii_uppercase();
656 if matches!(
657 upper.as_str(),
658 "MH" | "MP"
659 | "MTG"
660 | "MOUNT"
661 | "SH"
662 | "SHLD"
663 | "SHIELD"
664 | "ALIGN"
665 | "LOC"
666 | "PEG"
667 | "TAB"
668 | "CASE"
669 | "CHAS"
670 | "CHASSIS"
671 | "GND"
672 | "EP"
673 | "EPAD"
674 | "PAD"
675 | "NC"
676 | "TH"
677 ) {
678 return None;
679 }
680 let col: u32 = digits.parse().ok()?;
681 Some((letters, col))
682}
683
684fn grid_row_index(row: &str) -> usize {
685 let mut value = 0usize;
686 for b in row.bytes() {
687 let u = b.to_ascii_uppercase();
688 if !u.is_ascii_uppercase() {
689 return usize::MAX;
690 }
691 value = value
692 .saturating_mul(26)
693 .saturating_add((u - b'A' + 1) as usize);
694 }
695 value
696}
697
698fn index_lands(items: &FabLayerItems) -> HashMap<&str, HashMap<String, Vec<&FabLand>>> {
699 let mut map: HashMap<&str, HashMap<String, Vec<&FabLand>>> = HashMap::new();
700 for land in &items.lands {
701 let (Some(cid), Some(pin)) = (land.component.as_deref(), land.pin.as_deref()) else {
702 continue;
703 };
704 map.entry(cid)
705 .or_default()
706 .entry(pin.trim().to_ascii_uppercase())
707 .or_default()
708 .push(land);
709 }
710 map
711}
712
713fn index_holes(view: &FabViewData) -> HashMap<&str, HashMap<String, i64>> {
714 let mut map: HashMap<&str, HashMap<String, i64>> = HashMap::new();
715 for hole in &view.holes {
716 let (Some(cid), Some(pin)) = (hole.component.as_deref(), hole.pin.as_deref()) else {
717 continue;
718 };
719 let entry = map
720 .entry(cid)
721 .or_default()
722 .entry(pin.trim().to_ascii_uppercase())
723 .or_insert(0);
724 *entry = (*entry).max(hole.diameter);
725 }
726 map
727}
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732
733 #[test]
734 fn diode_emits_ak_labels_instead_of_dot_and_ic_emits_dot() {
735 let pcb = r#"(kicad_pcb (version 20240108) (generator pcbnew)
736 (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user))
737 (gr_rect (start 0 0) (end 20 20) (stroke (width 0.1)) (layer "Edge.Cuts"))
738 (footprint "Diode_SMD:D_SOD-123" (layer "F.Cu") (at 5 10)
739 (property "Reference" "D1" (at 0 0) (layer "F.SilkS"))
740 (property "Value" "1N4148" (at 0 0) (layer "F.Fab"))
741 (pad "1" smd rect (at -1.5 0) (size 1.0 1.2) (layers "F.Cu"))
742 (pad "2" smd rect (at 1.5 0) (size 1.0 1.2) (layers "F.Cu")))
743 (footprint "Package_SO:SOIC-8" (layer "F.Cu") (at 14 10)
744 (property "Reference" "U1" (at 0 0) (layer "F.SilkS"))
745 (property "Value" "LM358" (at 0 0) (layer "F.Fab"))
746 (pad "1" smd rect (at -2 -1) (size 1.0 0.6) (layers "F.Cu"))
747 (pad "2" smd rect (at -2 1) (size 1.0 0.6) (layers "F.Cu"))))"#;
748 let view = FabViewData::from_pcb_source(pcb, "pin1_demo").unwrap();
749 let markers = build_pin1_markers(&view, LayerSide::Top, &Pin1Options::default());
750 assert!(
751 markers
752 .iter()
753 .any(|m| m.designator == "D1" && m.role == Pin1Role::DiodeA)
754 );
755 assert!(
756 markers
757 .iter()
758 .any(|m| m.designator == "D1" && m.role == Pin1Role::DiodeK)
759 );
760 assert!(
761 markers
762 .iter()
763 .any(|m| m.designator == "U1" && m.role == Pin1Role::Dot)
764 );
765 }
766
767 #[test]
768 fn bga_grid_sorts_column_first_and_guards_mechanical_m_row() {
769 let depop = vec!["A2".to_owned(), "B1".to_owned(), "B2".to_owned()];
770 assert_eq!(choose_pin1_designator(&depop, "U").as_deref(), Some("B1"));
771
772 let mech = vec![
773 "M1".to_owned(),
774 "M2".to_owned(),
775 "S1".to_owned(),
776 "S2".to_owned(),
777 ];
778 assert_eq!(choose_pin1_designator(&mech, "U").as_deref(), Some("S1"));
779 }
780
781 #[test]
782 fn oblique_diode_and_round_pad_cap_rotate_with_part_while_orthogonal_stays_upright() {
783 let pcb = r#"(kicad_pcb (version 20240108) (generator pcbnew)
784 (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user))
785 (gr_rect (start 0 0) (end 40 20) (stroke (width 0.1)) (layer "Edge.Cuts"))
786 (footprint "Diode_SMD:D_SMB" (layer "F.Cu") (at 10 10 45)
787 (property "Reference" "D8" (at 0 0) (layer "F.SilkS"))
788 (property "Value" "SMBJ100A" (at 0 0) (layer "F.Fab"))
789 (pad "1" smd rect (at -2.15 0 45) (size 2.5 2.3) (layers "F.Cu"))
790 (pad "2" smd rect (at 2.15 0 225) (size 2.5 2.3) (layers "F.Cu")))
791 (footprint "Capacitor_SMD:CP_Elec" (layer "F.Cu") (at 22 10 -90)
792 (property "Reference" "C2" (at 0 0) (layer "F.SilkS"))
793 (property "Value" "100uF" (at 0 0) (layer "F.Fab"))
794 (pad "1" smd rect (at -2 0 270) (size 3.0 1.4) (layers "F.Cu"))
795 (pad "2" smd rect (at 2 0 270) (size 3.0 1.4) (layers "F.Cu")))
796 (footprint "Capacitor_THT:CP_Radial_Elec" (layer "F.Cu") (at 32 10 30)
797 (property "Reference" "C3" (at 0 0) (layer "F.SilkS"))
798 (property "Value" "10uF" (at 0 0) (layer "F.Fab"))
799 (pad "1" thru_hole circle (at -1.5 0 30) (size 1.8 1.8) (drill 0.8) (layers "*.Cu"))
800 (pad "2" thru_hole circle (at 1.5 0 30) (size 1.8 1.8) (drill 0.8) (layers "*.Cu"))))"#;
801 let view = FabViewData::from_pcb_source(pcb, "oblique_pin1").unwrap();
802
803 let longest_angle = |m: &Pin1Marker| -> f64 {
804 let mut best_len = -1.0_f64;
805 let mut best_ang = 0.0_f64;
806 for s in &m.items.strokes {
807 if let StrokePath::Line { start, end } = s.path {
808 let dx = (end.x - start.x) as f64;
809 let dy = (end.y - start.y) as f64;
810 let len = dx.hypot(dy);
811 if len > best_len {
812 best_len = len;
813 best_ang = dy.atan2(dx).to_degrees().rem_euclid(180.0);
814 }
815 }
816 }
817 best_ang
818 };
819
820 let pad_markers = build_pin1_markers(&view, LayerSide::Top, &Pin1Options::default());
822 let d8_k = pad_markers
823 .iter()
824 .find(|m| m.designator == "D8" && m.role == Pin1Role::DiodeK)
825 .expect("D8 K marker");
826 assert!(
827 (longest_angle(d8_k) - 135.0).abs() < 2.0,
828 "expected D8 K stem at ~135 deg, got {}",
829 longest_angle(d8_k)
830 );
831 let c2_neg = pad_markers
832 .iter()
833 .find(|m| m.designator == "C2" && m.role == Pin1Role::PolarityNeg)
834 .expect("C2 - marker");
835 let c2_ang = longest_angle(c2_neg);
836 assert!(
837 c2_ang.abs() < 2.0 || (c2_ang - 180.0).abs() < 2.0,
838 "expected orthogonal C2 '-' horizontal, got {c2_ang}"
839 );
840 let c3_neg = pad_markers
841 .iter()
842 .find(|m| m.designator == "C3" && m.role == Pin1Role::PolarityNeg)
843 .expect("C3 - marker");
844 assert!(
845 (longest_angle(c3_neg) - 30.0).abs() < 2.0,
846 "expected oblique round-pad C3 '-' at ~30 deg, got {}",
847 longest_angle(c3_neg)
848 );
849
850 for mode in [
852 PadLabelOrientation::Upright,
853 PadLabelOrientation::Orthogonal,
854 ] {
855 let opts = Pin1Options {
856 label_orientation: mode,
857 ..Pin1Options::default()
858 };
859 let ms = build_pin1_markers(&view, LayerSide::Top, &opts);
860 let k = ms
861 .iter()
862 .find(|m| m.designator == "D8" && m.role == Pin1Role::DiodeK)
863 .expect("D8 K");
864 assert!(
865 (longest_angle(k) - 90.0).abs() < 2.0,
866 "mode {mode:?}: expected D8 K stem at 90 deg, got {}",
867 longest_angle(k)
868 );
869 let neg = ms
870 .iter()
871 .find(|m| m.designator == "C3" && m.role == Pin1Role::PolarityNeg)
872 .expect("C3 -");
873 let ang = longest_angle(neg);
874 assert!(
875 ang.abs() < 2.0 || (ang - 180.0).abs() < 2.0,
876 "mode {mode:?}: expected C3 '-' horizontal, got {ang}"
877 );
878 }
879 }
880}