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.

fix(visual): review minors: checkpoint restores settings on failure and never discards QualitySettings edits, art-log identity, a discarded warm-up pass

eyalgolan0b6058e28b45
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 4083cb15c..620648ad6 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -28,7 +28,11 @@ Plan: `docs/superpowers/plans/2026-10-11-statecraft-visual-v1.md`. Promo targets
or the profile waits.
- Screenshots: `tools/art_checkpoint.sh [--no-build] <name>` (WebGL `?shot` + editor renders of both tiers + side-by-side
images and their deuteranopia/protanopia copies under `captures/visual/<name>/`, git-ignored; rows in the main
- checkout's `captures/visual/art-log.tsv`).
+ checkout's `captures/visual/art-log.tsv` with the branch, short commit and the image's absolute path). It refuses to run
+ while `QualitySettings.asset` (and, when it builds, `unity/Assets/Settings` or `ProjectSettings.asset`) has unstaged
+ changes, restores them on every exit, and takes the pose list from `PromoPose.cs`. Each checkpoint switches the
+ worktree's build target WebGL -> OSXUniversal (editor renders) and back at the next build, a reimport each way: budget
+ a few minutes per checkpoint.
## Budgets (proposed; ratified in Task 10)
Measured on the development Mac (Apple silicon, integrated GPU), 1920x1080 at DPR 1, Chrome for Testing:
diff --git a/tools/README.md b/tools/README.md
index 697ce3cc6..9cc0badf7 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -34,7 +34,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q
```
-Expected: `142 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `143 passed, 1 skipped` (the skipped one is the headed browser check; add `--headed` and `--with websockets==15.0.1` to run it). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
diff --git a/tools/art_checkpoint.sh b/tools/art_checkpoint.sh
index 952ebab6e..d57de5a14 100755
--- a/tools/art_checkpoint.sh
+++ b/tools/art_checkpoint.sh
@@ -13,11 +13,17 @@ cd "$root"
main_root="$(cd "$(git rev-parse --path-format=absolute --git-common-dir)/.." && pwd)"
: "${UNITY:?set UNITY as in docs/dev-setup.md}"
shared() { uv run tools/machine_lock.py --shared -- "$@"; }
+# The build rewrites URP and player settings, and the editor capture may write QualitySettings' m_CurrentQuality; this
+# script restores them from the index, so it refuses to run while any of them has unstaged changes (review M4: never
+# discard an edit silently) and restores them on every exit, a failed build included (review M3).
+guarded=(unity/ProjectSettings/QualitySettings.asset)
+[[ $build == 1 ]] && guarded+=(unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset)
+if ! git diff --quiet -- "${guarded[@]}"; then
+ echo "art_checkpoint: stage your changes to ${guarded[*]} first (this script restores them from the index)" >&2
+ exit 2
+fi
+trap 'git checkout -- "${guarded[@]}"' EXIT
if [[ $build == 1 ]]; then
- if ! git diff --quiet -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset; then
- echo "art_checkpoint: stage your changes under unity/Assets/Settings and ProjectSettings.asset first (the build rewrites them and this script restores them from the index)" >&2
- exit 2
- fi
shared "$UNITY" -batchmode -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression disabled -logFile "$root/unity-build-web-art.log"
git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset
if grep -n "Shader error" "$root/unity-build-web-art.log"; then echo "art_checkpoint: shader errors in the WebGL build" >&2; exit 1; fi
@@ -25,12 +31,15 @@ fi
[[ -f unity/Builds/Web-disabled/index.html ]] || { echo "art_checkpoint: no build at unity/Builds/Web-disabled (run without --no-build)" >&2; exit 2; }
out="captures/visual/$name"
rm -rf "$out"; mkdir -p "$out"
-uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767" --expect "SHOT done" --shots "$out" \
+uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot" --expect "GOLDEN OK 1950 71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07" --expect "GOLDEN OK 1952 73590e324f19e9959a455a4da79e93d7089dfcf283c13aac02af6b0a624b9767" --expect "SHOT done" --shots "$out" --stall 180 \
--fail 'GOLDEN FAIL|SMOKE FAIL|BOOT FAIL|Statecraft/.*(not supported|Unsupported)|(not supported|Unsupported).*Statecraft/'
-for pose in gameplay03 diorama02; do
+# The poses come from PromoPose.All's source, so a new pose is checked without editing this script (review M3).
+poses=$(grep -o 'new PromoPose("[A-Za-z0-9_]*"' unity/Assets/Scripts/Map/PromoPose.cs | cut -d'"' -f2)
+[[ -n "$poses" ]] || { echo "art_checkpoint: no PromoPose found in PromoPose.cs" >&2; exit 1; }
+for pose in $poses; do
[[ -s "$out/$pose.png" ]] || { echo "art_checkpoint: $out/$pose.png is missing" >&2; exit 1; }
done
shared "$UNITY" -batchmode -quit -projectPath unity -buildTarget OSXUniversal -executeMethod MapCapture.Promo -captureDir "$root/$out/editor" -logFile "$root/unity-capture-promo.log"
-git checkout -- unity/ProjectSettings/QualitySettings.asset # SetQualityLevel may have written m_CurrentQuality
+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" --log "$main_root/captures/visual/art-log.tsv"
echo "ART CHECKPOINT $name: $(ls "$out"/*-compare*.png "$out"/editor/*-compare*.png | tr '\n' ' ')"
diff --git a/tools/art_compare.py b/tools/art_compare.py
index 0f7b05263..b555dfaed 100644
--- a/tools/art_compare.py
+++ b/tools/art_compare.py
@@ -9,11 +9,13 @@ Usage: uv run tools/art_compare.py <shots-dir> <checkpoint-name> [--log PATH]
For every PNG under <shots-dir> whose name ends in a pose (gameplay03, diorama02), writes <name>-compare.png beside it
(screenshot left, promo right, a caption with the numbers), <name>-compare-deuteranopia.png and
<name>-compare-protanopia.png (Machado, Oliveira and Fernandes 2009, severity 1), and appends a row to the art log
-(default captures/visual/art-log.tsv; art_checkpoint.sh points every worktree at the main checkout's): checkpoint, image,
-saturation, contrast (luma std), warmth (mean R - B), and the palette distance to the promo (total variation between
+(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
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
import sys
from pathlib import Path
@@ -31,6 +33,16 @@ MACHADO = {
}
+def source_identity(root: Path) -> tuple[str, str]:
+ """(branch, short commit) of the checkout at root, so rows in the shared art log say which worktree made them."""
+ def git(*args: str) -> str:
+ r = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True)
+ return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else "-"
+ if git("rev-parse", "--show-toplevel") == "-" or Path(git("rev-parse", "--show-toplevel")).resolve() != root.resolve():
+ return "-", "-"
+ return git("rev-parse", "--abbrev-ref", "HEAD"), git("rev-parse", "--short", "HEAD")
+
+
def metrics(img: Image.Image) -> dict[str, float]:
rgb = img.convert("RGB")
a = np.asarray(rgb, dtype=np.float32) / 255.0
@@ -75,6 +87,7 @@ def main(argv: list[str], root: Path = ROOT, promos: dict[str, Path] = PROMOS) -
log = a.log or root / "captures" / "visual" / "art-log.tsv"
log.parent.mkdir(parents=True, exist_ok=True)
rows, uniform = 0, []
+ branch, commit = source_identity(root)
for path in sorted(a.shots.rglob("*.png")):
if "-compare" in path.stem:
continue
@@ -94,7 +107,7 @@ def main(argv: list[str], root: Path = ROOT, promos: dict[str, Path] = PROMOS) -
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, str(path), f"{m['saturation']:.4f}", f"{m['contrast']:.4f}", f"{m['warmth']:.4f}", f"{d:.4f}"]) + "\n")
+ 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")
print("ART " + title)
rows += 1
if uniform:
diff --git a/tools/tests/test_art_compare.py b/tools/tests/test_art_compare.py
index be784b609..ebccea059 100644
--- a/tools/tests/test_art_compare.py
+++ b/tools/tests/test_art_compare.py
@@ -64,3 +64,20 @@ def test_a_uniform_screenshot_fails(tmp_path):
shots = tmp_path / "shots"; shots.mkdir()
solid((0, 0, 0), (192, 108)).save(shots / "gameplay03.png") # a black capture (the WebGL readback failed)
assert ac.main(["art_compare.py", str(shots), "t"], root=tmp_path, promos={"gameplay03": promo, "diorama02": promo}) == 2
+
+
+def test_art_log_rows_name_the_branch_the_commit_and_the_absolute_image(tmp_path):
+ """Review M5: the art log is shared by every worktree, so a row says which branch and commit made it and where its
+ image is (absolute path), not a worktree-relative path."""
+ 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"
+ 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 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
diff --git a/unity/Assets/Scripts/Map/FrameProfile.cs b/unity/Assets/Scripts/Map/FrameProfile.cs
index 5023bb2b2..f319c032b 100644
--- a/unity/Assets/Scripts/Map/FrameProfile.cs
+++ b/unity/Assets/Scripts/Map/FrameProfile.cs
@@ -12,7 +12,8 @@ namespace Statecraft.Game.Map
{
/// <summary>Prices each visual feature on the real player. At every promo pose it runs every configuration (everything on:
/// "all"; each toggle off alone: "-name"; everything off: "none") Repeats times, in a different interleaved order each
- /// repeat (Order), 300 frames after 60 warm-up frames each, and logs one line per run with the resolution and the URP
+ /// repeat (Order), 300 frames after 60 warm-up frames each (after one unmeasured 60-frame pass of every configuration
+ /// before the first pose), and logs one line per run with the resolution and the URP
/// render scale, then one summary line per configuration: the median of the run averages, their spread (max - min) and
/// the median p95. A feature costs median(all) - median(-name); it is over a budget only when that exceeds the budget
/// plus the larger spread (docs/visual-v1.md). Asked for by "vprofile" in the WebGL page URL (a whole query parameter)
@@ -63,9 +64,22 @@ namespace Statecraft.Game.Map
var configs = new List<(string label, string? off)> { ("all", null) };
foreach (var name in VisualToggles.Names) configs.Add(("-" + name, name));
configs.Add(("none", "*"));
+ bool first = true;
foreach (var pose in PromoPose.All)
{
pose.Apply(rig, frame);
+ if (first)
+ {
+ // One discarded pass of every configuration: the first measured runs after the load were noisier
+ // (spreads about half the median, review M6).
+ first = false;
+ foreach (var (_, off) in configs)
+ {
+ VisualToggles.SetAll(off != "*");
+ if (off != null && off != "*") VisualToggles.Set(off, false);
+ for (int f = 0; f < WarmupFrames; f++) yield return null;
+ }
+ }
var results = configs.ToDictionary(c => c.label, c => new List<(float avg, float p95)>());
for (int rep = 0; rep < Repeats; rep++)
foreach (var i in Order(configs.Count, rep))
diff --git a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
index 66f1f0d7e..1882285fa 100644
--- a/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
+++ b/unity/Assets/Tests/EditMode/VisualHarnessTests.cs
@@ -264,4 +264,27 @@ public class VisualHarnessTests
}
finally { Object.DestroyImmediate(shader); }
}
+
+ /// <summary>Review M6: the first pose's first runs were noisier (a cold start), so before the first pose every
+ /// configuration runs once for WarmupFrames, unmeasured; then each pose runs every configuration Repeats times.</summary>
+ [Test]
+ public void TheProfileStartsWithOneDiscardedPassOfEveryConfiguration()
+ {
+ var go = new GameObject("cam", typeof(Camera)); var rig = go.AddComponent<CameraRig>();
+ var frame = new GeoFrame(34.2, 35.9, 29.45, 33.35, 161529f, 431223f);
+ VisualToggles.Register("grade", _ => { });
+ var log = new List<string>();
+ int frames = 0;
+ try
+ {
+ var run = FrameProfile.Run(rig, frame, log.Add, false);
+ while (run.MoveNext()) frames++;
+ }
+ finally { Object.DestroyImmediate(go); }
+ int configs = 3; // all, -grade, none
+ int perRun = FrameProfile.WarmupFrames + FrameProfile.MeasuredFrames;
+ Assert.AreEqual(configs * FrameProfile.WarmupFrames + PromoPose.All.Count * FrameProfile.Repeats * configs * perRun, frames);
+ Assert.AreEqual(PromoPose.All.Count * FrameProfile.Repeats * configs, log.Count(l => l.StartsWith("PROFILE visual=")));
+ Assert.AreEqual("PROFILE visual done", log.Last());
+ }
}