view tools/build.py @ 13:8df95050fc8b

no more build during pause; tower popup closes on any click outside it
author ark
date 2026-10-19 21:59 +0200
parents 22b604680c5a
children 7fda634d15ad
line wrap: on
line source

#!/usr/bin/env python3
"""
build the game data from art/ and config/ into game/assets/ and game/data/.

usage: python3 tools/build.py [--force] [--watch]

steps: sprites, tower levels, maps, masks, sounds, config, checks, previews.
a step
is skipped when all its outputs are newer than its inputs and the build
scripts; --force runs every step. --watch reruns the build whenever a file
in art/, art/sounds/, art/digits/ or config/ changes.

requires python 3.11 or later and pillow.
"""

import base64
import json
import math
import re
import sys
import time
import tomllib
from pathlib import Path

from PIL import Image

# keep tools/ free of __pycache__
sys.dont_write_bytecode = True

import images
import masks
import preview

ROOT = Path(__file__).resolve().parent.parent
ART = ROOT / "art"
SOUNDS = ART / "sounds"
DIGITS = ART / "digits"
CONFIG = ROOT / "config"
ASSETS = ROOT / "game" / "assets"
DATA = ROOT / "game" / "data"
TEMP = ROOT / "temp"
PREVIEW = TEMP / "preview"
# route data of the last mask step, read when the step is skipped
MAPS_CACHE = TEMP / "build" / "maps.json"

TOOLS = sorted((ROOT / "tools").glob("*.py"))
HEADER = "// generated by tools/build.py from {src}, do not edit\n"

SPRITES = (["m%d" % i for i in range(5)] + ["b%d" % i for i in range(4)]
           + ["t%d" % i for i in range(4)] + ["p%d" % i for i in range(4)]
           + ["c%d" % i for i in range(4)] + ["hpm", "hpb"]
           # icons, buttons and screens (art.md)
           + ["coin_icon", "heart", "monster_icon", "play_button", "pause_button",
              "speed_x1", "speed_x2", "speed_x4", "sound_on", "sound_off", "next_wave",
              "shop_bubble", "shop_bubble_dark", "shop_bubble_dark2", "tower_popup",
              "upgrade_button", "sell_button", "monster_death", "boss_death",
              "splash", "splash_play", "map_won", "map_won_button",
              "game_lost", "game_lost_button", "game_won", "game_won_button"])
# hp bar variants (art.md): the empty part is a darkened copy, the bar of a
# slowed monster has its colour set to this hue in degrees
BAR_DARKEN = 0.35
BAR_SLOW_HUE = 220
BARS = ["hpm", "hpb"]
BAR_VARIANTS = [f"{n}{v}" for n in BARS for v in ("_empty", "_slow", "_slow_empty")]
MAPS = 4
MAP_QUALITY = 88
# centre line smoothing: moving average half window, simplify tolerance
ROUTE_SMOOTH = 8
ROUTE_TOLERANCE = 0.8
# number of decimals of route points in maps.js
ROUTE_DECIMALS = 1
# per map settings used by the mask step
MASK_SETTINGS = ("path_half_width", "spawn_distance", "exit_distance")

warnings = []


def warn(msg):
    warnings.append(msg)
    print("  warning:", msg)


def stale(inputs, outputs, force):
    """true when an output is missing or older than an input or a build script."""
    if force:
        return True
    try:
        oldest = min(p.stat().st_mtime for p in outputs)
    except FileNotFoundError:
        return True
    newest = max(p.stat().st_mtime for p in list(inputs) + TOOLS)
    return newest > oldest


def write_text(path, text):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text)


# 1. sprites

def step_sprites(force):
    # digits cut by tools/cut_digits.py, written as digit_NAME_N
    digits = sorted(DIGITS.glob("*.png"))
    inputs = [ART / f"{n}.png" for n in SPRITES] + digits + [DIGITS]
    outputs = ([ASSETS / f"{n}.png" for n in SPRITES + BAR_VARIANTS]
               + [ASSETS / f"digit_{p.name}" for p in digits])
    if not stale(inputs, outputs, force):
        print("sprites: up to date")
        return False
    ASSETS.mkdir(parents=True, exist_ok=True)
    for p in ASSETS.glob("digit_*.png"):
        p.unlink()
    for p in digits:
        images.trim(Image.open(p).convert("RGBA")).save(ASSETS / f"digit_{p.name}", optimize=True)
    for n in SPRITES:
        im = images.trim(Image.open(ART / f"{n}.png").convert("RGBA"))
        im.save(ASSETS / f"{n}.png", optimize=True)
        if n in BARS:
            slow = images.recolour(im, BAR_SLOW_HUE)
            images.darken(im, BAR_DARKEN).save(ASSETS / f"{n}_empty.png", optimize=True)
            slow.save(ASSETS / f"{n}_slow.png", optimize=True)
            images.darken(slow, BAR_DARKEN).save(ASSETS / f"{n}_slow_empty.png", optimize=True)
    print(f"sprites: wrote {len(SPRITES)} sprites, {len(BAR_VARIANTS)} bar variants"
          f" and {len(digits)} digits")
    return True


# 2. tower levels

def step_towers(force):
    changed = False
    for t in range(4):
        src = ART / f"t{t}p.png"
        outputs = [ASSETS / f"t{t}_{lv}.png" for lv in range(2, 6)]
        if not stale([src], outputs, force):
            continue
        for lv, im in enumerate(images.tower_levels(src), start=2):
            im.save(ASSETS / f"t{t}_{lv}.png", optimize=True)
        changed = True
    print("towers:", "wrote levels 2-5" if changed else "up to date")
    return changed


# 3. maps

def step_maps(force):
    changed = False
    for m in range(MAPS):
        src, dst = ART / f"map{m}.png", ASSETS / f"map{m}.jpg"
        if stale([src], [dst], force):
            images.map_copy(src, dst, MAP_QUALITY)
            changed = True
    print("maps:", "wrote jpeg copies" if changed else "up to date")
    return changed


# 4. masks

def apply_corrections(m, routes, fix):
    """
    apply routes.toml corrections for map m to a list of route dicts.
    each route dict has points, and gets a fixed weight or None.
    """
    for r in routes:
        r["weight"] = None
    for spec in fix.get("route", []):
        pts = [tuple(p) for p in spec["points"]]
        if "replace" in spec:
            routes[spec["replace"]]["points"] = pts
            routes[spec["replace"]]["manual"] = True
        else:
            routes.append({"points": pts, "weight": None, "manual": True})
    for k, v in fix.get("weights", {}).items():
        routes[int(k)]["weight"] = float(v)
    drop = set(fix.get("drop", []))
    for i, r in enumerate(routes):
        r["number"] = i
    return [r for i, r in enumerate(routes) if i not in drop]


def route_values(routes):
    """
    fill in length, turning and value of each route (balance.md, route
    preference): the average of length relative to the longest route and
    straightness relative to the straightest, that is the least turning.
    """
    for r in routes:
        r["length"] = masks.polyline_length(r["points"])
        r["turning"] = masks.turning(r["points"])
    longest = max(r["length"] for r in routes)
    least = min(r["turning"] for r in routes)
    for r in routes:
        straight = least / r["turning"] if r["turning"] else 1.0
        r["value"] = (r["length"] / longest + straight) / 2


def step_masks(cfg, force):
    placement = cfg["placement"]
    settings = {"placement": placement,
                "maps": [{k: cfg["map"][str(m)][k] for k in MASK_SETTINGS} for m in range(MAPS)]}
    routes_toml = CONFIG / "routes.toml"
    inputs = [ART / f"map{m}mask.png" for m in range(MAPS)] + [routes_toml]
    outputs = [DATA / "maps.js", MAPS_CACHE]
    cached = None
    if MAPS_CACHE.exists():
        cached = json.loads(MAPS_CACHE.read_text())
    # the placement settings are part of the input, compared by value
    if not stale(inputs, outputs, force) and cached and cached.get("settings") == settings:
        print("masks: up to date")
        return cached["maps"], False

    fixes = tomllib.loads(routes_toml.read_text()).get("map", {})
    out = []
    for m in range(MAPS):
        t0 = time.time()
        mc = settings["maps"][m]
        mask = masks.Mask(ART / f"map{m}mask.png")
        found = masks.extract_routes(mask, ROUTE_SMOOTH, ROUTE_TOLERANCE)
        spaces = [(found["spawns"], mc["spawn_distance"]),
                  (found["exit_points"], mc["exit_distance"])]
        cols, rows, grid = masks.placement_grid(mask, placement, found["centre"],
                                                mc["path_half_width"], spaces)
        routes = [{"points": pts, "manual": False} for pts in found["routes"]]
        routes = apply_corrections(m, routes, fixes.get(str(m), {}))
        route_values(routes)
        g = found["graph"]
        out.append({
            "name": f"map{m}",
            "width": mask.w,
            "height": mask.h,
            "cell": placement["grid_cell"],
            "cols": cols,
            "rows": rows,
            "grid": grid,
            "line_width": found["width"],
            "entrances": [b[:3] for b in found["entrances"]],
            "exits": [b[:3] for b in found["exits"]],
            "routes": routes,
            "graph": {
                "nodes": [list(p) for p in g.nodes.values()],
                "edges": [e[2] for e in g.edges.values()],
            },
        })
        print(f"masks: map{m} {len(routes)} route(s), {time.time() - t0:.1f} s")

    write_maps_js(out)
    MAPS_CACHE.parent.mkdir(parents=True, exist_ok=True)
    MAPS_CACHE.write_text(json.dumps({"settings": settings, "maps": out}))
    return out, True


def write_maps_js(maps):
    def rnd(v):
        return round(v, ROUTE_DECIMALS)

    js = []
    for mp in maps:
        js.append({
            "name": mp["name"],
            "image": f"assets/{mp['name']}.jpg",
            "width": mp["width"],
            "height": mp["height"],
            "cell": mp["cell"],
            "cols": mp["cols"],
            "rows": mp["rows"],
            "grid": mp["grid"],
            "entrances": [[rnd(v) for v in b] for b in mp["entrances"]],
            "exits": [[rnd(v) for v in b] for b in mp["exits"]],
            "routes": [{
                "points": [rnd(v) for p in r["points"] for v in p],
                "length": rnd(r["length"]),
                "turning": rnd(r["turning"]),
                "value": round(r["value"], 3),
                "weight": r["weight"],
            } for r in mp["routes"]],
        })
    body = ",\n".join(json.dumps(m, separators=(",", ":")) for m in js)
    write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png and config/routes.toml")
               + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n")


# 5. sounds

def step_sounds(cfg, force):
    """
    embed art/sounds/*.mp3 as base64 in game/data/sounds.js, grouped by
    event: NAME.mp3 or the variants NAME_1.mp3, NAME_2.mp3 and so on.
    """
    inputs = sorted(SOUNDS.glob("*.mp3"))
    dst = DATA / "sounds.js"
    if not stale(inputs, [dst], force):
        print("sounds: up to date")
        return
    events = {}
    for p in inputs:
        name = re.sub(r"_\d+$", "", p.stem)
        events.setdefault(name, []).append(base64.b64encode(p.read_bytes()).decode("ascii"))
    for name in events:
        if name not in cfg["sound"]["event"]:
            warn(f"sounds: {name} has no entry in [sound.event]")
    body = ",\n".join(f" {json.dumps(k)}: {json.dumps(v)}" for k, v in events.items())
    write_text(dst, HEADER.format(src="art/sounds/")
               + "window.MM = window.MM || {};\nMM.sounds = {\n" + body + "\n};\n")
    size = dst.stat().st_size / 1024
    print(f"sounds: wrote {len(inputs)} sounds for {len(events)} events, {size:.0f} KB")


# 6. config

class ConfigError(Exception):
    pass


def need(table, key, kind, where):
    if key not in table:
        raise ConfigError(f"{where}: {key} missing")
    v = table[key]
    if kind is float:
        ok = isinstance(v, (int, float)) and not isinstance(v, bool)
    else:
        ok = isinstance(v, kind)
    if not ok:
        raise ConfigError(f"{where}: {key} should be {kind.__name__}, is {v!r}")
    return v


def check_config(cfg):
    """raise ConfigError on missing or malformed settings."""
    for sec in ("scale", "monster", "animation", "movement", "route_preference", "tower",
                "placement", "economy", "waves", "hearts", "coins", "controls", "art", "debug",
                "sound", "map"):
        if sec not in cfg:
            raise ConfigError(f"section [{sec}] missing")
    for mid, mon in cfg["monster"].items():
        for k in ("hp", "coins", "speed"):
            need(mon, k, float, f"monster.{mid}")
    for tid, tw in cfg["tower"].items():
        for k in ("damage", "range"):
            v = need(tw, k, list, f"tower.{tid}")
            if len(v) != 5:
                raise ConfigError(f"tower.{tid}: {k} needs 5 levels, has {len(v)}")
        for k in ("cost", "attack_time", "projectile_speed"):
            need(tw, k, float, f"tower.{tid}")
        need(tw, "projectile", str, f"tower.{tid}")
        if "slow" in tw and len(tw["slow"]) != 5:
            raise ConfigError(f"tower.{tid}: slow needs 5 levels")
    for k in ("speed_variation", "offset", "lean", "wander_step", "fade_in"):
        need(cfg["movement"], k, float, "movement")
    for k in ("footprint_radius", "max_gap", "min_tower_distance", "edge_distance",
              "snap_radius", "grid_cell"):
        need(cfg["placement"], k, float, "placement")
    snd = cfg["sound"]
    need(snd, "enabled", bool, "sound")
    need(snd, "volume", float, "sound")
    need(snd, "beep_wave", str, "sound")
    for name, ev in need(snd, "event", dict, "sound").items():
        where = f"sound.event.{name}"
        need(ev, "volume", float, where)
        if "min_interval" in ev:
            need(ev, "min_interval", float, where)
        for note in ev.get("beep", []):
            if not (isinstance(note, list) and len(note) == 2):
                raise ConfigError(f"{where}: beep notes should be [frequency, seconds]")
    for m in range(MAPS):
        mp = cfg["map"].get(str(m))
        if mp is None:
            raise ConfigError(f"[map.{m}] missing")
        where = f"map.{m}"
        for k in ("starting_coins", "early_bonus", "wave_count") + MASK_SETTINGS:
            need(mp, k, float, where)
        need(mp, "monster_share", list, where)
        for w, wave in enumerate(mp.get("wave", []), start=1):
            for g, grp in enumerate(need(wave, "groups", list, f"{where} wave {w}"), start=1):
                gw = f"{where} wave {w} group {g}"
                mon = need(grp, "monster", str, gw)
                if mon not in cfg["monster"]:
                    raise ConfigError(f"{gw}: unknown monster {mon}")
                need(grp, "count", int, gw)
                for k in ("interval", "delay"):
                    if k in grp:
                        need(grp, k, float, gw)


def sprite_table():
    """name -> [width, height] of every image in game/assets/ except maps."""
    out = {}
    for p in sorted(ASSETS.glob("*.png")):
        with Image.open(p) as im:
            out[p.stem] = list(im.size)
    return out


def step_config(cfg, force, assets_changed):
    src = CONFIG / "game.toml"
    dst = DATA / "config.js"
    if not stale([src], [dst], force) and not assets_changed:
        print("config: up to date")
        return
    out = {k: v for k, v in cfg.items() if k != "map"}
    out["maps"] = []
    for m in range(MAPS):
        mp = dict(cfg["map"][str(m)])
        mp["waves"] = mp.pop("wave", [])
        out["maps"].append(mp)
    out["sprites"] = sprite_table()
    write_text(dst, HEADER.format(src="config/game.toml")
               + "window.MM = window.MM || {};\nMM.config = "
               + json.dumps(out, indent=1) + ";\n")
    print("config: wrote game/data/config.js")


# 7. checks

def wave_totals(cfg, waves):
    """return per monster counts, regular coins, boss coins, regular hp."""
    counts = {}
    for wave in waves:
        for grp in wave["groups"]:
            counts[grp["monster"]] = counts.get(grp["monster"], 0) + grp["count"]
    mons = cfg["monster"]
    reg = sum(n * mons[k]["coins"] for k, n in counts.items() if not mons[k].get("boss"))
    boss = sum(n * mons[k]["coins"] for k, n in counts.items() if mons[k].get("boss"))
    hp = sum(n * mons[k]["hp"] for k, n in counts.items() if not mons[k].get("boss"))
    return counts, reg, boss, hp


def step_checks(cfg, maps):
    print("\nchecks")
    mons = cfg["monster"]
    regular = sorted(k for k, v in mons.items() if not v.get("boss"))
    speeds = sorted({v["speed"] for v in mons.values()})
    for m, mp in enumerate(maps):
        c = cfg["map"][str(m)]
        print(f"\nmap{m}: {mp['width']}x{mp['height']}, line width {mp['line_width']:.0f},"
              f" road half width {c['path_half_width']}, {mp['grid'].count('1')} placement cells")
        if len(mp["entrances"]) == 0 or len(mp["exits"]) == 0:
            warn(f"map{m}: no entrance or no exit found")
        if not mp["routes"]:
            warn(f"map{m}: no routes")
        for r in mp["routes"]:
            times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds)
            fixed = f", weight {r['weight']}" if r["weight"] is not None else ""
            manual = ", manual" if r.get("manual") else ""
            print(f"  route {r['number']}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
                  f" value {r['value']:.2f}{fixed}{manual}; walk time {times} s"
                  f" at speed {', '.join(str(s) for s in speeds)}")

        waves = c.get("wave", [])
        if len(waves) != c["wave_count"]:
            warn(f"map{m}: {len(waves)} waves, wave_count says {c['wave_count']}")
        if not waves:
            continue
        counts, reg, boss, hp = wave_totals(cfg, waves)
        target = c["starting_coins"] * cfg["economy"]["coin_total_factor"]
        total = reg + boss
        print("  monsters: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in sorted(counts))
              + f", {sum(counts.values())} in all")
        share = [100 * counts.get(k, 0) * mons[k]["coins"] / reg if reg else 0 for k in regular]
        print("  coin share %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t
                                             in zip(regular, share, c["monster_share"])))
        print(f"  coins: regular {reg}, boss {boss}, total {total}, target {target:.0f};"
              f" regular hp {hp}")
        if abs(total - target) > cfg["economy"]["coin_tolerance"] * target:
            warn(f"map{m}: coins {total} are more than"
                 f" {cfg['economy']['coin_tolerance'] * 100:.0f} % off the target {target:.0f}")
        per_wave = []
        for w, wave in enumerate(waves, start=1):
            _, r, b, _ = wave_totals(cfg, [wave])
            per_wave.append(r + b)
        print("  coins per wave: " + ", ".join(str(v) for v in per_wave))

        last = waves[-1]["groups"]
        bosses = [g["monster"] for w in waves for g in w["groups"] if mons[g["monster"]].get("boss")]
        if bosses != [f"b{m}"] or not mons[last[-1]["monster"]].get("boss") or last[-1]["count"] != 1:
            warn(f"map{m}: expected one b{m} as the last group of the last wave")
        bonus = c["early_bonus"] * (cfg["waves"]["first_break"]
                                    + cfg["waves"]["break"] * (len(waves) - 1))
        print(f"  early start bonus if every break is skipped: {math.floor(bonus)}")


# 8. previews

def step_previews(cfg, maps, force, changed):
    outputs = [PREVIEW / f"map{m}.png" for m in range(MAPS)] + [PREVIEW / "towers.png"]
    # the tower sheet shows the pivots from game.toml
    if not changed and not stale([CONFIG / "game.toml"], outputs, force):
        print("previews: up to date")
        return
    PREVIEW.mkdir(parents=True, exist_ok=True)
    for m, mp in enumerate(maps):
        preview.map_preview(ART / f"map{m}.png", mp).save(PREVIEW / f"map{m}.png")
        if len(mp["routes"]) > 1:
            preview.route_sheet(ART / f"map{m}.png", mp).save(PREVIEW / f"map{m}_routes.png")
    preview.tower_sheet(ASSETS, cfg["art"]["pivot"]).save(PREVIEW / "towers.png")
    print(f"previews: wrote {PREVIEW.relative_to(ROOT)}/")


def build(force):
    warnings.clear()
    try:
        cfg = tomllib.loads((CONFIG / "game.toml").read_text())
        check_config(cfg)
    except (tomllib.TOMLDecodeError, ConfigError) as e:
        print("config error:", e)
        return False
    changed = step_sprites(force)
    changed |= step_towers(force)
    step_maps(force)
    maps, masks_changed = step_masks(cfg, force)
    step_sounds(cfg, force)
    step_config(cfg, force, changed)
    step_checks(cfg, maps)
    step_previews(cfg, maps, force, changed or masks_changed)
    print(f"\n{len(warnings)} warning(s)")
    return True


def watch():
    def snapshot():
        files = (list(ART.iterdir()) + list(SOUNDS.glob("*.mp3")) + list(DIGITS.glob("*.png"))
                 + list(CONFIG.iterdir()) + TOOLS)
        return {p: p.stat().st_mtime for p in files if p.is_file()}

    seen = None
    while True:
        now = snapshot()
        if now != seen:
            seen = now
            print(time.strftime("\n== build %H:%M:%S"))
            try:
                build(False)
            except Exception as e:  # keep watching after a failed build
                print("build failed:", e)
        time.sleep(1)


def main():
    args = sys.argv[1:]
    if "--watch" in args:
        # show each line at once, also when the output goes to a file
        sys.stdout.reconfigure(line_buffering=True)
        try:
            watch()
        except KeyboardInterrupt:
            pass
        return 0
    return 0 if build("--force" in args) else 1


if __name__ == "__main__":
    sys.exit(main())