changeset 0:b5a96b547b01

initial public version
author ark
date 2026-11-03 01:29 +0100
parents
children aa23650954d6
files .hgignore README.md fontlib.py main.scad make_glyphs.py make_preview.py make_template.py
diffstat 7 files changed, 2301 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.hgignore	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,7 @@
+.DS_Store
+preview/
+generated/
+glyphs.scad
+.stl
+.svg
+.pdf
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/README.md	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,235 @@
+# House number
+
+3D-printed house numbers, or any other text, to screw to a wall. Each glyph
+is a separate flat piece with two countersunk screw holes. Distance washers
+behind the holes keep it off the wall and take up unevenness. The glyphs
+print face down. A two-colour look with an outline band is possible on a
+single-colour printer by changing filament once.
+
+The work is split in three steps:
+
+1. `make_preview.py` renders the text in every installed font, to choose
+   one.
+2. `make_glyphs.py` turns the text in the chosen font into glyph outlines,
+   works out the largest printable size and places the screw holes.
+3. `main.scad` builds the printable parts in OpenSCAD, and a drilling
+   template, which `make_template.py` splits into printable pages.
+
+## Requirements
+
+- Python 3 with fontTools, Pillow and numpy. `make_template.py` needs only
+  the standard library.
+- fontconfig's `fc-list`, which the scripts use to find fonts.
+- An OpenSCAD development snapshot. The model uses features newer than the
+  2021.01 release.
+
+## Choosing a font
+
+    ./make_preview.py --text 24
+
+writes one PNG per font into `preview/`. Each image shows the text as it
+will be printed, drawn from the same outlines as the model. The caption
+gives family, style, PostScript name, weight, classification and the
+largest printable size. The file name is the font's PostScript name, so the
+image can be passed to `make_glyphs.py` as it is. Named instances of
+variable fonts, such as the weights of SF Pro, count as separate fonts.
+Fonts that lack a character of the text are skipped.
+
+On the development machine, all installed fonts took about 2 minutes and
+244 MB. Filters narrow the selection:
+
+    ./make_preview.py --text 24 --family 'helvetica|futura' --weight-min 600
+    ./make_preview.py --text 24 --class serif --no-italic
+
+`--family` and `--name` take regular expressions, matched against the
+family and the PostScript name. `--italic`, `--mono` and their `--no-`
+forms select by style. `--class serif` or `--class sans` keeps only fonts
+that classify themselves that way; many fonts carry no classification and
+appear only without this filter. `--list` prints the matching fonts
+without rendering.
+
+To see the two-colour look, give the band width in mm:
+
+    ./make_preview.py --text 24 --band 4 --fill '#202020' --outline '#c03030' --background '#e8e4dc'
+
+The band is scaled to each font's largest print size in the single-glyph
+layout, or in the whole-text layout with `--layout text`.
+
+## Glyph data
+
+    ./make_glyphs.py preview/Futura-Bold.png 24
+    ./make_glyphs.py Futura-Bold 24
+
+The font is given by PostScript name or preview image. The script writes
+`glyphs.scad`, which `main.scad` includes, and a directory
+`generated/<font>_<text>/` with an SVG outline and a check image per glyph.
+It prints the largest sizes and the hole positions; warnings go to standard
+error.
+
+### Size
+
+Size is the height of the tallest glyph, in mm. The usable area is the bed
+(300 mm) minus its margin (10 mm) and the frame of the two-colour print:
+280 mm minus 4 line widths. Two layouts fit differently:
+
+- text: the whole text in one print, spaced as the font spaces it.
+- glyph: one glyph per print, all glyphs at the same size.
+
+For both, the script reports the largest size unrotated and at the best
+angle between 0 and 90 degrees. In Helvetica Bold, "24" reaches 189 mm in
+the text layout and 278 mm per glyph; rotation gains nothing. In SF Extra
+Compressed Thin, turning the glyphs by 45 degrees raises the size per glyph
+from 278 to 325 mm.
+
+The holes are placed for one size, by default the largest unrotated size in
+the glyph layout. `--layout`, `--angle` (-1 for the best) and `--size`
+choose another. OpenSCAD can scale to any size later; it then checks that
+the screw heads still fit.
+
+### Screw holes
+
+Each glyph gets two holes, one near its upper and one near its lower end:
+
+1. Only points where the screw head (8 mm, `--head-d`) plus a wall of 2
+   line widths (`--wall-lines`) fits inside the glyph are considered.
+2. The glyph's main axis is found from its inked area. It follows the slant
+   of italic and script fonts and turns sideways for wide glyphs.
+   `--vertical-axis` forces it upright.
+3. Along the axis, the holes aim at 85% and 15% of the glyph length
+   (`--target`). Distance from the axis is penalised (`--side-weight`);
+   sitting in the middle of the stroke is rewarded (`--centre-weight`).
+4. Where no point has room for the head, the hole goes to the thickest
+   point of that half, and the script warns.
+
+The check images show the glyph in grey, the area with room for the head in
+green, the axis in blue and the holes in red, orange where the head does not
+fit.
+
+### Glyphs of several parts
+
+Glyphs such as "i", "รค" or "%" consist of separate parts. The script
+reports them and works out a backing that connects them, see below. A hole
+can land in a separate part when the target position lies there, such as
+the dot of "i".
+
+### Fonts with overlapping outlines
+
+Many fonts, variable fonts in particular, draw glyphs from overlapping or
+self-crossing contours. OpenSCAD's SVG import would turn the overlaps into
+holes. The script splits and groups the contours so the imported shape
+matches the font, and compares the result with the font's own filling. Both
+scripts report a difference.
+
+## The model
+
+Open `main.scad` in OpenSCAD and set the parameters in the customizer. The
+console shows the size, thicknesses, warnings and a file name for the
+export.
+
+### Parts
+
+- `all`: the glyphs as they hang on the wall, with the washers behind them.
+- `body`: the glyph in print orientation, face on the bed. In single-colour
+  mode this is the whole print.
+- `decal`: the outline band of the two-colour print.
+- `washer`: one distance washer. Make copies in the slicer.
+- `template`: the drilling template, 2D.
+
+### Layout and size
+
+`layout` chooses between the whole text and one glyph per print.
+`glyph_index` picks the glyph, counted from 0 without spaces. `size` 0 uses
+the largest size that fits, `angle` -1 the best angle. `bed_size` and
+`bed_margin` describe the printer.
+
+### Glyph
+
+`glyph_layers` sets the thickness, 6 layers by default: 1.2 mm at 0.2 mm
+layers. `backing` adds `backing_layers` (4 by default) behind the glyph,
+covering its outline. For glyphs of several parts the backing is the outline
+grown and shrunk back, so the parts join; where that does not work, it fills
+the convex hull. The gaps between parts are bridged and may need supports.
+
+### Screws
+
+`screw_d` (4 mm) and `head_d` (8 mm) set the hole and the countersink, each
+widened by `clearance` on both sides. The countersink is 90 degrees and
+opens towards the bed. With thin glyphs it is deeper than the glyph: at the
+defaults 2 mm against 1.2 mm. The washer then continues the cone.
+
+### Washers
+
+The washer wall is `washer_wall_lines` line widths around the hole, 8 by
+default. `washer_height` defaults to 10 mm. It is raised, with a warning,
+to the part of the countersink inside the washer plus 4 layers. The washer
+prints with the glyph side up.
+
+With `washers_on_body`, the washers are part of the body instead, standing
+on the glyph's back. Where a washer is wider than the glyph at that point,
+it is cut back to the outline so it does not overhang, and a warning is
+shown.
+
+### Two-colour print
+
+With `two_colour`, the glyph is split into a body and a decal:
+
+- The decal is a band of `band_width` (4 mm) along the glyph outline, two
+  layers thick.
+- The body leaves out the band plus one line width, so the nozzle does not
+  touch the printed decal.
+- Both contain the same frame, one layer high and one line width wide,
+  around the glyphs. It makes the slicer place both parts in the same spot.
+
+To print:
+
+1. Slice decal and body with the same settings.
+2. Print the decal.
+3. Change filament. Remove the skirt, if any, and the frame.
+4. Print the body on top.
+
+Where a stroke is too narrow to leave body material between the bands, the
+face shows only the decal colour.
+
+### Export
+
+Render (F6) and export the 3D parts as STL. The file name echoed in the
+console carries font, text, glyph, options, size, angle and print settings,
+for example
+
+    house_number_body_Futura-Bold_24_g0_2c_cs_s2780a0t6_lw40lh20.stl
+
+## Drilling template
+
+The holes do not line up with each other, so a full-size template shows
+where to drill. Set `part` to `template`, render and export as SVG. The
+template uses the same size as the print and shows:
+
+- the glyph outlines where they hang on the wall, spaced as the font spaces
+  them, also when the glyphs are printed one at a time;
+- a circle of the hole diameter at each hole, with a cross reaching past the
+  washer;
+- a level line along the baseline;
+- a 100 mm scale bar with 10 mm ticks.
+
+Then
+
+    ./make_template.py house_number_template_Futura-Bold_24_s2780_lw40lh20.svg
+
+writes a PDF of the same name, split over A4 pages, portrait or landscape,
+whichever needs fewer. Print it at 100% and check the scale bar.
+Neighbouring pages overlap by 10 mm. A dashed line with crosses every 50 mm
+runs through the middle of each overlap. Trim one sheet along the line, lay
+it over its neighbour so line and crosses match, and tape it. Each page
+names its row and column in the bottom margin.
+
+`--paper` (a4, a3, letter, legal), `--margin` (unprintable edge, 6 mm) and
+`--overlap` change the page layout.
+
+## Files
+
+- `make_preview.py`, `make_glyphs.py`, `make_template.py`: the scripts.
+  Each lists its options with `--help`.
+- `fontlib.py`: code shared by the first two.
+- `main.scad`: the model.
+- `glyphs.scad`, `generated/`: written by `make_glyphs.py`.
+- `preview/`: written by `make_preview.py`.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/fontlib.py	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,861 @@
+"""Font lookup, glyph outlines and geometry helpers for the house number scripts.
+
+Shared by make_preview.py and make_glyphs.py. Fonts are found through
+fontconfig (fc-list) and read with fontTools. Glyph outlines are flattened
+into polygons, so the preview, the hole calculation and the OpenSCAD model
+all use the same shapes.
+
+Coordinates are in font units until a script scales them to mm. The y axis
+points up.
+"""
+
+import math
+import os
+import subprocess
+from collections import deque
+from dataclasses import dataclass, field
+
+import numpy as np
+from fontTools.pens.basePen import BasePen
+from fontTools.ttLib import TTFont
+
+FC_FORMAT = ("%{file}\t%{index}\t%{postscriptname}\t%{family[0]}\t"
+             "%{style[0]}\t%{slant}\t%{spacing}\t%{variable}\n")
+
+
+# ---------------------------------------------------------------- font lookup
+
+@dataclass
+class FaceInfo:
+    """One font face as listed by fontconfig.
+
+    Attributes:
+        file: path of the font file.
+        index: fontconfig index. The lower 16 bits are the face number in a
+            collection, the upper 16 bits the 1-based named instance of a
+            variable font (0 for the default instance).
+        psname: PostScript name, used as the identifier of the face.
+        family: family name.
+        style: style name.
+        italic: true for italic and oblique faces.
+        mono: true for monospaced faces.
+    """
+    file: str
+    index: int
+    psname: str
+    family: str
+    style: str
+    italic: bool
+    mono: bool
+
+    @property
+    def file_name(self):
+        """File name stem for this face: the PostScript name without a
+        leading dot, so the files of Apple's system fonts are not hidden."""
+        return self.psname.lstrip(".")
+
+
+def list_faces():
+    """List the font faces known to fontconfig.
+
+    Variable font entries that stand for the whole variable font are left
+    out; their named instances are listed separately. Faces without a
+    PostScript name are left out. When several faces share a PostScript
+    name, the first one is kept.
+
+    Returns:
+        list of FaceInfo, sorted by file name stem.
+    """
+    out = subprocess.run(["fc-list", "--format", FC_FORMAT],
+                         capture_output=True, text=True, check=True).stdout
+    faces = {}
+    for line in out.splitlines():
+        parts = line.split("\t")
+        if len(parts) != 8:
+            continue
+        file, index, psname, family, style, slant, spacing, variable = parts
+        if variable == "True" or not psname:
+            continue
+        if not file.lower().endswith((".ttf", ".otf", ".ttc", ".otc")):
+            continue
+        info = FaceInfo(file=file, index=int(index), psname=psname,
+                        family=family, style=style,
+                        italic=float(slant or 0) > 0,
+                        mono=spacing == "100")
+        faces.setdefault(info.file_name, info)
+    return [faces[k] for k in sorted(faces, key=str.lower)]
+
+
+def find_face(name):
+    """Find a face by PostScript name or by the path of its preview PNG.
+
+    Args:
+        name: PostScript name, with or without leading dot, or a path whose
+            file name stem is the name (such as preview/Helvetica-Bold.png).
+
+    Returns:
+        the FaceInfo.
+
+    Raises:
+        LookupError: no face of that name.
+    """
+    stem = os.path.basename(name)
+    if stem.lower().endswith(".png"):
+        stem = stem[:-4]
+    stem = stem.lstrip(".")
+    for face in list_faces():
+        if face.file_name == stem:
+            return face
+    raise LookupError(f"no font with PostScript name {stem!r}")
+
+
+# ------------------------------------------------------------------ outlines
+
+class _FlattenPen(BasePen):
+    """Pen that turns glyph outlines into closed polygons.
+
+    Curves are split into straight segments so that no point of a segment
+    is further than the tolerance from the curve.
+    """
+
+    def __init__(self, glyphset, tolerance):
+        """Args:
+            glyphset: glyph set, used to draw components.
+            tolerance: largest distance between curve and segments, in font
+                units.
+        """
+        super().__init__(glyphset)
+        self.tolerance = tolerance
+        self.contours = []
+        self._cur = []
+
+    def _segments(self, second_diff):
+        """Number of segments for a curve whose largest second difference of
+        control points is second_diff."""
+        return max(1, math.ceil(math.sqrt(second_diff / (4 * self.tolerance))))
+
+    def _moveTo(self, pt):
+        self._cur = [pt]
+
+    def _lineTo(self, pt):
+        self._cur.append(pt)
+
+    def _curveToOne(self, p1, p2, p3):
+        p0 = self._getCurrentPoint()
+        dd = max(math.dist((p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]), (0, 0)),
+                 math.dist((p1[0] - 2 * p2[0] + p3[0], p1[1] - 2 * p2[1] + p3[1]), (0, 0)))
+        n = self._segments(3 * dd)
+        for i in range(1, n + 1):
+            t = i / n
+            a, b, c, d = (1 - t) ** 3, 3 * t * (1 - t) ** 2, 3 * t * t * (1 - t), t ** 3
+            self._cur.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
+                              a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]))
+
+    def _qCurveToOne(self, p1, p2):
+        p0 = self._getCurrentPoint()
+        dd = math.dist((p0[0] - 2 * p1[0] + p2[0], p0[1] - 2 * p1[1] + p2[1]), (0, 0))
+        n = self._segments(dd)
+        for i in range(1, n + 1):
+            t = i / n
+            a, b, c = (1 - t) ** 2, 2 * t * (1 - t), t * t
+            self._cur.append((a * p0[0] + b * p1[0] + c * p2[0],
+                              a * p0[1] + b * p1[1] + c * p2[1]))
+
+    def _closePath(self):
+        pts = np.array(self._cur, dtype=float)
+        self._cur = []
+        if len(pts) and np.allclose(pts[0], pts[-1]):
+            pts = pts[:-1]
+        if len(pts) >= 3:
+            # drop repeated points
+            keep = np.any(np.diff(pts, axis=0, append=pts[:1]) != 0, axis=1)
+            pts = pts[keep]
+        if len(pts) >= 3:
+            self.contours.append(pts)
+
+    def _endPath(self):
+        # open contours do not occur in fonts; close them anyway
+        self._closePath()
+
+
+@dataclass
+class Glyph:
+    """Outline of one character.
+
+    Attributes:
+        char: the character.
+        advance: advance width in font units.
+        contours: closed polygons as (n, 2) arrays, font units.
+        groups: contours grouped for filling, see group_contours().
+        fill_error: fraction of the glyph area where the grouped outline
+            differs from the font's intended filling, see fill_error().
+    """
+    char: str
+    advance: float
+    contours: list
+    groups: list = field(default_factory=list)
+    fill_error: float = 0.0
+
+    @property
+    def empty(self):
+        """True for glyphs without outline, such as a space."""
+        return not self.contours
+
+    def bbox(self):
+        """Ink bounding box as (xmin, ymin, xmax, ymax)."""
+        pts = np.concatenate(self.contours)
+        return (*pts.min(axis=0), *pts.max(axis=0))
+
+    def scaled(self, k, dx=0.0):
+        """Copy with all coordinates multiplied by k and shifted by dx."""
+        off = np.array([dx, 0.0])
+        return Glyph(self.char, self.advance * k,
+                     [c * k + off for c in self.contours],
+                     [[c * k + off for c in g] for g in self.groups])
+
+
+class Face:
+    """An opened font face, positioned at its named instance if it has one.
+
+    Attributes:
+        info: the FaceInfo.
+        font: the fontTools TTFont.
+        upm: units per em.
+        location: axis coordinates of the named instance, or None.
+    """
+
+    def __init__(self, info):
+        """Open the face.
+
+        Args:
+            info: FaceInfo from list_faces() or find_face().
+        """
+        self.info = info
+        self.font = TTFont(info.file, fontNumber=info.index & 0xFFFF, lazy=True)
+        self.upm = self.font["head"].unitsPerEm
+        self.location = None
+        instance = info.index >> 16
+        if instance and "fvar" in self.font:
+            self.location = dict(self.font["fvar"].instances[instance - 1].coordinates)
+        self.glyphset = self.font.getGlyphSet(location=self.location)
+        self.cmap = self.font.getBestCmap() or {}
+
+    @property
+    def weight(self):
+        """Weight on the 100 to 900 scale of the OS/2 table."""
+        if self.location and "wght" in self.location:
+            return round(self.location["wght"])
+        if "fvar" in self.font:
+            for axis in self.font["fvar"].axes:
+                if axis.axisTag == "wght":
+                    return round(axis.defaultValue)
+        if "OS/2" in self.font:
+            return self.font["OS/2"].usWeightClass
+        return 400
+
+    @property
+    def classification(self):
+        """'serif' or 'sans' from the PANOSE data of the OS/2 table, or None
+        when the font does not classify itself as Latin text."""
+        if "OS/2" not in self.font:
+            return None
+        panose = self.font["OS/2"].panose
+        if panose.bFamilyType != 2:
+            return None
+        if 2 <= panose.bSerifStyle <= 10:
+            return "serif"
+        if 11 <= panose.bSerifStyle <= 13:
+            return "sans"
+        return None
+
+    @property
+    def mono(self):
+        """True for monospaced faces."""
+        return self.info.mono or bool(getattr(self.font.get("post"), "isFixedPitch", 0))
+
+    def has_chars(self, text):
+        """True if the face has a glyph for every character of text."""
+        return all(ord(c) in self.cmap for c in text)
+
+    def glyph(self, char, tolerance=None):
+        """Outline of one character.
+
+        Args:
+            char: the character.
+            tolerance: flattening tolerance in font units. Default: 1/10000
+                of the em, about 0.04 mm for a 280 mm digit.
+
+        Returns:
+            Glyph with contours and fill groups.
+
+        Raises:
+            KeyError: the face has no glyph for the character.
+        """
+        name = self.cmap.get(ord(char))
+        if name is None:
+            raise KeyError(f"{self.info.psname} has no glyph for {char!r}")
+        pen = _FlattenPen(self.glyphset, tolerance or self.upm / 10000)
+        g = self.glyphset[name]
+        g.draw(pen)
+        glyph = Glyph(char, g.width, pen.contours)
+        if glyph.contours:
+            glyph.groups = group_contours(glyph.contours)
+            glyph.fill_error = fill_error(glyph.contours, glyph.groups)
+        return glyph
+
+    def layout(self, text):
+        """Outlines of the characters of text, placed as the font spaces
+        them on one line.
+
+        Args:
+            text: the text.
+
+        Returns:
+            list of (x offset in font units, Glyph), one per character,
+            spaces included.
+        """
+        x, out = 0.0, []
+        for char in text:
+            glyph = self.glyph(char)
+            out.append((x, glyph))
+            x += glyph.advance
+        return out
+
+
+# --------------------------------------------------------------- polygons
+
+def signed_area(poly):
+    """Signed area of a polygon, positive for counter-clockwise order."""
+    x, y = poly[:, 0], poly[:, 1]
+    return 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y))
+
+
+def points_in_polygon(points, poly):
+    """Even-odd inside test of points against one polygon.
+
+    Args:
+        points: (n, 2) array.
+        poly: (m, 2) array, closed implicitly.
+
+    Returns:
+        bool array of length n.
+    """
+    inside = np.zeros(len(points), dtype=bool)
+    px, py = points[:, 0], points[:, 1]
+    ax, ay = poly[:, 0], poly[:, 1]
+    bx, by = np.roll(ax, -1), np.roll(ay, -1)
+    for i in range(len(poly)):
+        crosses = (ay[i] > py) != (by[i] > py)
+        if not crosses.any():
+            continue
+        xc = ax[i] + (py - ay[i]) * (bx[i] - ax[i]) / (by[i] - ay[i] + (by[i] == ay[i]))
+        inside ^= crosses & (px < xc)
+    return inside
+
+
+def split_self_intersections(contour):
+    """Split a contour that crosses itself into loops that do not.
+
+    The crossing points are inserted on both segments. Then, as long as a
+    crossing point occurs twice in the point sequence, the part between the
+    two occurrences is cut off as a separate loop.
+
+    Args:
+        contour: (n, 2) array.
+
+    Returns:
+        list of (k, 2) arrays. Loops of negligible area are dropped.
+    """
+    n = len(contour)
+    a, b = contour, np.roll(contour, -1, axis=0)
+    d = b - a
+    cuts = [[] for _ in range(n)]
+    label = 0
+    for i in range(n - 2):
+        j = np.arange(i + 2, n if i else n - 1)
+        if not len(j):
+            continue
+        den = d[i, 0] * d[j, 1] - d[i, 1] * d[j, 0]
+        ok = np.abs(den) > 1e-12
+        den = np.where(ok, den, 1)
+        w = a[j] - a[i]
+        t = (w[:, 0] * d[j, 1] - w[:, 1] * d[j, 0]) / den
+        u = (w[:, 0] * d[i, 1] - w[:, 1] * d[i, 0]) / den
+        hit = ok & (t > 1e-9) & (t < 1 - 1e-9) & (u > 1e-9) & (u < 1 - 1e-9)
+        for k in np.nonzero(hit)[0]:
+            pt = a[i] + t[k] * d[i]
+            cuts[i].append((t[k], label, pt))
+            cuts[j[k]].append((u[k], label, pt))
+            label += 1
+    if not label:
+        return [contour]
+    seq = []
+    for i in range(n):
+        seq.append((-1, a[i]))
+        seq.extend((lab, pt) for _, lab, pt in sorted(cuts[i], key=lambda c: c[0]))
+    loops, todo = [], [seq]
+    while todo:
+        cur = todo.pop()
+        first = {}
+        for pos, (lab, _) in enumerate(cur):
+            if lab < 0:
+                continue
+            if lab in first:
+                p, q = first[lab], pos
+                todo.append([(-1, pt) for _, pt in cur[p:q]])
+                todo.append(cur[:p] + [(-1, cur[q][1])] + cur[q + 1:])
+                break
+            first[lab] = pos
+        else:
+            loops.append(np.array([pt for _, pt in cur]))
+    scale = abs(signed_area(contour)) or 1
+    return [lp for lp in loops if len(lp) >= 3 and abs(signed_area(lp)) > 1e-6 * scale]
+
+
+def group_contours(contours):
+    """Group contours so that even-odd filling of each group, combined by
+    union, gives the non-zero filling the font intends.
+
+    Contours that cross themselves are split into simple loops first. Each
+    group is one outer contour followed by the holes inside it. Outer
+    contours turn the same way as the largest contour; the others are
+    holes. A hole is given to the smallest outer contour that contains all
+    its points. A hole inside no outer contour is filled under the non-zero
+    rule, so it becomes an outer contour itself. Outer contours come out
+    counter-clockwise, holes clockwise.
+
+    Args:
+        contours: list of (n, 2) arrays.
+
+    Returns:
+        list of groups, each a list of (n, 2) arrays, outer contour first.
+    """
+    contours = [lp for c in contours for lp in split_self_intersections(c)]
+    areas = [signed_area(c) for c in contours]
+    outer_sign = math.copysign(1, areas[int(np.argmax(np.abs(areas)))])
+    outers = [i for i, a in enumerate(areas) if math.copysign(1, a) == outer_sign]
+    holes = {}
+    for i, a in enumerate(areas):
+        if i in outers:
+            continue
+        best = None
+        for j in outers:
+            if abs(areas[j]) > abs(a) and points_in_polygon(contours[i], contours[j]).all():
+                if best is None or abs(areas[j]) < abs(areas[best]):
+                    best = j
+        holes.setdefault(best, []).append(i)
+    ccw = [c if signed_area(c) > 0 else c[::-1] for c in contours]
+    groups = [[ccw[i]] + [ccw[h][::-1] for h in holes.get(i, [])] for i in outers]
+    groups += [[ccw[h]] for h in holes.get(None, [])]
+    return groups
+
+
+def fill_error(contours, groups, cells=250):
+    """Compare the union of even-odd filled groups with the non-zero filling
+    of the original contours, on a coarse grid.
+
+    Args:
+        contours: original contours.
+        groups: result of group_contours().
+        cells: grid cells along the longer side of the bounding box.
+
+    Returns:
+        mismatching cells as a fraction of the non-zero filled cells.
+    """
+    pts = np.concatenate(contours)
+    lo, hi = pts.min(axis=0), pts.max(axis=0)
+    step = max(hi - lo) / cells
+    grid = Grid.around((*lo, *hi), step, 2 * step)
+    nonzero = rasterise_winding(contours, grid)
+    grouped, _ = rasterise(groups, grid)
+    return float((nonzero != grouped).sum()) / max(1, int(nonzero.sum()))
+
+
+def densify(contour, max_len):
+    """Contour with long segments split so none is longer than max_len."""
+    a, b = contour, np.roll(contour, -1, axis=0)
+    n = np.maximum(1, np.ceil(np.linalg.norm(b - a, axis=1) / max_len).astype(int))
+    if (n == 1).all():
+        return contour
+    out = [a[i] + (b[i] - a[i]) * (k / n[i]) for i in range(len(a)) for k in range(n[i])]
+    return np.array(out)
+
+
+def visible_runs(groups, max_len):
+    """Polylines along the outline of the union of all groups.
+
+    Parts of a contour that lie inside another group are hidden by the
+    union and left out. Contours are first split into segments no longer
+    than max_len; each segment is kept or dropped by its midpoint.
+
+    Args:
+        groups: contour groups from group_contours().
+        max_len: longest segment for the visibility test.
+
+    Returns:
+        list of (k, 2) arrays. A fully visible contour comes out closed,
+        with its first point repeated at the end.
+    """
+    runs = []
+    for gi, group in enumerate(groups):
+        others = [g for gj, g in enumerate(groups) if gj != gi]
+        for c in group:
+            if not others:
+                runs.append(np.vstack([c, c[:1]]))
+                continue
+            c = densify(c, max_len)
+            a, b = c, np.roll(c, -1, axis=0)
+            mid = (a + b) / 2
+            hidden = np.zeros(len(c), dtype=bool)
+            for o in others:
+                hidden |= inside_group(mid, o)
+            if not hidden.any():
+                runs.append(np.vstack([c, c[:1]]))
+                continue
+            # start at a hidden segment so every visible run is contiguous
+            run = []
+            for k in np.roll(np.arange(len(c)), -int(np.argmax(hidden))):
+                if hidden[k]:
+                    if run:
+                        runs.append(np.array(run))
+                    run = []
+                else:
+                    if not run:
+                        run.append(a[k])
+                    run.append(b[k])
+            if run:
+                runs.append(np.array(run))
+    return runs
+
+
+def boundary_segments(groups, max_len):
+    """Segments of the outline of the union of all groups, see
+    visible_runs().
+
+    Returns:
+        (a, b): (m, 2) arrays of segment start and end points.
+    """
+    runs = visible_runs(groups, max_len)
+    return (np.concatenate([r[:-1] for r in runs]),
+            np.concatenate([r[1:] for r in runs]))
+
+
+def inside_group(points, group):
+    """Even-odd inside test of points against one contour group."""
+    inside = np.zeros(len(points), dtype=bool)
+    for c in group:
+        inside ^= points_in_polygon(points, c)
+    return inside
+
+
+def convex_hull(points):
+    """Convex hull by the monotone chain method.
+
+    Args:
+        points: (n, 2) array.
+
+    Returns:
+        (k, 2) array, counter-clockwise.
+    """
+    pts = sorted(map(tuple, np.unique(points, axis=0)))
+    if len(pts) < 3:
+        return np.array(pts)
+
+    def half(seq):
+        out = []
+        for p in seq:
+            while len(out) >= 2 and ((out[-1][0] - out[-2][0]) * (p[1] - out[-2][1])
+                                     - (out[-1][1] - out[-2][1]) * (p[0] - out[-2][0])) <= 0:
+                out.pop()
+            out.append(p)
+        return out
+
+    lower, upper = half(pts), half(reversed(pts))
+    return np.array(lower[:-1] + upper[:-1])
+
+
+def rotated_extent(points, angle):
+    """Width and height of the bounding box of points rotated by angle
+    degrees counter-clockwise."""
+    a = math.radians(angle)
+    rot = np.array([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]])
+    r = points @ rot.T
+    return np.ptp(r[:, 0]), np.ptp(r[:, 1])
+
+
+# ------------------------------------------------------------- size fitting
+
+def usable_area(bed, margin, line_width):
+    """Side of the square available for glyphs: the bed minus its margin,
+    minus frame and frame gap of one line width each on both sides."""
+    return bed - 2 * margin - 4 * line_width
+
+
+def _fit_shapes(placed):
+    """Convex hulls to fit on the bed and the tallest ink height.
+
+    Returns:
+        (height, {'text': [hull of the whole text], 'glyph': [hull per glyph]})
+    """
+    inked = [(x, g) for x, g in placed if not g.empty]
+    height = max(g.bbox()[3] - g.bbox()[1] for _, g in inked)
+    hulls = [convex_hull(np.concatenate(g.contours)) for _, g in inked]
+    text_hull = convex_hull(np.concatenate([h + [x, 0] for (x, _), h in zip(inked, hulls)]))
+    return height, {"text": [text_hull], "glyph": hulls}
+
+
+def size_at(placed, usable, layout, angle):
+    """Largest print size for one layout and angle.
+
+    Size is the height of the tallest glyph's ink. In the text layout the
+    whole text has to fit the usable square; in the glyph layout every glyph
+    on its own, all at the same scale.
+
+    Args:
+        placed: result of Face.layout(), or the same structure in mm.
+        usable: side of the usable square in mm.
+        layout: 'text' or 'glyph'.
+        angle: rotation on the bed in degrees.
+
+    Returns:
+        size in mm.
+    """
+    height, shapes = _fit_shapes(placed)
+    extent = max(max(rotated_extent(h, angle)) for h in shapes[layout])
+    return usable / extent * height
+
+
+def max_sizes(placed, usable):
+    """Largest print size for both layouts, at 0 degrees and at the best
+    angle. Angles from 0 to 90 degrees in 1 degree steps are tried.
+
+    Args:
+        placed: result of Face.layout(), or the same structure in mm.
+        usable: side of the usable square in mm.
+
+    Returns:
+        dict with keys 'text' and 'glyph', each a dict with 'size0' (size at
+        0 degrees), 'angle' (best angle) and 'size' (size at that angle), in
+        mm. See size_at().
+    """
+    height, shapes = _fit_shapes(placed)
+    result = {}
+    for layout, hulls in shapes.items():
+        sizes = [usable / max(max(rotated_extent(h, a)) for h in hulls) * height
+                 for a in range(91)]
+        best = int(np.argmax(sizes))
+        result[layout] = {"size0": sizes[0], "angle": best, "size": sizes[best]}
+    return result
+
+
+# ------------------------------------------------------------------ rasters
+
+@dataclass
+class Grid:
+    """Regular grid of sample points.
+
+    Point (i, j) lies at (x0 + i * step, y0 + j * step). Arrays over the
+    grid have shape (ny, nx), row j and column i.
+    """
+    x0: float
+    y0: float
+    step: float
+    nx: int
+    ny: int
+
+    @classmethod
+    def around(cls, bbox, step, pad):
+        """Grid covering bbox = (xmin, ymin, xmax, ymax) plus pad on all
+        sides."""
+        x0, y0 = bbox[0] - pad, bbox[1] - pad
+        nx = int(math.ceil((bbox[2] + pad - x0) / step)) + 1
+        ny = int(math.ceil((bbox[3] + pad - y0) / step)) + 1
+        return cls(x0, y0, step, nx, ny)
+
+    def points(self):
+        """All grid points as an (ny * nx, 2) array, row by row."""
+        xs = self.x0 + np.arange(self.nx) * self.step
+        ys = self.y0 + np.arange(self.ny) * self.step
+        gx, gy = np.meshgrid(xs, ys)
+        return np.stack([gx.ravel(), gy.ravel()], axis=1)
+
+
+def _scanline_toggles(contours, grid, signed):
+    """Crossings of contour edges with the grid rows.
+
+    Each crossing is counted at the first grid point to its right. With
+    signed set, upward edges count +1 and downward edges -1; otherwise all
+    count 1.
+
+    Returns:
+        int array of shape (grid.ny, grid.nx + 1). Its cumulative sum along
+        the rows gives the crossing count left of each point.
+    """
+    toggles = np.zeros((grid.ny, grid.nx + 1), dtype=np.int32)
+    for c in contours:
+        a, b = c, np.roll(c, -1, axis=0)
+        ya, yb = a[:, 1], b[:, 1]
+        lo, hi = np.minimum(ya, yb), np.maximum(ya, yb)
+        # rows whose y lies in [lo, hi)
+        j0 = np.clip(np.ceil((lo - grid.y0) / grid.step).astype(int), 0, grid.ny)
+        j1 = np.clip(np.ceil((hi - grid.y0) / grid.step).astype(int), 0, grid.ny)
+        counts = np.maximum(j1 - j0, 0)
+        total = int(counts.sum())
+        if not total:
+            continue
+        edge = np.repeat(np.arange(len(c)), counts)
+        rows = np.repeat(j0, counts) + (np.arange(total)
+                                        - np.repeat(np.cumsum(counts) - counts, counts))
+        y = grid.y0 + rows * grid.step
+        t = (y - ya[edge]) / (yb[edge] - ya[edge])
+        x = a[edge, 0] + t * (b[edge, 0] - a[edge, 0])
+        col = np.clip(np.floor((x - grid.x0) / grid.step).astype(int) + 1, 0, grid.nx)
+        weight = np.where(yb[edge] > ya[edge], 1, -1) if signed else 1
+        np.add.at(toggles, (rows, col), weight)
+    return toggles
+
+
+def rasterise_group(group, grid):
+    """Even-odd inside test of all grid points against one contour group.
+
+    Returns:
+        bool array of shape (grid.ny, grid.nx).
+    """
+    toggles = _scanline_toggles(group, grid, signed=False)
+    return (np.cumsum(toggles, axis=1)[:, :grid.nx] % 2).astype(bool)
+
+
+def rasterise_winding(contours, grid):
+    """Non-zero inside test of all grid points against a set of contours.
+
+    Returns:
+        bool array of shape (grid.ny, grid.nx).
+    """
+    toggles = _scanline_toggles(contours, grid, signed=True)
+    return np.cumsum(toggles, axis=1)[:, :grid.nx] != 0
+
+
+def rasterise(groups, grid):
+    """Inside test of all grid points against the union of contour groups.
+
+    Returns:
+        (mask, group_masks): bool array of shape (grid.ny, grid.nx) and the
+        list of masks of the single groups.
+    """
+    masks = [rasterise_group(g, grid) for g in groups]
+    return np.logical_or.reduce(masks), masks
+
+
+def distance_to_segments(points, a, b, chunk=2048):
+    """Distance from each point to the nearest of a set of segments.
+
+    Args:
+        points: (n, 2) array.
+        a, b: (m, 2) arrays of segment start and end points.
+        chunk: points handled per step, to limit memory use.
+
+    Returns:
+        (n,) array.
+    """
+    # float32 and separate x and y arrays: about 3 times faster than
+    # float64 arrays with a coordinate axis
+    a = np.asarray(a, dtype=np.float32)
+    ab = np.asarray(b, dtype=np.float32) - a
+    inv = 1 / np.maximum((ab ** 2).sum(axis=1), 1e-12)
+    ax, ay, abx, aby = a[:, 0], a[:, 1], ab[:, 0], ab[:, 1]
+    pts = np.asarray(points, dtype=np.float32)
+    out = np.empty(len(points))
+    for s in range(0, len(points), chunk):
+        dx = pts[s:s + chunk, 0:1] - ax
+        dy = pts[s:s + chunk, 1:2] - ay
+        t = np.clip((dx * abx + dy * aby) * inv, 0, 1)
+        dx -= t * abx
+        dy -= t * aby
+        out[s:s + chunk] = np.sqrt((dx * dx + dy * dy).min(axis=1))
+    return out
+
+
+def max_filter(arr, radius):
+    """Largest value within a square window of radius cells around each
+    cell, computed with doubling shifts along both axes."""
+    out = arr
+    for axis in (0, 1):
+        out = _max_1d(out, radius, axis)
+    return out
+
+
+def _max_1d(arr, radius, axis):
+    """Largest value within radius cells along one axis."""
+    width = 2 * radius + 1
+    pad = [(0, 0), (0, 0)]
+    pad[axis] = (radius, radius + width)
+    a = np.pad(arr, pad, constant_values=-np.inf)
+    span, cur = 1, a
+    # cur holds the maximum over windows of length span
+    while span * 2 <= width:
+        cur = np.maximum(cur, np.roll(cur, -span, axis=axis))
+        span *= 2
+    res = np.maximum(cur, np.roll(cur, -(width - span), axis=axis))
+    n = arr.shape[axis]
+    return np.take(res, np.arange(n), axis=axis)
+
+
+def components(mask):
+    """Number of 4-connected components of a bool mask."""
+    seen = np.zeros_like(mask)
+    ny, nx = mask.shape
+    count = 0
+    for start in zip(*np.nonzero(mask)):
+        if seen[start]:
+            continue
+        count += 1
+        seen[start] = True
+        queue = deque([start])
+        while queue:
+            j, i = queue.popleft()
+            for dj, di in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+                q = (j + dj, i + di)
+                if 0 <= q[0] < ny and 0 <= q[1] < nx and mask[q] and not seen[q]:
+                    seen[q] = True
+                    queue.append(q)
+    return count
+
+
+def part_count(groups, group_masks):
+    """Number of separate parts of a glyph: groups that overlap or touch
+    form one part.
+
+    Args:
+        groups: contour groups.
+        group_masks: their masks from rasterise().
+
+    Returns:
+        (count, labels): number of parts and the part number of each group.
+    """
+    n = len(groups)
+    parent = list(range(n))
+
+    def root(i):
+        while parent[i] != i:
+            parent[i] = parent[parent[i]]
+            i = parent[i]
+        return i
+
+    grown = [grow1(m) for m in group_masks]
+    for i in range(n):
+        for j in range(i + 1, n):
+            if (grown[i] & group_masks[j]).any():
+                parent[root(i)] = root(j)
+    roots = sorted({root(i) for i in range(n)})
+    labels = [roots.index(root(i)) for i in range(n)]
+    return len(roots), labels
+
+
+def grow1(mask):
+    """Mask grown by one cell in the four axis directions."""
+    out = mask.copy()
+    out[1:] |= mask[:-1]
+    out[:-1] |= mask[1:]
+    out[:, 1:] |= mask[:, :-1]
+    out[:, :-1] |= mask[:, 1:]
+    return out
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.scad	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,340 @@
+// House number: glyphs of a text, printed face down, screwed to a wall
+// with distance washers. Glyph outlines and hole positions come from
+// glyphs.scad, written by make_glyphs.py.
+
+/* [part selection] */
+// part to show or export; the decal needs two-colour mode; the template is
+// 2D, for SVG export and make_template.py
+part = "all"; // [all, body, decal, washer, template]
+
+/* [layout] */
+// whole text in one print, or one glyph per print
+layout = "glyph"; // [text, glyph]
+// glyph to print in the glyph layout, counted from 0, spaces not counted
+glyph_index = 0; // [0:1:30]
+// height of the tallest glyph, 0 for the largest that fits
+size = 0; // [0:.1:500]
+// rotation on the bed in degrees, -1 for the best angle
+angle = 0; // [-1:1:90]
+// bed size
+bed_size = 300; // [100:1:500]
+// unusable margin along the bed edges
+bed_margin = 10; // [0:.5:50]
+
+/* [glyph] */
+// glyph thickness in layers, decal layers included
+glyph_layers = 6; // [3:1:60]
+// backing behind the glyph, covering its outline and connecting separate parts
+backing = false;
+// backing thickness in layers
+backing_layers = 4; // [1:1:20]
+
+/* [screws] */
+// screw diameter
+screw_d = 4; // [2:.5:8]
+// countersunk holes, 90 degrees
+countersink = true;
+// screw head diameter
+head_d = 8; // [3:.5:16]
+// minimum material around the screw head, in line widths, for the fit check
+head_wall_lines = 2; // [0:1:10]
+
+/* [two-colour] */
+// split into body and decal, for a filament change on a single-colour printer
+two_colour = false;
+// width of the decal band along the outline
+band_width = 4; // [.5:.1:20]
+
+/* [washer] */
+// print the washers as part of the body, on the back of the glyph
+washers_on_body = false;
+// washer wall around the screw hole, in line widths
+washer_wall_lines = 8; // [1:1:40]
+// washer height, raised to the countersink part inside the washer plus 4 layers
+washer_height = 10; // [0:.5:30]
+
+/* [print settings] */
+line_width = .4; // [0:.01:1]
+layer_height = .2; // [0:.01:.5]
+clearance = .1; // [0:.01:.5]
+
+module dummy() {}
+
+include <glyphs.scad>
+
+epsilon = .001;
+$fn = $preview ? 60 : 180;
+
+lw = line_width;
+lh = layer_height;
+
+// thicknesses
+glyph_t = glyph_layers * lh;
+backing_t = backing ? backing_layers * lh : 0;
+total_t = glyph_t + backing_t;
+decal_t = 2 * lh;      // 2 layers
+frame_t = lh;          // 1 layer
+
+// screw holes: 90 degree countersink, depth is half the diameter difference
+hole_d = screw_d + 2 * clearance;
+cs_d = head_d + 2 * clearance;
+cs_depth = countersink ? (cs_d - hole_d) / 2 : 0;
+// part of the countersink that reaches beyond the glyph into the washer
+cs_washer = max(0, cs_depth - total_t);
+
+// washer
+washer_od = hole_d + 2 * washer_wall_lines * lw;
+washer_min = cs_washer + 4 * lh;   // 4 layers below the countersink
+washer_h = max(washer_height, washer_min);
+
+// layout and size
+n_glyphs = len(g_glyphs);
+sel = layout == "text" ? [for (i = [0 : n_glyphs - 1]) i] : [glyph_index];
+usable = bed_size - 2 * bed_margin - 4 * lw;   // frame and gap, 1 line width each
+best_angle = layout == "text" ? g_max_text[1] : g_max_glyph[1];
+print_angle = angle < 0 ? best_angle : angle;
+// glyphs are drawn unrotated in the assembly view
+ang = part == "all" ? 0 : print_angle;
+fit_extent = layout == "text"
+    ? _extent([for (g = g_glyphs) for (p = g[4]) [p.x + g[2], p.y]], print_angle)
+    : max([for (g = g_glyphs) _extent(g[4], print_angle)]);
+max_size = usable / fit_extent * g_size;
+final_size = size > 0 ? size : max_size;
+k = final_size / g_size;   // scale from the data file to the print
+
+// placement: centre the bounding box of the shown glyphs on the origin
+raw_pts = [for (i = sel) for (p = g_glyphs[i][4]) _tf0([p.x + _off(i), p.y])];
+bb = [min([for (p = raw_pts) p.x]), min([for (p = raw_pts) p.y]),
+      max([for (p = raw_pts) p.x]), max([for (p = raw_pts) p.y])];
+centre = [(bb[0] + bb[2]) / 2, (bb[1] + bb[3]) / 2];
+
+// holes of the shown glyphs: [position, largest circle radius at the print size]
+holes = [for (i = sel) for (h = g_glyphs[i][5]) [_tf([h.x + _off(i), h.y]), h[2] * k]];
+head_r_req = head_d / 2 + head_wall_lines * lw;
+
+assert(glyph_index < n_glyphs, str("glyph_index must be below ", n_glyphs));
+assert(part != "decal" || two_colour, "the decal needs two_colour");
+
+echo(str("size: ", final_size, " mm, largest that fits ", max_size, " mm at ",
+         print_angle, " degrees"));
+echo(str("glyph thickness: ", glyph_t, " mm, with backing ", total_t, " mm"));
+echo(str("hole: ", hole_d, " mm, countersink ", cs_d, " mm, depth ", cs_depth,
+         " mm, of which in the washer ", cs_washer, " mm"));
+echo(str("washer: ", washer_od, " mm outside, ", washer_h, " mm high, wall ",
+         washer_wall_lines, " line widths"));
+if (size > max_size + .01)
+    echo(str("WARNING: size ", size, " mm does not fit the bed, largest is ", max_size, " mm"));
+if (washer_height < washer_min)
+    echo(str("WARNING: washer height raised to ", washer_min, " mm"));
+for (h = holes) if (h[1] < head_r_req)
+    echo(str("WARNING: hole at ", h[0], ": largest circle radius ", h[1],
+             " mm, head plus wall needs ", head_r_req, " mm"));
+if (washers_on_body) for (h = holes) if (h[1] < washer_od / 2)
+    echo(str("WARNING: washer at ", h[0], " is cut back to the glyph outline"));
+
+// Size of the bounding box of points rotated by a degrees, along its longer side.
+// pts: list of 2D points. a: angle in degrees.
+function _extent(pts, a) =
+    let (r = [for (p = pts) [p.x * cos(a) - p.y * sin(a), p.x * sin(a) + p.y * cos(a)]])
+    max(max([for (q = r) q.x]) - min([for (q = r) q.x]),
+        max([for (q = r) q.y]) - min([for (q = r) q.y]));
+
+// x offset of glyph i: its place in the text in the text layout, else 0.
+function _off(i) = layout == "text" ? g_glyphs[i][2] : 0;
+
+// Point from the data file to the print, before centring: scaled, rotated,
+// mirrored for printing face down.
+function _tf0(p) =
+    let (q = k * p, r = [q.x * cos(ang) - q.y * sin(ang), q.x * sin(ang) + q.y * cos(ang)])
+    [-r.x, r.y];
+
+// Point from the data file to its place in the print.
+function _tf(p) = _tf0(p) - centre;
+
+// Apply the placement of _tf() to 2D children given in data file coordinates.
+module _place() {
+    translate(-centre) mirror([1, 0]) rotate(ang) scale(k) children();
+}
+
+// Outline of glyph i in data file coordinates, at its place in the layout.
+module _glyph2d(i) {
+    translate([_off(i), 0]) import(g_glyphs[i][1]);
+}
+
+// Backing outline of glyph i in data file coordinates: the outline itself,
+// grown and shrunk to connect separate parts, or the convex hull.
+module _backing2d(i) {
+    r = g_glyphs[i][7];
+    if (r > 0) offset(r = -r) offset(r = r) _glyph2d(i);
+    else if (r < 0) hull() _glyph2d(i);
+    else _glyph2d(i);
+}
+
+// Outline of all shown glyphs, placed for printing.
+module _placed2d() {
+    for (i = sel) _place() _glyph2d(i);
+}
+
+// Decal band: the outline minus the outline shrunk by the band width.
+module _band2d() {
+    difference() {
+        _placed2d();
+        offset(r = -band_width) _placed2d();
+    }
+}
+
+// Screw holes and countersinks, opening towards the bed, through washers
+// printed on the body.
+module _holes() {
+    for (h = holes) translate(h[0]) {
+        translate([0, 0, -1])
+            cylinder(d = hole_d, h = total_t + (washers_on_body ? washer_h : 0) + 2);
+        if (countersink)
+            translate([0, 0, -epsilon])
+                cylinder(d1 = cs_d + 2 * epsilon, d2 = hole_d, h = cs_depth + epsilon);
+    }
+}
+
+// Frame of one layer and one line width, one line width around the shown
+// glyphs. Decal and body both contain it, so the slicer places them alike.
+module _frame() {
+    linear_extrude(frame_t) difference() {
+        translate([bb[0] - centre.x - 2 * lw, bb[1] - centre.y - 2 * lw])
+            square([bb[2] - bb[0] + 4 * lw, bb[3] - bb[1] + 4 * lw]);
+        translate([bb[0] - centre.x - lw, bb[1] - centre.y - lw])
+            square([bb[2] - bb[0] + 2 * lw, bb[3] - bb[1] + 2 * lw]);
+    }
+}
+
+// Outline of the back of the shown glyphs, placed for printing: the backing
+// if there is one, else the glyph outline.
+module _back2d() {
+    if (backing) for (i = sel) _place() _backing2d(i);
+    else _placed2d();
+}
+
+// Glyph body in print orientation, face on the bed. In two-colour mode the
+// decal band plus one line width is left out of the decal layers. Washers
+// printed on the body stand on its back, cut back to the outline of the back
+// so they do not overhang.
+// frame: include the frame (two-colour mode only).
+module body(frame = true) {
+    difference() {
+        union() {
+            linear_extrude(glyph_t) _placed2d();
+            if (backing)
+                translate([0, 0, glyph_t - epsilon]) linear_extrude(backing_t + epsilon)
+                    _back2d();
+            if (washers_on_body)
+                translate([0, 0, total_t - epsilon]) intersection() {
+                    for (h = holes) translate(h[0]) cylinder(d = washer_od, h = washer_h + epsilon);
+                    linear_extrude(washer_h + epsilon) _back2d();
+                }
+        }
+        _holes();
+        if (two_colour)
+            translate([0, 0, -epsilon]) linear_extrude(decal_t + epsilon)
+                offset(delta = lw) _band2d();
+    }
+    if (two_colour && frame) _frame();
+}
+
+// Decal in print orientation: the band along the outline, with the frame.
+// frame: include the frame.
+module decal(frame = true) {
+    difference() {
+        linear_extrude(decal_t) _band2d();
+        _holes();
+    }
+    if (frame) _frame();
+}
+
+// Distance washer, printed with the glyph side up. With countersinks deeper
+// than the glyph, the cone continues in the top of the washer.
+module washer() {
+    difference() {
+        cylinder(d = washer_od, h = washer_h);
+        translate([0, 0, -1]) cylinder(d = hole_d, h = washer_h + 2);
+        if (cs_washer > 0)
+            translate([0, 0, washer_h - cs_washer])
+                cylinder(d1 = hole_d, d2 = hole_d + 2 * cs_washer + 2 * epsilon,
+                         h = cs_washer + epsilon);
+    }
+}
+
+// Drilling template in 2D, as seen on the wall: all glyphs of the text at
+// their place, a circle and cross at each hole, a level line along the
+// baseline and a 100 mm scale bar with 10 mm ticks. Everything is made of
+// thin strips, so the outlines of the SVG export show each line.
+module template() {
+    t = .2;   // strip width
+    // wall layout: text positions, no rotation, no mirroring
+    function pos(g, p) = k * [p.x + g[2], p.y];
+    pts = [for (g = g_glyphs) for (p = g[4]) pos(g, p)];
+    x0 = min([for (p = pts) p.x]);
+    x1 = max([for (p = pts) p.x]);
+    y0 = min([for (p = pts) p.y]);
+    arm = washer_od / 2 + 5;
+    for (g = g_glyphs) {
+        scale(k) translate([g[2], 0]) difference() {
+            import(g[1]);
+            offset(delta = -t / k) import(g[1]);
+        }
+        for (h = g[5]) translate(pos(g, h)) {
+            difference() {
+                circle(d = hole_d);
+                circle(d = hole_d - 2 * t);
+            }
+            square([2 * arm, t], center = true);
+            square([t, 2 * arm], center = true);
+        }
+    }
+    // level line along the baseline
+    translate([x0 - 20, -t / 2]) square([x1 - x0 + 40, t]);
+    // scale bar below the text
+    translate([x0, y0 - 20]) {
+        square([100, t]);
+        for (i = [0 : 10])
+            translate([10 * i - t / 2, 0]) square([t, i % 5 == 0 ? 6 : 3]);
+    }
+}
+
+// Assembly view: glyphs face up as on the wall, washers behind the holes.
+module assembly() {
+    rotate([0, 180, 0]) {
+        color("lightgray") body(frame = false);
+        if (two_colour) color("firebrick") decal(frame = false);
+        if (!washers_on_body)
+            color("steelblue") for (h = holes)
+                translate([h[0].x, h[0].y, total_t + washer_h]) mirror([0, 0, 1]) washer();
+    }
+}
+
+// Output the selected part.
+module main() {
+    if (part == "all") assembly();
+    else if (part == "body") body();
+    else if (part == "decal") decal();
+    else if (part == "washer") washer();
+    else if (part == "template") template();
+}
+
+main();
+
+// Export file name without extension, see the print settings for lw and lh.
+// prefix: project name with trailing underscore. suffix: appended as is.
+function paramstring(prefix = "", suffix = "") = str(
+    prefix,
+    part == "all" ? "" : str(part, "_"),
+    part == "template" ? str(g_name, "_s", round(10 * final_size))
+    : part == "washer"
+        ? str(countersink ? "cs_" : "", "d", round(10 * screw_d), "w", washer_wall_lines,
+              "h", round(10 * washer_h), countersink ? str("c", round(10 * cs_washer)) : "")
+        : str(g_name, "_", layout == "glyph" ? str("g", glyph_index, "_") : "",
+              two_colour ? "2c_" : "", backing ? "bk_" : "", countersink ? "cs_" : "",
+              washers_on_body ? str("wh", round(10 * washer_h), "_") : "",
+              "s", round(10 * final_size), "a", round(print_angle), "t", glyph_layers),
+    "_lw", round(100 * line_width), "lh", round(100 * layer_height),
+    suffix);
+
+echo(paramstring("house_number_"));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make_glyphs.py	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+"""Write glyph outlines and screw hole positions for the OpenSCAD model.
+
+For one font and text, this writes an SVG file per glyph and a check image
+per glyph into generated/<font>_<text>/, and the data file glyphs.scad,
+which main.scad includes. All sizes are in mm at the size the holes were
+placed for.
+
+Holes: per glyph one near the top and one near the bottom end, along the
+glyph's main axis, in the middle of the stroke and with room for the
+countersink head plus a minimum wall. See place_holes().
+"""
+
+import argparse
+import logging
+import math
+import os
+import re
+import shlex
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw
+
+import fontlib as fl
+
+
+def parse_args():
+    """Parse the command line."""
+    p = argparse.ArgumentParser(description=__doc__,
+                                formatter_class=argparse.RawDescriptionHelpFormatter)
+    p.add_argument("font", help="PostScript name of the font, or the path of its preview PNG")
+    p.add_argument("text", help="the text, one line")
+    p.add_argument("--out", default="generated",
+                   help="directory for the glyph directories (default: %(default)s)")
+    p.add_argument("--data", default="glyphs.scad",
+                   help="data file for main.scad (default: %(default)s)")
+    s = p.add_argument_group("size")
+    s.add_argument("--layout", choices=["text", "glyph"], default="glyph",
+                   help="layout whose maximum size is the default size (default: %(default)s)")
+    s.add_argument("--angle", type=float, default=0,
+                   help="rotation on the bed in degrees, for the default size; "
+                        "-1 for the best angle (default: %(default)s)")
+    s.add_argument("--size", type=float,
+                   help="height of the tallest glyph in mm (default: the maximum)")
+    h = p.add_argument_group("holes")
+    h.add_argument("--screw-d", type=float, default=4,
+                   help="screw diameter in mm, for the check images (default: %(default)s)")
+    h.add_argument("--head-d", type=float, default=8,
+                   help="countersink head diameter in mm (default: %(default)s)")
+    h.add_argument("--wall-lines", type=float, default=2,
+                   help="minimum wall around the head, in line widths (default: %(default)s)")
+    h.add_argument("--target", type=float, default=.85,
+                   help="position of the top hole along the axis, 0 bottom to 1 top; "
+                        "the bottom hole mirrors it (default: %(default)s)")
+    h.add_argument("--side-weight", type=float, default=.5,
+                   help="penalty for sideways distance from the axis (default: %(default)s)")
+    h.add_argument("--centre-weight", type=float, default=.3,
+                   help="reward for sitting in the middle of the stroke (default: %(default)s)")
+    h.add_argument("--vertical-axis", action="store_true",
+                   help="use a vertical axis instead of the glyph's main axis")
+    h.add_argument("--grid", type=float, default=.5,
+                   help="sample spacing in mm (default: %(default)s)")
+    b = p.add_argument_group("printer")
+    b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)")
+    b.add_argument("--margin", type=float, default=10,
+                   help="bed margin in mm (default: %(default)s)")
+    b.add_argument("--line-width", type=float, default=.4,
+                   help="line width in mm (default: %(default)s)")
+    return p.parse_args()
+
+
+def warn(msg):
+    """Print a warning to stderr."""
+    print(f"warning: {msg}", file=sys.stderr)
+
+
+def text_name(text):
+    """Text as a file name part: letters and digits kept, other characters
+    as u and their hexadecimal code point."""
+    return "".join(c if re.fullmatch(r"[A-Za-z0-9]", c) else f"u{ord(c):04x}" for c in text)
+
+
+# --------------------------------------------------------------- hole placement
+
+def place_holes(g, args):
+    """Find the two screw hole positions of a glyph.
+
+    1. Distance from each inside grid point to the outline.
+    2. Allowed points: room for the countersink head plus the minimum wall.
+    3. Axis: main axis of the inked area (or vertical), pointing up.
+    4. Each point gets a position along the axis, 0 at the lower end and 1
+       at the upper end, and a sideways distance from the axis.
+    5. In each half, the allowed point with the best score wins. The score
+       rewards closeness to the target position, penalises sideways
+       distance relative to the glyph length, and rewards being in the
+       middle of the stroke: distance to the outline relative to the
+       largest distance nearby.
+    6. A half without allowed points gets its largest inscribed circle.
+
+    Args:
+        g: Glyph in mm.
+        args: command line arguments.
+
+    Returns:
+        dict with 'holes' ([[x, y, r], [x, y, r]], top first, r the radius of
+        the largest circle that fits there), 'fits' (per hole), 'grid',
+        'mask', 'allowed', 'axis' (centre, direction, lower and upper end
+        along the axis), 'r_req' and 'group_masks'.
+    """
+    r_req = args.head_d / 2 + args.wall_lines * args.line_width
+    grid = fl.Grid.around(g.bbox(), args.grid, 2 * args.grid)
+    mask, group_masks = fl.rasterise(g.groups, grid)
+    pts = grid.points().reshape(grid.ny, grid.nx, 2)
+    a, b = fl.boundary_segments(g.groups, 1.0)
+    d = np.zeros(mask.shape)
+    d[mask] = fl.distance_to_segments(pts[mask], a, b)
+
+    inside = pts[mask]
+    centre = inside.mean(axis=0)
+    if args.vertical_axis:
+        axis = np.array([0.0, 1.0])
+    else:
+        evals, evecs = np.linalg.eigh(np.cov((inside - centre).T))
+        axis = evecs[:, int(np.argmax(evals))]
+    if axis[1] < 0 or (axis[1] == 0 and axis[0] < 0):
+        axis = -axis
+    normal = np.array([-axis[1], axis[0]])
+    s = (pts - centre) @ axis
+    u = (pts - centre) @ normal
+    smin, smax = s[mask].min(), s[mask].max()
+    length = smax - smin
+    t = (s - smin) / length
+
+    radius = max(1, int(math.ceil(d.max() / grid.step)))
+    nearby = fl.max_filter(d, radius)
+    centred = d / np.maximum(nearby, 1e-9)
+    score = (-np.abs(t - np.where(t >= .5, args.target, 1 - args.target))
+             - args.side_weight * np.abs(u) / length
+             + args.centre_weight * centred)
+    allowed = mask & (d >= r_req)
+
+    holes, fits = [], []
+    for half in (t >= .5, t <= .5):
+        cand = allowed & half
+        fits.append(bool(cand.any()))
+        if cand.any():
+            idx = np.unravel_index(np.argmax(np.where(cand, score, -np.inf)), mask.shape)
+        else:
+            cand = mask & half
+            idx = np.unravel_index(np.argmax(np.where(cand, d, -np.inf)), mask.shape)
+        holes.append([*pts[idx], d[idx]])
+    return {"holes": holes, "fits": fits, "grid": grid, "mask": mask, "allowed": allowed,
+            "axis": (centre, axis, smin, smax), "r_req": r_req, "group_masks": group_masks}
+
+
+# --------------------------------------------------------------------- backing
+
+def closing_connected(groups, radius, step):
+    """True if growing the outline by radius and shrinking it back gives a
+    single piece. Checked on a grid of the given step."""
+    pts_all = np.concatenate([c for grp in groups for c in grp])
+    bbox = (*pts_all.min(axis=0), *pts_all.max(axis=0))
+    grid = fl.Grid.around(bbox, step, radius + 3 * step)
+    mask, _ = fl.rasterise(groups, grid)
+    pts = grid.points()
+    flat = mask.ravel()
+    a, b = fl.boundary_segments(groups, 1.0)
+    d_out = np.full(len(pts), np.inf)
+    d_out[~flat] = fl.distance_to_segments(pts[~flat], a, b)
+    grown = mask | (d_out.reshape(mask.shape) <= radius)
+    # shrink: keep points at least radius from the cells outside the grown shape
+    edge = ~grown & fl.grow1(grown)
+    q = pts[edge.ravel()]
+    keep = np.zeros(len(pts), dtype=bool)
+    gflat = grown.ravel()
+    keep[gflat] = fl.distance_to_segments(pts[gflat], q, q) >= radius - step / 2
+    closed = mask | keep.reshape(mask.shape)
+    return fl.components(closed) == 1
+
+
+def backing_radius(g, labels, count, args):
+    """Radius for growing and shrinking the outline so that the backing
+    connects all parts of a glyph.
+
+    The gaps between parts are measured, and the largest gap needed to
+    connect them all is found (largest edge of a minimum spanning tree).
+    Radii from half that gap upwards are tried until the result is one
+    piece.
+
+    Returns:
+        the radius in mm, 0 for a glyph of one part, -1 if no tried radius
+        connects the parts (the backing then uses the convex hull).
+    """
+    if count == 1:
+        return 0.0
+    parts = [[grp for grp, lab in zip(g.groups, labels) if lab == p] for p in range(count)]
+    segs = [fl.boundary_segments(pg, 1.0) for pg in parts]
+    gap = np.zeros((count, count))
+    for i in range(count):
+        for j in range(count):
+            if i != j:
+                gap[i, j] = fl.distance_to_segments(segs[i][0], *segs[j]).min()
+    gap = np.minimum(gap, gap.T)
+    # Prim's algorithm for the minimum spanning tree
+    in_tree, worst = {0}, 0.0
+    while len(in_tree) < count:
+        best = min((gap[i, j], j) for i in in_tree for j in range(count) if j not in in_tree)
+        worst = max(worst, best[0])
+        in_tree.add(best[1])
+    for radius in (worst / 2 + args.line_width, worst, 1.5 * worst, 2 * worst):
+        step = max(args.grid, min(1.0, radius / 3))
+        if closing_connected(g.groups, radius, step):
+            return radius
+    return -1.0
+
+
+# ---------------------------------------------------------------------- output
+
+def write_svg(path, g):
+    """Write the glyph as SVG, one path element per contour group.
+
+    OpenSCAD fills each path element by the even-odd rule and combines the
+    elements. Coordinates are mm, glyph origin at the SVG origin. The page
+    is the positive quadrant up to the glyph's extent; OpenSCAD maps an SVG
+    point (x, y) to (x, page height - y).
+    """
+    _, _, xmax, ymax = g.bbox()
+    w, h = max(xmax, 1.0), max(ymax, 1.0)
+    paths = []
+    for group in g.groups:
+        d = " ".join("M " + " L ".join(f"{x:.4f},{h - y:.4f}" for x, y in c) + " Z"
+                     for c in group)
+        paths.append(f'<path d="{d}"/>')
+    with open(path, "w") as f:
+        f.write(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w:.4f}mm" '
+                f'height="{h:.4f}mm" viewBox="0 0 {w:.4f} {h:.4f}">\n')
+        f.write("\n".join(paths))
+        f.write("\n</svg>\n")
+
+
+def write_check_image(path, res, args):
+    """Write an image of the hole placement: glyph grey, allowed area green,
+    axis blue, screw hole and countersink head red."""
+    grid, mask, allowed = res["grid"], res["mask"], res["allowed"]
+    img = np.full(mask.shape + (3,), 255, dtype=np.uint8)
+    img[mask] = (190, 190, 190)
+    img[allowed] = (170, 220, 170)
+    im = Image.fromarray(img[::-1])
+    d = ImageDraw.Draw(im)
+
+    def px(x, y):
+        return ((x - grid.x0) / grid.step, grid.ny - 1 - (y - grid.y0) / grid.step)
+
+    centre, axis, smin, smax = res["axis"]
+    d.line([px(*(centre + smin * axis)), px(*(centre + smax * axis))],
+           fill=(40, 80, 220), width=3)
+    for (x, y, r), fits in zip(res["holes"], res["fits"]):
+        cx, cy = px(x, y)
+        for rad, width in ((args.head_d / 2, 3), (res["r_req"], 1)):
+            rp = rad / grid.step
+            d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp), outline=(200, 30, 30), width=width)
+        rp = args.screw_d / 2 / grid.step
+        d.ellipse((cx - rp, cy - rp, cx + rp, cy + rp),
+                  fill=(200, 30, 30) if fits else (240, 140, 0))
+    im.save(path, optimize=True)
+
+
+def scad_str(s):
+    """OpenSCAD string literal."""
+    return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def scad_num(v):
+    """Number for OpenSCAD with 4 decimals, trailing zeros removed."""
+    return f"{v:.4f}".rstrip("0").rstrip(".")
+
+
+def scad_pts(pts):
+    """List of points for OpenSCAD."""
+    return "[" + ", ".join(f"[{scad_num(x)}, {scad_num(y)}]" for x, y in pts) + "]"
+
+
+# ------------------------------------------------------------------------ main
+
+def main():
+    """Lay out the text, place the holes and write the output files."""
+    logging.disable(logging.WARNING)
+    args = parse_args()
+    info = fl.find_face(args.font)
+    face = fl.Face(info)
+    missing = [c for c in args.text if ord(c) not in face.cmap]
+    if missing:
+        sys.exit(f"{info.psname} has no glyph for {''.join(missing)!r}")
+    placed = face.layout(args.text)
+    if all(g.empty for _, g in placed):
+        sys.exit("the text has no visible glyphs")
+    for _, g in placed:
+        if g.fill_error > 0.001:
+            warn(f"{g.char!r}: outline differs from the font's filling "
+                 f"on {100 * g.fill_error:.1f}% of its area")
+
+    usable = fl.usable_area(args.bed, args.margin, args.line_width)
+    sizes = fl.max_sizes(placed, usable)
+    angle = sizes[args.layout]["angle"] if args.angle < 0 else args.angle
+    size_max = fl.size_at(placed, usable, args.layout, angle)
+    size = args.size or size_max
+    if size > size_max + 1e-6:
+        warn(f"size {size:.1f} mm exceeds the maximum of {size_max:.1f} mm "
+             f"for the {args.layout} layout at {angle:g} degrees")
+    height = max(g.bbox()[3] - g.bbox()[1] for _, g in placed if not g.empty)
+    k = size / height
+
+    name = f"{info.file_name}_{text_name(args.text)}"
+    outdir = os.path.join(args.out, name)
+    os.makedirs(outdir, exist_ok=True)
+    for f in os.listdir(outdir):
+        if f.endswith((".svg", ".png")):
+            os.remove(os.path.join(outdir, f))
+
+    print(f"font {info.psname} ({info.family} {info.style}), text {args.text!r}")
+    print(f"maximum size: text layout {sizes['text']['size0']:.1f} mm, "
+          f"best {sizes['text']['size']:.1f} mm at {sizes['text']['angle']} degrees; "
+          f"glyph layout {sizes['glyph']['size0']:.1f} mm, "
+          f"best {sizes['glyph']['size']:.1f} mm at {sizes['glyph']['angle']} degrees")
+    print(f"holes placed for size {size:.1f} mm")
+
+    done, entries = {}, []
+    for x, g in placed:
+        if g.empty:
+            continue
+        stem = f"u{ord(g.char):04x}"
+        if g.char not in done:
+            gm = g.scaled(k)
+            res = place_holes(gm, args)
+            count, labels = fl.part_count(gm.groups, res["group_masks"])
+            back_r = backing_radius(gm, labels, count, args)
+            write_svg(os.path.join(outdir, stem + ".svg"), gm)
+            write_check_image(os.path.join(outdir, f"check_{stem}.png"), res, args)
+            hull = fl.convex_hull(np.concatenate(gm.contours))
+            done[g.char] = (gm, res, count, back_r, hull)
+            for (hx, hy, r), fits, where in zip(res["holes"], res["fits"], ("top", "bottom")):
+                if not fits:
+                    warn(f"{g.char!r}: no room for the countersink head at the {where} hole: "
+                         f"largest circle radius {r:.1f} mm, needed {res['r_req']:.1f} mm")
+            if count > 1:
+                warn(f"{g.char!r} has {count} separate parts; print it with backing")
+                if back_r < 0:
+                    warn(f"{g.char!r}: growing and shrinking does not connect the parts; "
+                         f"the backing uses the convex hull")
+            print(f"{g.char!r}: holes " + ", ".join(
+                f"({hx:.1f}, {hy:.1f}) r {r:.1f}" for hx, hy, r in res["holes"])
+                  + (f", {count} parts, backing radius {back_r:.1f}" if count > 1 else ""))
+        gm, res, count, back_r, hull = done[g.char]
+        entries.append((g.char, f"{outdir}/{stem}.svg", x * k, gm.bbox(), hull,
+                        res["holes"], count, back_r))
+
+    with open(args.data, "w") as f:
+        f.write(f"// generated by make_glyphs.py, do not edit\n"
+                f"// {shlex.join(['make_glyphs.py'] + sys.argv[1:])}\n\n")
+        f.write(f"g_font = {scad_str(info.psname)};\n")
+        f.write(f"g_text = {scad_str(args.text)};\n")
+        f.write(f"// font and text for file names\ng_name = {scad_str(name)};\n")
+        f.write(f"// height of the tallest glyph in mm; all lengths below are at this size\n"
+                f"g_size = {scad_num(size)};\n")
+        f.write(f"// placement parameters: head diameter, wall in line widths, line width\n"
+                f"g_placement = [{scad_num(args.head_d)}, {scad_num(args.wall_lines)}, "
+                f"{scad_num(args.line_width)}];\n")
+        f.write("// maximum sizes in mm: [size at 0 degrees, best angle, size at best angle]\n")
+        for layout in ("text", "glyph"):
+            m = sizes[layout]
+            f.write(f"g_max_{layout} = [{scad_num(m['size0'])}, {m['angle']}, "
+                    f"{scad_num(m['size'])}];\n")
+        f.write("// glyphs without spaces: [character, svg file, x offset in the text,\n"
+                "//   ink bounding box [xmin, ymin, xmax, ymax], convex hull,\n"
+                "//   holes [[x, y, largest circle radius], ...] top first, parts,\n"
+                "//   backing radius (0 one part, -1 convex hull)]\n")
+        f.write("g_glyphs = [\n")
+        for char, svg, off, bbox, hull, holes, count, back_r in entries:
+            f.write(f"  [{scad_str(char)}, {scad_str(svg)}, {scad_num(off)},\n"
+                    f"   [{', '.join(scad_num(v) for v in bbox)}],\n"
+                    f"   {scad_pts(hull)},\n"
+                    f"   [{', '.join('[' + ', '.join(scad_num(v) for v in h) + ']' for h in holes)}],"
+                    f" {count}, {scad_num(back_r)}],\n")
+        f.write("];\n")
+    print(f"wrote {outdir}/ and {args.data}")
+
+
+if __name__ == "__main__":
+    main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make_preview.py	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,232 @@
+#!/usr/bin/env python3
+"""Render a preview PNG of a text in every installed font.
+
+Each PNG is named after the font's PostScript name, so the file can be
+passed to make_glyphs.py as it is. The text is drawn from the same outlines
+the printed model uses. Optionally the glyphs get an outline band like the
+decal of the two-colour print, with its width given in mm at the font's
+maximum print size.
+"""
+
+import argparse
+import logging
+import os
+import re
+import sys
+from concurrent.futures import ProcessPoolExecutor
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+import fontlib as fl
+
+SUPERSAMPLE = 3
+
+
+def parse_args():
+    """Parse the command line."""
+    p = argparse.ArgumentParser(description=__doc__,
+                                formatter_class=argparse.RawDescriptionHelpFormatter)
+    p.add_argument("--text", default="24", help="text to render (default: %(default)s)")
+    p.add_argument("--out", default="preview", help="output directory (default: %(default)s)")
+    p.add_argument("--list", action="store_true",
+                   help="only list the fonts that pass the filters")
+    f = p.add_argument_group("filters")
+    f.add_argument("--family", help="regular expression on the family name, case-insensitive")
+    f.add_argument("--name", help="regular expression on the PostScript name, case-insensitive")
+    f.add_argument("--weight-min", type=int, help="lowest weight, 100 to 900")
+    f.add_argument("--weight-max", type=int, help="highest weight, 100 to 900")
+    f.add_argument("--italic", action=argparse.BooleanOptionalAction,
+                   help="only italic (--italic) or only upright (--no-italic) faces")
+    f.add_argument("--mono", action=argparse.BooleanOptionalAction,
+                   help="only monospaced (--mono) or only proportional (--no-mono) faces")
+    f.add_argument("--class", dest="cls", choices=["serif", "sans"],
+                   help="only fonts classified as serif or sans-serif")
+    r = p.add_argument_group("rendering")
+    r.add_argument("--fill", default="#202020", help="glyph colour (default: %(default)s)")
+    r.add_argument("--outline", default="#c03030", help="outline colour (default: %(default)s)")
+    r.add_argument("--background", default="#f4f4f0",
+                   help="background colour (default: %(default)s)")
+    r.add_argument("--band", type=float, default=0,
+                   help="outline band width in mm at maximum print size, 0 for none "
+                        "(default: %(default)s)")
+    r.add_argument("--layout", choices=["text", "glyph"], default="glyph",
+                   help="layout whose maximum size scales the band (default: %(default)s)")
+    r.add_argument("--px", type=int, default=2000,
+                   help="image size along the longer side (default: %(default)s)")
+    r.add_argument("--jobs", type=int, default=os.cpu_count(),
+                   help="parallel processes (default: %(default)s)")
+    b = p.add_argument_group("printer")
+    b.add_argument("--bed", type=float, default=300, help="bed size in mm (default: %(default)s)")
+    b.add_argument("--margin", type=float, default=10,
+                   help="bed margin in mm (default: %(default)s)")
+    b.add_argument("--line-width", type=float, default=.4,
+                   help="line width in mm (default: %(default)s)")
+    return p.parse_args()
+
+
+def select(args):
+    """Faces that pass the filters given on the command line.
+
+    Filters that need the font file (weight, class, missing characters) are
+    applied while rendering, see render().
+    """
+    fam = re.compile(args.family, re.I) if args.family else None
+    name = re.compile(args.name, re.I) if args.name else None
+    out = []
+    for face in fl.list_faces():
+        if fam and not fam.search(face.family):
+            continue
+        if name and not name.search(face.file_name):
+            continue
+        if args.italic is not None and face.italic != args.italic:
+            continue
+        out.append(face)
+    return out
+
+
+def check_face(face, args):
+    """Apply the filters that need the opened font.
+
+    Returns:
+        None if the face passes, else the reason it does not.
+    """
+    if not face.has_chars(args.text):
+        return "missing characters"
+    if args.weight_min is not None and face.weight < args.weight_min:
+        return "weight"
+    if args.weight_max is not None and face.weight > args.weight_max:
+        return "weight"
+    if args.mono is not None and face.mono != args.mono:
+        return "spacing"
+    if args.cls and face.classification != args.cls:
+        return "class"
+    return None
+
+
+def render(face_info, args):
+    """Render the preview PNG of one face.
+
+    Returns:
+        (PostScript name, None) on success, or (PostScript name, reason)
+        when the face is skipped.
+    """
+    logging.disable(logging.WARNING)
+    try:
+        face = fl.Face(face_info)
+        reason = check_face(face, args)
+        if reason:
+            return face_info.psname, reason
+        placed = face.layout(args.text)
+    except Exception as e:  # damaged or unusual fonts are skipped, not fatal
+        return face_info.psname, f"error: {e}"
+    inked = [(x, g) for x, g in placed if not g.empty]
+    if not inked:
+        return face_info.psname, "no outline"
+    sizes = fl.max_sizes(placed, fl.usable_area(args.bed, args.margin, args.line_width))
+    bboxes = [g.bbox() for _, g in inked]
+    xmin = min(x + b[0] for (x, _), b in zip(inked, bboxes))
+    xmax = max(x + b[2] for (x, _), b in zip(inked, bboxes))
+    ymin = min(b[1] for b in bboxes)
+    ymax = max(b[3] for b in bboxes)
+    height = max(b[3] - b[1] for b in bboxes)
+
+    # image geometry, in supersampled pixels
+    pad = args.px // 20
+    caption_h = args.px // 14
+    k = (args.px - 2 * pad) / max(xmax - xmin, ymax - ymin)
+    w = int(round((xmax - xmin) * k)) + 2 * pad
+    h = int(round((ymax - ymin) * k)) + 2 * pad
+    ss = SUPERSAMPLE
+
+    def to_px(pts, dx):
+        return [((x + dx - xmin) * k * ss + pad * ss, (ymax - y) * k * ss + pad * ss)
+                for x, y in pts]
+
+    fill = Image.new("L", (w * ss, h * ss), 0)
+    band = Image.new("L", (w * ss, h * ss), 0)
+    for dx, g in inked:
+        for group in g.groups:
+            layer = Image.new("L", fill.size, 0)
+            d = ImageDraw.Draw(layer)
+            d.polygon(to_px(group[0], dx), fill=255)
+            for hole in group[1:]:
+                d.polygon(to_px(hole, dx), fill=0)
+            fill.paste(255, mask=layer)
+        if args.band > 0:
+            mm_px = height * k * ss / sizes[args.layout]["size0"]
+            width = max(1, int(round(2 * args.band * mm_px)))
+            d = ImageDraw.Draw(band)
+            r = width / 2
+            for line in fl.visible_runs(g.groups, face.upm / 200):
+                pts = to_px(line, dx)
+                # single segments with a disc at every point: polyline joints
+                # leave hairline gaps between nearly collinear segments
+                for p, q in zip(pts, pts[1:]):
+                    d.line([p, q], fill=255, width=width)
+                for x, y in pts:
+                    d.ellipse((x - r, y - r, x + r, y + r), fill=255)
+    if args.band > 0:
+        band = Image.fromarray(np.minimum(np.asarray(band), np.asarray(fill)))
+
+    img = Image.new("RGB", fill.size, args.background)
+    img.paste(Image.new("RGB", fill.size, args.fill), mask=fill)
+    if args.band > 0:
+        img.paste(Image.new("RGB", fill.size, args.outline), mask=band)
+    img = img.resize((w, h), Image.LANCZOS)
+
+    # caption below the text; narrow images are widened to fit it
+    font = ImageFont.load_default(size=caption_h // 3)
+    flags = [f"weight {face.weight}", face.classification or "unclassified"]
+    if face_info.italic:
+        flags.append("italic")
+    if face.mono:
+        flags.append("mono")
+    fill_error = max(g.fill_error for _, g in inked)
+    if fill_error > 0.001:
+        flags.append(f"OUTLINE DIFFERS FROM FONT ON {100 * fill_error:.1f}%")
+    lines = [f"{face_info.family} {face_info.style}  ({face_info.psname})",
+             f"{', '.join(flags)}   max size: text {sizes['text']['size0']:.0f} mm, "
+             f"glyph {sizes['glyph']['size0']:.0f} mm"]
+    text_w = max(font.getbbox(line)[2] for line in lines)
+    out_w = max(w, int(text_w) + 2 * pad)
+    out = Image.new("RGB", (out_w, h + caption_h), args.background)
+    out.paste(img, ((out_w - w) // 2, 0))
+    d = ImageDraw.Draw(out)
+    for i, line in enumerate(lines):
+        d.text((pad, h + i * caption_h * 0.42), line, fill=args.fill, font=font)
+    out.save(os.path.join(args.out, face_info.file_name + ".png"), optimize=True)
+    return face_info.psname, None
+
+
+def main():
+    """Select the faces and render them in parallel."""
+    args = parse_args()
+    faces = select(args)
+    if args.list:
+        logging.disable(logging.WARNING)
+        for info in faces:
+            try:
+                face = fl.Face(info)
+                if check_face(face, args):
+                    continue
+            except Exception:
+                continue
+            print(f"{info.file_name}\t{info.family}\t{info.style}\t"
+                  f"weight {face.weight}\t{face.classification or '-'}")
+        return
+    os.makedirs(args.out, exist_ok=True)
+    done = skipped = 0
+    with ProcessPoolExecutor(max_workers=args.jobs) as pool:
+        for name, reason in pool.map(render, faces, [args] * len(faces), chunksize=4):
+            if reason is None:
+                done += 1
+            else:
+                skipped += 1
+                if reason.startswith("error"):
+                    print(f"{name}: {reason}", file=sys.stderr)
+    print(f"{done} previews written to {args.out}, {skipped} faces skipped")
+
+
+if __name__ == "__main__":
+    main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make_template.py	Tue Nov 03 01:29:38 2026 +0100
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+"""Tile a drilling template exported from OpenSCAD onto printable pages.
+
+Reads the SVG export of the template part of main.scad and writes a PDF at
+1:1 scale, split over pages of the chosen paper size. Neighbouring pages
+overlap. A dashed line runs through the middle of each overlap, with
+crosses every 50 mm along it: trim one sheet along the line, lay it over
+its neighbour so line and crosses match, and tape it. Each page names its
+row and column.
+
+Print at 100% (actual size) and check the 100 mm scale bar.
+
+Only the Python standard library is used. The SVG must consist of path
+elements with straight segments (M, L and z commands), which is what
+OpenSCAD exports for 2D shapes.
+"""
+
+import argparse
+import math
+import os
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+MM = 72 / 25.4   # PDF points per mm
+PAPER = {"a4": (210, 297), "a3": (297, 420), "letter": (215.9, 279.4),
+         "legal": (215.9, 355.6)}
+
+
+def parse_args():
+    """Parse the command line."""
+    p = argparse.ArgumentParser(description=__doc__,
+                                formatter_class=argparse.RawDescriptionHelpFormatter)
+    p.add_argument("svg", help="SVG export of the template part")
+    p.add_argument("-o", "--output", help="output PDF (default: the SVG name with .pdf)")
+    p.add_argument("--paper", choices=sorted(PAPER), default="a4",
+                   help="paper size (default: %(default)s)")
+    p.add_argument("--margin", type=float, default=6,
+                   help="unprintable margin along the paper edges in mm (default: %(default)s)")
+    p.add_argument("--overlap", type=float, default=10,
+                   help="overlap between neighbouring pages in mm (default: %(default)s)")
+    p.add_argument("--line", type=float, default=.2,
+                   help="line width in mm (default: %(default)s)")
+    return p.parse_args()
+
+
+def read_svg(path):
+    """Read the polygons of an OpenSCAD SVG export.
+
+    Returns:
+        (polygons, width, height): polygons as lists of (x, y) in mm with
+        the origin at the lower left corner of the drawing and y up, and the
+        drawing size in mm.
+
+    Raises:
+        SystemExit: the file contains elements or path commands other than
+            those OpenSCAD writes for 2D shapes, or its units are not mm.
+    """
+    root = ET.parse(path).getroot()
+    ns = "{http://www.w3.org/2000/svg}"
+    vb = [float(v) for v in root.get("viewBox", "").replace(",", " ").split()]
+    if len(vb) != 4:
+        sys.exit(f"{path}: no viewBox")
+    minx, miny, w, h = vb
+    width = root.get("width", "")
+    if not width.endswith("mm") or not math.isclose(float(width[:-2]), w, rel_tol=1e-6):
+        sys.exit(f"{path}: width {width!r} does not match the viewBox in mm")
+    polygons = []
+    for el in root.iter():
+        tag = el.tag.replace(ns, "")
+        if tag in ("svg", "title"):
+            continue
+        if tag != "path":
+            sys.exit(f"{path}: unexpected element {tag!r}")
+        tokens = re.findall(r"[A-Za-z]|-?[\d.]+(?:[eE][-+]?\d+)?", el.get("d", ""))
+        cur, i = None, 0
+        while i < len(tokens):
+            t = tokens[i]
+            if t in ("M", "L"):
+                x, y = float(tokens[i + 1]), float(tokens[i + 2])
+                pt = (x - minx, miny + h - y)
+                if t == "M":
+                    cur = [pt]
+                    polygons.append(cur)
+                else:
+                    cur.append(pt)
+                i += 3
+            elif t in ("z", "Z"):
+                i += 1
+            else:
+                sys.exit(f"{path}: unexpected path data {t!r}")
+    return polygons, w, h
+
+
+def tiles(total, page, overlap):
+    """Start positions of pages covering a length.
+
+    Args:
+        total: length of the drawing.
+        page: printable length of a page.
+        overlap: overlap between neighbouring pages.
+
+    Returns:
+        list of start positions, the first at 0.
+    """
+    step = page - overlap
+    n = max(1, math.ceil((total - overlap) / step))
+    return [i * step for i in range(n)]
+
+
+def layout(w, h, args):
+    """Choose portrait or landscape pages, whichever needs fewer.
+
+    Returns:
+        (paper width, paper height, x starts, y starts) in mm.
+    """
+    best = None
+    for pw, ph in (PAPER[args.paper], PAPER[args.paper][::-1]):
+        xs = tiles(w, pw - 2 * args.margin, args.overlap)
+        ys = tiles(h, ph - 2 * args.margin, args.overlap)
+        if best is None or len(xs) * len(ys) < len(best[2]) * len(best[3]):
+            best = (pw, ph, xs, ys)
+    return best
+
+
+def fmt(v):
+    """Number for a PDF content stream."""
+    return f"{v:.3f}".rstrip("0").rstrip(".")
+
+
+def page_content(polygons, x0, y0, pw, ph, w, h, cuts_x, cuts_y, label, args):
+    """Content stream of one page.
+
+    The drawing is shifted so that (x0, y0) lies at the lower left corner of
+    the printable area, and clipped to that area.
+
+    Args:
+        polygons, w, h: the drawing, see read_svg().
+        x0, y0: drawing position at the lower left of the printable area.
+        pw, ph: paper size in mm.
+        cuts_x, cuts_y: positions of the trim lines in the drawing.
+        label: page name for the bottom margin.
+        args: command line arguments.
+    """
+    m = args.margin
+    out = [f"q {fmt(m * MM)} {fmt(m * MM)} {fmt((pw - 2 * m) * MM)} {fmt((ph - 2 * m) * MM)} "
+           f"re W n",
+           f"1 0 0 1 {fmt((m - x0) * MM)} {fmt((m - y0) * MM)} cm",
+           f"{fmt(args.line * MM)} w 1 j 1 J 0 G"]
+    for poly in polygons:
+        out.append(f"{fmt(poly[0][0] * MM)} {fmt(poly[0][1] * MM)} m " +
+                   " ".join(f"{fmt(x * MM)} {fmt(y * MM)} l" for x, y in poly[1:]) + " h S")
+    # guides: dashed trim lines through the overlaps, crosses every 50 mm
+    out.append(f"0.6 G {fmt(.15 * MM)} w")
+    out.append(f"[{fmt(3 * MM)} {fmt(2 * MM)}] 0 d")
+    for x in cuts_x:
+        out.append(f"{fmt(x * MM)} 0 m {fmt(x * MM)} {fmt(h * MM)} l S")
+    for y in cuts_y:
+        out.append(f"0 {fmt(y * MM)} m {fmt(w * MM)} {fmt(y * MM)} l S")
+    out.append("[] 0 d")
+    c = 3   # half cross size
+    for x in cuts_x:
+        for y in range(0, int(h) + 1, 50):
+            out.append(f"{fmt((x - c) * MM)} {fmt(y * MM)} m {fmt((x + c) * MM)} {fmt(y * MM)} l "
+                       f"{fmt(x * MM)} {fmt((y - c) * MM)} m {fmt(x * MM)} {fmt((y + c) * MM)} l S")
+    for y in cuts_y:
+        for x in range(0, int(w) + 1, 50):
+            out.append(f"{fmt((x - c) * MM)} {fmt(y * MM)} m {fmt((x + c) * MM)} {fmt(y * MM)} l "
+                       f"{fmt(x * MM)} {fmt((y - c) * MM)} m {fmt(x * MM)} {fmt((y + c) * MM)} l S")
+    out.append("Q")
+    # page name in the bottom margin
+    out.append(f"BT /F1 7 Tf 0 g {fmt(m * MM)} {fmt(m / 2 * MM)} Td "
+               f"({label}, print at 100%) Tj ET")
+    return "\n".join(out).encode("ascii")
+
+
+def write_pdf(path, pages, pw, ph):
+    """Write a PDF with one page per content stream.
+
+    Args:
+        path: output file.
+        pages: list of content streams (bytes).
+        pw, ph: page size in mm.
+    """
+    n = len(pages)
+    # objects: 1 catalog, 2 page tree, 3 font, then page and content per page
+    objs = [b"<< /Type /Catalog /Pages 2 0 R >>",
+            ("<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(n))
+             + f"] /Count {n} >>").encode(),
+            b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
+    for i, content in enumerate(pages):
+        objs.append((f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {fmt(pw * MM)} "
+                     f"{fmt(ph * MM)}] /Resources << /Font << /F1 3 0 R >> >> "
+                     f"/Contents {5 + 2 * i} 0 R >>").encode())
+        objs.append(f"<< /Length {len(content)} >>\nstream\n".encode() + content
+                    + b"\nendstream")
+    data = bytearray(b"%PDF-1.4\n")
+    offsets = []
+    for i, obj in enumerate(objs):
+        offsets.append(len(data))
+        data += f"{i + 1} 0 obj\n".encode() + obj + b"\nendobj\n"
+    xref = len(data)
+    data += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode()
+    for off in offsets:
+        data += f"{off:010d} 00000 n \n".encode()
+    data += (f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\n"
+             f"startxref\n{xref}\n%%EOF\n").encode()
+    with open(path, "wb") as f:
+        f.write(data)
+
+
+def main():
+    """Read the SVG, lay out the pages and write the PDF."""
+    args = parse_args()
+    polygons, w, h = read_svg(args.svg)
+    pw, ph, xs, ys = layout(w, h, args)
+    tile_h = ph - 2 * args.margin
+    ov = args.overlap
+    # ys count from the top of the drawing, so the pages come in reading order
+    cuts_x = [x + ov / 2 for x in xs[1:]]
+    cuts_y = [h - y - ov / 2 for y in ys[1:]]
+    pages = []
+    for row, y in enumerate(ys):
+        for col, x0 in enumerate(xs):
+            label = f"row {row + 1} of {len(ys)}, column {col + 1} of {len(xs)}"
+            pages.append(page_content(polygons, x0, h - y - tile_h, pw, ph, w, h,
+                                      cuts_x, cuts_y, label, args))
+    out = args.output or os.path.splitext(args.svg)[0] + ".pdf"
+    write_pdf(out, pages, pw, ph)
+    orient = "portrait" if pw < ph else "landscape"
+    print(f"{w:.0f} x {h:.0f} mm on {len(pages)} {args.paper} pages, {orient}, "
+          f"{len(ys)} rows of {len(xs)}: {out}")
+
+
+if __name__ == "__main__":
+    main()