Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

8.1 KB
Raw Blame
# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy==2.5.3", "pyyaml==6.0.3"]
# ///
"""True 1949 armistice lines -> the per-hex layer the map draws over the 1948 sub-districts (MapBorders; docs/visual-v1.md
"Region borders").

Usage: uv run tools/armistice_bake.py   (reads content/map/armistice_lines_1949.geojson, content/map/hexes.json and
content/map/subdistrict_hexes_1948.yaml; writes content/map/armistice_hexes_1949.yaml)

The GeoJSON keeps the true lines (tools/armistice_digitise.py); the game shows them snapped to hex edges (owner ruling
2026-10-11), deterministically (float64, features in file order):
  zones (the Demilitarized Zones): each land hex of the sub-district layer whose centre lies inside a zone takes that
    zone; drawn from the zone's date over the sub-districts (MapRegions in Unity). A zone narrower than a hex may take
    no hex at all: it stays in the true lines, and the bake lists it (`no_hex`).
  lines: every map hex the true line passes through (the line sampled every 0.25 km, each sample's containing hex);
    the info panel names the line and its agreement there, from the line's date. A line is drawn only where it bounds
    a zone, or where it is the Mandate frontier the sub-district layer already draws (Lebanon; the Syrian line along
    the border).
  fronts: each agreement, its date, whether a line exists (a front without one keeps the Mandate sub-district layer,
    says so, and has no date) and whether it is low-accuracy (Jordan: traced from a low-resolution scan). Each zone and
    line also names its own agreement and date (the 1950 modus vivendi is not the 1949 agreement) and a label note. tools/borders_bake.py writes the same dates into the sub-district
    layer as each front's end there.
The sim never reads the output (display only: the content hash and the goldens do not move).
"""
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
import borders_bake as bb  # noqa: E402
import hexgrid as hg  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
MAP = ROOT / "content" / "map"
SOURCE = MAP / "armistice_lines_1949.geojson"
OUT = MAP / "armistice_hexes_1949.yaml"
SUBDISTRICT_LAYER = MAP / "subdistrict_hexes_1948.yaml"
LABEL = "1949 armistice lines"
FRONT_NAMES = {"egypt": "Egypt", "lebanon": "Lebanon", "jordan": "Jordan", "syria": "Syria"}
STEP_KM = 0.25
HEADER = ("# Generated by tools/armistice_bake.py from armistice_lines_1949.geojson (the true lines), hexes.json and the\n"
          "# sub-district layer. Do not edit by hand: rerun the tool. Display only (MapBorders): the sim never reads this file.\n"
          "# Zones take the land hexes whose centre they contain; lines name the hexes they pass through (info panel).\n")


def land_hexes() -> set:
    """The land hexes the sub-district layer covers (every land hex of the map)."""
    rows = [ln for ln in SUBDISTRICT_LAYER.read_text(encoding="utf-8").splitlines() if ln.startswith("  - [")]
    return {tuple(int(v) for v in ln.strip()[3:-1].split(",")[:2]) for ln in rows}


def line_hexes(coords: list, grid: dict) -> list:
    """Hexes a polyline passes through, in order along it (each once), on the tools' projection."""
    b, size = grid["bounds"], grid["hex_size_km"]
    on_map = {(h["q"], h["r"]) for h in grid["hexes"]}
    pts = np.array([hg.lonlat_to_km(lon, lat, b) for lon, lat in coords], dtype=np.float64)
    xs, ys = [], []
    for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]):
        n = max(1, int(np.ceil(np.hypot(x1 - x0, y1 - y0) / STEP_KM)))
        t = np.arange(n, dtype=np.float64) / n
        xs.append(x0 + t * (x1 - x0)); ys.append(y0 + t * (y1 - y0))
    xs.append(pts[-1:, 0]); ys.append(pts[-1:, 1])
    q, r = hg.point_to_hex(np.concatenate(xs), np.concatenate(ys), size)
    out, seen = [], set()
    for c in zip(q, r):
        if c in on_map and c not in seen:
            seen.add(c); out.append(c)
    return out


def item(i: int, p: dict) -> dict:
    return {"id": i, "key": p["id"], "front": p["front"], "name": p["name"], "shown_from": p["shown_from"], "agreement": p["agreement"],
            "signed": p["signed"], "label_note": p.get("label_note", ""), "low_accuracy": p.get("source_quality") == "low_res_scan"}


def bake(source: dict, grid: dict, land: set) -> dict:
    zones, lines, zone_cells, line_cells, no_hex = [], [], {}, [], []
    for f in source["features"]:
        p = f["properties"]
        if p["kind"] == "zone":
            zid = len(zones) + 1
            zones.append(item(zid, p))
            shape = bb.rings(f["geometry"])
            n = 0
            for h in grid["hexes"]:
                c = (h["q"], h["r"])
                if c in land and c not in zone_cells and bb.contains(shape, h["lon"], h["lat"]):
                    zone_cells[c] = zid; n += 1
            if n == 0:
                no_hex.append(p["id"])
        else:
            lid = len(lines) + 1
            lines.append(item(lid, p))
            g = f["geometry"]
            parts = [g["coordinates"]] if g["type"] == "LineString" else g["coordinates"]
            seen = set()
            for part in parts:
                for c in line_hexes(part, grid):
                    if c not in seen:
                        seen.add(c); line_cells.append((c[0], c[1], lid))
    return {"zones": zones, "lines": lines, "zone_cells": zone_cells, "line_cells": line_cells, "no_hex": no_hex}


def render(source: dict, baked: dict) -> str:
    meta = source["statecraft"]
    q = json.dumps

    def extra(x: dict) -> str:
        return (f"agreement: {q(x['agreement'])}, signed: {x['signed']}, label_note: {q(x['label_note'])}, "
                f"low_accuracy: {str(x['low_accuracy']).lower()}")
    out = [HEADER, "layer: armistice_1949\n", f"title: {q(meta['title'])}\n",
           f"line: {q('The true lines are content/map/armistice_lines_1949.geojson (status ' + meta['status'] + '): the agreements and their annexed maps; shown here to the nearest hex edge, up to half a hex (about 4 km) from the true line.')}\n",
           f"label: {q(LABEL)}   # added to the map label while any front's line is shown\n",
           "fronts:   # each agreement; shown_from null: no line data, the Mandate sub-district layer stays on that front\n"]
    for f in meta["fronts"]:
        note = f.get("gap", "")
        out.append(f"  - {{ key: {f['key']}, name: {q(FRONT_NAMES[f['key']])}, agreement: {q(f['agreement'])}, signed: {f['signed']}, "
                   f"shown_from: {f['shown_from'] or 'null'}, low_accuracy: {str(f.get('source_quality') == 'low_res_scan').lower()}, note: {q(note)} }}\n")
    out.append("zones:   # drawn over the sub-districts from shown_from (style secondary)\n")
    for z in baked["zones"]:
        out.append(f"  - {{ id: {z['id']}, key: {z['key']}, front: {z['front']}, name: {q(z['name'])}, shown_from: {z['shown_from']}, style: secondary, {extra(z)} }}\n")
    out.append("lines:   # named in the info panel on the hexes they pass through, from shown_from\n")
    for ln in baked["lines"]:
        out.append(f"  - {{ id: {ln['id']}, key: {ln['key']}, front: {ln['front']}, name: {q(ln['name'])}, shown_from: {ln['shown_from']}, {extra(ln)} }}\n")
    out.append(f"no_hex: {q(baked['no_hex'])}   # zones narrower than any hex centre: kept in the true lines only\n")
    out.append("zone_hexes:   # [q, r, zone id], ordered by r then q\n")
    for (qq, rr), zid in sorted(baked["zone_cells"].items(), key=lambda kv: (kv[0][1], kv[0][0])):
        out.append(f"  - [{qq}, {rr}, {zid}]\n")
    out.append("line_hexes:   # [q, r, line id], in order along each line\n")
    for qq, rr, lid in baked["line_cells"]:
        out.append(f"  - [{qq}, {rr}, {lid}]\n")
    return "".join(out)


def build() -> str:
    source = json.loads(SOURCE.read_text(encoding="utf-8"))
    grid = json.loads((MAP / "hexes.json").read_text())
    return render(source, bake(source, grid, land_hexes()))


def main() -> None:
    text = build()
    OUT.write_text(text, encoding="utf-8")
    print(f"wrote {OUT.relative_to(ROOT)} ({text.count(chr(10) + '  - [')} rows)")
    print(text[text.index("zones:"):text.index("zone_hexes:")])


if __name__ == "__main__":
    main()