aboutsummaryrefslogtreecommitdiff
path: root/tools/router/src/config.rs
blob: 090d999b0d4ff524ef55d22f1745397afdc30100 (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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! route.toml: the board's routing rules (replaces the Python route scripts).
//!
//! ```toml
//! prefix = "/My Sheet/"         # net names may leave it out
//! plane_nets = ["GND"]
//!
//! [[fixed]]                     # fixed copper, loaded before the steps
//! name = "bus"                  # path from --fixed bus=FILE, or `path` (relative to the toml)
//! done = true                   # its nets are complete: `rest` leaves them alone
//! [[fixed]]
//! name = "keep"
//! unmoved = true                # a board dump: keep copper of nets whose parts did not move
//! exclude = ["GND"]
//! optional = true
//!
//! [costs.sig]                   # cost maps: rectangles relative to a footprint's origin
//! zones = [{ layer = "F", fp = "U1", rect = [-8.1, -9.2, 8.1, 10.66], cost = 200 }]
//! [costs.rudy]
//! rudy = { scale = 4.0, max = 20.0 }   # RUDY congestion of the pads' MSTs on F.Cu
//!
//! [[step]]
//! do = "connect"                # via, plane, connect, pair, decaps, rest, repair, tie, stitch
//! nets = ["XI", "XO"]
//! cost = "sig"                  # "none" clears; left out, the previous map stays
//! ```
//!
//! Steps run in order. Pads are written "REF:NUM".
//!
//! `do = "pour"` checks the plane nets' pours (board.json `zones`) for islands that leave
//! pads apart and, with `fix` (default), joins them with vias of diameter `d` (0.6).
//! `planes = true` on a negotiate step routes the plane nets' drops in the negotiation
//! (instead of a `plane` step before it), so they can give way to signals.
//! `[rank]` sets how routed boards compare (see Rank).
//!
//! `area = "pours"` keeps all copper inside the plane nets' pours (board.json `zones`), e.g. a
//! design block's area; `area = [[x, y], ...]` gives a polygon. `area_margin` (mm, default 0)
//! keeps copper that far inside.
//!
//! `[[bundle]] nets = [...]` (pairs, buses): a step of one of these nets that does not run
//! alongside its bundle partners' copper costs `attract` more (hug is 0.3): on the negotiate
//! step (default 0, off; 0.5 works well) and on the cleanup step (default 0.5). Soft:
//! nothing is forced, and the cleanup still keeps a reroute only if it is at most 2 % worse.
//! Negotiation is where it counts: in the cleanup the space beside a partner is mostly taken.
//!
//! `do = "negotiate"` routes every net still in pieces at once (negotiated congestion), with
//! `cost`, `rounds`, `pres`, `pres_mult`, `hist` and search settings as defaults; a
//! `[nets.NAME]` table overrides them per net (w, wneck, neck_zone, via_d, root, decaps,
//! priority, cost, ...) and `[[nets.NAME.join]]` adds pad pairs routed first (a, b, cost, w, wneck,
//! allow_via). Higher `priority` routes first in each round.
//!
//! `[[escape]] nets = [...], from = [x, y], to = [x, y]` reserves escape lines for nets that
//! leave the block (a module's interface nets, one pad each): a virtual pad per net, spread
//! evenly from `from` to `to` in the order given (`size` mm square, default 0.25, on F.Cu),
//! routed with everything else (`w` mm wide, default the nets' own width), so a board only
//! counts as complete when every such net can still reach the block edge past the block's own
//! copper. Their copper is left out of the
//! output (`keep = true` keeps it); the base board routes the real lines.
//!
//! `neck_zone` (mm, default 1): a track may neck to `wneck` only within this distance of the
//! pads it joins. A fine-pitch part whose pins are nearly all used needs more (0.4 mm-pitch
//! QFN: 2), so neighbouring lines can spread apart before they must be full width.

use crate::router::{NetOpts, PadRef};
use anyhow::{anyhow, bail, Result};
use serde::Deserialize;
use std::collections::BTreeMap;

fn default_planes() -> Vec<String> {
    vec!["GND".into()]
}

fn yes() -> bool {
    true
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    pub prefix: String,
    #[serde(default = "default_planes")]
    pub plane_nets: Vec<String>,
    #[serde(default)]
    pub fixed: Vec<Fixed>,
    #[serde(default)]
    pub costs: BTreeMap<String, CostDef>,
    #[serde(default)]
    pub nets: BTreeMap<String, NetCfg>,
    #[serde(default)]
    pub step: Vec<Step>,
    #[serde(default)]
    pub rank: Rank,
    /// Routing area: all copper stays inside it (`area_margin` mm in, default 0).
    #[serde(default)]
    pub area: Option<Area>,
    #[serde(default)]
    pub area_margin: f64,
    /// Nets the cleanup draws together: `[[bundle]] nets = ["USB_DP", "USB_DN"]`.
    #[serde(default)]
    pub bundle: Vec<Bundle>,
    /// Escape lines for nets that leave the block, to virtual pads along an edge.
    #[serde(default)]
    pub escape: Vec<Escape>,
}

fn escape_size() -> f64 {
    0.25
}

#[derive(Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct Escape {
    /// in their order along the edge, from `from` to `to`
    pub nets: Vec<String>,
    pub from: [f64; 2],
    pub to: [f64; 2],
    #[serde(default = "escape_size")]
    pub size: f64,
    /// track width of the escape lines (default: the nets' own); the lines only reserve room,
    /// so they may be as thin as the base board will route them (e.g. 0.15 at a 0.4 mm pitch)
    pub w: Option<f64>,
    /// write the escape copper to the output too
    #[serde(default)]
    pub keep: bool,
}

#[derive(Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct Bundle {
    pub nets: Vec<String>,
}

/// `area = "pours"` (the union of the plane nets' zones in board.json) or a polygon.
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum Area {
    Pours(String),
    Poly(Vec<[f64; 2]>),
}

/// How routed boards of the same board compare (placer --route): fewer split nets, failed
/// connections and pour islands first, then the lowest score = net length x weight +
/// via_mm x vias + neck_mm x necked length + bcu_mm x B.Cu length.
#[derive(Deserialize, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct Rank {
    pub via_mm: f64,
    pub neck_mm: f64,
    pub bcu_mm: f64,
    /// net length weights by glob (`*` only), e.g. { match = "*/SENSE*", weight = 2.0 }
    pub nets: Vec<RankNet>,
}

impl Default for Rank {
    fn default() -> Self {
        Rank { via_mm: 2.0, neck_mm: 2.0, bcu_mm: 0.0, nets: vec![] }
    }
}

#[derive(Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct RankNet {
    #[serde(rename = "match")]
    pub pattern: String,
    pub weight: f64,
}

/// Glob with `*` only.
pub fn glob(pat: &str, s: &str) -> bool {
    let parts: Vec<&str> = pat.split('*').collect();
    if parts.len() == 1 {
        return pat == s;
    }
    let mut rest = s;
    for (i, p) in parts.iter().enumerate() {
        if i == 0 {
            if !rest.starts_with(p) {
                return false;
            }
            rest = &rest[p.len()..];
        } else if i == parts.len() - 1 {
            return rest.ends_with(p);
        } else if let Some(k) = rest.find(p) {
            rest = &rest[k + p.len()..];
        } else {
            return false;
        }
    }
    true
}

#[derive(Deserialize, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct NetCfg {
    #[serde(default)]
    pub join: Vec<JoinCfg>,
    pub cost: Option<String>,
    pub root: Option<String>,
    pub decaps: Option<bool>,
    pub priority: Option<i32>,
    pub w: Option<f64>,
    pub wneck: Option<f64>,
    pub via_d: Option<f64>,
    pub via_cost: Option<f64>,
    pub via_cmult: Option<f64>,
    pub bmult: Option<f64>,
    pub turn: Option<f64>,
    pub allow_via: Option<bool>,
    pub max_expand: Option<i64>,
    pub neck: Option<f64>,
    pub neck_zone: Option<f64>,
}

/// A pad pair of the net routed first, with its own settings (e.g. AVDD pins joined inside
/// a QFP's pad ring without vias).
#[derive(Deserialize, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct JoinCfg {
    pub a: String,
    pub b: String,
    pub cost: Option<String>,
    pub w: Option<f64>,
    pub wneck: Option<f64>,
    pub allow_via: Option<bool>,
}

impl NetCfg {
    /// Search settings: these where set, else the step's.
    pub fn opts(&self, step: &NetOpts) -> NetOpts {
        NetOpts {
            w: self.w.or(step.w),
            wneck: self.wneck.or(step.wneck),
            via_d: self.via_d.or(step.via_d),
            via_cost: self.via_cost.or(step.via_cost),
            via_cmult: self.via_cmult.or(step.via_cmult),
            bmult: self.bmult.or(step.bmult),
            turn: self.turn.or(step.turn),
            allow_via: self.allow_via.or(step.allow_via),
            max_expand: self.max_expand.or(step.max_expand),
            hweight: step.hweight,
            margin: step.margin,
            hug: step.hug,
            neck: self.neck.or(step.neck),
            neck_zone: self.neck_zone.or(step.neck_zone),
        }
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Fixed {
    pub name: String,
    pub path: Option<String>,
    #[serde(default)]
    pub unmoved: bool,
    #[serde(default)]
    pub exclude: Vec<String>,
    #[serde(default = "yes")]
    pub protect: bool,
    #[serde(default)]
    pub done: bool,
    #[serde(default)]
    pub optional: bool,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CostDef {
    #[serde(default)]
    pub zones: Vec<Zone>,
    pub rudy: Option<Rudy>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Zone {
    pub layer: String,
    pub fp: Option<String>,
    pub rect: [f64; 4],
    pub cost: f64,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rudy {
    #[serde(default = "f_layer")]
    pub layer: String,
    pub scale: f64,
    pub max: f64,
}

fn f_layer() -> String {
    "F".into()
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct Step {
    #[serde(rename = "do")]
    pub kind: String,
    pub label: Option<String>,
    pub cost: Option<String>,
    pub net: Option<String>,
    pub nets: Option<Vec<String>>,
    pub fp: Option<String>,
    pub at: Option<Vec<[f64; 2]>>,
    pub d: Option<f64>,
    pub only: Option<Vec<String>>,
    pub skip: Option<Vec<String>>,
    pub exclude: Option<Vec<String>>,
    pub root: Option<String>,
    pub pads: Option<Vec<String>>,
    pub a: Option<String>,
    pub b: Option<String>,
    pub pad: Option<String>,
    pub rounds: Option<usize>,
    pub radius: Option<f64>,
    pub pitch: Option<f64>,
    pub area: Option<[f64; 4]>,
    pub w: Option<f64>,
    pub wneck: Option<f64>,
    pub via_d: Option<f64>,
    pub via_cost: Option<f64>,
    pub via_cmult: Option<f64>,
    pub bmult: Option<f64>,
    pub turn: Option<f64>,
    pub allow_via: Option<bool>,
    pub max_expand: Option<i64>,
    pub hweight: Option<f64>,
    pub margin: Option<f64>,
    pub hug: Option<f64>,
    /// negotiate (default 0) and cleanup (default 0.5): extra cost per step away from the
    /// net's [[bundle]] partners
    pub attract: Option<f64>,
    /// necked step cost per mm of width given up (cleanup default 4, elsewhere 0)
    pub neck: Option<f64>,
    /// a track may neck to `wneck` within this distance (mm) of the pads it joins (default 1)
    pub neck_zone: Option<f64>,
    pub pres: Option<f64>,
    pub pres_mult: Option<f64>,
    pub hist: Option<f64>,
    pub decaps: Option<bool>,
    /// negotiate: route the plane nets' drops in the negotiation too
    pub planes: Option<bool>,
    /// pour: stitch islands to the rest of the pour with vias
    pub fix: Option<bool>,
}

impl Step {
    pub fn opts(&self) -> NetOpts {
        NetOpts {
            w: self.w,
            wneck: self.wneck,
            via_d: self.via_d,
            via_cost: self.via_cost,
            via_cmult: self.via_cmult,
            bmult: self.bmult,
            turn: self.turn,
            allow_via: self.allow_via,
            max_expand: self.max_expand,
            hweight: self.hweight,
            margin: self.margin,
            hug: self.hug,
            neck: self.neck,
            neck_zone: self.neck_zone,
        }
    }

    pub fn net(&self) -> Result<&str> {
        self.net.as_deref().ok_or_else(|| anyhow!("step {}: `net` missing", self.kind))
    }
}

pub fn pad_ref(s: &str) -> Result<PadRef> {
    let Some((r, n)) = s.split_once(':') else { bail!("pad {s:?}: write REF:NUM") };
    Ok((r.to_string(), n.to_string()))
}

pub fn pad_refs(v: &[String]) -> Result<Vec<PadRef>> {
    v.iter().map(|s| pad_ref(s)).collect()
}

impl Config {
    pub fn load(path: &str) -> Result<Config> {
        use anyhow::Context;
        let s = std::fs::read_to_string(path).with_context(|| path.to_string())?;
        toml::from_str(&s).with_context(|| path.to_string())
    }
}