"""Drawing primitives for IRON ARC art. Everything is authored as SVG (real gradients, blur, grain) and rasterised with `rsvg-convert`, so the same source yields a crisp 48 dp launcher icon and a 1024 px store graphic. No pixel pushing, no hand-tuned anti-aliasing. Style rules that make the output look deliberate (see docs/art-direction.md): * light comes from the horizon, never from the top corners; * every silhouette gets a warm rim on its upper edge; * grain + vignette are applied to the *whole* composition, not per shape; * type is Roboto Black with negative tracking, one accent word only. """ from __future__ import annotations import json import math import random import subprocess import tempfile from pathlib import Path from typing import Iterable, Sequence ROOT = Path(__file__).resolve().parents[2] ART_DIR = Path(__file__).resolve().parent # --------------------------------------------------------------------------- # # palette # --------------------------------------------------------------------------- # class Palette: def __init__(self, data: dict): self._d = data @classmethod def load(cls, path: Path | None = None) -> "Palette": path = path or (ART_DIR / "palette.json") return cls(json.loads(path.read_text(encoding="utf-8"))) def color(self, path: str) -> str: """`P.color('solar.base')` -> '#FFB347'.""" node: object = self._d for part in path.split("."): node = node[part] # type: ignore[index] return str(node) def value(self, path: str): node: object = self._d for part in path.split("."): node = node[part] # type: ignore[index] return node def rgba(hex_color: str, alpha: float) -> str: """`#FFB347` + 0.4 -> `rgba(255,179,71,0.4)` for SVG fills/strokes.""" h = hex_color.lstrip("#") r, g, b = (int(h[i : i + 2], 16) for i in (0, 2, 4)) return f"rgba({r},{g},{b},{alpha:.3f})" # --------------------------------------------------------------------------- # # document # --------------------------------------------------------------------------- # def svg_doc(width: float, height: float, body: str, defs: str = "") -> str: return ( f'' f"{defs}{body}" ) def linear_gradient( gid: str, stops: Sequence[tuple[float, str, float]], x1: float = 0, y1: float = 0, x2: float = 0, y2: float = 1, ) -> str: parts = "".join( f'' for o, c, a in stops ) return ( f'' f"{parts}" ) def radial_gradient( gid: str, stops: Sequence[tuple[float, str, float]], cx: float = 0.5, cy: float = 0.5, r: float = 0.5, ) -> str: parts = "".join( f'' for o, c, a in stops ) return ( f'' f"{parts}" ) def blur_filter(fid: str, std: float) -> str: return ( f'' f'' ) def grain_filter(fid: str = "grain", freq: float = 0.9, octaves: int = 3) -> str: """Monochrome fractal noise; overlay it at 3-8 % for a filmic finish.""" return ( f'' f'' f'' ) def vignette_def(gid: str = "vignette", strength: float = 0.55) -> str: return radial_gradient( gid, [(0.45, "#000000", 0.0), (1.0, "#000000", strength)], r=0.78, ) # --------------------------------------------------------------------------- # # geometry # --------------------------------------------------------------------------- # def smooth_path(points: Sequence[tuple[float, float]], closed: bool = False) -> str: """Catmull-Rom through the points, emitted as cubic beziers.""" if len(points) < 2: raise ValueError("need at least two points") pts = list(points) if closed: pts = [pts[-1]] + pts + [pts[0], pts[1]] else: pts = [pts[0]] + pts + [pts[-1]] d = f"M {pts[1][0]:.2f} {pts[1][1]:.2f}" for i in range(1, len(pts) - 2): p0, p1, p2, p3 = pts[i - 1], pts[i], pts[i + 1], pts[i + 2] c1 = (p1[0] + (p2[0] - p0[0]) / 6.0, p1[1] + (p2[1] - p0[1]) / 6.0) c2 = (p2[0] - (p3[0] - p1[0]) / 6.0, p2[1] - (p3[1] - p1[1]) / 6.0) d += ( f" C {c1[0]:.2f} {c1[1]:.2f} {c2[0]:.2f} {c2[1]:.2f} " f"{p2[0]:.2f} {p2[1]:.2f}" ) if closed: d += " Z" return d def hill_ridge( width: float, base_y: float, amplitude: float, seed: int, *, steps: int = 7, phase: float = 0.0, foot: float | None = None, ) -> list[tuple[float, float]]: """Reproducible skyline: two sines + seeded jitter, optionally closed to the foot.""" rnd = random.Random(seed) pts: list[tuple[float, float]] = [] for i in range(steps + 1): t = i / steps x = t * width wave = math.sin((t * 2.2 + phase) * math.tau) * 0.55 wave += math.sin((t * 5.1 + phase * 1.7) * math.tau) * 0.22 jitter = (rnd.random() - 0.5) * 0.30 if 0 < i < steps else 0.0 y = base_y - amplitude * (0.5 + 0.5 * wave + jitter) pts.append((x, y)) if foot is not None: pts.append((width, foot)) pts.append((0, foot)) return pts def ballistic_arc( x0: float, y0: float, x1: float, y1: float, apex_y: float, steps: int = 26 ) -> list[tuple[float, float]]: """Parabola through the apex height - the game's signature shape.""" pts = [] for i in range(steps + 1): t = i / steps x = x0 + (x1 - x0) * t base = y0 + (y1 - y0) * t bump = 4 * t * (1 - t) # vanishes at both ends y = base + (apex_y - (y0 + y1) / 2) * bump pts.append((x, y)) return pts # --------------------------------------------------------------------------- # # type # --------------------------------------------------------------------------- # def text( x: float, y: float, content: str, *, size: float, fill: str, weight: int = 400, family: str = "Roboto", anchor: str = "start", tracking: float = 0.0, opacity: float = 1.0, extra: str = "", ) -> str: return ( f'{content}' ) # --------------------------------------------------------------------------- # # raster # --------------------------------------------------------------------------- # def render(svg: str, out: Path, width: int | None = None) -> Path: """Rasterise SVG with librsvg (crisp text, real filters).""" out.parent.mkdir(parents=True, exist_ok=True) cmd = ["rsvg-convert", "-o", str(out)] if width: cmd += ["-w", str(width)] with tempfile.NamedTemporaryFile("w", suffix=".svg", delete=False) as fh: fh.write(svg) tmp = fh.name try: subprocess.run(cmd + [tmp], check=True, capture_output=True) finally: Path(tmp).unlink(missing_ok=True) return out def contact_sheet( paths: Iterable[Path], out: Path, cols: int = 3, cell: int = 320 ) -> Path: """Preview grid so generated art can be reviewed at a glance.""" from PIL import Image, ImageDraw files = [p for p in paths if p.exists()] if not files: raise SystemExit("nothing to preview") rows = (len(files) + cols - 1) // cols sheet = Image.new("RGB", (cols * cell, rows * (cell + 22)), (18, 20, 24)) draw = ImageDraw.Draw(sheet) for i, path in enumerate(files): img = Image.open(path).convert("RGBA") size = img.size img.thumbnail((cell - 16, cell - 16), Image.LANCZOS) x = (i % cols) * cell + 8 y = (i // cols) * (cell + 22) + 8 # checkerboard so transparency is obvious for cy in range(y, y + cell - 16, 16): for cx in range(x, x + cell - 16, 16): shade = 40 if ((cx // 16 + cy // 16) % 2) else 30 draw.rectangle([cx, cy, cx + 15, cy + 15], fill=(shade, shade, shade)) sheet.paste(img, (x, y), img) draw.text((x, y + cell - 14), f"{path.name} {size}", fill=(180, 190, 205)) out.parent.mkdir(parents=True, exist_ok=True) sheet.save(out) return out