The engine's settings registry now carries --compare's dimensions, each with its choices (names in order), the most strips and a suggested comparison (compare.registry(), in specs_json). The launcher parses it leniently (registry::CompareDim), checks a comparison against it and offers one per dimension (aa:off,fxaa,smaa,cas, scaler:off,bilinear,fsr,vsr, framegen:off,on, look:off,on) instead of guessing from setting keys (interp:true,false...). Tests on both sides: the registry's choices and suggestions parse in the engine, the old guesses do not; the real-registry Rust test asks the engine's own parser to accept every offer.
293 lines
13 KiB
Python
293 lines
13 KiB
Python
"""Compare settings live (framegen/compare.py) and anti-aliasing (framegen/aa.py), checked without a GPU or a window."""
|
|
import pathlib
|
|
import sys
|
|
|
|
import numpy as np
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
from framegen import aa, compare as C
|
|
from framegen.menu import Menu
|
|
from framegen.settings import BY_KEY, Settings
|
|
|
|
|
|
# ---- anti-aliasing ----------------------------------------------------------------------------------------------
|
|
def scene(ss: int) -> np.ndarray:
|
|
"""Slanted edges and a circle, drawn with `ss` x `ss` samples a pixel (1: aliased; 8: the reference)."""
|
|
H, W = 96, 128
|
|
y, x = np.mgrid[0:H * ss, 0:W * ss] / ss
|
|
m = (((y - 24) > 0.23 * (x - 8)) & ((x - 64) ** 2 + (y - 48) ** 2 < 36 ** 2)) | (np.abs((y - 16) - 1.7 * (x - 96)) < 5)
|
|
img = np.where(m[..., None], [40, 60, 220], [230, 220, 200]).astype(np.float32)
|
|
return img.reshape(H, ss, W, ss, 3).mean((1, 3)).astype(np.uint8)
|
|
|
|
|
|
ALIASED, TRUTH = scene(1), scene(8)
|
|
EDGES = np.abs(ALIASED.astype(int) - TRUTH).max(-1) > 8
|
|
|
|
|
|
def edge_error(img) -> float:
|
|
return float(np.abs(img.astype(float) - TRUTH)[EDGES].mean())
|
|
|
|
|
|
def test_off_is_the_frame_itself():
|
|
assert aa.apply(ALIASED, "off") is ALIASED
|
|
|
|
|
|
@pytest.mark.parametrize("mode", ["fxaa", "smaa"])
|
|
def test_aa_brings_edges_closer_to_a_supersampled_picture(mode):
|
|
out = aa.apply(ALIASED, mode)
|
|
assert out.dtype == np.uint8 and out.shape == ALIASED.shape
|
|
assert edge_error(out) < 0.8 * edge_error(ALIASED)
|
|
|
|
|
|
@pytest.mark.parametrize("mode", ["fxaa", "smaa", "cas"])
|
|
def test_flat_areas_stay_as_they_are(mode):
|
|
flat = np.full((40, 50, 3), (90, 120, 30), np.uint8)
|
|
assert np.array_equal(aa.apply(flat, mode), flat)
|
|
|
|
|
|
def test_cas_sharpens():
|
|
soft = np.zeros((32, 32, 3), np.uint8)
|
|
soft[:, 16:] = 200
|
|
soft[:, 15] = 100 # a soft step
|
|
out = aa.apply(soft, "cas").astype(int)
|
|
assert out[0, 14, 0] < 1 and out[0, 16, 0] > 200 or abs(out[0, 15, 0] - 100) > 5
|
|
|
|
|
|
def test_numpy_and_torch_give_the_same_picture():
|
|
torch = pytest.importorskip("torch")
|
|
for mode in aa.MODES[1:]:
|
|
a = aa.apply(ALIASED, mode)
|
|
b = aa.apply(torch.from_numpy(ALIASED.copy()), mode)
|
|
assert torch.is_tensor(b) and b.dtype == torch.uint8
|
|
assert np.abs(b.numpy().astype(int) - a).max() <= 1, mode
|
|
|
|
|
|
def test_the_setting():
|
|
s = BY_KEY["aa"]
|
|
assert s.group == "Upscaling" and s.default == "off" and s.choices == aa.MODES
|
|
m = Menu(Settings())
|
|
assert "aa" in [r.key for r in m.tab_rows("Upscaling")]
|
|
|
|
|
|
# ---- --compare and the settings ---------------------------------------------------------------------------------
|
|
def test_parse():
|
|
assert C.parse("aa:off,fxaa,smaa,cas") == ("aa", ["off", "fxaa", "smaa", "cas"])
|
|
assert C.parse("upscaler:Off, FSR") == ("scaler", ["off", "fsr"])
|
|
assert C.parse("fg") == ("framegen", ["off", "on"])
|
|
for bad in ("colour:off,on", "aa:off,dlss", "aa:off", "look:off,on,off"):
|
|
with pytest.raises(ValueError):
|
|
C.parse(bad)
|
|
|
|
|
|
def test_compare_settings():
|
|
st = Settings()
|
|
assert st.compare is False and not BY_KEY["compare"].saved # off at the start of each session
|
|
for k, v in C.settings_for("scaler:off,fsr-high,vsr").items():
|
|
st.override(k, v)
|
|
assert (st.compare_dim, st.compare_strips, st.compare_scaler_3) == ("scaler", 3, "vsr")
|
|
m = Menu(st)
|
|
keys = [r.key for r in m.tab_rows("Compare")]
|
|
assert ["compare_scaler_1", "compare_scaler_2", "compare_scaler_3"] == [k for k in keys if k.startswith("compare_scaler")]
|
|
assert "compare_aa_1" not in keys # only the dimension being compared
|
|
assert {"compare", "compare_dim", "compare_strips", "compare_layout", "compare_labels", "compare_timings",
|
|
"compare_clips"} <= set(keys)
|
|
|
|
|
|
def test_compare_settings_are_saved_but_compare_itself_is_not(tmp_path):
|
|
p = tmp_path / "s.json"
|
|
st = Settings(path=p)
|
|
st.set("compare", True)
|
|
st.set("compare_dim", "look")
|
|
st.set("compare_layout", "rows")
|
|
st2 = Settings.load(p)
|
|
assert st2.compare is False and st2.compare_dim == "look" and st2.compare_layout == "rows"
|
|
|
|
|
|
# ---- what can run -----------------------------------------------------------------------------------------------
|
|
def test_unavailable_variants_say_why_and_are_never_replaced():
|
|
caps = C.Caps(scalers=("off", "bilinear", "fsr"), scaler_why={"vsr": "NVIDIA's SDK isn't installed"})
|
|
p = C.plan(C.settings_for("scaler:off,fsr,vsr"), caps)
|
|
assert [s.variant for s in p.strips] == ["off", "fsr", "vsr"]
|
|
assert p.strips[2].why == "NVIDIA's SDK isn't installed" and p.strips[1].why is None
|
|
texts = C.labels(p, C.Timings())
|
|
assert texts[2] == ("RTX VSR", "Unavailable: NVIDIA's SDK isn't installed")
|
|
|
|
|
|
def test_frame_generation_availability():
|
|
caps = C.Caps(model="4.22.lite", multiplier=4)
|
|
assert C.why_not("framegen", "2x", caps) is None and C.why_not("framegen", "4x", caps) is None
|
|
assert "3x" not in (C.why_not("framegen", "3x", caps) or "3x") # (says why, about the 4x running)
|
|
assert C.why_not("framegen", "3x", caps)
|
|
assert "One AI model runs at a time" in C.why_not("framegen", "vfg", caps)
|
|
assert C.why_not("framegen", "rife", caps) is None
|
|
assert C.why_not("framegen", "on", C.Caps(interp=False))
|
|
assert C.why_not("framegen", "off", C.Caps(interp=False)) is None
|
|
assert C.variant_name("framegen", "on", caps) == "4x RIFE 4.22.lite"
|
|
|
|
|
|
def test_compare_is_off_until_asked():
|
|
assert C.plan(Settings().values(), C.Caps()) is None
|
|
|
|
|
|
def test_look_compares_two_at_most():
|
|
v = dict(C.settings_for("look:off,on"), compare_strips=4)
|
|
assert C.plan(v, C.Caps(look="Film")).n == 2
|
|
assert C.plan(v, C.Caps(look="Film")).strips[1].name == "Film"
|
|
|
|
|
|
# ---- geometry ---------------------------------------------------------------------------------------------------
|
|
def test_columns_cover_the_picture_once():
|
|
r = C.rects("columns", 4, 1920, 1080)
|
|
assert [d for d, _ in r] == [s for _, s in r] # each strip its own part of the scene
|
|
assert r[0][0][0] == 0 and r[-1][0][2] == 1920 and all(r[i][0][2] == r[i + 1][0][0] for i in range(3))
|
|
assert C.dividers("columns", 4, 1920, 1080) == [(480, 0, 480, 1080), (960, 0, 960, 1080), (1440, 0, 1440, 1080)]
|
|
|
|
|
|
def test_two_strips_split_where_dragged():
|
|
assert C.rects("columns", 2, 1000, 500, 0.3)[0][0] == (0, 0, 300, 500)
|
|
assert C.rects("rows", 2, 1000, 500, 0.3)[1][0] == (0, 150, 1000, 500)
|
|
assert C.drag_split("columns", 2000, 0, 1000, 500) == 0.95 # never off the picture
|
|
p = C.Plan("aa", (C.Strip("off", "Off"), C.Strip("fxaa", "FXAA")), split=0.3)
|
|
assert C.near_divider(p, 305, 200, 1000, 500, 8) and not C.near_divider(p, 340, 200, 1000, 500, 8)
|
|
|
|
|
|
def test_grid_shows_the_same_crop_in_each_cell():
|
|
r = C.rects("grid", 4, 1920, 1080)
|
|
assert len({s for _, s in r}) == 1 and r[0][1] == (480, 270, 1440, 810)
|
|
assert [d for d, _ in r][3] == (960, 540, 1920, 1080)
|
|
|
|
|
|
def test_compose_numpy_and_torch():
|
|
a, b = np.zeros((4, 8, 3), np.uint8), np.full((4, 8, 3), 9, np.uint8)
|
|
out = C.compose([a, b], C.rects("columns", 2, 8, 4))
|
|
assert out[:, :4].max() == 0 and out[:, 4:].min() == 9
|
|
out = C.compose([a, None], C.rects("columns", 2, 8, 4)) # unavailable: black
|
|
assert out.max() == 0
|
|
torch = pytest.importorskip("torch")
|
|
t = C.compose([torch.from_numpy(a), torch.from_numpy(b)], C.rects("rows", 2, 8, 4))
|
|
assert int(t[:2].max()) == 0 and int(t[2:].min()) == 9
|
|
|
|
|
|
# ---- timings and labels -----------------------------------------------------------------------------------------
|
|
def test_timings_are_average_and_worst_of_the_last_120():
|
|
t = C.Timings()
|
|
for v in [100.0] + [0.4] * 119 + [0.44]: # the 100 has fallen out of the window
|
|
t.add("aa:fxaa", v)
|
|
avg, worst = t.stat("aa:fxaa")
|
|
assert worst == 0.44 and abs(avg - 0.4003) < 1e-3
|
|
assert t.text("aa:fxaa") == "0.40 / 0.44 ms" and t.text("aa:smaa") == ""
|
|
|
|
|
|
def test_labels():
|
|
t = C.Timings()
|
|
t.add("aa:fxaa", 0.4)
|
|
p = C.plan(C.settings_for("aa:off,fxaa"), C.Caps())
|
|
assert C.labels(p, t) == [("Off", ""), ("FXAA", "0.40 / 0.40 ms")]
|
|
p2 = C.plan(dict(C.settings_for("aa:off,fxaa"), compare_timings=False), C.Caps())
|
|
assert C.labels(p2, t)[1] == ("FXAA", "")
|
|
caps = C.Caps(multiplier=4)
|
|
t.add("framegen:ai", 3.0)
|
|
p = C.plan(C.settings_for("fg:off,2x,on"), caps)
|
|
texts = C.labels(p, t, {"game": 30.0, "shown": 120.0}, caps)
|
|
assert texts[0] == ("Off", "30 fps") and texts[1][1].startswith("60 fps") and texts[2][1].startswith("120 fps")
|
|
assert "AI 3.00 / 3.00 ms" in texts[2][1]
|
|
|
|
|
|
# ---- frame generation strips ------------------------------------------------------------------------------------
|
|
def test_off_strip_holds_the_games_frames_while_on_moves():
|
|
caps = C.Caps(multiplier=4)
|
|
p = C.plan(C.settings_for("fg:off,2x,on"), caps)
|
|
fg = C.FrameGenStrips()
|
|
shown = []
|
|
for k in range(8): # a 4x run: a real frame, then three generated ones
|
|
frame = np.full((6, 12, 3), k, np.uint8)
|
|
if k % 4 == 0:
|
|
fg.real(frame)
|
|
out = fg.present(frame, p, 4, 12, 6)
|
|
shown.append((int(out[0, 0, 0]), int(out[0, 5, 0]), int(out[0, 11, 0])))
|
|
assert [s[0] for s in shown] == [0, 0, 0, 0, 4, 4, 4, 4] # Off: the game's own frames, held
|
|
assert [s[1] for s in shown] == [0, 0, 2, 2, 4, 4, 6, 6] # 2x: every 2nd frame
|
|
assert [s[2] for s in shown] == list(range(8)) # On: every frame
|
|
|
|
|
|
def test_aa_strips_time_each_variant():
|
|
t = C.Timings()
|
|
p = C.plan(C.settings_for("aa:off,fxaa,smaa"), C.Caps())
|
|
out = C.aa_strips(ALIASED, p, t)
|
|
assert out.shape == ALIASED.shape and t.stat("aa:fxaa") and t.stat("aa:smaa") and not t.stat("aa:off")
|
|
w = ALIASED.shape[1]
|
|
assert np.array_equal(out[:, : w // 3], ALIASED[:, : w // 3]) # the Off strip is the frame
|
|
|
|
|
|
# ---- labels and dividers as images ------------------------------------------------------------------------------
|
|
def test_overlay_items_are_drawn_inside_the_picture():
|
|
p = C.plan(C.settings_for("scaler:off,bilinear,fsr,vsr"), C.Caps(scalers=("off", "bilinear", "fsr")))
|
|
t = C.Timings()
|
|
items = C.overlay_items(p, C.labels(p, t), 1280, 720, 0.67)
|
|
assert len(items) == 3 + 4 # three dividers, four labels
|
|
for x, y, img in items:
|
|
assert img.shape[2] == 4 and x >= -2 and y >= 0 and x + img.shape[1] <= 1282 and y + img.shape[0] <= 720
|
|
img = C.blend(np.zeros((720, 1280, 3), np.uint8), items)
|
|
assert img[:, 320].mean() > 100 # a divider
|
|
p2 = C.Plan(p.dim, p.strips, labels=False)
|
|
assert len(C.overlay_items(p2, C.labels(p2, t), 1280, 720)) == 3
|
|
|
|
|
|
# ---- the pipeline's side while playing (Live) -------------------------------------------------------------------
|
|
def test_live_applies_the_aa_setting_and_keeps_clips_clean():
|
|
st = Settings()
|
|
live = C.Live(st, lambda: C.Caps(multiplier=2))
|
|
assert live.source_side(ALIASED, live.plan(), ALIASED, 2) is ALIASED # Off: the frame itself
|
|
st.override("aa", "fxaa")
|
|
shown = live.source_side(ALIASED, live.plan(), ALIASED, 2)
|
|
assert not np.array_equal(shown, ALIASED)
|
|
assert live.clip_frame(ALIASED, shown, live.plan()) is ALIASED # clips: the game's frame as it came
|
|
|
|
|
|
def test_live_compare_strips_and_burned_in_clips():
|
|
st = Settings()
|
|
for k, v in C.settings_for("aa:off,smaa").items():
|
|
st.override(k, v)
|
|
live = C.Live(st, lambda: C.Caps())
|
|
p = live.plan()
|
|
shown = live.source_side(ALIASED, p, ALIASED, 2)
|
|
w = ALIASED.shape[1]
|
|
assert np.array_equal(shown[:, : w // 2], ALIASED[:, : w // 2]) and not np.array_equal(shown, ALIASED)
|
|
assert live.clip_frame(ALIASED, shown, p) is ALIASED # not burned in unless asked
|
|
st.override("compare_clips", True)
|
|
clip = live.clip_frame(ALIASED, shown, p)
|
|
assert clip.shape == ALIASED.shape and clip[:, w // 2].mean() > 200 # the divider is in it
|
|
st.override("compare", False)
|
|
assert live.plan() is None
|
|
|
|
|
|
def test_live_multiplier():
|
|
st = Settings()
|
|
live = C.Live(st)
|
|
st.override("hz", 120)
|
|
assert live.multiplier() == 4
|
|
live.game60 = True
|
|
assert live.multiplier() == 2
|
|
st.override("interp", False)
|
|
assert live.multiplier() == 1
|
|
|
|
|
|
def test_the_registry_tells_the_launcher_what_compare_takes():
|
|
"""The launcher builds --compare only from this (framegen.settings prints it): every choice it lists and every
|
|
suggestion parses, and nothing else from the launcher's old guesses (interp:true,false, fg:60,90,120) does."""
|
|
import json
|
|
from framegen.settings import specs_json
|
|
reg = json.loads(json.dumps(specs_json()))["compare"]
|
|
assert [d["key"] for d in reg["dimensions"]] == list(C.DIMENSIONS)
|
|
for d in reg["dimensions"]:
|
|
values = [c["value"] for c in d["choices"]]
|
|
assert values == list(C.VARIANTS[d["key"]]) and all(c["name"] for c in d["choices"])
|
|
assert 2 <= len(d["suggested"]) <= d["max"] and set(d["suggested"]) <= set(values)
|
|
spec = f"{d['key']}:{','.join(d['suggested'])}"
|
|
assert C.parse(spec) == (d["key"], d["suggested"])
|
|
assert C.settings_for(spec)["compare_dim"] == d["key"]
|
|
for guess in ("interp:true,false", "fg:60,90,120", "scaler:off,rtx-vsr"):
|
|
with pytest.raises(ValueError):
|
|
C.parse(guess)
|