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.

tools: the art guards mask the HUD on both the build and promo 03 (refs #388) (#694)

Eyal Golan6d3487e1dfdf
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 446b4d916..054242fd0 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -3368,3 +3368,24 @@ budget: a `-compression disabled` WebGL build, `tools/headed.py boot --runs 3 --
not met.
- Main has moved since (HUD round 2: #584, #602; #598's `?mvp` flag). They are expected to run after `map built`, and
so outside this span, but that was not checked and they were not re-measured.
+
+## The art guards mask the HUD (T74, #388)
+Promo 03 has its own HUD, so the guards leave the same screen regions out of both images rather than hide ours.
+`tools/art_compare.py`'s `HUD_MASK`, as (x0, y0, x1, y1) fractions of the frame, is the top bar (0, 0, 1, 0.07), the
+date plate hanging below it (0, 0, 0.13, 0.10) and the left button column (0, 0.10, 0.045, 0.44). `metrics()` and
+`histogram_distance()` apply it by default; `mask=()` gives the whole frame. A mask that leaves less than half the
+frame raises. `art_compare.py`'s art-log rows are named `<checkpoint-name>-hudmask` (as `art_checkpoint.sh`'s `-units`
+rows), since masking alone moves main's gameplay03 palette distance by about 0.027, more than the main + 0.02 tolerance:
+compare masked rows only with masked rows.
+
+- **Why.** #624 alone moved diorama02's whole-frame warmth 0.1409 -> 0.1465 and gameplay03's palette distance
+ 0.3505 -> 0.3681 (988ad417 with only #624 cherry-picked, 3 WebGL `?shot` captures each). About half is the shorter
+ navy bar; the rest is the camera reframing to the new bar height (`TopBarInset` -> `CameraRig.TopInset`): with the
+ top 10% and the left column left out of both frames, diorama02 warmth still moves 0.1643 -> 0.1667.
+- **diorama02 warmth band: [0.087, 0.151]** (was [0.087, 0.145]). The top is promo 02's warmth measured the same masked
+ way, `metrics(promo/final/02-map-diorama.png, mask=HUD_MASK)` = 0.1509 (whole frame 0.1454, the old 0.145). Promo 02
+ has no HUD: on it the boxes are geometric, matching where our HUD sits in our diorama02 frame, and they remove a dark
+ backdrop band, part of the title plaque and some sea. The floor 0.087 has no recorded derivation (first in 9d28c722);
+ possibly 0.6 × the old whole-frame top. It is kept.
+- The other bars are unchanged: gameplay03 palette distance to promo 03 <= 0.44 and <= main + 0.02, diorama02
+ saturation <= 0.48, now all measured masked.
diff --git a/tools/README.md b/tools/README.md
index 8491572bb..4fbb493b9 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -65,8 +65,9 @@ Offline data tools (uv inline-script Python). Run from the repo root.
- `terrain_graph.py` writes `unity/Assets/Shaders/StatecraftTerrain.shadergraph` from Unity's "Terrain Simple" template
with one Custom Function node (`StatecraftTerrain.hlsl`); re-run it only when that function's inputs or outputs change.
- `art_compare.py` puts screenshots next to the promo image of their pose, writes deuteranopia and protanopia copies and
- logs rough colour numbers; `art_checkpoint.sh [--no-build] <name>` builds WebGL, takes the screenshots
- (`web_check.py --shots`) and runs it (docs/visual-v1.md).
+ logs rough colour numbers, leaving out the HUD (`HUD_MASK`) of both images (rows named `<name>-hudmask`);
+ `art_checkpoint.sh [--no-build] <name>` builds WebGL, takes the screenshots (`web_check.py --shots`) and runs it
+ (docs/visual-v1.md).
- `coast_measure.py <shots...> --window south|north [--promo] [--check]` measures the beach width, foam band, lace lines
and sand lightness across the coast of a gameplay03 screenshot (or promo 03's same coast), the median over several
shots, against bands set from promo 03 (#388).
diff --git a/tools/art_compare.py b/tools/art_compare.py
index b555dfaed..585b2cfa6 100644
--- a/tools/art_compare.py
+++ b/tools/art_compare.py
@@ -12,7 +12,9 @@ For every PNG under <shots-dir> whose name ends in a pose (gameplay03, diorama02
(default captures/visual/art-log.tsv; art_checkpoint.sh points every worktree at the main checkout's): checkpoint, branch,
short commit (both "-" outside a git checkout), the image's absolute path, saturation, contrast (luma std), warmth
(mean R - B), and the palette distance to the promo (total variation between
-8x8x8 RGB histograms; 0 = same palette, 1 = disjoint). The numbers inform the owner's review. Exit code 2 when a
+8x8x8 RGB histograms; 0 = same palette, 1 = disjoint). Every number leaves out HUD_MASK's boxes (the HUD) of both
+images (pass mask=() for the whole frame), and main() names its rows <checkpoint-name>-hudmask, so they cannot be
+mistaken for the whole-frame rows written before the mask. The numbers inform the owner's review. Exit code 2 when a
screenshot is near-uniform (luma std < 0.01: a black or blank WebGL capture), 1 when no screenshot matched a pose."""
import argparse
import subprocess
@@ -27,6 +29,18 @@ PROMOS = {"gameplay03": ROOT / "promo" / "final" / "03-gameplay-1936.png",
"diorama02": ROOT / "promo" / "final" / "02-map-diorama.png"}
CAPTION_PX, GAP_PX, HEIGHT_PX = 44, 16, 720
UNIFORM_STD = 0.01
+MIN_KEPT = 0.5 # a mask must leave at least this share of the frame measured
+MASKED_SUFFIX = "-hudmask" # main() names its art-log rows <checkpoint-name>-hudmask: they leave out HUD_MASK, and
+ # rows written before it measured the whole frame (as art_checkpoint.sh's -units rows)
+Mask = tuple[tuple[float, float, float, float], ...]
+# Screen regions the guards leave out of both the screenshot and the promo, as (x0, y0, x1, y1) fractions of the frame:
+# the HUD covers the same places in both, and promo 03's HUD cannot be hidden. Measured on 1920x1080 ?shot captures
+# after #624 and on promo 03 (2752x1536).
+HUD_MASK: Mask = (
+ (0.0, 0.0, 1.0, 0.07), # the top bar: ours 6.4% of the height, promo 03's 6.5%
+ (0.0, 0.0, 0.13, 0.10), # the date plate hanging below it: ours 12.4% x 9.1%, promo 03's 12% x 8.6%
+ (0.0, 0.10, 0.045, 0.44), # the left column of round buttons: ours (four) to 34% of the height, promo 03's (five) to 43%
+)
MACHADO = {
"deuteranopia": np.array([[0.367322, 0.860646, -0.227968], [0.280085, 0.672501, 0.047413], [-0.011820, 0.042940, 0.968881]]),
"protanopia": np.array([[0.152286, 1.052583, -0.204868], [0.114503, 0.786281, 0.099216], [-0.003882, -0.048116, 1.051998]]),
@@ -43,20 +57,45 @@ def source_identity(root: Path) -> tuple[str, str]:
return git("rev-parse", "--abbrev-ref", "HEAD"), git("rev-parse", "--short", "HEAD")
-def metrics(img: Image.Image) -> dict[str, float]:
+def keep(width: int, height: int, mask: Mask, pad: tuple[int, int] = (0, 0)) -> np.ndarray:
+ """(height, width) booleans, True outside every box of mask (each grown by pad pixels). Raises ValueError on a box
+ outside [0, 1] or inside out, and when the mask leaves less than MIN_KEPT of the frame: a guard must not pass on an
+ empty or near-empty region."""
+ k = np.ones((height, width), dtype=bool)
+ for x0, y0, x1, y1 in mask:
+ if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
+ raise ValueError(f"mask box {(x0, y0, x1, y1)} is not inside the frame")
+ k[max(0, int(np.floor(y0 * height)) - pad[1]):int(np.ceil(y1 * height)) + pad[1],
+ max(0, int(np.floor(x0 * width)) - pad[0]):int(np.ceil(x1 * width)) + pad[0]] = False
+ if k.mean() < MIN_KEPT:
+ raise ValueError(f"mask {mask} leaves {k.mean():.1%} of a {width}x{height} frame, under {MIN_KEPT:.0%}")
+ return k
+
+
+def metrics(img: Image.Image, mask: Mask = HUD_MASK) -> dict[str, float]:
rgb = img.convert("RGB")
- a = np.asarray(rgb, dtype=np.float32) / 255.0
- s = np.asarray(rgb.convert("HSV"), dtype=np.float32)[..., 1] / 255.0
- luma = 0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]
- return {"saturation": float(s.mean()), "contrast": float(luma.std()), "warmth": float((a[..., 0] - a[..., 2]).mean())}
+ k = keep(rgb.width, rgb.height, mask)
+ a = (np.asarray(rgb, dtype=np.float32) / 255.0)[k]
+ s = (np.asarray(rgb.convert("HSV"), dtype=np.float32)[..., 1] / 255.0)[k]
+ luma = 0.2126 * a[:, 0] + 0.7152 * a[:, 1] + 0.0722 * a[:, 2]
+ return {"saturation": float(s.mean()), "contrast": float(luma.std()), "warmth": float((a[:, 0] - a[:, 2]).mean())}
+
+
+def histogram(img: Image.Image, bins: int = 8, mask: Mask = HUD_MASK) -> np.ndarray:
+ """The normalised bins x bins x bins RGB histogram of img at 256x256, outside mask."""
+ px = np.asarray(img.convert("RGB")).copy()
+ px[~keep(px.shape[1], px.shape[0], mask)] = 0 # the masked pixels cannot reach the resize below
+ # and the 256x256 pixels the resize blended from them are dropped too (bicubic reaches 2 pixels of the
+ # smaller grid: 2 here when shrinking, 2 * 256 / side when enlarging)
+ pad = tuple(int(np.ceil(2 * max(1, 256 / side))) + 1 for side in (px.shape[1], px.shape[0]))
+ small = np.asarray(Image.fromarray(px, "RGB").resize((256, 256)), dtype=np.int64)
+ x = (small[keep(256, 256, mask, pad)] // (256 // bins)).reshape(-1, 3)
+ h = np.bincount(x[:, 0] * bins * bins + x[:, 1] * bins + x[:, 2], minlength=bins ** 3).astype(np.float64)
+ return h / h.sum()
-def histogram_distance(a: Image.Image, b: Image.Image, bins: int = 8) -> float:
- def hist(img: Image.Image) -> np.ndarray:
- x = (np.asarray(img.convert("RGB").resize((256, 256)), dtype=np.int64) // (256 // bins)).reshape(-1, 3)
- h = np.bincount(x[:, 0] * bins * bins + x[:, 1] * bins + x[:, 2], minlength=bins ** 3).astype(np.float64)
- return h / h.sum()
- return float(0.5 * np.abs(hist(a) - hist(b)).sum())
+def histogram_distance(a: Image.Image, b: Image.Image, bins: int = 8, mask: Mask = HUD_MASK) -> float:
+ return float(0.5 * np.abs(histogram(a, bins, mask) - histogram(b, bins, mask)).sum())
def simulate_cvd(img: Image.Image, kind: str) -> Image.Image:
@@ -100,14 +139,14 @@ def main(argv: list[str], root: Path = ROOT, promos: dict[str, Path] = PROMOS) -
uniform.append(path)
print(f"FAIL: {path} is near-uniform (luma std {m['contrast']:.4f}): the capture is blank")
continue
- title = (f"{a.name} | {path.stem} (left) vs {promos[pose].name} (right) | saturation {m['saturation']:.2f}/{p['saturation']:.2f}"
+ title = (f"{a.name}{MASKED_SUFFIX} (HUD masked) | {path.stem} (left) vs {promos[pose].name} (right) | saturation {m['saturation']:.2f}/{p['saturation']:.2f}"
f" contrast {m['contrast']:.3f}/{p['contrast']:.3f} warmth {m['warmth']:.3f}/{p['warmth']:.3f} palette distance {d:.2f}")
pair = compose(shot, promo, title)
pair.save(path.with_name(path.stem + "-compare.png"))
for kind in MACHADO:
simulate_cvd(pair, kind).save(path.with_name(f"{path.stem}-compare-{kind}.png"))
with log.open("a") as f:
- f.write("\t".join([a.name, branch, commit, str(path.resolve()), f"{m['saturation']:.4f}", f"{m['contrast']:.4f}", f"{m['warmth']:.4f}", f"{d:.4f}"]) + "\n")
+ f.write("\t".join([a.name + MASKED_SUFFIX, branch, commit, str(path.resolve()), f"{m['saturation']:.4f}", f"{m['contrast']:.4f}", f"{m['warmth']:.4f}", f"{d:.4f}"]) + "\n")
print("ART " + title)
rows += 1
if uniform:
diff --git a/tools/tests/test_art_compare.py b/tools/tests/test_art_compare.py
index ebccea059..9a16ee043 100644
--- a/tools/tests/test_art_compare.py
+++ b/tools/tests/test_art_compare.py
@@ -1,4 +1,5 @@
import numpy as np
+import pytest
from PIL import Image
import art_compare as ac
@@ -53,7 +54,7 @@ def test_main_pairs_each_pose_with_its_promo_logs_a_row_and_writes_cvd_copies(tm
for suffix in ("-compare.png", "-compare-deuteranopia.png", "-compare-protanopia.png"):
assert (shots / (stem + suffix)).exists(), stem + suffix
rows = log.read_text().splitlines()
- assert len(rows) == 2 and all(r.startswith("task-x\t") for r in rows)
+ assert len(rows) == 2 and all(r.startswith("task-x-hudmask\t") for r in rows)
assert ac.main(["art_compare.py", str(shots), "again", "--log", str(log)], root=tmp_path,
promos={"gameplay03": promo, "diorama02": promo}) == 0
assert not (shots / "gameplay03-compare-compare.png").exists()
@@ -76,8 +77,74 @@ def test_art_log_rows_name_the_branch_the_commit_and_the_absolute_image(tmp_path
assert ac.main(["art_compare.py", str(shots), "t", "--log", str(log)], root=tmp_path,
promos={"gameplay03": promo, "diorama02": promo}) == 0
name, branch, commit, image = log.read_text().splitlines()[0].split("\t")[:4]
- assert (name, branch, commit) == ("t", "-", "-") # tmp_path is not a git checkout
+ assert (name, branch, commit) == ("t-hudmask", "-", "-") # tmp_path is not a git checkout
assert image == str((shots / "gameplay03.png").resolve())
from pathlib import Path
branch, commit = ac.source_identity(Path(ac.__file__).resolve().parents[1])
assert branch != "-" and len(commit) >= 7
+
+
+def test_the_hud_mask_boxes_are_pinned():
+ """The top bar (6.4% of the frame since #624; promo 03's is 6.5%), the date plate hanging below it and the left column
+ of round buttons, as (x0, y0, x1, y1) fractions of the frame, applied alike to the build frame and the promo."""
+ assert ac.HUD_MASK == ((0.0, 0.0, 1.0, 0.07), (0.0, 0.0, 0.13, 0.10), (0.0, 0.10, 0.045, 0.44))
+
+
+def paint_inside(img, mask, seed):
+ """img with random pixels painted strictly inside every box of mask, and nowhere else."""
+ a = np.asarray(img, dtype=np.uint8).copy()
+ h, w = a.shape[:2]
+ rng = np.random.default_rng(seed)
+ for x0, y0, x1, y1 in mask:
+ r0, r1, c0, c1 = int(np.ceil(y0 * h)), int(y1 * h), int(np.ceil(x0 * w)), int(x1 * w)
+ a[r0:r1, c0:c1] = rng.integers(0, 255, (r1 - r0, c1 - c0, 3), dtype=np.uint8)
+ return Image.fromarray(a, "RGB")
+
+
+def test_pixels_inside_the_hud_mask_do_not_move_the_metrics():
+ frame, promo = noisy((480, 270), 6), noisy((688, 384), 7) # build 16:9, promo 03's 2752x1536 shape
+ frame2, promo2 = paint_inside(frame, ac.HUD_MASK, 8), paint_inside(promo, ac.HUD_MASK, 9)
+ assert ac.metrics(frame2) == ac.metrics(frame)
+ assert ac.histogram_distance(frame2, promo2) == ac.histogram_distance(frame, promo)
+ # not vacuous: the painted pixels do move the whole-frame numbers
+ assert ac.metrics(frame2, mask=()) != ac.metrics(frame, mask=())
+ assert ac.histogram_distance(frame2, promo2, mask=()) != ac.histogram_distance(frame, promo, mask=())
+
+
+def test_a_mask_that_leaves_no_pixels_fails_instead_of_passing_vacuously():
+ img = noisy()
+ for bad in (((0.0, 0.0, 1.0, 1.0),), ((0.0, 0.0, 1.0, 0.5), (0.0, 0.5, 1.0, 1.0)), ((0.5, 0.0, 0.2, 1.0),),
+ ((-0.1, 0.0, 0.5, 0.5),), ((0.0, 0.0, 1.0, 0.55),), ((0.0, 0.0, 0.999, 0.999),)):
+ with pytest.raises(ValueError):
+ ac.metrics(img, mask=bad)
+ with pytest.raises(ValueError):
+ ac.histogram_distance(img, img, mask=bad)
+
+
+def test_the_hud_mask_keeps_most_of_the_build_frame_and_of_promo_03():
+ for w, h in ((1920, 1080), (1280, 720), (2752, 1536)):
+ assert ac.keep(w, h, ac.HUD_MASK).mean() > 0.85, (w, h)
+ assert ac.MIN_KEPT == 0.5
+
+
+def test_the_resize_pad_drops_every_pixel_blended_from_the_masked_pixels():
+ """The masked pixels are zeroed before the 256x256 resize; without the pad the bicubic blend of that black with the
+ image would land in other bins. A solid image therefore keeps exactly one bin, enlarged or shrunk."""
+ for size in ((64, 36), (480, 270), (1920, 1080), (688, 384)):
+ h = ac.histogram(solid((200, 150, 60), size))
+ assert np.count_nonzero(h) == 1 and h.max() == 1.0, size
+
+
+def test_masked_art_log_rows_and_titles_are_labelled_so_they_are_not_mistaken_for_whole_frame_rows(tmp_path, capsys):
+ """Masking moves main's gameplay03 palette distance by about 0.027, more than the main + 0.02 tolerance, so a masked
+ row must never read as one of the whole-frame rows already in the shared log (art_checkpoint.sh's -units precedent)."""
+ promo = tmp_path / "promo.png"; noisy().save(promo)
+ shots = tmp_path / "shots"; shots.mkdir()
+ noisy(seed=5).save(shots / "gameplay03.png")
+ log = tmp_path / "art-log.tsv"
+ log.write_text("main6\tmain\t988ad417\t/x/gameplay03.png\t0.4\t0.2\t0.1\t0.3505\n") # a whole-frame row from before
+ assert ac.main(["art_compare.py", str(shots), "main6", "--log", str(log)], root=tmp_path,
+ promos={"gameplay03": promo, "diorama02": promo}) == 0
+ old, new = (r.split("\t")[0] for r in log.read_text().splitlines())
+ assert old == "main6" and new == "main6" + ac.MASKED_SUFFIX == "main6-hudmask"
+ assert "main6-hudmask (HUD masked)" in capsys.readouterr().out