"""Build a unified multi-resolution world composite and AI transition mask. Usage: python tools/composite.py --level 5 # 7368x7368 composite & mask (fast, cheap) python tools/composite.py --level 6 # 14736x14736 composite & mask (full target) Writes: build/world/composite-z{level}.png build/world/mask-z{level}.png (0 = protected art, 128 = transition band, 255 = satellite) build/world/composite-z{level}.json """ from __future__ import annotations import argparse import json import math import sys from pathlib import Path import numpy as np from PIL import Image, ImageChops, ImageDraw, ImageFilter from common import BUILD, CONFIG, ROOT, WORLD_ID, Config, load_config Image.MAX_IMAGE_PIXELS = None def get_trimmed_art(m: dict) -> tuple[Image.Image, Image.Image | None]: """Load the raw map artwork and its playable trim mask (skirts excluded).""" base_path = BUILD / m["id"] / "base.png" if not base_path.exists(): raise FileNotFoundError(f"[{m['id']}] base.png missing in {base_path.parent}") img = Image.open(base_path).convert("RGBA") if m.get("crop"): img = img.crop(tuple(m["crop"])) w, h = img.size trim = m.get("trim") points = trim.get("points", []) if isinstance(trim, dict) else [] if len(points) >= 3: poly = [(round(float(x) * (w - 1)), round(float(y) * (h - 1))) for x, y in points] poly_mask = Image.new("L", (w, h), 0) ImageDraw.Draw(poly_mask).polygon(poly, fill=255) # Apply alpha of image as well alpha = img.getchannel("A") combined_alpha = ImageChops.multiply(alpha, poly_mask) img.putalpha(combined_alpha) return img, poly_mask return img, None def build_composite(cfg: Config, level: int, out_dir: Path) -> tuple[Path, Path]: ww, wh = cfg.world_size() scale = 2.0 ** (level - cfg.max_zoom) cw, ch = max(1, round(ww * scale)), max(1, round(wh * scale)) print(f"Compositing World Level z{level} ({cw}x{ch} px)...") # 1. Base Layer (Square Satellite) base_src = Image.open(cfg.base_image_path()).convert("RGB") if cfg.rotate: base_src = base_src.rotate(cfg.rotate, expand=True, resample=Image.BICUBIC) base_scaled = base_src.resize((cw, ch), Image.LANCZOS) canvas = base_scaled.convert("RGBA") # Mask canvas: 255 = satellite-only (free to edit) mask = Image.new("L", (cw, ch), 255) # Sort detail maps by size (large maps first, finer/nested details on top) detail_maps = [m for m in cfg.maps if m["id"] != WORLD_ID] detail_maps.sort(key=lambda m: -(m.get("place", {}).get("w", 0) * (m.get("place", {}).get("h") or m.get("place", {}).get("w", 0)))) band_radius = max(8, round(24 * scale * 16)) # Transition band radius in level-z pixels layers_info = [] for m in detail_maps: try: art_rgba, poly_mask = get_trimmed_art(m) except Exception as exc: print(f" [{m['id']}] skipped: {exc}") continue pl = cfg.placement(m) tw = pl["width"] * scale th = (pl["height"] if pl["height"] is not None else tw * art_rgba.height / art_rgba.width) * scale tw_int, th_int = max(1, round(tw)), max(1, round(th)) x0 = round((pl["cx"] - pl["width"] / 2.0) * scale) y0 = round((pl["cy"] - (pl["height"] if pl["height"] is not None else pl["width"] * art_rgba.height / art_rgba.width) / 2.0) * scale) print(f" [{m['id']:<17}] placing {art_rgba.width}x{art_rgba.height} -> {tw_int}x{th_int} @ ({x0},{y0})") # Scale art scaled_art = art_rgba.resize((tw_int, th_int), Image.LANCZOS) # Paste onto RGBA canvas canvas.paste(scaled_art, (x0, y0), scaled_art) # Compute mask components if poly_mask is not None: scaled_poly = poly_mask.resize((tw_int, th_int), Image.BILINEAR) else: scaled_poly = scaled_art.getchannel("A") # Create inner protected (0) and outer transition (128) poly_arr = np.array(scaled_poly) is_inside = poly_arr > 128 # Erode for core protected area shrink_px = max(2, band_radius // 2) inner_mask_im = scaled_poly.filter(ImageFilter.MinFilter(shrink_px * 2 + 1)) inner_arr = np.array(inner_mask_im) > 128 # Transition band = inside or near edge dilate_px = max(2, band_radius) outer_mask_im = scaled_poly.filter(ImageFilter.MaxFilter(dilate_px * 2 + 1)) outer_arr = np.array(outer_mask_im) > 128 # Stamp onto world mask # Map rect bounds in canvas wx0, wy0 = max(0, x0), max(0, y0) wx1, wy1 = min(cw, x0 + tw_int), min(ch, y0 + th_int) ox0, oy0 = wx0 - x0, wy0 - y0 ox1, oy1 = ox0 + (wx1 - wx0), oy0 + (wy1 - wy0) world_mask_crop = np.array(mask.crop((wx0, wy0, wx1, wy1))) # Outer band gets 128 (transition) band_region = outer_arr[oy0:oy1, ox0:ox1] world_mask_crop[band_region] = 128 # Inner protected gets 0 (copy original) inner_region = inner_arr[oy0:oy1, ox0:ox1] world_mask_crop[inner_region] = 0 mask.paste(Image.fromarray(world_mask_crop, mode="L"), (wx0, wy0)) layers_info.append({ "id": m["id"], "name": m["name"], "rect": [x0, y0, x0 + tw_int, y0 + th_int], "size": [tw_int, th_int], }) out_dir.mkdir(parents=True, exist_ok=True) comp_path = out_dir / f"composite-z{level}.png" mask_path = out_dir / f"mask-z{level}.png" json_path = out_dir / f"composite-z{level}.json" canvas.convert("RGB").save(comp_path, format="PNG", compress_level=4) mask.save(mask_path, format="PNG", compress_level=4) meta = { "level": level, "dimensions": [cw, ch], "baseWorldSize": [ww, wh], "layers": layers_info, "composite": str(comp_path.relative_to(ROOT)), "mask": str(mask_path.relative_to(ROOT)), } json_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8") print(f"\nWrote composite -> {comp_path.relative_to(ROOT)}") print(f"Wrote mask -> {mask_path.relative_to(ROOT)}") print(f"Wrote metadata -> {json_path.relative_to(ROOT)}") return comp_path, mask_path def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--level", type=int, default=5, choices=[4, 5, 6, 7], help="Zoom level (default: 5)") parser.add_argument("--out-dir", type=Path, default=BUILD / "world") args = parser.parse_args(argv) cfg = load_config() build_composite(cfg, args.level, args.out_dir) if __name__ == "__main__": main(sys.argv[1:])