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

kicad_monkey_fab/
diodes.rs

1//! Virtual diode orientation layers (`DIODES_TOP`, `DIODES_BOTTOM`).
2//!
3//! Full pure-Rust parity with Python's `kicad_monkey.fab.virtual._diodes`:
4//!
5//! Resolution precedence per fitted component on the requested side:
6//! 1. Per-component config override (`DiodeOptions.overrides.<ref>`)
7//! 2. Footprint parameters on `FabComponent.parameters`:
8//!    - `CATHODE_PAD` (if present, skips auto-detection heuristics; value
9//!      `"none"`/`"false"`/`"off"`/`"no"`/`"0"`/`"disable"`/`"disabled"` suppresses)
10//!    - optional `ANODE_PAD`
11//!    - optional `DIODE_TYPE` (`normal`, `led`, `schottky`, `zener`, `tvs`)
12//!    - optional `DIODE_COLOR` (hex `#RRGGBB` or named color for SVG shading)
13//!    - optional `DIODE_SYMBOL` visibility boolean
14//! 3. Auto-detection heuristics (only when neither override nor `CATHODE_PAD` decided):
15//!    - 2-terminal fitted part matching `designator_prefixes` (e.g. `D`, `LED`)
16//!      or ASCII word-boundary `keywords` across designator, description, value,
17//!      footprint, and parameters (blocked when prefix belongs to another passive
18//!      family such as `C`/`L`/`R`)
19//!    - Pad name polarity hints (`K`/`C`/`CATHODE`/`CAT`/`-` vs `A`/`ANODE`/`ANO`/`+`),
20//!      falling back to `default_cathode_pad` (default `"2"`)
21//!
22//! Glyph geometry follows PCBE's `terminal_presentation_geometry.rs`:
23//! axis shaft, filled triangle pointing anode -> cathode, subtype-specific
24//! cathode bar (straight / Schottky S-hook / Zener & TVS angled wings), and
25//! LED light-ray arrows.
26
27use crate::FabViewData;
28use crate::geom::{
29    AreaKind, AreaShape, CoordNm, FabArea, FabComponent, FabLand, FabLayerItems, FabStroke,
30    LayerSide, Placement2D, Ring2D, StrokeKind, StrokePath,
31};
32use serde::{Deserialize, Serialize};
33use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
34
35const SYMBOL_HALF_WIDTH_RATIO: f64 = 1.0 / 6.0;
36const LINE_WIDTH_RATIO: f64 = 0.35;
37const MIN_LINE_WIDTH_NM: f64 = 35_000.0;
38const MIN_RAY_WIDTH_NM: f64 = 25_000.0;
39const MIN_TRI_OUTLINE_NM: f64 = 40_000.0;
40const MIN_SPAN_LEN_NM: f64 = 100_000.0;
41const COINCIDENT_NM: f64 = 1.0;
42
43const ANODE_TOKENS: &[&str] = &["A", "ANODE", "ANO", "+"];
44const DEFAULT_CATHODE_TOKENS: &[&str] = &["K", "C", "CATHODE", "CAT", "-"];
45const SUPPRESS_VALUES: &[&str] = &["none", "false", "off", "no", "0", "disable", "disabled"];
46const TRUE_VIS_TOKENS: &[&str] = &[
47    "1", "true", "yes", "on", "show", "include", "enable", "enabled",
48];
49const FALSE_VIS_TOKENS: &[&str] = &[
50    "0", "false", "no", "off", "none", "hide", "exclude", "disable", "disabled",
51];
52
53const NAMED_COLORS: &[(&str, &str)] = &[
54    ("red", "#E11D48"),
55    ("green", "#16A34A"),
56    ("emerald", "#10B981"),
57    ("blue", "#2563EB"),
58    ("yellow", "#EAB308"),
59    ("amber", "#EA580C"),
60    ("orange", "#F97316"),
61    ("white", "#64748B"),
62    ("warm white", "#D97706"),
63    ("cool white", "#0EA5E9"),
64    ("cyan", "#06B6D4"),
65    ("teal", "#007C83"),
66    ("purple", "#7C3AED"),
67    ("violet", "#7C3AED"),
68    ("magenta", "#DB2777"),
69    ("pink", "#EC4899"),
70    ("ir", "#7C2D12"),
71    ("infrared", "#7C2D12"),
72    ("uv", "#6D28D9"),
73    ("ultraviolet", "#6D28D9"),
74    ("black", "#111827"),
75];
76
77const LED_COLOR_INFERENCE_ORDER: &[&str] = &[
78    "warm white",
79    "cool white",
80    "infrared",
81    "ultraviolet",
82    "emerald",
83    "amber",
84    "orange",
85    "yellow",
86    "green",
87    "blue",
88    "cyan",
89    "purple",
90    "violet",
91    "magenta",
92    "pink",
93    "white",
94    "red",
95    "ir",
96    "uv",
97];
98
99/// Canonical diode subtype.
100#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum DiodeType {
103    Normal,
104    Led,
105    Schottky,
106    Zener,
107    Tvs,
108}
109
110impl DiodeType {
111    /// Default `(fill, stroke)` hex palette aligned with PCBE `autodoc_diode_palette.rs`.
112    #[must_use]
113    pub const fn default_palette(self) -> (&'static str, &'static str) {
114        match self {
115            Self::Normal => ("#E67E22", "#9C4A09"),
116            Self::Schottky => ("#007C83", "#005A60"),
117            Self::Zener => ("#C16B00", "#874B00"),
118            Self::Tvs => ("#8E44AD", "#623075"),
119            Self::Led => ("#74BC00", "#487400"),
120        }
121    }
122}
123
124/// SVG color rendering mode for virtual diode overlays.
125#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127pub enum DiodeColorMode {
128    #[default]
129    Shaded,
130    Monochrome,
131}
132
133/// Visibility mode for diode virtual layers.
134#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum DiodeVisibilityMode {
137    #[default]
138    All,
139    Explicit,
140}
141
142/// Per-component diode polarity and style override.
143#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
144pub struct DiodeOverride {
145    pub enabled: Option<bool>,
146    pub cathode_pad: Option<String>,
147    pub anode_pad: Option<String>,
148    pub diode_type: Option<String>,
149    pub color: Option<String>,
150}
151
152/// Configuration for `DIODES_TOP` and `DIODES_BOTTOM` detection and rendering.
153#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154pub struct DiodeOptions {
155    pub cathode_parameter: String,
156    pub anode_parameter: String,
157    pub type_parameter: String,
158    pub color_parameter: String,
159    pub visibility_parameter: String,
160    pub positive_parameter: String,
161    pub negative_parameter: String,
162    pub default_cathode_pad: String,
163    pub color_mode: DiodeColorMode,
164    pub visibility_mode: DiodeVisibilityMode,
165    pub designator_prefixes: Vec<String>,
166    pub keywords: Vec<String>,
167    pub cathode_pad_names: Vec<String>,
168    pub other_family_prefixes: Vec<String>,
169    pub overrides: BTreeMap<String, DiodeOverride>,
170    pub excluded_designators: BTreeSet<String>,
171}
172
173impl Default for DiodeOptions {
174    fn default() -> Self {
175        Self {
176            cathode_parameter: "CATHODE_PAD".to_owned(),
177            anode_parameter: "ANODE_PAD".to_owned(),
178            type_parameter: "DIODE_TYPE".to_owned(),
179            color_parameter: "DIODE_COLOR".to_owned(),
180            visibility_parameter: "DIODE_SYMBOL".to_owned(),
181            positive_parameter: "POSITIVE_PAD".to_owned(),
182            negative_parameter: "NEGATIVE_PAD".to_owned(),
183            default_cathode_pad: "2".to_owned(),
184            color_mode: DiodeColorMode::Shaded,
185            visibility_mode: DiodeVisibilityMode::All,
186            designator_prefixes: vec!["D".to_owned(), "LED".to_owned()],
187            keywords: vec![
188                "diode".to_owned(),
189                "led".to_owned(),
190                "schottky".to_owned(),
191                "tvs".to_owned(),
192                "zener".to_owned(),
193                "1n".to_owned(),
194            ],
195            cathode_pad_names: DEFAULT_CATHODE_TOKENS
196                .iter()
197                .map(|s| (*s).to_owned())
198                .collect(),
199            other_family_prefixes: vec![
200                "C".to_owned(),
201                "L".to_owned(),
202                "FB".to_owned(),
203                "IND".to_owned(),
204                "R".to_owned(),
205            ],
206            overrides: BTreeMap::new(),
207            excluded_designators: BTreeSet::new(),
208        }
209    }
210}
211
212/// Resolved diode polarity, subtype, and shading palette for one component.
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct ResolvedDiode {
215    pub component_id: String,
216    pub designator: String,
217    pub anode_pins: Vec<String>,
218    pub cathode_pins: Vec<String>,
219    pub diode_type: DiodeType,
220    pub fill_color: String,
221    pub stroke_color: String,
222}
223
224/// Semantic kind of one stroke inside a diode glyph.
225#[derive(Clone, Copy, Debug, Eq, PartialEq)]
226pub enum DiodeStrokeKind {
227    Shaft,
228    Bar,
229    LedRay,
230}
231
232/// One straight stroke segment in a diode glyph (`+Y` up, whole nm).
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub struct DiodeGlyphStroke {
235    pub start: CoordNm,
236    pub end: CoordNm,
237    pub width_nm: i64,
238    pub halo_width_nm: i64,
239    pub kind: DiodeStrokeKind,
240}
241
242/// Complete styled vector geometry of one diode symbol (`+Y` up, whole nm).
243#[derive(Clone, Debug, PartialEq, Eq)]
244pub struct DiodeGlyph {
245    pub component_id: String,
246    pub designator: String,
247    pub diode_type: DiodeType,
248    pub fill_color: String,
249    pub stroke_color: String,
250    pub triangle: [CoordNm; 3],
251    pub triangle_halo_width_nm: i64,
252    pub triangle_outline_width_nm: i64,
253    pub strokes: Vec<DiodeGlyphStroke>,
254}
255
256/// Resolve all visible diode components on `side`.
257#[must_use]
258pub fn resolve_diodes(
259    view: &FabViewData,
260    side: LayerSide,
261    options: &DiodeOptions,
262) -> Vec<ResolvedDiode> {
263    let prefixes = upper_set(&options.designator_prefixes);
264    let other_prefixes = upper_set(&options.other_family_prefixes);
265    let overrides_folded = fold_overrides(&options.overrides);
266    let excluded_folded = fold_set(&options.excluded_designators);
267
268    let mut out = Vec::new();
269    for comp in &view.components {
270        if comp.side != side || !is_fitted(comp, &excluded_folded) {
271            continue;
272        }
273        let ov = lookup_override(&overrides_folded, &comp.designator);
274        let Some(resolved) = resolve_diode_component(comp, options, ov, &prefixes, &other_prefixes)
275        else {
276            continue;
277        };
278        if !resolve_visibility(comp, options, ov) {
279            continue;
280        }
281        out.push(resolved);
282    }
283    out
284}
285
286/// Build full styled diode glyphs on `side` for SVG or Gerber lowering.
287#[must_use]
288pub fn build_diode_glyphs(
289    view: &FabViewData,
290    side: LayerSide,
291    options: &DiodeOptions,
292) -> Vec<DiodeGlyph> {
293    let resolved_list = resolve_diodes(view, side, options);
294    if resolved_list.is_empty() {
295        return Vec::new();
296    }
297    let idx = PadIndex::collect(view, side);
298    let mut glyphs = Vec::with_capacity(resolved_list.len());
299    for resolved in &resolved_list {
300        if let Some(glyph) = emit_diode_glyph(resolved, side, &idx) {
301            glyphs.push(glyph);
302        }
303    }
304    glyphs
305}
306
307/// Build canonical monochrome `FabLayerItems` for `DIODES_TOP` or `DIODES_BOTTOM`.
308#[must_use]
309pub fn build_diodes_layer(
310    view: &FabViewData,
311    side: LayerSide,
312    options: &DiodeOptions,
313) -> FabLayerItems {
314    let glyphs = build_diode_glyphs(view, side, options);
315    let mut out = FabLayerItems::default();
316    for glyph in glyphs {
317        if let Some(ring) = Ring2D::from_points_oriented(&glyph.triangle, true) {
318            out.areas.push(FabArea {
319                kind: AreaKind::Virtual,
320                shape: AreaShape::Region {
321                    outer: ring,
322                    holes: Vec::new(),
323                },
324                placement: Placement2D::identity(),
325                net: None,
326                component: Some(glyph.component_id.clone()),
327                source: None,
328            });
329        }
330        for st in glyph.strokes {
331            out.strokes.push(FabStroke {
332                kind: StrokeKind::Virtual,
333                path: StrokePath::Line {
334                    start: st.start,
335                    end: st.end,
336                },
337                width: st.width_nm,
338                net: None,
339                component: Some(glyph.component_id.clone()),
340                source: None,
341            });
342        }
343    }
344    out
345}
346
347/// Darken a `#RRGGBB` hex color by `factor` (matching Python `_darken_hex`).
348#[must_use]
349pub fn darken_hex(hex_color: &str, factor: f64) -> String {
350    let Some((r, g, b)) = parse_hex_rgb(hex_color) else {
351        return "#111827".to_owned();
352    };
353    let dr = ((f64::from(r) * factor) as i32).clamp(0, 255) as u8;
354    let dg = ((f64::from(g) * factor) as i32).clamp(0, 255) as u8;
355    let db = ((f64::from(b) * factor) as i32).clamp(0, 255) as u8;
356    format!("#{dr:02X}{dg:02X}{db:02X}")
357}
358
359fn parse_hex_rgb(raw: &str) -> Option<(u8, u8, u8)> {
360    let s = raw.trim();
361    let hex = s.strip_prefix('#')?;
362    if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
363        return None;
364    }
365    let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
366    let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
367    let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
368    Some((r, g, b))
369}
370
371fn parse_color(raw: Option<&str>) -> Option<String> {
372    let cleaned = raw?.trim();
373    if cleaned.is_empty() {
374        return None;
375    }
376    if parse_hex_rgb(cleaned).is_some() {
377        return Some(cleaned.to_ascii_uppercase());
378    }
379    let lower = cleaned.to_ascii_lowercase();
380    NAMED_COLORS
381        .iter()
382        .find(|(name, _)| *name == lower)
383        .map(|(_, hex)| (*hex).to_owned())
384}
385
386fn normalize_diode_type(raw: Option<&str>) -> Option<DiodeType> {
387    let tok = raw?.trim().to_ascii_lowercase();
388    match tok.as_str() {
389        "normal" | "diode" | "generic" | "rectifier" | "switching" | "signal" | "standard" => {
390            Some(DiodeType::Normal)
391        }
392        "led" | "light_emitting" | "light-emitting" => Some(DiodeType::Led),
393        "schottky" | "sbd" => Some(DiodeType::Schottky),
394        "zener" => Some(DiodeType::Zener),
395        "tvs" | "esd" | "transient" => Some(DiodeType::Tvs),
396        _ => None,
397    }
398}
399
400fn is_suppressed_value(raw: Option<&str>) -> bool {
401    raw.is_some_and(|v| {
402        let low = v.trim().to_ascii_lowercase();
403        SUPPRESS_VALUES.contains(&low.as_str())
404    })
405}
406
407fn parse_bool_token(raw: Option<&str>) -> Option<bool> {
408    let tok = raw?.trim().to_ascii_lowercase();
409    if TRUE_VIS_TOKENS.contains(&tok.as_str()) {
410        Some(true)
411    } else if FALSE_VIS_TOKENS.contains(&tok.as_str()) {
412        Some(false)
413    } else {
414        None
415    }
416}
417
418fn designator_prefix(designator: &str) -> String {
419    designator
420        .trim()
421        .chars()
422        .take_while(char::is_ascii_alphabetic)
423        .map(|c| c.to_ascii_uppercase())
424        .collect()
425}
426
427fn is_fitted(comp: &FabComponent, excluded_folded: &HashSet<String>) -> bool {
428    if !comp.fitted || comp.board_only {
429        return false;
430    }
431    let des = comp.designator.trim().to_ascii_lowercase();
432    des.is_empty() || !excluded_folded.contains(&des)
433}
434
435fn resolve_visibility(
436    comp: &FabComponent,
437    options: &DiodeOptions,
438    override_entry: Option<&DiodeOverride>,
439) -> bool {
440    if let Some(flag) = override_entry.and_then(|ov| ov.enabled) {
441        return flag;
442    }
443    let param_val = lookup_param(comp, &options.visibility_parameter);
444    if let Some(flag) = parse_bool_token(param_val) {
445        return flag;
446    }
447    match options.visibility_mode {
448        DiodeVisibilityMode::All => true,
449        DiodeVisibilityMode::Explicit => false,
450    }
451}
452
453fn lookup_param<'a>(comp: &'a FabComponent, param_name: &str) -> Option<&'a str> {
454    let wanted = param_name.trim();
455    if wanted.is_empty() {
456        return None;
457    }
458    comp.parameters
459        .iter()
460        .find(|(k, _)| k.trim().eq_ignore_ascii_case(wanted))
461        .map(|(_, v)| v.trim())
462}
463
464fn component_text_blob(comp: &FabComponent) -> String {
465    let mut parts: Vec<&str> = Vec::new();
466    for s in [
467        comp.designator.as_str(),
468        comp.description.as_str(),
469        comp.value.as_str(),
470        comp.footprint.as_str(),
471    ] {
472        let t = s.trim();
473        if !t.is_empty() {
474            parts.push(t);
475        }
476    }
477    for v in comp.parameters.values() {
478        let t = v.trim();
479        if !t.is_empty() {
480            parts.push(t);
481        }
482    }
483    parts.join(" ")
484}
485
486/// ASCII prefix/word-boundary match (`(?<![a-z0-9])kw(?![a-z])`) so `"led"` does
487/// not match `"enabled"` or `"drilled"`, while `"1n"` matches `"1n4148"`.
488fn has_word_token(blob_lower: &str, keyword: &str) -> bool {
489    let kw = keyword.trim().to_ascii_lowercase();
490    if kw.is_empty() {
491        return false;
492    }
493    let bytes = blob_lower.as_bytes();
494    let kw_len = kw.len();
495    let mut start = 0usize;
496    while let Some(rel) = blob_lower[start..].find(&kw) {
497        let idx = start + rel;
498        let end = idx + kw_len;
499        let left_ok = idx == 0 || !bytes[idx - 1].is_ascii_alphanumeric();
500        let right_ok = end == bytes.len() || !bytes[end].is_ascii_alphabetic();
501        if left_ok && right_ok {
502            return true;
503        }
504        let step = blob_lower[idx..].chars().next().map_or(1, char::len_utf8);
505        start = idx + step;
506    }
507    false
508}
509
510fn infer_diode_type(designator: &str, blob_lower: &str) -> DiodeType {
511    if designator.trim().to_ascii_uppercase().starts_with("LED")
512        || has_word_token(blob_lower, "led")
513    {
514        return DiodeType::Led;
515    }
516    if ["schottky", "sbd", "bat54", "ss14", "ss24", "ss34", "mbr"]
517        .iter()
518        .any(|kw| has_word_token(blob_lower, kw))
519    {
520        return DiodeType::Schottky;
521    }
522    if ["zener", "mmbz", "bzt", "bzx"]
523        .iter()
524        .any(|kw| has_word_token(blob_lower, kw))
525    {
526        return DiodeType::Zener;
527    }
528    if ["tvs", "esd", "smaj", "smbj", "smcj", "pesd"]
529        .iter()
530        .any(|kw| has_word_token(blob_lower, kw))
531    {
532        return DiodeType::Tvs;
533    }
534    DiodeType::Normal
535}
536
537fn infer_led_color(blob_lower: &str) -> Option<String> {
538    for token in LED_COLOR_INFERENCE_ORDER {
539        if has_word_token(blob_lower, token) {
540            return NAMED_COLORS
541                .iter()
542                .find(|(name, _)| name == token)
543                .map(|(_, hex)| (*hex).to_owned());
544        }
545    }
546    None
547}
548
549fn split_pins_by_name(pins: &[String], pad_spec: &str) -> (Vec<String>, Vec<String>) {
550    let wanted: HashSet<String> = pad_spec
551        .split(',')
552        .map(|tok| tok.trim().to_ascii_lowercase())
553        .filter(|tok| !tok.is_empty())
554        .collect();
555    let mut matched = Vec::new();
556    let mut others = Vec::new();
557    for p in pins {
558        if wanted.contains(&p.trim().to_ascii_lowercase()) {
559            matched.push(p.clone());
560        } else {
561            others.push(p.clone());
562        }
563    }
564    (matched, others)
565}
566
567fn resolve_diode_component(
568    comp: &FabComponent,
569    options: &DiodeOptions,
570    override_entry: Option<&DiodeOverride>,
571    prefixes: &HashSet<String>,
572    other_prefixes: &HashSet<String>,
573) -> Option<ResolvedDiode> {
574    if !comp.fitted || comp.pins.len() < 2 {
575        return None;
576    }
577    let unique_names: HashSet<String> = comp
578        .pins
579        .iter()
580        .map(|p| p.trim().to_ascii_lowercase())
581        .filter(|p| !p.is_empty())
582        .collect();
583
584    let has_semantic_override = override_entry.is_some_and(|ov| {
585        ov.cathode_pad.is_some()
586            || ov.anode_pad.is_some()
587            || ov.diode_type.is_some()
588            || ov.color.is_some()
589    });
590
591    let cathode_param = lookup_param(comp, &options.cathode_parameter);
592    let anode_param = lookup_param(comp, &options.anode_parameter);
593    let type_param = lookup_param(comp, &options.type_parameter);
594    let color_param = lookup_param(comp, &options.color_parameter);
595
596    if override_entry.is_some_and(|ov| is_suppressed_value(ov.diode_type.as_deref())) {
597        return None;
598    }
599    if !has_semantic_override && is_suppressed_value(type_param) {
600        return None;
601    }
602
603    let blob_lower = component_text_blob(comp).to_ascii_lowercase();
604
605    let (cathode_spec, anode_spec): (Option<&str>, Option<&str>) = if let Some(ov) = override_entry
606        && (ov.cathode_pad.is_some() || ov.anode_pad.is_some())
607    {
608        if is_suppressed_value(ov.cathode_pad.as_deref())
609            || is_suppressed_value(ov.anode_pad.as_deref())
610        {
611            return None;
612        }
613        (ov.cathode_pad.as_deref(), ov.anode_pad.as_deref())
614    } else if cathode_param.is_some() || (anode_param.is_some() && unique_names.len() == 2) {
615        if is_suppressed_value(cathode_param) || is_suppressed_value(anode_param) {
616            return None;
617        }
618        (cathode_param, anode_param)
619    } else {
620        if unique_names.len() != 2 {
621            return None;
622        }
623        let explicit_type = normalize_diode_type(type_param).is_some();
624        let prefix = designator_prefix(&comp.designator);
625        let prefix_hit = prefixes.contains(&prefix);
626        let blocked_by_family =
627            !prefix.is_empty() && !prefix_hit && other_prefixes.contains(&prefix);
628        let keyword_hit = !blocked_by_family
629            && options
630                .keywords
631                .iter()
632                .any(|kw| has_word_token(&blob_lower, kw));
633        if !(prefix_hit || keyword_hit || explicit_type || has_semantic_override) {
634            return None;
635        }
636        (None, None)
637    };
638
639    let (cathodes, anodes) = resolve_pin_groups(comp, cathode_spec, anode_spec, options);
640    if cathodes.is_empty() || anodes.is_empty() {
641        return None;
642    }
643
644    let diode_type = normalize_diode_type(override_entry.and_then(|ov| ov.diode_type.as_deref()))
645        .or_else(|| normalize_diode_type(type_param))
646        .unwrap_or_else(|| infer_diode_type(&comp.designator, &blob_lower));
647
648    let explicit_color = parse_color(override_entry.and_then(|ov| ov.color.as_deref()))
649        .or_else(|| parse_color(color_param))
650        .or_else(|| {
651            if diode_type == DiodeType::Led {
652                infer_led_color(&blob_lower)
653            } else {
654                None
655            }
656        });
657
658    let (fill_color, stroke_color) = if let Some(fill) = explicit_color {
659        let stroke = darken_hex(&fill, 0.62);
660        (fill, stroke)
661    } else {
662        let (f, s) = diode_type.default_palette();
663        (f.to_owned(), s.to_owned())
664    };
665
666    Some(ResolvedDiode {
667        component_id: comp.id.clone(),
668        designator: comp.designator.trim().to_owned(),
669        anode_pins: anodes,
670        cathode_pins: cathodes,
671        diode_type,
672        fill_color,
673        stroke_color,
674    })
675}
676
677fn resolve_pin_groups(
678    comp: &FabComponent,
679    cathode_spec: Option<&str>,
680    anode_spec: Option<&str>,
681    options: &DiodeOptions,
682) -> (Vec<String>, Vec<String>) {
683    let pins = &comp.pins;
684    if let Some(cspec) = cathode_spec {
685        let (cathodes, rest) = split_pins_by_name(pins, cspec);
686        let anodes = match anode_spec {
687            Some(aspec) => split_pins_by_name(pins, aspec).0,
688            None => rest,
689        };
690        return (cathodes, anodes);
691    }
692    if let Some(aspec) = anode_spec {
693        let (anodes, cathodes) = split_pins_by_name(pins, aspec);
694        return (cathodes, anodes);
695    }
696
697    let pos_raw = lookup_param(comp, &options.positive_parameter);
698    let neg_raw = lookup_param(comp, &options.negative_parameter);
699    let pos_spec = if is_suppressed_value(pos_raw) {
700        None
701    } else {
702        pos_raw
703    };
704    let neg_spec = if is_suppressed_value(neg_raw) {
705        None
706    } else {
707        neg_raw
708    };
709    if let (Some(ps), Some(ns)) = (pos_spec, neg_spec) {
710        let (anodes, _) = split_pins_by_name(pins, ps);
711        let (cathodes, _) = split_pins_by_name(pins, ns);
712        return (cathodes, anodes);
713    }
714    if let Some(ps) = pos_spec {
715        let (anodes, cathodes) = split_pins_by_name(pins, ps);
716        return (cathodes, anodes);
717    }
718    if let Some(ns) = neg_spec {
719        return split_pins_by_name(pins, ns);
720    }
721
722    let mut cathode_tokens: HashSet<String> = options
723        .cathode_pad_names
724        .iter()
725        .map(|s| s.trim().to_ascii_uppercase())
726        .filter(|s| !s.is_empty())
727        .collect();
728    if cathode_tokens.is_empty() {
729        cathode_tokens = DEFAULT_CATHODE_TOKENS
730            .iter()
731            .map(|s| (*s).to_owned())
732            .collect();
733    }
734    let token_cathodes: Vec<String> = pins
735        .iter()
736        .filter(|p| cathode_tokens.contains(&p.trim().to_ascii_uppercase()))
737        .cloned()
738        .collect();
739    let token_anodes: Vec<String> = pins
740        .iter()
741        .filter(|p| ANODE_TOKENS.contains(&p.trim().to_ascii_uppercase().as_str()))
742        .cloned()
743        .collect();
744    if !token_cathodes.is_empty() && !token_anodes.is_empty() {
745        return (token_cathodes, token_anodes);
746    }
747    split_pins_by_name(pins, &options.default_cathode_pad)
748}
749
750struct PadIndex<'a> {
751    lands_by_pin: HashMap<(String, String), &'a FabLand>,
752    lands_by_comp: HashMap<String, Vec<&'a FabLand>>,
753    holes_by_pin: HashMap<(String, String), (f64, f64)>,
754}
755
756impl<'a> PadIndex<'a> {
757    fn collect(view: &'a FabViewData, side: LayerSide) -> Self {
758        let layer_key = if side == LayerSide::Bottom {
759            "BOTTOM"
760        } else {
761            "TOP"
762        };
763        let mut lands_by_pin: HashMap<(String, String), &'a FabLand> = HashMap::new();
764        let mut lands_by_comp: HashMap<String, Vec<&'a FabLand>> = HashMap::new();
765        if let Some(items) = view.layers_items.get(layer_key) {
766            for land in &items.lands {
767                let Some(cid) = land.component.as_deref() else {
768                    continue;
769                };
770                lands_by_comp.entry(cid.to_owned()).or_default().push(land);
771                if let Some(pin) = land.pin.as_deref() {
772                    let pkey = pin.trim().to_ascii_lowercase();
773                    if !pkey.is_empty() {
774                        lands_by_pin.entry((cid.to_owned(), pkey)).or_insert(land);
775                    }
776                }
777            }
778        }
779        let mut holes_by_pin: HashMap<(String, String), (f64, f64)> = HashMap::new();
780        for hole in &view.holes {
781            if let (Some(cid), Some(pin)) = (hole.component.as_deref(), hole.pin.as_deref()) {
782                let pkey = pin.trim().to_ascii_lowercase();
783                if !pkey.is_empty() {
784                    holes_by_pin
785                        .entry((cid.to_owned(), pkey))
786                        .or_insert((hole.center.x as f64, hole.center.y as f64));
787                }
788            }
789        }
790        Self {
791            lands_by_pin,
792            lands_by_comp,
793            holes_by_pin,
794        }
795    }
796
797    fn pin_point(&self, comp_id: &str, pin: &str) -> Option<(f64, f64)> {
798        let key = (comp_id.to_owned(), pin.trim().to_ascii_lowercase());
799        if let Some(land) = self.lands_by_pin.get(&key) {
800            let b = land_bounds_nm(land);
801            return Some((0.5 * (b[0] + b[2]), 0.5 * (b[1] + b[3])));
802        }
803        self.holes_by_pin.get(&key).copied()
804    }
805
806    fn terminal_lands(&self, comp_id: &str, pins: &[String]) -> Vec<&'a FabLand> {
807        let mut out = Vec::new();
808        let mut seen: HashSet<*const FabLand> = HashSet::new();
809        for pin in pins {
810            let key = (comp_id.to_owned(), pin.trim().to_ascii_lowercase());
811            if let Some(&land) = self.lands_by_pin.get(&key)
812                && seen.insert(std::ptr::from_ref(land))
813            {
814                out.push(land);
815            }
816        }
817        out
818    }
819}
820
821fn land_bounds_nm(land: &FabLand) -> [f64; 4] {
822    let pl = land.placement;
823    let tx = pl.tx as f64;
824    let ty = pl.ty as f64;
825    match &land.shape {
826        AreaShape::Disk { radius } => {
827            let r = *radius as f64;
828            [tx - r, ty - r, tx + r, ty + r]
829        }
830        AreaShape::Capsule { length, width } => {
831            let r = (*width as f64) * 0.5;
832            let half_spine = ((*length - *width).max(0) as f64) * 0.5;
833            let p0 = pl.transform(-half_spine, 0.0);
834            let p1 = pl.transform(half_spine, 0.0);
835            [
836                (p0.x.min(p1.x) as f64) - r,
837                (p0.y.min(p1.y) as f64) - r,
838                (p0.x.max(p1.x) as f64) + r,
839                (p0.y.max(p1.y) as f64) + r,
840            ]
841        }
842        AreaShape::Rect { width, height }
843        | AreaShape::RoundedRect { width, height, .. }
844        | AreaShape::ChamferedRect { width, height, .. } => {
845            let hw = (*width as f64) * 0.5;
846            let hh = (*height as f64) * 0.5;
847            points_bounds(&[
848                pl.transform(-hw, -hh),
849                pl.transform(hw, -hh),
850                pl.transform(hw, hh),
851                pl.transform(-hw, hh),
852            ])
853        }
854        AreaShape::Trapezoid {
855            width,
856            height,
857            delta_x,
858            delta_y,
859        } => {
860            let hw = (*width as f64) * 0.5;
861            let hh = (*height as f64) * 0.5;
862            let dx = (*delta_x as f64) * 0.5;
863            let dy = (*delta_y as f64) * 0.5;
864            points_bounds(&[
865                pl.transform(-hw - dy, -hh - dx),
866                pl.transform(hw + dy, -hh + dx),
867                pl.transform(hw - dy, hh - dx),
868                pl.transform(-hw + dy, hh + dx),
869            ])
870        }
871        AreaShape::Region { outer, .. } => {
872            let pts: Vec<CoordNm> = outer
873                .points
874                .iter()
875                .map(|p| pl.transform(p.x as f64, p.y as f64))
876                .collect();
877            if pts.is_empty() {
878                [tx, ty, tx, ty]
879            } else {
880                points_bounds(&pts)
881            }
882        }
883    }
884}
885
886fn points_bounds(pts: &[CoordNm]) -> [f64; 4] {
887    let mut min_x = f64::INFINITY;
888    let mut min_y = f64::INFINITY;
889    let mut max_x = f64::NEG_INFINITY;
890    let mut max_y = f64::NEG_INFINITY;
891    for pt in pts {
892        let x = pt.x as f64;
893        let y = pt.y as f64;
894        min_x = min_x.min(x);
895        min_y = min_y.min(y);
896        max_x = max_x.max(x);
897        max_y = max_y.max(y);
898    }
899    [min_x, min_y, max_x, max_y]
900}
901
902fn frame_point(a: (f64, f64), u: (f64, f64), p: (f64, f64), along: f64, normal: f64) -> (f64, f64) {
903    // Matches PCBE terminal_presentation_geometry.rs::Frame::point and Python _diodes.py::_frame_point
904    (
905        a.0 + u.0 * along - p.0 * normal,
906        a.1 + u.1 * along - p.1 * normal,
907    )
908}
909
910fn to_coord(pt: (f64, f64)) -> CoordNm {
911    CoordNm::new(pt.0.round() as i64, pt.1.round() as i64)
912}
913
914fn push_polyline_strokes(
915    out: &mut Vec<DiodeGlyphStroke>,
916    pts: &[(f64, f64)],
917    width_nm: f64,
918    halo_width_nm: f64,
919    kind: DiodeStrokeKind,
920) {
921    let w = width_nm.round().max(1.0) as i64;
922    let hw = halo_width_nm.round().max(0.0) as i64;
923    for seg in pts.windows(2) {
924        let (p0, p1) = (seg[0], seg[1]);
925        if (p1.0 - p0.0).hypot(p1.1 - p0.1) <= COINCIDENT_NM {
926            continue;
927        }
928        out.push(DiodeGlyphStroke {
929            start: to_coord(p0),
930            end: to_coord(p1),
931            width_nm: w,
932            halo_width_nm: hw,
933            kind,
934        });
935    }
936}
937
938fn emit_diode_glyph(
939    resolved: &ResolvedDiode,
940    side: LayerSide,
941    idx: &PadIndex<'_>,
942) -> Option<DiodeGlyph> {
943    let a_pts: Vec<(f64, f64)> = resolved
944        .anode_pins
945        .iter()
946        .filter_map(|pin| idx.pin_point(&resolved.component_id, pin))
947        .collect();
948    let c_pts: Vec<(f64, f64)> = resolved
949        .cathode_pins
950        .iter()
951        .filter_map(|pin| idx.pin_point(&resolved.component_id, pin))
952        .collect();
953    if a_pts.is_empty() || c_pts.is_empty() {
954        return None;
955    }
956
957    let a = (
958        a_pts.iter().map(|pt| pt.0).sum::<f64>() / (a_pts.len() as f64),
959        a_pts.iter().map(|pt| pt.1).sum::<f64>() / (a_pts.len() as f64),
960    );
961    let c = (
962        c_pts.iter().map(|pt| pt.0).sum::<f64>() / (c_pts.len() as f64),
963        c_pts.iter().map(|pt| pt.1).sum::<f64>() / (c_pts.len() as f64),
964    );
965    let dx = c.0 - a.0;
966    let dy = c.1 - a.1;
967    let length = dx.hypot(dy);
968    if !length.is_finite() || length < MIN_SPAN_LEN_NM {
969        return None;
970    }
971    let u = (dx / length, dy / length);
972    let mut p = (-u.1, u.0);
973    if side == LayerSide::Bottom {
974        p = (-p.0, -p.1);
975    }
976
977    let span = compute_perpendicular_span(resolved, idx, a, p, length);
978    let wing = (length * SYMBOL_HALF_WIDTH_RATIO).min(span * 0.43);
979    let line_w = (wing * LINE_WIDTH_RATIO).max(MIN_LINE_WIDTH_NM);
980    let base = length / 3.0;
981    let tip = length * 2.0 / 3.0;
982
983    let mut strokes = Vec::new();
984    let shaft_pts = [
985        frame_point(a, u, p, 0.0, 0.0),
986        frame_point(a, u, p, length, 0.0),
987    ];
988    push_polyline_strokes(
989        &mut strokes,
990        &shaft_pts,
991        line_w,
992        line_w * 2.0,
993        DiodeStrokeKind::Shaft,
994    );
995
996    let triangle = [
997        to_coord(frame_point(a, u, p, base, wing)),
998        to_coord(frame_point(a, u, p, base, -wing)),
999        to_coord(frame_point(a, u, p, tip, 0.0)),
1000    ];
1001    let tri_halo = line_w * 2.0;
1002    let tri_outline = (tri_halo * 0.45).max(MIN_TRI_OUTLINE_NM);
1003
1004    push_cathode_bar(
1005        &mut strokes,
1006        resolved.diode_type,
1007        a,
1008        u,
1009        p,
1010        tip,
1011        wing,
1012        line_w,
1013    );
1014    if resolved.diode_type == DiodeType::Led {
1015        push_led_rays(&mut strokes, a, u, p, length, line_w);
1016    }
1017
1018    Some(DiodeGlyph {
1019        component_id: resolved.component_id.clone(),
1020        designator: resolved.designator.clone(),
1021        diode_type: resolved.diode_type,
1022        fill_color: resolved.fill_color.clone(),
1023        stroke_color: resolved.stroke_color.clone(),
1024        triangle,
1025        triangle_halo_width_nm: tri_halo.round().max(0.0) as i64,
1026        triangle_outline_width_nm: tri_outline.round().max(1.0) as i64,
1027        strokes,
1028    })
1029}
1030
1031fn compute_perpendicular_span(
1032    resolved: &ResolvedDiode,
1033    idx: &PadIndex<'_>,
1034    a: (f64, f64),
1035    p: (f64, f64),
1036    length: f64,
1037) -> f64 {
1038    let all_pins: Vec<String> = resolved
1039        .anode_pins
1040        .iter()
1041        .chain(resolved.cathode_pins.iter())
1042        .cloned()
1043        .collect();
1044    let active_lands = idx.terminal_lands(&resolved.component_id, &all_pins);
1045    let fallback_lands = idx.lands_by_comp.get(&resolved.component_id);
1046    let span_lands: &[&FabLand] = if !active_lands.is_empty() {
1047        &active_lands
1048    } else if let Some(fl) = fallback_lands {
1049        fl.as_slice()
1050    } else {
1051        &[]
1052    };
1053    if span_lands.is_empty() {
1054        return length * 0.65;
1055    }
1056    let mut min_x = f64::INFINITY;
1057    let mut min_y = f64::INFINITY;
1058    let mut max_x = f64::NEG_INFINITY;
1059    let mut max_y = f64::NEG_INFINITY;
1060    for land in span_lands {
1061        let b = land_bounds_nm(land);
1062        min_x = min_x.min(b[0]);
1063        min_y = min_y.min(b[1]);
1064        max_x = max_x.max(b[2]);
1065        max_y = max_y.max(b[3]);
1066    }
1067    let corners = [
1068        (min_x, min_y),
1069        (min_x, max_y),
1070        (max_x, min_y),
1071        (max_x, max_y),
1072    ];
1073    let mut lo = f64::INFINITY;
1074    let mut hi = f64::NEG_INFINITY;
1075    for (x, y) in corners {
1076        let pr = (x - a.0) * p.0 + (y - a.1) * p.1;
1077        lo = lo.min(pr);
1078        hi = hi.max(pr);
1079    }
1080    (hi - lo).max(length * 0.55)
1081}
1082
1083#[allow(
1084    clippy::too_many_arguments,
1085    reason = "local frame axes (a, u, p) and scalar proportions match PCBE terminal_presentation_geometry"
1086)]
1087fn push_cathode_bar(
1088    strokes: &mut Vec<DiodeGlyphStroke>,
1089    diode_type: DiodeType,
1090    a: (f64, f64),
1091    u: (f64, f64),
1092    p: (f64, f64),
1093    tip: f64,
1094    wing: f64,
1095    line_w: f64,
1096) {
1097    let (bar_local, bar_width, bar_halo): (Vec<(f64, f64)>, f64, f64) = match diode_type {
1098        DiodeType::Schottky => (
1099            vec![
1100                (tip - wing * 0.52, wing * 0.55),
1101                (tip - wing * 0.52, wing),
1102                (tip, wing),
1103                (tip, -wing),
1104                (tip + wing * 0.52, -wing),
1105                (tip + wing * 0.52, -wing * 0.55),
1106            ],
1107            (line_w * 0.85).max(MIN_LINE_WIDTH_NM),
1108            line_w * 1.5,
1109        ),
1110        DiodeType::Zener | DiodeType::Tvs => (
1111            vec![
1112                (tip - wing * 0.36, wing * 1.18),
1113                (tip, wing),
1114                (tip, -wing),
1115                (tip + wing * 0.36, -wing * 1.18),
1116            ],
1117            line_w * 1.25,
1118            line_w * 2.25,
1119        ),
1120        DiodeType::Normal | DiodeType::Led => (
1121            vec![(tip, wing), (tip, -wing)],
1122            line_w * 1.25,
1123            line_w * 2.25,
1124        ),
1125    };
1126    let bar_pts: Vec<(f64, f64)> = bar_local
1127        .into_iter()
1128        .map(|(al, nm)| frame_point(a, u, p, al, nm))
1129        .collect();
1130    push_polyline_strokes(strokes, &bar_pts, bar_width, bar_halo, DiodeStrokeKind::Bar);
1131}
1132
1133fn push_led_rays(
1134    strokes: &mut Vec<DiodeGlyphStroke>,
1135    a: (f64, f64),
1136    u: (f64, f64),
1137    p: (f64, f64),
1138    length: f64,
1139    line_w: f64,
1140) {
1141    let ray_w = (line_w * 0.5).max(MIN_RAY_WIDTH_NM);
1142    let ray_specs: [&[(f64, f64)]; 4] = [
1143        &[
1144            (7.0 / 15.0, -1.0 / 5.0),
1145            (17.0 / 30.0, -3.0 / 10.0),
1146            (3.0 / 5.0, -1.0 / 5.0),
1147            (23.0 / 30.0, -11.0 / 30.0),
1148            (23.0 / 30.0, -3.0 / 10.0),
1149        ],
1150        &[
1151            (7.0 / 15.0, -1.0 / 3.0),
1152            (17.0 / 30.0, -13.0 / 30.0),
1153            (3.0 / 5.0, -1.0 / 3.0),
1154            (23.0 / 30.0, -1.0 / 2.0),
1155            (23.0 / 30.0, -13.0 / 30.0),
1156        ],
1157        &[(23.0 / 30.0, -11.0 / 30.0), (7.0 / 10.0, -11.0 / 30.0)],
1158        &[(23.0 / 30.0, -1.0 / 2.0), (7.0 / 10.0, -1.0 / 2.0)],
1159    ];
1160    for spec in ray_specs {
1161        let world_pts: Vec<(f64, f64)> = spec
1162            .iter()
1163            .map(|&(rx, ry)| frame_point(a, u, p, rx * length, ry * length))
1164            .collect();
1165        push_polyline_strokes(strokes, &world_pts, ray_w, line_w, DiodeStrokeKind::LedRay);
1166    }
1167}
1168
1169fn upper_set(values: &[String]) -> HashSet<String> {
1170    values
1171        .iter()
1172        .map(|s| s.trim().to_ascii_uppercase())
1173        .filter(|s| !s.is_empty())
1174        .collect()
1175}
1176
1177fn fold_set(values: &BTreeSet<String>) -> HashSet<String> {
1178    values
1179        .iter()
1180        .map(|s| s.trim().to_ascii_lowercase())
1181        .filter(|s| !s.is_empty())
1182        .collect()
1183}
1184
1185fn fold_overrides(overrides: &BTreeMap<String, DiodeOverride>) -> HashMap<String, &DiodeOverride> {
1186    overrides
1187        .iter()
1188        .map(|(k, v)| (k.trim().to_ascii_lowercase(), v))
1189        .collect()
1190}
1191
1192fn lookup_override<'a>(
1193    overrides_folded: &HashMap<String, &'a DiodeOverride>,
1194    designator: &str,
1195) -> Option<&'a DiodeOverride> {
1196    let key = designator.trim().to_ascii_lowercase();
1197    if key.is_empty() {
1198        return None;
1199    }
1200    overrides_folded.get(&key).copied()
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205    use super::*;
1206
1207    #[test]
1208    fn word_token_respects_boundaries() {
1209        assert!(has_word_token("green led 0603", "led"));
1210        assert!(has_word_token("led_green", "led"));
1211        assert!(has_word_token("led1", "led"));
1212        assert!(!has_word_token("enabled", "led"));
1213        assert!(!has_word_token("drilled", "led"));
1214        assert!(!has_word_token("unshielded", "led"));
1215        assert!(has_word_token("1n4148w", "1n"));
1216        assert!(has_word_token("warm white led", "warm white"));
1217        // UTF-8 safe around multi-byte characters
1218        assert!(has_word_token("10µf led", "led"));
1219        assert!(!has_word_token("10µf enabled", "led"));
1220    }
1221
1222    #[test]
1223    fn darken_hex_matches_python() {
1224        assert_eq!(darken_hex("#16A34A", 0.62), "#0D652D");
1225        assert_eq!(darken_hex("#E11D48", 0.62), "#8B112C");
1226        assert_eq!(darken_hex("not-a-color", 0.62), "#111827");
1227    }
1228}