Files
DungeonCrawlerWorld/scripts/check-visual-capture.py
T

195 lines
7.2 KiB
Python
Executable File

#!/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)