#!/usr/bin/env python3 """Download the Aion 2 dungeon and raid maps for the Raidplaner. The map images come from the game client; the DPS meter repository Waffle-ens/waffle_meter publishes them (dotnet/Assets/Maps, 2048x2048 PNG). Which maps we use, their slugs and German names are maintained by hand in dungeons/dungeons.json - this script only fetches the images listed there: - dungeons/.webp the map itself (WebP, same size as the original) - previews/.webp a small square preview for the map picker - size / bounds written back into dungeons.json: image size and the part of the map with the dungeon on it (world coordinates 0..4096, like the tactics) - the viewer zooms there when the map is opened The bounds are found by comparing each map with the shared background of all maps (every map texture has the same clouds and rings, only the dungeon differs). Usage: python download_dungeon_maps.py # all maps from dungeons.json python download_dungeon_maps.py --slug fire-temple python download_dungeon_maps.py --commit # other version of the repository Requires Pillow and numpy. """ import argparse import io import json import os import sys import time import urllib.error import urllib.request import numpy as np from PIL import Image, ImageFilter HERE = os.path.dirname(os.path.abspath(__file__)) MAP_DIR = os.path.dirname(HERE) LIST_FILE = os.path.join(MAP_DIR, "dungeons", "dungeons.json") OUT_DIR = os.path.join(MAP_DIR, "dungeons") PREVIEW_DIR = os.path.join(MAP_DIR, "previews") RAW_URL = "https://raw.githubusercontent.com/{repo}/{commit}/{path}/{key}.png" USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) aion2-dungeon-maps/1.0" WORLD_SIZE = 4096 # world coordinates of the viewer (CONFIG.WORLD_MAX_X) PREVIEW_SIZE = 320 BOUNDS_MARGIN = 0.04 # share of the image added around the dungeon DIFF_THRESHOLD = 30 # colour difference to the shared background that counts as "dungeon" def http_get(url: str, retries: int = 3) -> bytes: last_err = None for attempt in range(1, retries + 1): try: req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(req, timeout=60) as resp: return resp.read() except (urllib.error.URLError, TimeoutError) as exc: last_err = exc if attempt < retries: time.sleep(1.5 * attempt) raise RuntimeError(f"GET {url} failed after {retries} attempts: {last_err}") def world_bounds(box, size): """Pixel box (x0, y0, x1, y1) of an image -> world coordinates. The viewer draws the image as large as possible into the square 0..4096 world, centered (MapView.imageRect).""" width, height = size scale = WORLD_SIZE / max(width, height) off_x = (WORLD_SIZE - width * scale) / 2 off_y = (WORLD_SIZE - height * scale) / 2 x0, y0, x1, y1 = box return [round(off_x + x0 * scale), round(off_y + y0 * scale), round(off_x + x1 * scale), round(off_y + y1 * scale)] def content_box(image, background): """Part of the image that differs from the shared background (with a margin), as a pixel box.""" width, height = image.size if background is None or (width, height) != (2048, 2048): return (0, 0, width, height) small = np.asarray(image.resize((512, 512), Image.BILINEAR)).astype(np.int16) diff = np.abs(small - background).sum(axis=2) >= DIFF_THRESHOLD # single stray pixels (e.g. slightly different clouds) do not count mask = Image.fromarray((diff * 255).astype("uint8")).filter(ImageFilter.MinFilter(3)).filter(ImageFilter.MaxFilter(3)) ys, xs = np.nonzero(np.asarray(mask) > 0) if len(xs) == 0: return (0, 0, width, height) factor = width / 512 margin = BOUNDS_MARGIN * width return (max(0, int(xs.min() * factor - margin)), max(0, int(ys.min() * factor - margin)), min(width, int((xs.max() + 1) * factor + margin)), min(height, int((ys.max() + 1) * factor + margin))) def square_box(box, size): """Enlarge a box to a square (for the preview), kept inside the image.""" width, height = size x0, y0, x1, y1 = box side = min(max(x1 - x0, y1 - y0), width, height) cx, cy = (x0 + x1) / 2, (y0 + y1) / 2 left = int(min(max(0, cx - side / 2), width - side)) top = int(min(max(0, cy - side / 2), height - side)) return (left, top, left + side, top + side) def dump_list(data) -> str: """dungeons.json in its hand-written layout: one map per line, so it stays easy to edit.""" compact = lambda value: json.dumps(value, ensure_ascii=False, separators=(", ", ": ")) lines = ["{"] for key in [k for k in data if k != "groups"]: lines.append(f' {compact(key)}: {json.dumps(data[key], ensure_ascii=False, indent=2).replace(chr(10), chr(10) + " ")},') lines.append(' "groups": [') for g_index, group in enumerate(data["groups"]): lines.append(" {") for key in [k for k in group if k != "maps"]: lines.append(f" {compact(key)}: {compact(group[key])},") lines.append(' "maps": [') for m_index, entry in enumerate(group["maps"]): text = compact(entry) lines.append(" { " + text[1:-1] + " }" + ("," if m_index < len(group["maps"]) - 1 else "")) lines.append(" ]") lines.append(" }" + ("," if g_index < len(data["groups"]) - 1 else "")) lines.append(" ]") lines.append("}") return "\n".join(lines) + "\n" def main(): parser = argparse.ArgumentParser(description="Download the dungeon maps listed in dungeons/dungeons.json") parser.add_argument("--slug", help="only this map (all are still downloaded for the shared background)") parser.add_argument("--commit", help="commit of the source repository (default: dungeons.json source.commit)") args = parser.parse_args() with open(LIST_FILE, encoding="utf-8") as fh: data = json.load(fh) source = data["source"] if args.commit: source["commit"] = args.commit entries = [m for group in data["groups"] for m in group["maps"] if m.get("key")] selected = [m for m in entries if not args.slug or m["slug"] == args.slug] if not selected: sys.exit(f"Unknown slug {args.slug}") images = {} for entry in entries: url = RAW_URL.format(repo=source["repo"], commit=source["commit"], path=source["path"], key=entry["key"]) print(f" {entry['slug']:<20} {entry['key']}") images[entry["slug"]] = Image.open(io.BytesIO(http_get(url))).convert("RGB") # Shared background: per-pixel median of all square maps squares = [np.asarray(img.resize((512, 512), Image.BILINEAR)).astype(np.int16) for img in images.values() if img.size == (2048, 2048)] background = np.median(np.stack(squares), axis=0).astype(np.int16) if len(squares) >= 5 else None if background is None: print("Too few maps for the shared background - bounds = whole image") os.makedirs(OUT_DIR, exist_ok=True) os.makedirs(PREVIEW_DIR, exist_ok=True) for entry in selected: image = images[entry["slug"]] image.save(os.path.join(OUT_DIR, entry["slug"] + ".webp"), "WEBP", quality=85, method=6) box = content_box(image, background) entry["size"] = list(image.size) entry["bounds"] = world_bounds(box, image.size) preview = image.crop(square_box(box, image.size)).resize((PREVIEW_SIZE, PREVIEW_SIZE), Image.LANCZOS) preview.save(os.path.join(PREVIEW_DIR, entry["slug"] + ".webp"), "WEBP", quality=80, method=6) with open(LIST_FILE, "w", encoding="utf-8", newline="\n") as fh: fh.write(dump_list(data)) print(f"{len(selected)} maps written to {OUT_DIR}") if __name__ == "__main__": main()