aboutsummaryrefslogtreecommitdiff
path: root/tools/router-rs/src/placement.rs
blob: 94097425fadcbc5e9854d3bb443a1c402badfda9 (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
//! Move footprints of a board.json to a placer result without KiCad.
//!
//! Placement files are ref -> [x, y, rotation in degrees], at the top level or under
//! "placement" (tools/placer). KiCad's y axis points down and its angles turn counter-clockwise
//! on screen, so a footprint-local point (u, v) lies at
//! (x + u cos a + v sin a, y - u sin a + v cos a) for orientation a; moving from pose
//! (x0, y0, a0) to (x1, y1, a1) is that rotation by a1 - a0 about the old origin, then the shift.
//!
//! Pads, the footprint's own copper and its rule areas (via `keepout_refs`) move with it.
//! `tracks` and `vias` stay where they are: the old copper belongs to the old placement.
//! Footprints on the bottom side are not handled.

use crate::io::BoardJson;
use anyhow::{bail, Context, Result};
use std::collections::BTreeMap;

/// Reads a placement file.
pub fn load(path: &str) -> Result<BTreeMap<String, [f64; 3]>> {
    let s = std::fs::read_to_string(path).with_context(|| path.to_string())?;
    let v: serde_json::Value = serde_json::from_str(&s).with_context(|| path.to_string())?;
    let v = v.get("placement").cloned().unwrap_or(v);
    serde_json::from_value(v).with_context(|| format!("{path}: expected ref -> [x, y, rot]"))
}

/// Rigid transform: rotate by an angle (KiCad sense) about (ox, oy), then shift to (nx, ny).
struct Pose {
    ox: f64,
    oy: f64,
    nx: f64,
    ny: f64,
    c: f64,
    s: f64,
}

impl Pose {
    fn new(from: (f64, f64, f64), to: [f64; 3]) -> Pose {
        let a = (to[2] - from.2).rem_euclid(360.0);
        // exact values at right angles, so the common rotations add no noise
        let (s, c) = match a {
            0.0 => (0.0, 1.0),
            90.0 => (1.0, 0.0),
            180.0 => (0.0, -1.0),
            270.0 => (-1.0, 0.0),
            _ => a.to_radians().sin_cos(),
        };
        Pose { ox: from.0, oy: from.1, nx: to[0], ny: to[1], c, s }
    }

    fn pt(&self, x: f64, y: f64) -> (f64, f64) {
        let (u, v) = (x - self.ox, y - self.oy);
        (self.nx + u * self.c + v * self.s, self.ny - u * self.s + v * self.c)
    }

    fn poly(&self, p: &mut [[f64; 2]]) {
        for q in p {
            let (x, y) = self.pt(q[0], q[1]);
            *q = [x, y];
        }
    }
}

/// Moves each listed footprint; errors on unknown references and on bottom-side parts.
pub fn apply(d: &mut BoardJson, placement: &BTreeMap<String, [f64; 3]>) -> Result<()> {
    let mut poses = BTreeMap::new();
    for (r, to) in placement {
        let f = d.fps.get_mut(r.as_str()).with_context(|| format!("{r} is not on the board"))?;
        poses.insert(r.as_str(), Pose::new((f.x, f.y, f.rot), *to));
        (f.x, f.y, f.rot) = (to[0], to[1], to[2]);
    }
    for p in &mut d.pads {
        let Some(pose) = poses.get(p.refdes.as_str()) else { continue };
        if !p.npth && p.f.is_none() && p.b.is_some() {
            bail!("{} has a bottom-side pad; flipped footprints are not supported", p.refdes);
        }
        (p.x, p.y) = pose.pt(p.x, p.y);
        for poly in [&mut p.f, &mut p.b].into_iter().flatten() {
            pose.poly(poly);
        }
    }
    for c in &mut d.fpcopper {
        if let Some(pose) = poses.get(c.refdes.as_str()) {
            pose.poly(&mut c.poly);
        }
    }
    if d.keepout_refs.is_empty() {
        if !d.keepouts.is_empty() {
            eprintln!("warning: board.json has no keepout_refs (old dump): footprint keep-outs are not moved");
        }
    } else if d.keepout_refs.len() != d.keepouts.len() {
        bail!("keepout_refs and keepouts differ in length");
    } else {
        for (k, r) in d.keepouts.iter_mut().zip(&d.keepout_refs) {
            if let Some(pose) = poses.get(r.as_str()) {
                pose.poly(k);
            }
        }
    }
    Ok(())
}