Files

236 lines
9.2 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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
REFERENCE_WIDTH = 1920
REFERENCE_HEIGHT = 1080
EXPECTED_DIMENSIONS = {
"visual-check.png": (REFERENCE_WIDTH, REFERENCE_HEIGHT),
"visual-check-exit.png": (REFERENCE_WIDTH, REFERENCE_HEIGHT),
"visual-check-compact.png": (1280, 720),
}
# The unmasked PlayAreaFrame in the reference 1920×1080 artboard.
# This is scaled for the real 720p capture.
PLAY_AREA_REFERENCE = (498, 125, 1422, 955)
UNKNOWN = (1, 2, 5)
# Captured explored tiles are texture modulated, so classify their blue-black
# pixels by palette range rather than expecting one flat overlay color.
EXPLORED_MAX_LUMINANCE = 0.35
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
expected_dimensions = EXPECTED_DIMENSIONS.get(path.name)
if expected_dimensions is None:
fail(f"unsupported visual capture name: {path.name}")
if (width, height) != expected_dimensions:
fail(
f"expected {expected_dimensions[0]}x{expected_dimensions[1]} PNG, "
f"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 is_visible(pixel: tuple[int, int, int]) -> bool:
# Visible terrain can be either the neutral wall texture or the brown floor
# texture. The authored surface begins in a large open room, so a capture is
# not required to include a wall inside the central measurement crop.
neutral_wall = max(pixel) - min(pixel) <= 3 and max(pixel) >= 112
unmodulated_floor = pixel in {
(23, 4, 0), (23, 7, 0), (10, 10, 0), (30, 13, 0),
(4, 4, 0), (41, 23, 1), (30, 9, 0), (66, 36, 6),
}
return neutral_wall or unmodulated_floor
def is_explored(pixel: tuple[int, int, int]) -> bool:
# Texture-preserving explored terrain is rendered under a blue-black fog
# overlay. GPU blend rounding and the authored floor texture produce a
# palette rather than one portable exact RGB value; accept only its dark,
# blue-shifted range so HUD chrome and visible brown terrain cannot match.
red, green, blue = pixel
return 4 <= red <= 14 and 7 <= green <= 22 and 16 <= blue <= 32 and blue >= green + 4 and green >= red + 3
def viewport_for(width: int, height: int) -> tuple[int, int, int, int]:
scale_x = width / REFERENCE_WIDTH
scale_y = height / REFERENCE_HEIGHT
return tuple(round(coordinate * (scale_x if index % 2 == 0 else scale_y)) for index, coordinate in enumerate(PLAY_AREA_REFERENCE))
def measure(path: Path) -> None:
width, height = EXPECTED_DIMENSIONS[path.name]
observed = list(pixels(path))
viewport = viewport_for(width, height)
dungeon_pixels = [
observed[y * width + x]
for y in range(viewport[1], viewport[3])
for x in range(viewport[0], viewport[2])
]
non_black = sum(pixel != (0, 0, 0) for pixel in dungeon_pixels)
unknown_pixels = [pixel for pixel in dungeon_pixels if pixel == UNKNOWN]
visible_pixels = [pixel for pixel in dungeon_pixels if is_visible(pixel)]
explored_pixels = [pixel for pixel in dungeon_pixels if is_explored(pixel)]
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
)
explored_luminance = (
sum(luminance(pixel) for pixel in explored_pixels) / len(explored_pixels)
if explored_pixels
else 1.0
)
if not unknown_pixels or UNKNOWN != (1, 2, 5) or unknown_luminance >= explored_luminance:
fail("missing or incorrectly ordered unknown black-blue fog pixels")
if not visible_pixels:
fail("missing unmodulated visible terrain pixels")
if path.name == "visual-check-exit.png":
if not explored_pixels:
fail("missing texture-preserving explored terrain pixels in exit capture")
if explored_luminance > EXPLORED_MAX_LUMINANCE:
fail(
f"detected explored luminance {explored_luminance:.3f} exceeds "
f"{EXPLORED_MAX_LUMINANCE:.2f}"
)
print(
f"visual measurement: {path} "
f"dungeon_non_black_pixels={non_black} "
f"visible_pixels={len(visible_pixels)} "
f"explored_pixels={len(explored_pixels)} explored_luminance={explored_luminance:.3f} "
f"unknown_pixels={len(unknown_pixels)} unknown_luminance={unknown_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)