aboutsummaryrefslogtreecommitdiff
path: root/tools/router-rs/src/pour.rs
blob: b7aaab4c2a3a8fa447e3695e15fec72e9aa2a7eb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//! Pour connectivity of the plane nets: where each copper pour of the board.json (`zones`)
//! will fill, which pieces of the net's copper the fill joins, and stitching vias for islands.
//!
//! A cell fills when it lies in the pour outline and the nearest copper of another net (or the
//! board edge, keep-out, hole) is at least FILL_R away: the zone clearance plus half KiCad's
//! minimum fill width, so a neck too thin to fill does not count as a connection. Fill cells
//! form islands (4-connected, per layer). The net's copper joins an island where its tracks
//! and vias touch it and where a pad is within THERMAL_R (thermal gap plus spoke). Pieces of
//! copper with pads that end up apart are what KiCad's DRC reports as unconnected.

use crate::board::{via_drill, SearchOpts, CLR, HOLE_HOLE, M};
use crate::router::Router;
use serde_json::json;

/// Fill needs this much room to other nets' copper (mm): clearance 0.2 + half of 0.25.
const FILL_R: f32 = 0.325;
/// A pad joins fill within this distance (mm): thermal gap 0.5 plus a little spoke.
const THERMAL_R: f64 = 0.6;

struct Map {
    /// island of each state (cell * 2 + layer), -1 where nothing fills
    lab: Vec<i32>,
    nisl: usize,
    /// the net's copper pieces (item ids)
    pieces: Vec<Vec<usize>>,
    /// union-find over islands (0..nisl) and pieces (nisl..)
    par: Vec<usize>,
}

impl Map {
    fn find(&mut self, mut a: usize) -> usize {
        while self.par[a] != a {
            self.par[a] = self.par[self.par[a]];
            a = self.par[a];
        }
        a
    }

    fn union(&mut self, a: usize, b: usize) {
        let (a, b) = (self.find(a), self.find(b));
        if a != b {
            self.par[a] = b;
        }
    }
}

impl Router {
    fn pour_map(&self, net: i32) -> Option<Map> {
        let b = &self.b;
        let zones: Vec<_> = self.zones.iter().filter(|z| z.0 == net).collect();
        if zones.is_empty() {
            return None;
        }
        let mut fill = vec![false; 2 * b.n];
        for (_, l, poly) in &zones {
            let (i0, j0, i1, j1) = b.window(&poly.bbox, 0.0);
            for j in j0..=j1 {
                for i in i0..=i1 {
                    let s = (j * b.nx + i) * 2 + l;
                    if !fill[s] && b.f[s].fdist(net) >= FILL_R && poly.contains(b.cell_xy(i, j)) {
                        fill[s] = true;
                    }
                }
            }
        }
        let mut lab = vec![-1i32; 2 * b.n];
        let mut nisl = 0;
        let mut stack = Vec::new();
        for s0 in 0..2 * b.n {
            if !fill[s0] || lab[s0] >= 0 {
                continue;
            }
            lab[s0] = nisl as i32;
            stack.push(s0);
            while let Some(s) = stack.pop() {
                let (c, l) = (s >> 1, s & 1);
                let (i, j) = (c % b.nx, c / b.nx);
                let mut nb = [usize::MAX; 4];
                if i > 0 {
                    nb[0] = c - 1;
                }
                if i + 1 < b.nx {
                    nb[1] = c + 1;
                }
                if j > 0 {
                    nb[2] = c - b.nx;
                }
                if j + 1 < b.ny {
                    nb[3] = c + b.nx;
                }
                for q in nb.into_iter().filter(|&q| q != usize::MAX) {
                    let t = q * 2 + l;
                    if fill[t] && lab[t] < 0 {
                        lab[t] = nisl as i32;
                        stack.push(t);
                    }
                }
            }
            nisl += 1;
        }
        let pieces = self.components(&self.net_items_all(net));
        let mut m = Map { lab, nisl, par: (0..nisl + pieces.len()).collect(), pieces };
        for p in 0..m.pieces.len() {
            for id in m.pieces[p].clone() {
                let it = &b.items[id];
                let r = if matches!(it.shape, crate::board::Shape::Pad(_)) { THERMAL_R } else { crate::board::RES };
                let (i0, j0, i1, j1) = b.window(&it.bbox, r);
                for j in j0..=j1 {
                    for i in i0..=i1 {
                        let (x, y) = b.cell_xy(i, j);
                        for l in 0..2 {
                            let s = (j * b.nx + i) * 2 + l;
                            if it.on(l) && m.lab[s] >= 0 && (b.item_dist(it, x, y) as f64) <= r {
                                let isl = m.lab[s] as usize;
                                m.union(isl, nisl + p);
                            }
                        }
                    }
                }
            }
        }
        Some(m)
    }

    /// Roots of the pieces that hold pads, with their pad counts (most pads first).
    fn pad_groups(&self, m: &mut Map) -> Vec<(usize, usize)> {
        let mut cnt: std::collections::BTreeMap<usize, usize> = std::collections::BTreeMap::new();
        for p in 0..m.pieces.len() {
            let pads = m.pieces[p].iter().filter(|&&id| matches!(self.b.items[id].shape, crate::board::Shape::Pad(_))).count();
            if pads > 0 {
                let r = m.find(m.nisl + p);
                *cnt.entry(r).or_default() += pads;
            }
        }
        let mut v: Vec<(usize, usize)> = cnt.into_iter().collect();
        v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
        v
    }

    /// Groups of a plane net's pads that its pours and copper leave apart, beyond the first
    /// (0: connected; also 0 when the net has no pour in the board.json).
    pub fn pour_splits(&self, name: &str) -> usize {
        let Some(&net) = self.b.netid.get(name) else { return 0 };
        match self.pour_map(net) {
            Some(mut m) => self.pad_groups(&mut m).len().saturating_sub(1),
            None => 0,
        }
    }

    /// Join pour islands that hold pads to the main group: a via of diameter d where one layer
    /// belongs to the island and the other to the main group, else a track (and vias) from the
    /// group's copper to the main group's fill. Returns (groups left apart, joints added).
    pub fn pour_fix(&mut self, name: &str, d: f64) -> (usize, usize) {
        let Some(&net) = self.b.netid.get(name) else { return (0, 0) };
        let mut added = 0;
        loop {
            let Some(mut m) = self.pour_map(net) else { return (0, 0) };
            let groups = self.pad_groups(&mut m);
            if groups.len() <= 1 {
                self.log.push(json!([name, "pour groups apart", 0, "joints added", added]));
                return (0, added);
            }
            let main = groups[0].0;
            let b = &self.b;
            let (r_via, r_vpad) = ((d / 2.0 + CLR + M) as f32, (d / 2.0 + 0.05) as f32);
            let r_hole = (via_drill(d) / 2.0 + HOLE_HOLE + M) as f32;
            let mut spot = None;
            'groups: for &(g, _) in &groups[1..] {
                for c in 0..b.n {
                    let (s0, s1) = (c * 2, c * 2 + 1);
                    if m.lab[s0] < 0 || m.lab[s1] < 0 {
                        continue;
                    }
                    let (r0, r1) = (m.find(m.lab[s0] as usize), m.find(m.lab[s1] as usize));
                    if !((r0 == g && r1 == main) || (r0 == main && r1 == g)) {
                        continue;
                    }
                    if b.f[s0].fdist(net) >= r_via && b.f[s1].fdist(net) >= r_via && b.padd[s0] >= r_vpad && b.padd[s1] >= r_vpad && b.hole[c] >= r_hole {
                        spot = Some(b.cell_xy(c % b.nx, c / b.nx));
                        break 'groups;
                    }
                }
            }
            if let Some(p) = spot {
                let items = self.b.commit(net, &[], &[p], d);
                self.net_items[net as usize].extend_from_slice(&items);
                added += 1;
                continue;
            }
            // no via joins an island to the main group: route a group's copper to the main
            // group's fill (a drop that ended in a pocket no pour reaches)
            let roots: Vec<usize> = (0..m.nisl).map(|i| m.find(i)).collect();
            let tgt: Vec<i32> = (0..2 * b.n).filter(|&s| m.lab[s] >= 0 && roots[m.lab[s] as usize] == main).map(|s| s as i32).collect();
            let mut joined = false;
            for &(g, _) in &groups[1..] {
                let mine: Vec<usize> = (0..m.pieces.len()).filter(|&p| m.find(m.nisl + p) == g).collect();
                let src: Vec<usize> = mine.iter().flat_map(|&p| m.pieces[p].clone()).collect();
                let so = SearchOpts { hweight: 0.0, ..Default::default() };
                if self.join_to(net, &src, &tgt, d, &so) {
                    joined = true;
                    added += 1;
                    break;
                }
            }
            if !joined {
                // name the pads of the groups left apart
                let mut apart = Vec::new();
                for p in 0..m.pieces.len() {
                    let r = m.find(m.nisl + p);
                    if r == main {
                        continue;
                    }
                    for &id in &m.pieces[p] {
                        if let crate::board::Shape::Pad(k) = self.b.items[id].shape {
                            apart.push(format!("{}:{}", self.b.pads[k].refdes, self.b.pads[k].num));
                        }
                    }
                }
                self.log.push(json!([name, "pour groups apart", groups.len() - 1, "joints added", added, "pads apart", apart]));
                return (groups.len() - 1, added);
            }
        }
    }
}