"""Flat PNG -> XYZ tile pyramid. python tools/tile.py # every map python tools/tile.py customs # one map Reads build//base.png Writes web/tiles//{z}/{x}/{y}.webp (z = 0 .. maxZoom, 1:1 at maxZoom) Tile indices are local to the map's own top-left corner. The web app shifts them into world space -- see common.py for why that shift is always exact. """ from __future__ import annotations import math import shutil import sys import time from PIL import Image from common import BUILD, ROOT, TILES, Config, find_map, load_config Image.MAX_IMAGE_PIXELS = None WEBP = {"format": "WEBP", "quality": 82, "method": 4} def tile_map(cfg: Config, m: dict) -> dict: src = BUILD / m["id"] / "base.png" if not src.exists(): raise SystemExit(f"[{m['id']}] {src.relative_to(ROOT)} missing -- run export_base.py first") t0 = time.time() img = Image.open(src).convert("RGB") if m.get("crop"): x0, y0, x1, y1 = m["crop"] img = img.crop((x0, y0, x1, y1)) w, h = img.size cell = cfg.cell_size if w > cell or h > cell: raise SystemExit( f"[{m['id']}] cropped size {w}x{h} exceeds the {cell}px grid cell. " f"Raise maxZoom in maps.json (each +1 doubles the cell)." ) out = TILES / m["id"] if out.exists(): shutil.rmtree(out) ts = cfg.tile_size written = skipped = 0 for z in range(cfg.max_zoom, -1, -1): scale = 2.0 ** (z - cfg.max_zoom) zw, zh = max(1, round(w * scale)), max(1, round(h * scale)) level = img if z == cfg.max_zoom else img.resize((zw, zh), Image.LANCZOS) for ty in range(math.ceil(zh / ts)): for tx in range(math.ceil(zw / ts)): box = (tx * ts, ty * ts, min((tx + 1) * ts, zw), min((ty + 1) * ts, zh)) piece = level.crop(box) if piece.size == (ts, ts): tile = piece # interior tile, stays opaque RGB else: # Edge tile: pad to a full square with transparency rather # than letting the browser stretch a short tile. tile = Image.new("RGBA", (ts, ts), (0, 0, 0, 0)) tile.paste(piece, (0, 0)) if not tile.getbbox(): skipped += 1 continue dst = out / str(z) / str(tx) dst.mkdir(parents=True, exist_ok=True) tile.save(dst / f"{ty}.webp", **WEBP) written += 1 size_mb = sum(f.stat().st_size for f in out.rglob("*.webp")) / 1e6 print(f"[{m['id']}] {w}x{h} -> {written} tiles ({skipped} empty skipped), " f"{size_mb:.1f} MB, {time.time() - t0:.0f}s") ox, oy = cfg.origin(m) return { "id": m["id"], "name": m["name"], "cell": m["cell"], "origin": [ox, oy], "size": [w, h], "pxPerMeter": m.get("pxPerMeter"), } def main(argv: list[str]) -> list[dict]: cfg = load_config() targets = [find_map(cfg, i) for i in argv] if argv else cfg.maps return [tile_map(cfg, m) for m in targets] if __name__ == "__main__": main(sys.argv[1:])