diff 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 diff
--- a/make_glyphs.py	Tue Nov 03 13:54:57 2026 +0100
+++ b/make_glyphs.py	Tue Nov 03 15:51:23 2026 +0100
@@ -6,12 +6,14 @@
 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().
+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
@@ -44,6 +46,10 @@
     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,
@@ -51,14 +57,24 @@
     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; "
+                   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="penalty for sideways distance from the axis (default: %(default)s)")
+                   help="2 holes: 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)")
+                   help="2 holes: 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")
+                   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")
@@ -67,7 +83,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()
+    args = p.parse_args()
+    if not 0 <= args.ridge <= 1:
+        p.error("--ridge must be between 0 and 1")
+    return args
 
 
 def warn(msg):
@@ -83,30 +102,37 @@
 
 # --------------------------------------------------------------- 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 two screw hole positions of a glyph.
+    """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. 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.
+    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], [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'.
+        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)
@@ -115,9 +141,59 @@
     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]
-    centre = inside.mean(axis=0)
     if args.vertical_axis:
         axis = np.array([0.0, 1.0])
     else:
@@ -132,13 +208,9 @@
     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):
@@ -150,8 +222,151 @@
             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}
+    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
@@ -241,7 +456,7 @@
 
 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."""
+    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)
@@ -252,9 +467,17 @@
     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)
+    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)):
@@ -339,16 +562,17 @@
             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")):
+            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 the {where} hole: "
+                    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}: holes " + ", ".join(
+            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]
@@ -366,6 +590,7 @@
         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]
@@ -373,7 +598,8 @@
                     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"
+                "//   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: