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: diorama02 warmth is measured per material against promo 02 (refs #695) (#702)

Eyal Golan4d19031532c4
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 054242fd0..137ca4378 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -3389,3 +3389,46 @@ compare masked rows only with masked rows.
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.
+
+## diorama02 warmth per material (#695, T77)
+The owner ruled on #695: **"Measure each material"**. Whole-frame warmth compares geography as much as colour: masked,
+promo 02 is about a quarter sea and 6% dark wood, our diorama02 an eighth sea and a third table, and that mix alone puts
+our frame 0.028 warmer while our materials' colours put it 0.015 cooler (T77's split of the 0.0133 gap). So diorama02's
+warmth guard now compares each material with the same material in promo 02.
+
+- **Classifier** (`tools/art_compare.py`, `classify()`): neutral (chroma (max - min) / max under 0.08), sea (B > R),
+ green (G > R), then the warm pixels by luma: wood under 0.30, land 0.30-0.55, sand from 0.55. The cuts sit between
+ hand-picked **region means** (wood 0.13-0.26, our table 0.18-0.20; hills 0.35-0.50; Negev sand 0.70-0.71), not in gaps
+ of the pixel histograms: ours has a valley at 0.25-0.50, promo 02's runs flat there and 0.55 sits on its ramp. "Sand" is
+ therefore bright warm ground: the Negev, the beaches, and sunlit hills and stone towns in promo 02. Sensitivity of the
+ sand verdict on main: FAIL for a sand cut of 0.45, 0.50, 0.55 and 0.60 (ours 0.287-0.307 against floors 0.288-0.313);
+ at 0.65 it passes by 0.001 (0.3206 against 0.3197).
+- **Mask.** The material guard uses `MATERIAL_MASK`: `HUD_MASK` plus the minimap (0.86, 0.62, 1, 1), the "Click the map"
+ plate (0, 0.92, 0.17, 1) and the map-layer legend (0.76, 0.94, 0.87, 1). Their navy is B > R, so unmasked they read as
+ sea: about 16% of main's sea pixels, which made it -0.1729 instead of -0.2000. The boxes apply to promo 02 alike; there
+ they cover open sand, a corner of the Dead Sea and some hills, no UI (without them on promo 02: sand 0.3811, sea
+ -0.2598, within 0.002). `HUD_MASK` and the other guards are unchanged.
+- **Bands.** The gates are sand and sea. Each band is promo 02's mean warmth (R - B) for the material, masked with
+ `MATERIAL_MASK`, plus or minus 20% of its size: the old whole-frame band [0.087, 0.145] was 40% of its promo anchor
+ wide, here centred on the promo. Sand [0.3037, 0.4556] (promo 0.3796), sea [-0.3119, -0.2080] (promo -0.2599). No band
+ is fitted to our output. Known limitation: promo 02's "sea" also holds its glass towers and solar fields (B > R): 9% of
+ its sea pixels (chroma under 0.2, warmth -0.048); without them its sea reads -0.281, so the sea band's centre is about
+ 0.02 warmer than promo 02's water. A simple chroma cut does not separate them cleanly (it also drops shore and salt
+ pixels and keeps the bluest panels), so they stay in. The sand gate is the class mean. As a check, a pure-sand crop of the open Negev west of
+ Beersheba (ours (0.22, 0.80, 0.34, 0.93), promo 02 (0.08, 0.86, 0.28, 0.97), both over 99% sand) reads 0.344 against
+ promo 02's 0.468: the same direction, larger.
+- **Wood is printed, not gated.** It is not like-for-like: promo 02's dark backdrop lies mostly under `HUD_MASK`'s top-bar
+ box, so promo 02's "wood" is mostly the frame's walnut and terrain shadow (6% of the frame), while ours is mostly the
+ table (a third of it). Main reads 0.1126 against promo 02's 0.0908.
+- **Which image is gated.** Only the WebGL `?shot` (directly under the checkpoint folder): it is what the owner sees. The
+ editor renders (`editor/PC-diorama02.png`, `editor/Mobile-diorama02.png`) are printed as information. Every MATERIAL
+ line names its file.
+- **Fail-closed.** A gating material covering under 2% of the measured pixels of either image (about 37,000 pixels at
+ 1920x1080) cannot be measured. A gate out of band is a failure, not a note: `art_compare.py` exits 3 and prints
+ `GUARD FAIL: <material> <value> vs <band>` for each; it exits 4 when a gating material cannot be measured (1 when no
+ screenshot matched a pose, 2 on a blank capture). `art_checkpoint.sh` stops on 1, 2 and 4 as on any error; on 3 it
+ finishes the checkpoint (its images are what the owner reviews), lists every `GUARD FAIL` line and exits 3.
+- **Whole-frame warmth** is still printed, as information only; `[0.087, 0.151]` (T74) no longer decides.
+- **Where main stands** (d031af36, 3 WebGL `?shot` captures, spread 0.0000): sand 0.2952 (-0.085, paler and less
+ orange) and sea -0.2000 (+0.060, less blue; 0.008 short of the band's edge): both outside their bands, so `art_checkpoint.sh` exits 3 on main until
+ the art follow-up on #695 lands. This section only sets the measure.
diff --git a/tools/README.md b/tools/README.md
index 4fbb493b9..161bf6ae9 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -65,7 +65,8 @@ 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, leaving out the HUD (`HUD_MASK`) of both images (rows named `<name>-hudmask`);
+ logs rough colour numbers, leaving out the HUD (`HUD_MASK`) of both images (rows named `<name>-hudmask`), and
+ prints diorama02's warmth per material (sand, sea, wood) against promo 02's (#695);
`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
diff --git a/tools/art_checkpoint.sh b/tools/art_checkpoint.sh
index 92fc651e0..992380683 100755
--- a/tools/art_checkpoint.sh
+++ b/tools/art_checkpoint.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Owner art checkpoint (non-blocking): a WebGL build (skipped with --no-build when the task has just built), screenshots at
+# Owner art checkpoint (exits 3 when diorama02's material guards fail, after finishing): a WebGL build (skipped with --no-build when the task has just built), screenshots at
# the promo poses from the player itself (?shot: the web tier with its UI and labels), editor renders of both quality
# tiers, and side-by-side images against the promo with colour-blind simulations. Re-checks both golden hashes in the same
# player run and fails if a screenshot is missing or blank. The art log lives in the main checkout's captures/ so every
@@ -58,5 +58,19 @@ for pose in $poses; do
done
shared "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" ${units_arg[@]+"${units_arg[@]}"} ${proof_arg[@]+"${proof_arg[@]}"} -logFile "$root/unity-capture-promo.log"
git checkout -- unity/ProjectSettings/QualitySettings.asset # SetQualityLevel may have written m_CurrentQuality (no unstaged edits: checked above)
-uv run tools/art_compare.py "$out" "$name${units_query:+-units}${proof_query:+-borderproof}" --log "$main_root/captures/visual/art-log.tsv"
+# art_compare's exit codes (tools/art_compare.py): 0 passed; 1 no screenshot matched a pose, or a crash; 2 a blank
+# capture; 3 a material guard FAIL (#695: the art is off its promo-02 band); 4 a material too rare to measure. 1, 2 and 4
+# stop here as any error does. 3 lets the checkpoint finish (its images are what the owner reviews), then lists every
+# "GUARD FAIL: <material> <value> vs <band>" line and exits 3.
+compare_out="$out/art-compare.out"
+set +e
+uv run tools/art_compare.py "$out" "$name${units_query:+-units}${proof_query:+-borderproof}" --log "$main_root/captures/visual/art-log.tsv" | tee "$compare_out"
+compare=${PIPESTATUS[0]}
+set -e
+[[ $compare == 0 || $compare == 3 ]] || { echo "art_checkpoint: art_compare exited $compare" >&2; exit "$compare"; }
echo "ART CHECKPOINT $name: $(ls "$out"/*-compare*.png "$out"/editor/*-compare*.png | tr '\n' ' ')"
+if [[ $compare == 3 ]]; then
+ echo "art_checkpoint: the material guards failed (docs/visual-v1.md, \"diorama02 warmth per material\"):"
+ grep '^GUARD FAIL: ' "$compare_out" || true
+ exit 3
+fi
diff --git a/tools/art_compare.py b/tools/art_compare.py
index 585b2cfa6..94fe4b65d 100644
--- a/tools/art_compare.py
+++ b/tools/art_compare.py
@@ -14,8 +14,11 @@ short commit (both "-" outside a git checkout), the image's absolute path, satur
(mean R - B), and the palette distance to the promo (total variation between
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."""
+mistaken for the whole-frame rows written before the mask. For diorama02 it also prints a MATERIAL line per
+gating material (sand, sea) of the WebGL shot with its warmth against its band from promo 02, PASS or FAIL (#695),
+and wood, the whole-frame warmth and the editor renders as information. Exit codes (EXIT_GUARD_FAIL and its neighbours
+below): 0 all passed, 1 no screenshot matched a pose, 2 a near-uniform screenshot (luma std < 0.01: a black or blank
+WebGL capture), 3 a gating material out of its band, 4 a gating material too rare to measure."""
import argparse
import subprocess
import sys
@@ -41,6 +44,39 @@ HUD_MASK: Mask = (
(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%
)
+# diorama02's warmth is measured per material against promo 02 (owner's ruling on #695, "Measure each material"): the
+# whole frame mixes materials in different shares (promo 02's board is about a quarter sea, ours an eighth, with a third
+# table), so its warmth compares geography as much as colour. classify() puts each pixel in one class, in this order:
+# neutral chroma (max - min) / max under NEUTRAL_SAT: greys, white salt and labels, which carry no hue;
+# sea blue above red (B > R): the sea, the Dead Sea and the lakes (and promo 02's glass towers and solar fields);
+# green green above red (and B <= R): fields and orchards;
+# wood warm (R >= G, R >= B) and luma under WOOD_LUMA: the table, the frame's walnut and promo 02's dark backdrop;
+# land warm, luma WOOD_LUMA to SAND_LUMA: the hills and the cut earth;
+# sand warm, luma at or over SAND_LUMA: bright warm ground (the Negev, the beaches, sunlit hills and stone towns).
+# The luma cuts sit between hand-picked region means on promo 02 and main's diorama02 (T77), not in gaps of the pixel
+# histograms: the wood's mean luma is 0.13-0.26 (our table 0.18-0.20), the hills' 0.35-0.50 and the Negev sand's 0.70-0.71.
+MATERIALS = ("neutral", "sea", "green", "wood", "land", "sand")
+NEUTRAL_SAT, WOOD_LUMA, SAND_LUMA = 0.08, 0.30, 0.55
+GUARDED_MATERIALS = ("sand", "sea")
+# The material guard also leaves out the minimap (bottom right), the "Click the map" plate (bottom left) and the map-layer
+# legend (bottom right, beside the minimap): their navy is B > R and would count as sea, about 16% of main's diorama02 sea
+# pixels. Applied to promo 02 alike (there they cover open sand, a corner of the Dead Sea and some hills: no UI). HUD_MASK
+# itself, and the guards that use it, are unchanged.
+MATERIAL_MASK: Mask = HUD_MASK + ((0.86, 0.62, 1.0, 1.0), (0.0, 0.92, 0.17, 1.0), (0.76, 0.94, 0.87, 1.0))
+# Printed, not gated: promo 02's dark backdrop is mostly under HUD_MASK's top-bar box, so its "wood" is mostly the frame's
+# walnut and terrain shadow while ours is mostly the table, which is not like-for-like.
+INFO_MATERIALS = ("wood",)
+# main()'s exit codes: 0 every check passed; 1 no screenshot matched a pose (an uncaught crash also exits 1); 2 a blank
+# capture; 3 a gating material outside its band (EXIT_GUARD_FAIL; each failure printed as "GUARD FAIL: ..."); 4 a gating
+# material too rare to measure in the screenshot or the promo (EXIT_UNMEASURABLE). 1, 2 and 4 are errors in the capture
+# or the setup, 3 is the art missing its target.
+EXIT_GUARD_FAIL, EXIT_UNMEASURABLE = 3, 4
+# Each guarded material's band is promo 02's mean warmth (R - B) for it, plus or minus MATERIAL_TOLERANCE of its size: the
+# old whole-frame band [0.087, 0.145] was 40% of its promo anchor wide, here centred on the promo, so either way is a miss.
+MATERIAL_TOLERANCE = 0.2
+# A guarded material must cover at least this share of the measured pixels in both images (about 37,000 pixels of a
+# 1920x1080 frame); below it the guard raises, so a capture missing a material cannot pass on a handful of pixels.
+MIN_MATERIAL_SHARE = 0.02
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]]),
@@ -98,6 +134,53 @@ def histogram_distance(a: Image.Image, b: Image.Image, bins: int = 8, mask: Mask
return float(0.5 * np.abs(histogram(a, bins, mask) - histogram(b, bins, mask)).sum())
+def classify(img: Image.Image) -> np.ndarray:
+ """(height, width) indices into MATERIALS, one per pixel (the rules are above MATERIALS)."""
+ a = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
+ r, g, b = a[..., 0], a[..., 1], a[..., 2]
+ mx, mn = a.max(-1), a.min(-1)
+ chroma = np.where(mx > 0, (mx - mn) / np.maximum(mx, 1e-6), 0.0)
+ luma = 0.2126 * r + 0.7152 * g + 0.0722 * b
+ out = np.full(r.shape, MATERIALS.index("sand"), dtype=np.int8)
+ out[luma < SAND_LUMA] = MATERIALS.index("land")
+ out[luma < WOOD_LUMA] = MATERIALS.index("wood")
+ out[g > r] = MATERIALS.index("green")
+ out[b > r] = MATERIALS.index("sea")
+ out[chroma < NEUTRAL_SAT] = MATERIALS.index("neutral")
+ return out
+
+
+def material_warmth(img: Image.Image, mask: Mask = MATERIAL_MASK) -> dict[str, tuple[float, float | None]]:
+ """Per material: (its share of the pixels outside mask, its mean warmth R - B, or None when it has no pixel)."""
+ rgb = img.convert("RGB")
+ k = keep(rgb.width, rgb.height, mask)
+ a = np.asarray(rgb, dtype=np.float32) / 255.0
+ w, labels = (a[..., 0] - a[..., 2])[k], classify(rgb)[k]
+ return {name: (float((labels == i).mean()), float(w[labels == i].mean()) if (labels == i).any() else None)
+ for i, name in enumerate(MATERIALS)}
+
+
+def material_band(promo_warmth: float) -> tuple[float, float]:
+ t = MATERIAL_TOLERANCE * abs(promo_warmth)
+ return promo_warmth - t, promo_warmth + t
+
+
+def material_guard(shot: Image.Image, promo: Image.Image, mask: Mask = MATERIAL_MASK) -> dict[str, dict[str, float | bool]]:
+ """Each guarded material's mean warmth in shot against its band from promo. Raises ValueError when a guarded material
+ covers less than MIN_MATERIAL_SHARE of either image, rather than pass on too few pixels."""
+ ours, theirs = material_warmth(shot, mask), material_warmth(promo, mask)
+ out: dict[str, dict[str, float | bool]] = {}
+ for name in GUARDED_MATERIALS:
+ for who, m in (("the screenshot", ours), ("the promo", theirs)):
+ if m[name][0] < MIN_MATERIAL_SHARE:
+ raise ValueError(f"{name} covers {m[name][0]:.2%} of {who}, under {MIN_MATERIAL_SHARE:.0%}: cannot measure it")
+ o, p = ours[name][1], theirs[name][1]
+ assert o is not None and p is not None
+ lo, hi = material_band(p)
+ out[name] = {"ours": o, "promo": p, "lo": lo, "hi": hi, "ok": lo <= o <= hi}
+ return out
+
+
def simulate_cvd(img: Image.Image, kind: str) -> Image.Image:
a = np.asarray(img.convert("RGB"), dtype=np.float64) / 255.0
lin = np.where(a <= 0.04045, a / 12.92, ((a + 0.055) / 1.055) ** 2.4)
@@ -125,7 +208,7 @@ def main(argv: list[str], root: Path = ROOT, promos: dict[str, Path] = PROMOS) -
a = ap.parse_args(argv[1:])
log = a.log or root / "captures" / "visual" / "art-log.tsv"
log.parent.mkdir(parents=True, exist_ok=True)
- rows, uniform = 0, []
+ rows, uniform, unmeasurable, guard_fails = 0, [], [], []
branch, commit = source_identity(root)
for path in sorted(a.shots.rglob("*.png")):
if "-compare" in path.stem:
@@ -148,13 +231,42 @@ def main(argv: list[str], root: Path = ROOT, promos: dict[str, Path] = PROMOS) -
with log.open("a") as f:
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)
+ if pose == "diorama02":
+ # Only the WebGL ?shot (directly under <shots-dir>) is gated; the editor renders (editor/) are printed as
+ # information, since the WebGL player is what the owner sees.
+ rel, gated = path.relative_to(a.shots).as_posix(), path.parent == a.shots
+ tag = "" if gated else " (information only: editor render, not gated)"
+ print(f"MATERIAL {rel} whole-frame warmth (information only) {m['warmth']:.4f} vs promo {p['warmth']:.4f}")
+ try:
+ guard = material_guard(shot, promo, mask=MATERIAL_MASK)
+ except ValueError as e:
+ print(f"{'FAIL' if gated else 'NOTE'}: {path}: {e}")
+ if gated:
+ unmeasurable.append(path)
+ rows += 1
+ continue
+ for name, g in guard.items():
+ verdict = ('PASS' if g['ok'] else 'FAIL') if gated else ('in band' if g['ok'] else 'out of band')
+ print(f"MATERIAL {rel} {name} warmth {g['ours']:.4f} vs promo {g['promo']:.4f} band "
+ f"[{g['lo']:.4f}, {g['hi']:.4f}] {verdict}{tag}")
+ if gated and not g["ok"]:
+ guard_fails.append(f"GUARD FAIL: {name} {g['ours']:.4f} vs [{g['lo']:.4f}, {g['hi']:.4f}] in {path}")
+ ours, theirs = material_warmth(shot, MATERIAL_MASK), material_warmth(promo, MATERIAL_MASK)
+ for name in INFO_MATERIALS:
+ o, t = ours[name][1], theirs[name][1]
+ print(f"MATERIAL {rel} {name} warmth {'-' if o is None else f'{o:.4f}'} vs promo "
+ f"{'-' if t is None else f'{t:.4f}'} (information only: not like-for-like)")
rows += 1
+ for line in guard_fails:
+ print(line)
if uniform:
return 2
+ if unmeasurable:
+ return EXIT_UNMEASURABLE
if rows == 0:
print(f"no screenshot named after a pose ({', '.join(promos)}) under {a.shots}")
return 1
- return 0
+ return EXIT_GUARD_FAIL if guard_fails else 0
if __name__ == "__main__":
diff --git a/tools/tests/test_art_compare.py b/tools/tests/test_art_compare.py
index 9a16ee043..e15bb470e 100644
--- a/tools/tests/test_art_compare.py
+++ b/tools/tests/test_art_compare.py
@@ -1,3 +1,6 @@
+import os
+from pathlib import Path
+
import numpy as np
import pytest
from PIL import Image
@@ -148,3 +151,194 @@ def test_masked_art_log_rows_and_titles_are_labelled_so_they_are_not_mistaken_fo
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
+
+
+PATCH = {"sand": (219, 173, 129), "sea": (83, 116, 146), "wood": (60, 44, 31), "land": (150, 115, 80),
+ "green": (110, 140, 80), "neutral": (128, 128, 128)}
+
+
+def stripes(colours, size=(300, 200)):
+ """A frame of full-height vertical stripes, one per colour, equal widths."""
+ a = np.zeros((size[1], size[0], 3), dtype=np.uint8)
+ edges = np.linspace(0, size[0], len(colours) + 1).astype(int)
+ for c, x0, x1 in zip(colours, edges, edges[1:]):
+ a[:, x0:x1] = c
+ return Image.fromarray(a, "RGB")
+
+
+def test_the_material_classifier_labels_each_known_patch():
+ for name, rgb in PATCH.items():
+ labels = ac.classify(solid(rgb))
+ assert set(np.unique(labels)) == {ac.MATERIALS.index(name)}, name
+ edge = {(240, 238, 235): "neutral", # white salt and labels: chroma under NEUTRAL_SAT
+ (150, 120, 150): "land", # R == B is not sea; warm-or-level hue at mid luma
+ (120, 160, 170): "sea", # the Dead Sea's pale cyan is water
+ (70, 70, 63): "wood", # dark, barely warm (chroma 0.10) is still dark wood
+ (190, 150, 110): "sand"} # luma 0.6
+ for rgb, name in edge.items():
+ assert ac.MATERIALS[int(ac.classify(solid(rgb))[0, 0])] == name, (rgb, name)
+
+
+def test_the_wood_land_and_sand_luma_thresholds_are_pinned():
+ assert (ac.NEUTRAL_SAT, ac.WOOD_LUMA, ac.SAND_LUMA) == (0.08, 0.30, 0.55)
+ assert ac.GUARDED_MATERIALS == ("sand", "sea") and ac.INFO_MATERIALS == ("wood",) # wood is not like-for-like
+ assert (ac.MATERIAL_TOLERANCE, ac.MIN_MATERIAL_SHARE) == (0.2, 0.02)
+ assert ac.material_band(0.381) == pytest.approx((0.3048, 0.4572))
+ assert ac.material_band(-0.254) == pytest.approx((-0.3048, -0.2032))
+
+
+def test_material_warmth_gives_each_class_its_share_and_mean_warmth():
+ m = ac.material_warmth(stripes([PATCH["sea"], PATCH["sand"]]), mask=())
+ assert m["sea"][0] == pytest.approx(0.5) and m["sand"][0] == pytest.approx(0.5)
+ assert m["sand"][1] == pytest.approx((219 - 129) / 255) and m["sea"][1] == pytest.approx((83 - 146) / 255)
+ assert m["wood"] == (0.0, None)
+
+
+def test_a_warmer_sand_fails_the_sand_guard_although_the_whole_frame_warmth_is_unchanged():
+ promo = stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]])
+ assert all(r["ok"] for r in ac.material_guard(promo, promo).values())
+ # sand 20/255 warmer, wood 20/255 cooler: the same whole-frame warmth, so the old metric cannot tell them apart
+ shot = stripes([PATCH["sea"], (229, 173, 119), (50, 44, 41)])
+ assert ac.metrics(shot)["warmth"] == pytest.approx(ac.metrics(promo)["warmth"], abs=1e-6)
+ g = ac.material_guard(shot, promo)
+ assert set(g) == {"sand", "sea"} and not g["sand"]["ok"] and g["sea"]["ok"]
+ assert g["sand"]["ours"] > g["sand"]["hi"]
+
+
+def test_a_material_too_rare_in_either_image_raises_instead_of_passing():
+ full = stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]])
+ no_sea = stripes([PATCH["land"], PATCH["sand"], PATCH["wood"]])
+ with pytest.raises(ValueError, match="sea"):
+ ac.material_guard(no_sea, full)
+ with pytest.raises(ValueError, match="sea"):
+ ac.material_guard(full, no_sea)
+ a = np.asarray(full).copy(); a[:, :99] = PATCH["land"]; a[:, 99] = PATCH["sea"] # sea is 1 column of 300: 0.3%
+ with pytest.raises(ValueError, match="sea"):
+ ac.material_guard(Image.fromarray(a, "RGB"), full)
+
+
+def material_shots(tmp_path, sand=PATCH["sand"], sea=PATCH["sea"]):
+ promo = tmp_path / "promo.png"; stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]], (480, 270)).save(promo)
+ shots = tmp_path / "shots"; shots.mkdir()
+ stripes([sea, sand, PATCH["wood"]], (480, 270)).save(shots / "diorama02.png")
+ return ac.main(["art_compare.py", str(shots), "t", "--log", str(tmp_path / "art-log.tsv")], root=tmp_path,
+ promos={"gameplay03": promo, "diorama02": promo})
+
+
+def test_main_passes_when_every_gating_material_is_in_band(tmp_path, capsys):
+ assert material_shots(tmp_path) == 0
+ out = capsys.readouterr().out
+ assert "MATERIAL diorama02.png sand" in out and "PASS" in out and "GUARD FAIL" not in out
+ assert "whole-frame warmth (information only)" in out and "MATERIAL diorama02.png wood" in out and "information only" in out
+
+
+def test_a_material_guard_fail_exits_3_and_names_the_material_its_value_and_band(tmp_path, capsys):
+ assert material_shots(tmp_path, sand=(229, 173, 119)) == ac.EXIT_GUARD_FAIL == 3
+ fails = [l for l in capsys.readouterr().out.splitlines() if l.startswith("GUARD FAIL: ")]
+ assert len(fails) == 1 and fails[0].startswith("GUARD FAIL: sand 0.4314 vs [0.2824, 0.4235]")
+
+
+def test_a_gating_material_missing_from_the_capture_exits_4_not_3(tmp_path, capsys):
+ assert material_shots(tmp_path, sea=PATCH["land"]) == ac.EXIT_UNMEASURABLE == 4
+ assert "cannot measure" in capsys.readouterr().out
+
+
+STUB_UV = r"""#!/usr/bin/env bash
+# A stand-in for uv: Unity (through machine_lock) and the browser do nothing; web_check writes each pose's PNG;
+# art_compare writes a compare image, prints what STUB_ART_OUT holds and exits STUB_ART_EXIT.
+shift
+case "$1" in
+ tools/machine_lock.py) exit 0 ;;
+ tools/web_check.py) while [[ $# -gt 0 && "$1" != --shots ]]; do shift; done
+ for p in gameplay03 diorama02 hero06judea hero06negev; do echo x > "$2/$p.png"; done ;;
+ tools/art_compare.py) mkdir -p "$2/editor"; echo x > "$2/gameplay03-compare.png"; echo x > "$2/editor/a-compare.png"
+ printf '%b' "$STUB_ART_OUT"; exit "$STUB_ART_EXIT" ;;
+esac
+"""
+
+
+def run_checkpoint(tmp_path, art_exit, art_out=""):
+ """tools/art_checkpoint.sh in a scratch git repository holding only what it reads, with uv stubbed (no Unity)."""
+ import shutil
+ import subprocess
+ repo, tools = tmp_path / "repo", Path(__file__).resolve().parents[1]
+ for rel, text in {"unity/ProjectSettings/QualitySettings.asset": "q\n", "unity/Builds/Web-disabled/index.html": "x\n",
+ "sim/Statecraft.Sim.Tests/golden/manifest.txt": "hash1950 aa\nhash1952 bb\n"}.items():
+ (repo / rel).parent.mkdir(parents=True, exist_ok=True); (repo / rel).write_text(text)
+ (repo / "tools").mkdir(); shutil.copy(tools / "art_checkpoint.sh", repo / "tools")
+ (repo / "unity/Assets/Scripts/Map").mkdir(parents=True)
+ shutil.copy(tools.parent / "unity/Assets/Scripts/Map/PromoPose.cs", repo / "unity/Assets/Scripts/Map")
+ git = ["git", "-C", str(repo), "-c", "user.name=t", "-c", "[email protected]"]
+ subprocess.run(git + ["init", "-q"], check=True); subprocess.run(git + ["add", "-A"], check=True)
+ subprocess.run(git + ["commit", "-qm", "t"], check=True)
+ stub = tmp_path / "bin"; stub.mkdir(); (stub / "uv").write_text(STUB_UV); (stub / "uv").chmod(0o755)
+ env = {**os.environ, "PATH": f"{stub}:{os.environ['PATH']}", "UNITY": "/bin/true",
+ "STUB_ART_EXIT": str(art_exit), "STUB_ART_OUT": art_out}
+ return subprocess.run(["bash", "tools/art_checkpoint.sh", "--no-build", "cp"], cwd=repo, env=env, capture_output=True, text=True)
+
+
+def test_the_checkpoint_completes_then_lists_each_guard_fail_and_exits_3(tmp_path):
+ r = run_checkpoint(tmp_path, 3, "GUARD FAIL: sand 0.2948 vs [0.3049, 0.4574] in diorama02\nGUARD FAIL: sea -0.1729 vs [-0.3117, -0.2078] in diorama02\n")
+ assert r.returncode == 3, r.stderr
+ assert "ART CHECKPOINT cp:" in r.stdout
+ tail = r.stdout[r.stdout.index("ART CHECKPOINT cp:"):]
+ assert "GUARD FAIL: sand 0.2948 vs [0.3049, 0.4574] in diorama02" in tail and "GUARD FAIL: sea -0.1729" in tail
+
+
+def test_the_checkpoint_exits_3_even_without_a_guard_fail_line(tmp_path):
+ r = run_checkpoint(tmp_path, 3)
+ assert r.returncode == 3 and "ART CHECKPOINT cp:" in r.stdout, r.stderr
+
+
+def test_the_checkpoint_passes_and_stops_on_genuine_errors_as_before(tmp_path):
+ ok = run_checkpoint(tmp_path / "ok", 0)
+ assert ok.returncode == 0 and "ART CHECKPOINT cp:" in ok.stdout and "GUARD FAIL" not in ok.stdout
+ for code in (1, 2, 4): # no pose matched or a crash, a blank capture, a material too rare to measure
+ r = run_checkpoint(tmp_path / str(code), code)
+ assert r.returncode == code and "ART CHECKPOINT" not in r.stdout, code
+
+
+def test_the_material_mask_adds_the_minimap_and_the_bottom_plates_to_the_hud_mask():
+ """Their navy is B > R, so unmasked they read as sea (about 16% of main's diorama02 "sea")."""
+ assert ac.MATERIAL_MASK == ac.HUD_MASK + ((0.86, 0.62, 1.0, 1.0), (0.0, 0.92, 0.17, 1.0), (0.76, 0.94, 0.87, 1.0))
+ navy = np.asarray(stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]], (480, 270))).copy()
+ navy[int(0.62 * 270):, int(0.86 * 480):] = (14, 22, 38) # a minimap-like navy panel bottom right
+ with_ui = ac.material_warmth(Image.fromarray(navy, "RGB"))
+ plain = ac.material_warmth(stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]], (480, 270)))
+ assert with_ui["sea"] == plain["sea"]
+
+
+def test_a_cooler_sand_fails_the_sand_guard_below_its_band():
+ promo = stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]])
+ g = ac.material_guard(stripes([PATCH["sea"], (209, 173, 139), PATCH["wood"]]), promo) # 20/255 cooler
+ assert not g["sand"]["ok"] and g["sand"]["ours"] < g["sand"]["lo"] and g["sea"]["ok"]
+
+
+def test_only_the_webgl_shot_is_gated_and_every_material_line_names_its_file(tmp_path, capsys):
+ promo = tmp_path / "promo.png"; stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]], (480, 270)).save(promo)
+ shots = tmp_path / "shots"; (shots / "editor").mkdir(parents=True)
+ stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]], (480, 270)).save(shots / "diorama02.png")
+ stripes([PATCH["sea"], (229, 173, 119), PATCH["wood"]], (480, 270)).save(shots / "editor" / "PC-diorama02.png")
+ assert ac.main(["art_compare.py", str(shots), "t", "--log", str(tmp_path / "log.tsv")], root=tmp_path,
+ promos={"gameplay03": promo, "diorama02": promo}) == 0
+ out = capsys.readouterr().out
+ lines = [l for l in out.splitlines() if l.startswith("MATERIAL ")]
+ assert all(" diorama02.png " in l or " editor/PC-diorama02.png " in l for l in lines), lines
+ assert any(l.startswith("MATERIAL editor/PC-diorama02.png sand") and "information only" in l and "FAIL" not in l
+ for l in lines)
+ assert "GUARD FAIL" not in out
+
+
+def test_the_material_guard_and_main_leave_a_navy_minimap_out_of_the_sea(tmp_path, capsys):
+ """material_guard's default mask (and what main() passes) must be MATERIAL_MASK, not HUD_MASK."""
+ plain = stripes([PATCH["sea"], PATCH["sand"], PATCH["wood"]], (480, 270))
+ a = np.asarray(plain).copy(); a[int(0.62 * 270):, int(0.86 * 480):] = (14, 22, 38) # a navy minimap
+ with_ui = Image.fromarray(a, "RGB")
+ assert ac.material_guard(with_ui, plain)["sea"]["ours"] == ac.material_guard(plain, plain)["sea"]["ours"]
+ promo = tmp_path / "promo.png"; plain.save(promo)
+ for name, img in (("plain", plain), ("ui", with_ui)):
+ (tmp_path / name).mkdir(); img.save(tmp_path / name / "diorama02.png")
+ ac.main(["art_compare.py", str(tmp_path / name), "t", "--log", str(tmp_path / "log.tsv")], root=tmp_path,
+ promos={"gameplay03": promo, "diorama02": promo})
+ sea = [l.split(" vs ")[0] for l in capsys.readouterr().out.splitlines() if l.startswith("MATERIAL diorama02.png sea")]
+ assert len(sea) == 2 and sea[0] == sea[1], sea