aboutsummaryrefslogtreecommitdiff
path: root/tools/height_check.py
blob: fa1e6e80f9b6cf521ffca4dca44a6bf7e0525e6c (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
"""Check part heights on a DIN-rail board against the printed housing.

    tools/router/.venv/bin/python tools/height_check.py projects/<name>/kicad/<name>.kicad_pcb

Finds the HW:DIN_Housing_<k>TE footprint (its position is the housing centre), loads every
top-side footprint's 3D model (STEP vertices, transformed like KiCad does) and compares each
vertex with the height limit at its place, from tools/din_template.py dims():
- inside the front-cap box: h_tall; elsewhere h_low (bottom of the front-cap lip);
- outside the step lines (|y| > y_step): the 45 deg shoulder slope, h_edge at the PCB edge
  and 1 mm more per mm inward.
Parts that reach past the PCB edge are edge connectors: their notch runs up through the slope
(DIN housing model), so they are listed but not judged against the slope.
Bottom-side parts are not checked. Assembly STEP files (e.g. Phoenix's) cannot be placed
without their transforms: for them the F.CrtYd outline at the model's top height is used and the
result is flagged "approx".
"""
import math
import os
import re
import sys

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import din_template  # noqa: E402
import model_check  # noqa: E402
import sexpr  # noqa: E402

from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D  # noqa: E402
ENV = {
    "HW_LIB": os.path.join(ROOT, "libraries"),
    "KICAD10_3DMODEL_DIR": MODELS3D,
    "KICAD9_3DMODEL_DIR": MODELS3D,
}
_cache = {}


def vertices(path):
    """(points, exact) for a STEP file; assemblies fall back to all their points."""
    if path not in _cache:
        try:
            _cache[path] = (model_check.step_vertices(path), True)
        except SystemExit:
            txt = open(path, encoding="latin-1").read()
            pts = re.findall(r"CARTESIAN_POINT\s*\(\s*'[^']*'\s*,\s*\(\s*([-\d.eE+]+)\s*,\s*([-\d.eE+]+)\s*,\s*([-\d.eE+]+)", txt)
            _cache[path] = (np.array(pts, dtype=float), False)
    return _cache[path]


def resolve(path):
    path = re.sub(r"\$\{(\w+)\}", lambda m: ENV.get(m.group(1), m.group(0)), path)
    if not os.path.exists(path):
        for ext in (".step", ".stp"):
            alt = os.path.splitext(path)[0] + ext
            if os.path.exists(alt):
                return alt
        return None
    return path


def xyz(node, key):
    n = sexpr.first(node, key)
    v = sexpr.first(n, "xyz") if n else None
    return np.array([float(a) for a in v[1:4]]) if v else np.zeros(3) if key != "scale" else np.ones(3)


def courtyard(fp):
    """F.CrtYd corner points in footprint coordinates."""
    pts = []
    for kind in ("fp_line", "fp_rect", "fp_poly"):
        for g in sexpr.find(fp, kind):
            if str(sexpr.first(g, "layer")[1]) != "F.CrtYd":
                continue
            for key in ("start", "end"):
                n = sexpr.first(g, key)
                if n:
                    pts.append([float(n[1]), float(n[2])])
            if kind == "fp_rect":
                a, b = sexpr.first(g, "start"), sexpr.first(g, "end")
                pts += [[float(a[1]), float(b[2])], [float(b[1]), float(a[2])]]
            n = sexpr.first(g, "pts")
            pts += [[float(q[1]), float(q[2])] for q in sexpr.find(n, "xy")] if n else []
    return np.array(pts)


def model_points(fp):
    """Model vertices of a footprint in board coordinates (x, y down, z above the board)."""
    at = sexpr.first(fp, "at")
    fx, fy = float(at[1]), float(at[2])
    fa = math.radians(float(at[3])) if len(at) > 3 else 0.0
    c, s = math.cos(fa), math.sin(fa)
    out, exact = [], True
    for m in sexpr.find(fp, "model"):
        if sexpr.first(m, "hide"):
            continue
        path = resolve(str(m[1]))
        if not path or not path.lower().endswith((".step", ".stp")):
            continue
        P, ok = vertices(path)
        if not ok:  # assembly: courtyard outline at the model's top height
            exact = False
            cy = courtyard(fp)
            if not len(cy):
                continue
            top = (P * xyz(m, "scale"))[:, 2].max() + xyz(m, "offset")[2]
            P = np.column_stack([cy[:, 0], -cy[:, 1], np.full(len(cy), top)])
            rt = np.zeros(3)
            m = [None]
        else:
            rt = xyz(m, "rotate")
        R = model_check.rot(2, -rt[2]) @ model_check.rot(1, -rt[1]) @ model_check.rot(0, -rt[0])
        if ok:
            P = (P * xyz(m, "scale")) @ R.T + xyz(m, "offset")
        P[:, 1] = -P[:, 1]
        x = P[:, 0] * c + P[:, 1] * s + fx
        y = -P[:, 0] * s + P[:, 1] * c + fy
        out.append(np.column_stack([x, y, P[:, 2]]))
    return (np.vstack(out) if out else None), exact


def limit(d, u, v):
    """Height limit above the PCB at housing coordinates u, v (arrays)."""
    au, av = np.abs(u), np.abs(v)
    lim = np.where((au <= d["tall_x"]) & (av <= d["tall_y"]), d["h_tall"], d["h_low"])
    slope = d["h_edge"] + d["pcb_h"] / 2 - av
    return np.where(av > d["y_step"], np.minimum(lim, slope), lim)


def main():
    board = sexpr.parse(open(sys.argv[1]).read())
    fps = sexpr.find(board, "footprint")
    housing = [f for f in fps if re.match(r"HW:DIN_Housing_(\d+)TE$", str(f[1]))]
    if not housing:
        sys.exit("no HW:DIN_Housing_<k>TE footprint on the board")
    k = int(re.match(r"HW:DIN_Housing_(\d+)TE$", str(housing[0][1])).group(1))
    at = sexpr.first(housing[0], "at")
    cx, cy = float(at[1]), float(at[2])
    d = din_template.dims(k)
    edge = d["pcb_h"] / 2
    print("%d TE, centre (%.2f, %.2f): h_tall %.1f, h_low %.1f, step at |y| > %.1f: %.1f at the line to %.1f at the edge"
          % (k, cx, cy, d["h_tall"], d["h_low"], d["y_step"], d["h_edge"] + edge - d["y_step"], d["h_edge"]))
    bad, nomodel = 0, []
    for fp in fps:
        if fp is housing[0] or str(sexpr.first(fp, "layer")[1]) != "F.Cu":
            continue
        ref = next((str(p[2]) for p in sexpr.find(fp, "property") if str(p[1]) == "Reference"), "?")
        P, exact = model_points(fp)
        if P is None:
            nomodel.append(ref)
            continue
        P = P[P[:, 2] > 0.05]
        if not len(P):
            continue
        u, v = P[:, 0] - cx, P[:, 1] - cy
        note = "" if exact else " (approx: assembly)"
        if np.abs(v).max() > edge + 0.05:
            print("  %-6s edge connector, %.1f mm tall, |y| %.1f..%.1f: needs a notch through the slope%s"
                  % (ref, P[:, 2].max(), np.abs(v).min(), np.abs(v).max(), note))
            continue
        over = P[:, 2] - limit(d, u, v)
        if over.max() > 0:
            bad += 1
            i = over.argmax()
            print("  %-6s TOO TALL by %.1f mm: %.1f mm at (%.1f, %.1f) from the centre%s"
                  % (ref, over[i], P[i, 2], u[i], -v[i], note))
    if nomodel:
        print("  not checked (no STEP model): %s" % " ".join(sorted(nomodel)))
    print("%d part(s) too tall" % bad)
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()