463 lines · 19.6 KB · PythonRaw
#!/usr/bin/env python3"""Paint Cotton Health's instruments as wordless layers into the Loompackage's catalogue, procedurally, so they are reproducible from the repo. python3 scripts/paint-health.py [--out <directory>] [--icon <file.png>] [--object <file.png>] [--picture]Health's records lie on the honed slate (`FaceGround.slate`), lit from theupper left, each as the instrument that keeps it: health-pedometer a day's measure: a brass-cased pocket pedometer, its bow and crown at the top, a cream enamel dial ringed with a hundred ticks, every tenth long, and a small subdial above the arbor. The hand, the usual's tick and every figure are the face's, drawn live. health-stopwatch a workout: a nickel stopwatch, its crown and two pushers, a white dial of sixty seconds and a small thirty-minute register above the arbor. health-tag a measurement: a brass tag, an engraved border, a punched hole with a steel grommet and a loop of waxed red cord, its face left bare for the reading. health-glass the domed crystal over a dial: its highlight alone, laid over the hands of both instruments.Each is a 3x PNG on nothing, its shadow on the slate painted into its alpha.Where the dials lie in the layers are the faces' knobs(`HealthInstrumentKnobs`), printed when the layers are written; a repaintedinstrument owes new knobs.`--icon` paints the app's icon (1024 px, opaque): the pedometer on theslate, its hand past the usual. `--object` paints the same pedometer cut outon nothing (1024 px, RGBA): the launch screen's object(`scripts/gen-launch-screens.py --objects`). `--picture` paints the Healthtool's picture at 600 px under the tool's `pictures/`. No word, figure orletter is on any layer."""from __future__ import annotationsimport hashlibimport importlib.utilimport jsonimport mathimport sysfrom pathlib import Pathimport numpy as npfrom PIL import Image, ImageDraw, ImageFilterROOT = Path(__file__).resolve().parent.parentCATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"TOOL_PICTURES = ROOT / "crates/cotton-core/kits/personal/tools/health/pictures"TOOL_MANIFEST = ROOT / "crates/cotton-core/kits/personal/tools/health/manifest.json"BRASS = np.array([201.0, 160.0, 82.0])NICKEL = np.array([196.0, 199.0, 204.0])ENAMEL = np.array([244.0, 236.0, 216.0])WHITE_DIAL = np.array([248.0, 247.0, 242.0])INK = np.array([34.0, 30.0, 26.0])CORD = np.array([150.0, 38.0, 34.0])LIGHT = np.array([-0.45, -0.6, 0.66])LIGHT = LIGHT / np.linalg.norm(LIGHT)# The instruments, in pixels at 3x. A round instrument's case is centred# at (CX, CY) in a W by H layer; its dial is DIAL wide (a radius).W, H, PAD = 900, 1110, 60CX, CY = W // 2 + PAD, 660 + PADCASE, DIAL = 420, 362SUBDIAL = 78TAG_W, TAG_H, TAG_R = 600, 840, 70TAG_HOLE = (0.5, 0.115, 34) # x, y as shares; radius in pxdef noise(r: np.random.Generator, shape, sx: float, sy: float | None = None) -> np.ndarray: sy = sx if sy is None else sy hgt, wid = shape white = r.standard_normal((hgt, wid)) fy = np.fft.fftfreq(hgt)[:, None] fx = np.fft.fftfreq(wid)[None, :] gain = np.exp(-2 * (np.pi ** 2) * ((fx * sx) ** 2 + (fy * sy) ** 2)) out = np.real(np.fft.ifft2(np.fft.fft2(white) * gain)) return (out - out.mean()) / (out.std() + 1e-9)def grid(shape): hgt, wid = shape return np.mgrid[0:hgt, 0:wid].astype(float) + 0.5def coverage(sdf: np.ndarray) -> np.ndarray: return np.clip(0.5 - sdf, 0, 1)def rounded_rect_sdf(shape, x0, y0, x1, y1, radius) -> np.ndarray: yy, xx = grid(shape) cx, cy = (x0 + x1) / 2, (y0 + y1) / 2 hx, hy = (x1 - x0) / 2 - radius, (y1 - y0) / 2 - radius qx = np.abs(xx - cx) - hx qy = np.abs(yy - cy) - hy return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0) - radiusdef metal(base: np.ndarray, height: np.ndarray, albedo: np.ndarray, shine: float = 0.75, rough: float = 18) -> np.ndarray: """Polished metal of colour `base`, its height lit from the upper left: a dim diffuse, a broad reflected sky above and a hard highlight.""" gy, gx = np.gradient(height) n = np.stack([-gx, -gy, np.ones_like(height)], axis=-1) n /= np.linalg.norm(n, axis=-1, keepdims=True) diffuse = np.clip((n * LIGHT).sum(-1), 0, 1) half = LIGHT + np.array([0, 0, 1.0]) half /= np.linalg.norm(half) spec = np.clip((n * half).sum(-1), 0, 1) ** rough sky = np.clip(0.5 - 0.5 * n[..., 1], 0, 1) ** 2 # the room above reflected colour = base[None, None, :] * albedo[..., None] * (0.30 + 0.55 * diffuse + 0.35 * sky)[..., None] return colour + 255 * shine * spec[..., None] * (0.55 + 0.45 * base[None, None, :] / 255)def flat(base: np.ndarray, albedo: np.ndarray) -> np.ndarray: return base[None, None, :] * albedo[..., None]def shadow(alpha: np.ndarray, blur: float, dx: float, dy: float, strength: float) -> np.ndarray: img = Image.fromarray((np.clip(alpha, 0, 1) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(blur)) a = np.asarray(img, dtype=float) / 255 return np.roll(np.roll(a, int(dy), axis=0), int(dx), axis=1) * strengthdef rgba(colour: np.ndarray, alpha: np.ndarray, shade: np.ndarray | None = None) -> np.ndarray: out = np.zeros(alpha.shape + (4,)) if shade is None: out[..., :3], out[..., 3] = colour, alpha return out total = alpha + shade * (1 - alpha) out[..., :3] = np.where(total[..., None] > 0, colour * alpha[..., None] / np.maximum(total, 1e-6)[..., None], 0) out[..., 3] = total return outdef over(dst_colour: np.ndarray, dst_alpha: np.ndarray, colour: np.ndarray, alpha: np.ndarray): a = alpha[..., None] return dst_colour * (1 - a) + colour * a, dst_alpha + alpha * (1 - dst_alpha)def mask(shape, draw_fn, blur: float = 0.0) -> np.ndarray: hgt, wid = shape img = Image.new("L", (wid, hgt), 0) draw_fn(ImageDraw.Draw(img)) if blur: img = img.filter(ImageFilter.GaussianBlur(blur)) return np.asarray(img, dtype=float) / 255def ticks(shape, cx, cy, outer, count, long_every, long_len, short_len, long_w, short_w, mid_every: int = 0, mid_len: float = 0) -> np.ndarray: def draw(d): for k in range(count): a = 2 * math.pi * k / count - math.pi / 2 if k % long_every == 0: length, width = long_len, long_w elif mid_every and k % mid_every == 0: length, width = mid_len, (long_w + short_w) / 2 else: length, width = short_len, short_w x0, y0 = cx + (outer - length) * math.cos(a), cy + (outer - length) * math.sin(a) x1, y1 = cx + outer * math.cos(a), cy + outer * math.sin(a) d.line([(x0, y0), (x1, y1)], fill=255, width=max(1, int(round(width)))) return mask(shape, draw, 0.6)def ring(shape, cx, cy, radius, width) -> np.ndarray: yy, xx = grid(shape) return np.clip(1 - np.abs(np.hypot(xx - cx, yy - cy) - radius) / (width / 2), 0, 1)def torus_height(r: np.ndarray, inner: float, outer: float, lift: float) -> np.ndarray: mid, half = (inner + outer) / 2, (outer - inner) / 2 t = np.clip(1 - ((r - mid) / half) ** 2, 0, 1) return lift * np.sqrt(t)def round_case(shape, base: np.ndarray, seed: int, knurl: bool) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """The case's bezel ring, its stem, crown and (`knurl`) the pedometer's bow; answers colour, alpha and the dial's inner shadow.""" r = np.random.default_rng(seed) yy, xx = grid(shape) rr = np.hypot(xx - CX, yy - CY) alpha = coverage(rr - CASE) height = torus_height(rr, DIAL - 6, CASE, 46) + 0.05 * noise(r, shape, 2.0) brushed = 1 + 0.05 * noise(r, shape, 30, 2) + 0.03 * noise(r, shape, 120) colour = metal(base, height, brushed) # The stem and crown above the case, knurled; the bow through the crown. stem_top = CY - CASE - 70 stem = coverage(rounded_rect_sdf(shape, CX - 34, stem_top, CX + 34, CY - CASE + 30, 10)) crown_sdf = rounded_rect_sdf(shape, CX - 62, stem_top - 74, CX + 62, stem_top + 6, 18) crown = coverage(crown_sdf) across = (xx - CX) / 62 crown_h = 30 * np.sqrt(np.clip(1 - across ** 2, 0, 1)) + (6 * (np.sin(xx / 3.0) > 0) if knurl else 0) stem_h = 20 * np.sqrt(np.clip(1 - ((xx - CX) / 34) ** 2, 0, 1)) colour, alpha = over(colour, alpha, metal(base, stem_h, brushed, rough=22), stem * (1 - alpha)) colour, alpha = over(colour, alpha, metal(base, crown_h, brushed, rough=26), crown) if knurl: bow_r = np.hypot(xx - CX, yy - (stem_top - 130)) bow = coverage(np.abs(bow_r - 96) - 16) bow_h = torus_height(bow_r, 80, 112, 24) behind = bow * (1 - crown) colour, alpha = over(colour, alpha, metal(base, bow_h, brushed, rough=24), behind) # The bezel's inner lip casts a soft shadow onto the dial. lip = np.clip((rr - (DIAL - 26)) / 26, 0, 1) ** 2 * (rr < DIAL) return colour, alpha, lipdef dial_face(shape, base: np.ndarray, seed: int) -> tuple[np.ndarray, np.ndarray]: r = np.random.default_rng(seed) yy, xx = grid(shape) rr = np.hypot(xx - CX, yy - CY) alpha = coverage(rr - DIAL) albedo = 1 + 0.012 * noise(r, shape, 1.2) + 0.02 * noise(r, shape, 140) # enamel's soft depth: a touch darker toward the rim albedo *= 1 - 0.07 * np.clip((rr - DIAL * 0.6) / (DIAL * 0.4), 0, 1) return flat(base, albedo), alphadef ink_over(colour: np.ndarray, ink: np.ndarray, strength: float = 0.92) -> np.ndarray: a = np.clip(ink * strength, 0, 1)[..., None] return colour * (1 - a) + INK[None, None, :] * adef pedometer_layer() -> np.ndarray: shape = (H + 2 * PAD, W + 2 * PAD) case_c, case_a, lip = round_case(shape, BRASS, 11, knurl=True) dial_c, dial_a = dial_face(shape, ENAMEL, 12) dial_c = ink_over(dial_c, ticks(shape, CX, CY, DIAL - 18, 100, 10, 46, 20, 6, 2.4, 5, 30)) dial_c = ink_over(dial_c, ring(shape, CX, CY, DIAL - 18, 2.2)) sub_y = CY - DIAL * 0.42 dial_c = ink_over(dial_c, ring(shape, CX, sub_y, SUBDIAL, 2.4), 0.8) dial_c = ink_over(dial_c, ticks(shape, CX, sub_y, SUBDIAL - 2, 24, 6, 16, 8, 3.4, 1.6), 0.8) dial_c *= (1 - 0.35 * lip)[..., None] colour, alpha = over(case_c, case_a, dial_c, dial_a) return rgba(colour, alpha, shadow(alpha, 16, 10, 18, 0.62))def stopwatch_layer() -> np.ndarray: shape = (H + 2 * PAD, W + 2 * PAD) case_c, case_a, lip = round_case(shape, NICKEL, 21, knurl=False) # Its two pushers, either side of the crown. yy, xx = grid(shape) for side in (-1, 1): a = math.radians(-90 + side * 38) px, py = CX + (CASE + 26) * math.cos(a), CY + (CASE + 26) * math.sin(a) pr = np.hypot(xx - px, yy - py) push = coverage(pr - 34) push_h = 22 * np.sqrt(np.clip(1 - (pr / 34) ** 2, 0, 1)) case_c, case_a = over(case_c, case_a, metal(NICKEL, push_h, np.ones(shape), rough=30), push * (1 - case_a)) dial_c, dial_a = dial_face(shape, WHITE_DIAL, 22) dial_c = ink_over(dial_c, ticks(shape, CX, CY, DIAL - 18, 300, 25, 44, 12, 6, 1.2, 5, 26)) dial_c = ink_over(dial_c, ring(shape, CX, CY, DIAL - 18, 2.0)) sub_y = CY - DIAL * 0.42 dial_c = ink_over(dial_c, ring(shape, CX, sub_y, SUBDIAL, 2.4), 0.8) dial_c = ink_over(dial_c, ticks(shape, CX, sub_y, SUBDIAL - 2, 30, 5, 18, 8, 3.4, 1.4), 0.8) dial_c *= (1 - 0.32 * lip)[..., None] colour, alpha = over(case_c, case_a, dial_c, dial_a) return rgba(colour, alpha, shadow(alpha, 16, 10, 18, 0.62))def glass_layer() -> np.ndarray: """The crystal's highlight over a dial: a soft crescent upper left and a faint ring at the rim, on nothing.""" side = 2 * DIAL + 20 shape = (side, side) yy, xx = grid(shape) c = side / 2 rr = np.hypot(xx - c, yy - c) inside = coverage(rr - DIAL) crescent = np.clip(1 - np.hypot(xx - c * 0.72, yy - c * 0.62) / (DIAL * 0.95), 0, 1) ** 2.2 cut = np.clip((np.hypot(xx - c * 0.9, yy - c * 0.82) - DIAL * 0.62) / 40, 0, 1) rim = np.exp(-((rr - (DIAL - 8)) / 5) ** 2) * 0.25 a = np.clip(crescent * cut * 0.32 + rim, 0, 1) * inside out = np.zeros(shape + (4,)) out[..., :3] = 255 out[..., 3] = a return outdef tag_layer() -> np.ndarray: pad = PAD top = 260 # room above the tag for its cord shape = (TAG_H + 2 * pad + top, TAG_W + 2 * pad) r = np.random.default_rng(31) x0, y0 = pad, pad + top sdf = rounded_rect_sdf(shape, x0, y0, x0 + TAG_W, y0 + TAG_H, TAG_R) yy, xx = grid(shape) hx, hy = x0 + TAG_W * TAG_HOLE[0], y0 + TAG_H * TAG_HOLE[1] hole = np.hypot(xx - hx, yy - hy) alpha = coverage(sdf) * coverage(-(hole - TAG_HOLE[2])) inside = np.clip(-sdf, 0, None) height = 10 * np.sqrt(np.clip(inside / 22, 0, 1)) + 0.04 * noise(r, shape, 1.4) border = np.exp(-((inside - 34) / 1.6) ** 2) height -= 2.2 * border brushed = 1 + 0.025 * noise(r, shape, 60, 1.5) + 0.04 * noise(r, shape, 200) - 0.05 * np.clip(noise(r, shape, 90) - 0.8, 0, None) colour = metal(BRASS, height, brushed, shine=0.55, rough=14) colour *= (1 - 0.25 * border)[..., None] # The steel grommet round the hole. grom = coverage(hole - (TAG_HOLE[2] + 18)) * (hole >= TAG_HOLE[2] - 0.5) grom_h = torus_height(hole, TAG_HOLE[2], TAG_HOLE[2] + 18, 12) colour, alpha = over(colour, alpha, metal(NICKEL, grom_h, np.ones(shape), rough=28), grom * coverage(-(hole - TAG_HOLE[2]))) # The cord: a loop of waxed red cord through the hole, up out of the layer. def cord(d): for side in (-1, 1): pts = [(hx + side * 4, hy)] for k in range(1, 30): t = k / 29 pts.append((hx + side * (10 + 46 * math.sin(t * math.pi * 0.9)) + 6 * t, hy - t * (hy - 2))) d.line(pts, fill=255, width=16, joint="curve") cord_a = mask(shape, cord, 0.8) * (1 - coverage(sdf) * (yy > hy + 6)) cord_h = mask(shape, cord, 4.0) * 12 + 0.6 * noise(r, shape, 1.0) colour, alpha = over(colour, alpha, metal(CORD, cord_h, 1 + 0.08 * noise(r, shape, 3, 1), shine=0.25, rough=10), cord_a) return rgba(colour, alpha, shadow(alpha, 12, 8, 14, 0.58))def to_png(layer: np.ndarray) -> Image.Image: out = layer.copy() out[..., 3] *= 255 return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8), )def layers() -> dict[str, Image.Image]: return { "health-pedometer": to_png(pedometer_layer()), "health-stopwatch": to_png(stopwatch_layer()), "health-tag": to_png(tag_layer()), "health-glass": to_png(glass_layer()), }def knobs() -> dict: size = (W + 2 * PAD, H + 2 * PAD) tag = (TAG_W + 2 * PAD, TAG_H + 2 * PAD + 260) return { "round": {"width": size[0], "height": size[1], "centre": [CX / size[0], CY / size[1]], "dial": DIAL / size[0], "pedometerSub": [CX / size[0], (CY - DIAL * 0.42) / size[1], SUBDIAL / size[0]], "stopwatchSub": [CX / size[0], (CY - DIAL * 0.42) / size[1], SUBDIAL / size[0]]}, "tag": {"width": tag[0], "height": tag[1], "face": [PAD / tag[0], (PAD + 260 + TAG_H * 0.2) / tag[1], TAG_W / tag[0], TAG_H * 0.74 / tag[1]]}, }def hand(canvas: np.ndarray, angle_turns: float, length: float, colour, width: float) -> np.ndarray: """A blued steel hand drawn into a painted canvas (the icon's only).""" shape = canvas.shape[:2] a = 2 * math.pi * angle_turns - math.pi / 2 tip = (CX + length * math.cos(a), CY + length * math.sin(a)) tail = (CX - 0.18 * length * math.cos(a), CY - 0.18 * length * math.sin(a)) m = mask(shape, lambda d: (d.line([tail, tip], fill=255, width=int(width)), d.ellipse([CX - 22, CY - 22, CX + 22, CY + 22], fill=255)), 0.8) sh = shadow(m, 4, 5, 8, 0.4) canvas[..., :3] *= (1 - sh)[..., None] canvas[..., :3] = canvas[..., :3] * (1 - m[..., None]) + np.array(colour)[None, None, :] * m[..., None] return canvasdef pedometer_object() -> np.ndarray: layer = pedometer_layer() layer = hand(layer, 0.71, DIAL * 0.82, (40, 62, 112), 12) glass = glass_layer() g = glass.shape[0] x, y = int(CX - g / 2), int(CY - g / 2) sub = layer[y : y + g, x : x + g] a = glass[..., 3:4] sub[..., :3] = sub[..., :3] * (1 - a) + 255 * a return layerdef grounds(): spec = importlib.util.spec_from_file_location("paint_ground_tiles", ROOT / "scripts/paint-ground-tiles.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # type: ignore[union-attr] return moduledef square(cut: np.ndarray, side: int, fill: float, turn: float = -6) -> np.ndarray: img = to_png(cut).rotate(turn, resample=Image.BICUBIC, expand=True) img = img.crop(img.getbbox()) scale = side * fill / max(img.size) img = img.resize((max(1, int(img.width * scale)), max(1, int(img.height * scale))), Image.LANCZOS) out = Image.new("RGBA", (side, side), (0, 0, 0, 0)) out.alpha_composite(img, ((side - img.width) // 2, (side - img.height) // 2)) arr = np.asarray(out, dtype=float).copy() arr[..., 3] /= 255 return arrdef paint_object(side: int = 1024) -> Image.Image: return to_png(square(pedometer_object(), side, 0.84))def paint_icon() -> Image.Image: tile = np.clip(grounds().health_slate(), 0, 255) side = 1024 canvas = tile[:side, :side].copy() obj = square(pedometer_object(), side, 0.86) a = obj[..., 3:4] canvas = obj[..., :3] * a + canvas * (1 - a) yy, xx = np.mgrid[0:side, 0:side].astype(float) d = np.hypot(xx - side * 0.45, yy - side * 0.42) / (side * 0.75) canvas *= (1 - 0.35 * np.clip(d - 0.35, 0, 1))[..., None] return Image.fromarray(np.clip(canvas, 0, 255).astype(np.uint8))def write(name: str, image: Image.Image, out: Path) -> None: folder = out / f"{name}.imageset" folder.mkdir(parents=True, exist_ok=True) for old in folder.iterdir(): old.unlink() image.save(folder / f"{name}.png", optimize=True) contents = { "images": [ {"filename": f"{name}.png", "idiom": "universal", "scale": "3x"}, {"filename": f"{name}.png", "idiom": "mac", "scale": "2x"}, ], "info": {"author": "xcode", "version": 1}, "properties": {"preserves-vector-representation": False}, } (folder / "Contents.json").write_text(json.dumps(contents, indent=2) + "\n") print(f"{name}: {image.width}x{image.height}")def write_picture() -> None: image = paint_object(600) TOOL_PICTURES.mkdir(parents=True, exist_ok=True) data_path = TOOL_PICTURES / "_new.png" image.save(data_path, optimize=True) digest = hashlib.sha256(data_path.read_bytes()).hexdigest() for old in TOOL_PICTURES.glob("*.png"): if old != data_path: old.unlink() target = TOOL_PICTURES / f"{digest}.png" data_path.rename(target) manifest = json.loads(TOOL_MANIFEST.read_text()) manifest["picture"] = {"photo": f"photo:{digest}", "object": "tool-goals"} TOOL_MANIFEST.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n") print(f"picture: {target.relative_to(ROOT)}")def main() -> None: args = sys.argv[1:] out = CATALOGUE if "--out" in args: k = args.index("--out") out = Path(args[k + 1]) del args[k : k + 2] if "--icon" in args: paint_icon().save(args[args.index("--icon") + 1]) return if "--object" in args: paint_object().save(args[args.index("--object") + 1], optimize=True) return if "--picture" in args: write_picture() return for name, image in layers().items(): write(name, image, out) print("HealthInstrumentKnobs:", json.dumps(knobs()))if __name__ == "__main__": main()