diff --git a/.superpowers/sdd/S6-1-fov-zoom-hud/report.md b/.superpowers/sdd/S6-1-fov-zoom-hud/report.md index 460e88f..9d8d822 100644 --- a/.superpowers/sdd/S6-1-fov-zoom-hud/report.md +++ b/.superpowers/sdd/S6-1-fov-zoom-hud/report.md @@ -10,7 +10,7 @@ - Les cellules inconnues sont bleu-noir : `UNKNOWN_COLOR = (0.015, 0.025, 0.07)`, distinct des explorées. - `Camera2D.zoom = (2, 2)` dans `Game.tscn`. `Game.TILE_SIZE` et `MapRenderer.TILE_SIZE` restent tous deux à `Vector2i(32, 32)` ; les coordonnées métier et les chemins publics ne changent pas. - HUD réduit : stats et journal en coins, prompt inférieur centré, aide basse compacte. La zone centrale vérifiée (`Rect2(300, 120, 680, 480)`) n’est recouverte par aucun panneau ; l’occupation cumulée est plafonnée par test à 15 % du viewport 1280×720. -- `run-visual-check.sh` vérifie désormais aussi les pixels avec Pillow, en plus du format PNG, des dimensions et des erreurs Godot. +- `run-visual-check.sh` vérifie désormais aussi les pixels avec un lecteur PNG Python basé uniquement sur la bibliothèque standard (`struct`/`zlib`), sans Pillow ni dépendance externe. ## TDD @@ -45,7 +45,7 @@ git diff --check PASS ./scripts/verify.sh PASS — unit + E2E + visual ``` -Les avertissements GUT existants concernant des UID de ressources GUI sont émis par Godot mais aucun `SCRIPT ERROR`, `Parse Error` ou `ERROR:` n’est présent dans les vérifications applicatives ; les runners terminent avec succès. +Les runners échouent sur les diagnostics applicatifs Godot `SCRIPT ERROR`, `Parse Error` ou `ERROR:`. Les lignes `xkbcommon: ERROR` concernant Compose/keymap, émises par l’environnement Snap/Xvfb et attendues sur cette machine, sont documentées comme bruit backend et ne sont pas assimilées à une erreur applicative. Les runners terminent avec succès. ## Capture Xvfb et mesures automatisées @@ -62,14 +62,14 @@ visual-check.png: unknown_pixels=235256 unknown_luminance=0.002 explored_floor_pixels=4 - explored_tint_luminance=0.875 + detected_explored_luminance=0.815 visual-check-exit.png: dungeon_non_black_pixels=488160 unknown_pixels=86908 unknown_luminance=0.002 explored_floor_pixels=141108 - explored_tint_luminance=0.875 + detected_explored_luminance=0.661 ``` Le runner échoue si la zone de donjon est noire, si l’inconnu initial n’est pas bleu-noir, ou si l’overlay exploré mesuré dans la capture de sortie est absent / sous 0,55. diff --git a/README.md b/README.md index acec1b7..75ee4f3 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ GODOT_BIN=/snap/bin/godot4 ./scripts/verify.sh Each runner first executes `godot --headless --path . --import`. This generates the ignored `.godot` cache required for global script classes and imported assets, so the commands are reproducible from a newly checked-out worktree. Import failures stop the runner and retain Godot's error output. -`run-visual-check.sh` runs the actual project twice: `--capture` records the initial state at `artifacts/visual-check.png`, while `--capture-exit` records the reached-exit state at `artifacts/visual-check-exit.png`. Both must be valid **1280×720** PNGs, and output is logged to `artifacts/visual-check.log`. The runner also measures the dungeon viewport pixels with Pillow: an initial blue-black unknown region, a readable explored-tile overlay (luminance ≥ 0.55), and non-black dungeon pixels in both captures. It chooses `xvfb-run` with a 1280×720 screen when no display is available, enforces a timeout, and reports **unavailable** (rather than a false pass) when neither a display nor Xvfb exists. `verify.sh` runs unit tests and headless E2E before visual verification; unavailable visual verification is reported distinctly from a failed test or failed visual capture. +`run-visual-check.sh` runs the actual project twice: `--capture` records the initial state at `artifacts/visual-check.png`, while `--capture-exit` records the reached-exit state at `artifacts/visual-check-exit.png`. Both must be valid **1280×720** PNGs, and output is logged to `artifacts/visual-check.log`. The runner measures the dungeon viewport pixels with the Python standard library only (PNG parsing uses `struct`/`zlib`, with no Pillow or other external dependency): an initial blue-black unknown region, a readable explored-tile overlay (luminance ≥ 0.55), and non-black dungeon pixels in both captures. The explored luminance is calculated from the detected captured pixels, not from a pre-render tint constant. It chooses `xvfb-run` with a 1280×720 screen when no display is available, enforces a timeout, and reports **unavailable** (rather than a false pass) when neither a display nor Xvfb exists. Godot `SCRIPT ERROR` and `Parse Error` diagnostics fail the check; `xkbcommon: ERROR` Compose/keymap warnings from the Snap/Xvfb environment are expected backend noise and are not treated as application errors. `verify.sh` runs unit tests and headless E2E before visual verification; unavailable visual verification is reported distinctly from a failed test or failed visual capture. For a direct headless startup check: diff --git a/scripts/check-visual-capture.py b/scripts/check-visual-capture.py new file mode 100755 index 0000000..82afefb --- /dev/null +++ b/scripts/check-visual-capture.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Validate a visual-check PNG and measure the pixels used by its contract. + +This intentionally uses only Python's standard library. Godot writes 8-bit RGB(A) +PNG captures, so supporting those non-interlaced PNGs is sufficient and avoids +making the visual check depend on Pillow being installed. +""" +from __future__ import annotations + +import binascii +import struct +import sys +import zlib +from pathlib import Path + +WIDTH = 1280 +HEIGHT = 720 +VIEWPORT = (256, 40, 1024, 678) +UNKNOWN = (4, 6, 18) + + +def fail(message: str) -> "NoReturn": + raise SystemExit(message) + + +def read_png(path: Path) -> tuple[int, int, list[bytes]]: + try: + data = path.read_bytes() + except OSError as error: + fail(f"cannot read PNG: {error}") + if data[:8] != b"\x89PNG\r\n\x1a\n": + fail("invalid PNG signature") + + offset = 8 + header: tuple[int, int, int, int, int, int, int] | None = None + compressed = bytearray() + saw_iend = False + while offset < len(data): + if offset + 12 > len(data): + fail("truncated PNG chunk") + length = struct.unpack_from(">I", data, offset)[0] + chunk_end = offset + 12 + length + if chunk_end > len(data): + fail("truncated PNG chunk data") + kind = data[offset + 4 : offset + 8] + chunk = data[offset + 8 : offset + 8 + length] + expected_crc = struct.unpack_from(">I", data, offset + 8 + length)[0] + actual_crc = binascii.crc32(kind + chunk) & 0xFFFFFFFF + if actual_crc != expected_crc: + fail(f"invalid PNG CRC for {kind.decode('latin1')}") + offset = chunk_end + + if kind == b"IHDR": + if header is not None or len(chunk) != 13: + fail("invalid PNG IHDR") + header = struct.unpack(">IIBBBBB", chunk) + elif kind == b"IDAT": + compressed.extend(chunk) + elif kind == b"IEND": + if length != 0: + fail("invalid PNG IEND") + saw_iend = True + break + + if header is None or not saw_iend or offset != len(data): + fail("incomplete PNG") + width, height, depth, color_type, compression, filtering, interlace = header + if (width, height) != (WIDTH, HEIGHT): + fail(f"expected {WIDTH}x{HEIGHT} PNG, got {width}x{height}") + if depth != 8 or color_type not in (2, 6): + fail("visual capture must be an 8-bit RGB or RGBA PNG") + if (compression, filtering, interlace) != (0, 0, 0): + fail("visual capture uses unsupported PNG compression, filter, or interlace") + if not compressed: + fail("PNG has no image data") + return width, height, [bytes(compressed), bytes([color_type])] + + +def pixels(path: Path): + width, height, payload = read_png(path) + compressed, color_type = payload + channels = 3 if color_type[0] == 2 else 4 + try: + raw = zlib.decompress(compressed) + except zlib.error as error: + fail(f"invalid PNG image data: {error}") + stride = width * channels + expected = height * (stride + 1) + if len(raw) != expected: + fail(f"invalid PNG scanline data: expected {expected} bytes, got {len(raw)}") + + previous = bytearray(stride) + offset = 0 + for _ in range(height): + filter_type = raw[offset] + offset += 1 + row = bytearray(raw[offset : offset + stride]) + offset += stride + for index in range(stride): + left = row[index - channels] if index >= channels else 0 + above = previous[index] + upper_left = previous[index - channels] if index >= channels else 0 + if filter_type == 1: + row[index] = (row[index] + left) & 255 + elif filter_type == 2: + row[index] = (row[index] + above) & 255 + elif filter_type == 3: + row[index] = (row[index] + (left + above) // 2) & 255 + elif filter_type == 4: + estimate = left + above - upper_left + left_distance = abs(estimate - left) + above_distance = abs(estimate - above) + upper_left_distance = abs(estimate - upper_left) + predictor = ( + left + if left_distance <= above_distance and left_distance <= upper_left_distance + else above if above_distance <= upper_left_distance else upper_left + ) + row[index] = (row[index] + predictor) & 255 + elif filter_type != 0: + fail(f"unsupported PNG row filter {filter_type}") + previous = row + yield from ( + (row[index], row[index + 1], row[index + 2]) + for index in range(0, stride, channels) + ) + + +def linear(channel: int) -> float: + value = channel / 255.0 + return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4 + + +def luminance(rgb: tuple[int, int, int]) -> float: + red, green, blue = (linear(channel) for channel in rgb) + return 0.2126 * red + 0.7152 * green + 0.0722 * blue + + +def measure(path: Path) -> None: + observed = list(pixels(path)) + dungeon = ( + observed[y * WIDTH + x] + for y in range(VIEWPORT[1], VIEWPORT[3]) + for x in range(VIEWPORT[0], VIEWPORT[2]) + ) + dungeon_pixels = list(dungeon) + non_black = sum(pixel != (0, 0, 0) for pixel in dungeon_pixels) + unknown_pixels = [pixel for pixel in dungeon_pixels if pixel == UNKNOWN] + explored_pixels = [ + pixel + for pixel in dungeon_pixels + if pixel[0] >= 196 and pixel[1] >= 207 and pixel[2] >= 217 + ] + if non_black == 0: + fail("capture dungeon region is entirely black") + + unknown_luminance = ( + sum(luminance(pixel) for pixel in unknown_pixels) / len(unknown_pixels) + if unknown_pixels + else 1.0 + ) + if path.name == "visual-check.png": + if not unknown_pixels or UNKNOWN[2] <= UNKNOWN[0] or unknown_luminance >= 0.1: + fail("unknown fog is not distinguishable blue-black") + else: + if not explored_pixels: + fail("missing explored floor pixels in exit capture") + # Measure the RGB values that were actually detected, rather than the + # renderer's pre-modulation tint. This catches capture/readback regressions. + explored_luminances = [luminance(pixel) for pixel in explored_pixels] + explored_luminance = sum(explored_luminances) / len(explored_luminances) + if explored_luminance < 0.55: + fail(f"detected explored luminance {explored_luminance:.3f} is below 0.55") + explored_luminance = ( + sum(luminance(pixel) for pixel in explored_pixels) / len(explored_pixels) + if explored_pixels + else 0.0 + ) + print( + f"visual measurement: {path} " + f"dungeon_non_black_pixels={non_black} " + f"unknown_pixels={len(unknown_pixels)} unknown_luminance={unknown_luminance:.3f} " + f"explored_floor_pixels={len(explored_pixels)} " + f"detected_explored_luminance={explored_luminance:.3f}" + ) + + +if __name__ == "__main__": + if len(sys.argv) != 2: + fail(f"usage: {Path(sys.argv[0]).name} CAPTURE.png") + capture = Path(sys.argv[1]) + if not capture.is_file() or capture.stat().st_size == 0: + fail(f"missing or empty capture {capture}") + measure(capture) diff --git a/scripts/run-visual-check.sh b/scripts/run-visual-check.sh index bb4113f..5b6c53d 100755 --- a/scripts/run-visual-check.sh +++ b/scripts/run-visual-check.sh @@ -44,103 +44,23 @@ run_capture() { fi } -validate_capture() { - local capture_path="$1" - if [[ ! -s "$capture_path" ]]; then - echo "visual check failed: missing capture $capture_path" >&2 - exit 1 - fi - if ! python3 - "$capture_path" <<'PY' -import struct -import sys - -path = sys.argv[1] -with open(path, "rb") as capture: - signature = capture.read(8) - length = struct.unpack(">I", capture.read(4))[0] - kind = capture.read(4) - data = capture.read(length) -if signature != b"\x89PNG\r\n\x1a\n" or kind != b"IHDR" or len(data) != 13: - raise SystemExit("invalid PNG") -width, height = struct.unpack(">II", data[:8]) -if (width, height) != (1280, 720): - raise SystemExit(f"expected 1280x720 PNG, got {width}x{height}") -print(f"visual capture: {path} ({width}x{height})") -PY - then - echo "visual check failed: capture is not a nonempty valid PNG" >&2 - exit 1 - fi -} - run_capture "initial" "capture" run_capture "exit" "capture-exit" +# Godot's SCRIPT ERROR / Parse Error diagnostics are actionable application +# failures. Do not treat unrelated backend diagnostics (for example the +# expected xkbcommon Compose warnings emitted by some Snap/Xvfb setups) as an +# application failure. if grep -Eq 'SCRIPT ERROR|Parse Error|^ERROR:' "$log_path"; then - echo "visual check failed: Godot reported errors; see $log_path" >&2 + echo "visual check failed: Godot application error; see $log_path" >&2 exit 1 fi -validate_capture "$initial_capture_path" -validate_capture "$exit_capture_path" measure_capture() { local capture_path="$1" - python3 - "$capture_path" <<'PY' -from collections import Counter -from pathlib import Path -import sys - -from PIL import Image - -path = Path(sys.argv[1]) -image = Image.open(path).convert("RGB") -if image.size != (1280, 720): - raise SystemExit(f"expected 1280x720 PNG, got {image.size[0]}x{image.size[1]}") - -# This is the renderer's unfiltered unknown-fog color in the captured viewport. -unknown = (4, 6, 18) -counts = Counter(image.getdata()) -unknown_pixels = counts[unknown] -# Explored cells use a pale blue overlay. With alpha compositing their captured -# RGB components are all at least 196; count those pixels in the dungeon below. - -def linear(channel: int) -> float: - value = channel / 255.0 - return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4 - -def luminance(rgb: tuple[int, int, int]) -> float: - red, green, blue = (linear(channel) for channel in rgb) - return 0.2126 * red + 0.7152 * green + 0.0722 * blue - -# Both captures must expose a measurable dungeon region. The initial one also -# proves blue-black unknown fog and a lit explored floor. The expected -# luminance is computed from the renderer tint, before texture modulation. -dungeon = image.crop((256, 40, 1024, 678)) -dungeon_pixels = list(dungeon.getdata()) -non_black = sum(1 for pixel in dungeon_pixels if pixel != (0, 0, 0)) -explored_pixels = sum( - 1 for red, green, blue in dungeon_pixels - if red >= 196 and green >= 207 and blue >= 217 -) -if non_black == 0: - raise SystemExit("capture dungeon region is entirely black") -if path.name == "visual-check.png": - if unknown_pixels == 0 or unknown[2] <= unknown[0] or luminance(unknown) >= 0.1: - raise SystemExit("unknown fog is not distinguishable blue-black") -else: - if explored_pixels == 0: - raise SystemExit("missing explored floor pixels in exit capture") - explored_tint_luminance = luminance((230, 242, 255)) - if explored_tint_luminance < 0.55: - raise SystemExit(f"explored luminance {explored_tint_luminance:.3f} is below 0.55") - -print( - f"visual measurement: {path} " - f"dungeon_non_black_pixels={non_black} " - f"unknown_pixels={unknown_pixels} unknown_luminance={luminance(unknown):.3f} " - f"explored_floor_pixels={explored_pixels} explored_tint_luminance=" - f"{luminance((230, 242, 255)):.3f}" -) -PY + if ! python3 "$root_dir/scripts/check-visual-capture.py" "$capture_path"; then + echo "visual check failed: invalid or unreadable capture $capture_path" >&2 + exit 1 + fi } measure_capture "$initial_capture_path" diff --git a/tests/scripts/test_godot_import_runners.sh b/tests/scripts/test_godot_import_runners.sh index e1f8b29..88cc421 100755 --- a/tests/scripts/test_godot_import_runners.sh +++ b/tests/scripts/test_godot_import_runners.sh @@ -27,11 +27,20 @@ if [[ " $* " == *" --capture "* || " $* " == *" --capture-exit "* ]]; then import os import struct import sys +import zlib os.makedirs("artifacts", exist_ok=True) +width, height = 1280, 720 +color = (199, 207, 217) if sys.argv[1].endswith("-exit.png") else (4, 6, 18) +scanlines = b"".join(b"\x00" + bytes(color) * width for _ in range(height)) +def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) +png = b"\x89PNG\r\n\x1a\n" +png += chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) +png += chunk(b"IDAT", zlib.compress(scanlines)) +png += chunk(b"IEND", b"") with open(f"artifacts/{sys.argv[1]}", "wb") as capture: - capture.write(b"\x89PNG\r\n\x1a\n") - capture.write(struct.pack(">I4sII5B", 13, b"IHDR", 1280, 720, 8, 2, 0, 0, 0)) + capture.write(png) PY fi exit 0