view make_glyphs.py @ 4:4836a7408849

more elaborate hole finding
author ark
date 2026-11-03 15:51 +0100
parents b5a96b547b01
children
line wrap: on
line source

#!/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 two, one near the top and one near the bottom end, along
the glyph's main axis; or, with a maximum of three or more, as many as the
glyph benefits from, spread around its centre of area. Always in the middle of the stroke and with room for the countersink
head plus a minimum wall. See place_holes().
"""

import argparse
import itertools
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("--holes", type=int, default=2, choices=range(2, MAX_HOLES + 1),
                   metavar="N",
                   help=f"most holes per glyph, 2 to {MAX_HOLES}: 2 along the main axis, "
                        "more spread around the centre (default: %(default)s)")
    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="2 holes: 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="2 holes: penalty for sideways distance from the axis "
                        "(default: %(default)s)")
    h.add_argument("--centre-weight", type=float, default=.3,
                   help="2 holes: reward for sitting in the middle of the stroke "
                        "(default: %(default)s)")
    h.add_argument("--vertical-axis", action="store_true",
                   help="2 holes: use a vertical axis instead of the glyph's main axis")
    h.add_argument("--hole-gain", type=float, default=.5,
                   help="3 or more holes: a further hole is used only if it moves the "
                        "nearest side of the hole polygon this share further from the "
                        "centre (default: %(default)s)")
    h.add_argument("--ridge", type=float, default=.8,
                   help="3 or more holes: how close to the middle of the stroke a hole must "
                        "be, as a share of the largest distance to the outline nearby "
                        "(default: %(default)s)")
    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)")
    args = p.parse_args()
    if not 0 <= args.ridge <= 1:
        p.error("--ridge must be between 0 and 1")
    return 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

MAX_HOLES = 6
# most hole combinations tried per glyph with 3 or more holes
MAX_COMBINATIONS = 200000


def place_holes(g, args):
    """Find the 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. Centredness of each point: its distance to the outline relative to
       the largest distance nearby, 1 in the middle of the stroke.
    4. Two holes: see _holes_axis(). With a maximum of three or more, the
       fewest holes from 3 up that _holes_spread() can place, then one more
       at a time while each raises the lever (the distance from the centre
       to the nearest side of the hole polygon) by --hole-gain. Two holes
       if not even 3 can be placed. At the default of 50%, in Futura Bold,
       "W", "M", "H" and "X" get four holes; round glyphs such as "D", "O"
       and "0" stay at three, where a fourth hole adds 39 to 43%.

    Args:
        g: Glyph in mm.
        args: command line arguments.

    Returns:
        dict with 'holes' ([[x, y, r], ...], the top one first, then
        counter-clockwise; r the radius of the largest circle that fits
        there), 'fits' (per hole), 'reason' (why fewer than the maximum
        holes, else None), 'grid', 'mask', 'allowed', 'centre' (of
        the inked area), 'axis' (two holes: centre, direction, lower and
        upper end along the axis; else None), '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)
    centre = pts[mask].mean(axis=0)
    radius = max(1, int(math.ceil(d.max() / grid.step)))
    centred = d / np.maximum(fl.max_filter(d, radius), 1e-9)
    allowed = mask & (d >= r_req)

    res = {"grid": grid, "mask": mask, "allowed": allowed, "centre": centre, "axis": None,
           "reason": None, "r_req": r_req, "group_masks": group_masks}
    best = None
    for n in range(3, args.holes + 1):
        r = _holes_spread(pts, mask, d, centred, allowed, centre, r_req, n, args)
        if r is None:
            if best is None:
                continue
            res["reason"] = f"{n} holes would be too close together or in a line"
            break
        if best is not None and r["lever"] < (1 + args.hole_gain) * best["lever"]:
            gain = 100 * (r["lever"] / best["lever"] - 1)
            res["reason"] = (f"{n} holes would raise the lever by only {gain:.0f}%"
                             if gain >= .5 else f"{n} holes would not raise the lever")
            break
        best = r
    if best is None:
        res.update(_holes_axis(pts, mask, d, centred, allowed, centre, r_req, args))
        if args.holes > 2:
            res["reason"] = "3 holes would be too close together or in a line"
    else:
        res.update(best)
    return res


def _holes_axis(pts, mask, d, centred, allowed, centre, r_req, args):
    """Two holes along the glyph's main axis.

    1. Axis: main axis of the inked area (or vertical), pointing up. It
       follows the slant of italic and script fonts and turns sideways for
       wide glyphs.
    2. 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.
    3. 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 centredness.
    4. A half without allowed points gets its largest inscribed circle.

    Args:
        pts: grid points, shape (ny, nx, 2). mask: inside points.
        d: distance to the outline. centred: centredness.
        allowed: points with room for the head. centre: of the inked area.
        r_req: head radius plus wall. args: command line arguments.

    Returns:
        dict with 'holes' (top first), 'fits' and 'axis', see place_holes().
    """
    inside = pts[mask]
    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

    score = (-np.abs(t - np.where(t >= .5, args.target, 1 - args.target))
             - args.side_weight * np.abs(u) / length
             + args.centre_weight * centred)

    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, "axis": (centre, axis, smin, smax)}


def _holes_spread(pts, mask, d, centred, allowed, centre, r_req, n, args):
    """Three or more holes spread around the centre of the inked area.

    1. Candidates: allowed points with a centredness of at least --ridge;
       if their convex hull has fewer than 3 corners, all allowed points.
    2. Points to choose from: candidates on the convex hull of the
       candidates, see _hull_points(), as many as keep all combinations of
       them below MAX_COMBINATIONS.
    3. Combinations whose holes are closer together than head and wall, or
       a third of the hull perimeter divided by the number of holes, are
       left out.
    4. Of the remaining combinations, the one whose polygon keeps the
       centre furthest inside: the largest lever, the smallest distance
       from the centre to a side. If that is less than the head diameter,
       the holes are close to a line and none are placed. Of the
       combinations within 10% of the largest lever, or one grid step, the
       one with the largest area wins.

    Args:
        as for _holes_axis(); n: number of holes.

    Returns:
        dict with 'holes' (top first, then counter-clockwise), 'fits' and
        'lever', see place_holes(); None if n holes cannot be placed.
    """
    step = pts[0, 1, 0] - pts[0, 0, 0]
    for cand in (allowed & (centred >= args.ridge), allowed):
        cpts = pts[cand]
        hull = fl.convex_hull(cpts) if len(cpts) else cpts
        if len(hull) >= 3:
            break
    else:
        return None

    h = n
    while h < len(cpts) and math.comb(h + 1, n) <= MAX_COMBINATIONS:
        h += 1
    corners = _hull_points(hull, cpts, h, step)
    if len(corners) < n:
        return None
    combo = np.array(list(itertools.combinations(range(len(corners)), n)))
    poly = corners[combo]                         # (combinations, n, 2), counter-clockwise
    lever = _lever(poly, centre)
    area = (poly[..., 0] * np.roll(poly[..., 1], -1, axis=1)
            - np.roll(poly[..., 0], -1, axis=1) * poly[..., 1]).sum(axis=1) / 2
    i, j = np.triu_indices(n, 1)
    gap = np.linalg.norm(poly[:, i] - poly[:, j], axis=2).min(axis=1)
    perimeter = np.linalg.norm(np.roll(hull, -1, axis=0) - hull, axis=1).sum()
    spaced = gap >= max(2 * r_req, perimeter / (3 * n))
    if not spaced.any():
        return None
    top = lever[spaced].max()
    if top < args.head_d:
        return None
    near = spaced & (lever >= top - max(step, .1 * top))
    best = int(np.argmax(np.where(near, area, -np.inf)))
    chosen = np.roll(poly[best], -int(np.argmax(poly[best][:, 1])), axis=0)

    # back to grid indices for the distance to the outline
    flat = pts.reshape(-1, 2)
    holes, fits = [], []
    for c in chosen:
        idx = np.unravel_index(np.argmin(np.linalg.norm(flat - c, axis=1)), mask.shape)
        holes.append([*pts[idx], d[idx]])
        fits.append(bool(allowed[idx]))
    return {"holes": holes, "fits": fits, "lever": float(lever[best])}


def _lever(poly, centre):
    """Signed distance from the centre to the nearest side of each polygon,
    positive inside.

    Args:
        poly: (..., n, 2) array of counter-clockwise polygons. centre: point.

    Returns:
        array of the leading shape of poly.
    """
    edge = np.roll(poly, -1, axis=-2) - poly
    to_c = centre - poly
    cross = edge[..., 0] * to_c[..., 1] - edge[..., 1] * to_c[..., 0]
    return (cross / np.maximum(np.linalg.norm(edge, axis=-1), 1e-9)).min(axis=-1)


def _hull_points(hull, cpts, count, step):
    """Points on the convex hull of the candidates, spread along it.

    Up to half the points are hull corners, those that shape the hull
    most. The rest are candidates on the hull's sides, each time the one
    furthest along the perimeter from the points already taken.

    Args:
        hull: (k, 2) array, counter-clockwise. cpts: candidate points.
        count: number of points. step: grid step.

    Returns:
        (at most count, 2) array, counter-clockwise.
    """
    edge = np.roll(hull, -1, axis=0) - hull
    length = np.linalg.norm(edge, axis=1)
    start = np.concatenate([[0], np.cumsum(length)[:-1]])
    perimeter = length.sum()
    # position along the perimeter of candidates within 1.5 steps of a side
    rel = cpts[:, None, :] - hull[None, :, :]
    t = np.clip((rel * edge).sum(axis=2) / np.maximum(length, 1e-9) ** 2, 0, 1)
    dist = np.linalg.norm(rel - t[..., None] * edge, axis=2)
    side = dist.argmin(axis=1)
    on = dist.min(axis=1) <= 1.5 * step
    pool_pts = cpts[on]
    pool_pos = (start[side] + t[np.arange(len(cpts)), side] * length[side])[on]

    keep = _thin_polygon(hull, min(len(hull), max(3, count // 2)))
    pts, pos = list(hull[keep]), list(start[keep])
    while len(pts) < count and len(pool_pts):
        gap = np.abs(pool_pos[:, None] - np.array(pos)[None, :])
        gap = np.minimum(gap, perimeter - gap).min(axis=1)
        best = int(np.argmax(gap))
        if gap[best] < step:
            break
        pts.append(pool_pts[best])
        pos.append(pool_pos[best])
    return np.array(pts)[np.argsort(pos)]


def _thin_polygon(poly, count):
    """Reduce a convex polygon to count corners by repeatedly removing the
    corner whose triangle with its neighbours has the smallest area.

    Args:
        poly: (k, 2) array, counter-clockwise. count: corners to keep.

    Returns:
        indices of the kept corners, in the original order.
    """
    keep = list(range(len(poly)))
    while len(keep) > count:
        p = poly[keep]
        prev, nxt = np.roll(p, 1, axis=0), np.roll(p, -1, axis=0)
        tri = np.abs((p[:, 0] - prev[:, 0]) * (nxt[:, 1] - prev[:, 1])
                     - (nxt[:, 0] - prev[:, 0]) * (p[:, 1] - prev[:, 1]))
        del keep[int(np.argmin(tri))]
    return keep


# --------------------------------------------------------------------- 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 or hole polygon and centre 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)

    blue = (40, 80, 220)
    if res["axis"]:
        centre, axis, smin, smax = res["axis"]
        d.line([px(*(centre + smin * axis)), px(*(centre + smax * axis))], fill=blue, width=3)
    else:
        corners = [px(x, y) for x, y, _ in res["holes"]]
        d.line(corners + corners[:1], fill=blue, width=3)
        cx, cy = px(*res["centre"])
        rp = args.head_d / 2 / grid.step
        d.line([(cx - rp, cy), (cx + rp, cy)], fill=blue, width=3)
        d.line([(cx, cy - rp), (cx, cy + rp)], fill=blue, 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 i, ((hx, hy, r), fits) in enumerate(zip(res["holes"], res["fits"])):
                if not fits:
                    warn(f"{g.char!r}: no room for the countersink head at hole {i + 1}: "
                         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}: {len(res['holes'])} holes"
                  + (f" ({res['reason']})" if res["reason"] else "") + ": " + ", ".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(f"// most holes per glyph\ng_holes = {args.holes};\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, then\n"
                "//   counter-clockwise, 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()