Engine: anti-aliasing (FXAA, SMAA-style, CAS) and the logic of a live settings comparison
framegen/aa.py: three clean-room filters on the game's frame, one implementation for torch (the GPU path) and numpy (the CPU fallback). framegen/compare.py: what can be compared, which variants can run here and why not, strip layouts and dividers, timings and labels, composing strips, the frame generation strips and the labels as ui_draw images. The aa setting and the Compare rows in settings.py; tests without a GPU or a window.
This commit is contained in:
1 parent
7b3c42aa6d
commit
e605987e77
4 files changed
+1057
-3
No files matched your search
@@ -0,0 +1,290 @@
|
||||
"""Anti-aliasing and sharpening of the game's picture (settings "aa"), at the game's own size, before the upscaler.
|
||||
|
||||
Three clean-room filters, written for Summit from the published ideas (no code from the reference implementations):
|
||||
|
||||
- "fxaa": FXAA-style. Per pixel: the local luma contrast decides whether it is on an edge; the edge's direction
|
||||
(horizontal or vertical) and its side come from luma differences; a short search along the edge finds how far its
|
||||
ends are, and the pixel is blended towards its neighbour across the edge by how near it is to an end (plus a
|
||||
sub-pixel term for single-pixel detail).
|
||||
- "smaa": SMAA/MLAA-style morphological AA. Luma edges between pixels (with SMAA's local contrast adaptation), each
|
||||
run of edge pixels measured to its ends, the ends' shapes read from the crossing edges (L, Z and U shapes), and each
|
||||
pixel blended with its neighbour by the area under the line that joins the ends. Not Jimenez' SMAA: no lookup
|
||||
textures, no diagonal or corner passes.
|
||||
- "cas": contrast-adaptive sharpening (the idea of AMD's CAS): a sharpening kernel whose strength falls where the
|
||||
neighbourhood is already near black or white, so edges don't ring. Not anti-aliasing, offered next to it because
|
||||
it is the usual partner of a softening AA.
|
||||
|
||||
One implementation for both paths: frames on the GPU (torch tensors, what the live pipeline has) and numpy arrays
|
||||
(the CPU fallback: tests, stills, devtools/compare_shot.py). The few array operations that differ are in _Ops.
|
||||
Frames are HxWx3 uint8, BGR (as everywhere in the engine); the result has the same type, device and shape.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
MODES = ("off", "fxaa", "smaa", "cas")
|
||||
NAMES = {"off": "Off", "fxaa": "FXAA", "smaa": "SMAA-style", "cas": "CAS sharpen"}
|
||||
|
||||
# FXAA's thresholds (the "quality" preset's usual values)
|
||||
FXAA_EDGE = 0.125 # local contrast needed, as a share of the brightest of the five pixels
|
||||
FXAA_EDGE_MIN = 0.0312 # ... and at least this much (dark areas)
|
||||
FXAA_SUBPIX = 0.75 # how much single-pixel detail is softened
|
||||
FXAA_STEPS = (1, 2, 3, 4, 6, 8, 12) # how far the search along an edge looks, in pixels
|
||||
FXAA_GUESS = 16.0 # an edge's end not found: taken to be this far
|
||||
SMAA_THRESHOLD = 0.1 # luma step that counts as an edge
|
||||
SMAA_ADAPT = 2.0 # an edge must be at least 1/this of its strongest neighbouring edge (local contrast adaptation)
|
||||
CAS_SHARPNESS = 0.5 # 0..1
|
||||
|
||||
|
||||
def is_tensor(x) -> bool:
|
||||
return type(x).__module__.startswith("torch")
|
||||
|
||||
|
||||
class _Ops:
|
||||
"""numpy or torch, whichever the frame is: the handful of calls that are spelled differently."""
|
||||
|
||||
def __init__(self, like) -> None:
|
||||
self.t = is_tensor(like)
|
||||
if self.t:
|
||||
import torch
|
||||
self.torch, self.dev = torch, like.device
|
||||
self._idx: dict = {}
|
||||
|
||||
def f32(self, a):
|
||||
return a.float() / 255.0 if self.t else a.astype(np.float32) / 255.0
|
||||
|
||||
def u8(self, a, like):
|
||||
if self.t:
|
||||
return (a.clamp(0.0, 1.0) * 255.0 + 0.5).to(self.torch.uint8)
|
||||
return (np.clip(a, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)
|
||||
|
||||
def arange(self, n: int):
|
||||
return self.torch.arange(n, device=self.dev) if self.t else np.arange(n)
|
||||
|
||||
def index(self, n: int, d: int):
|
||||
"""Indices 0..n-1 moved by d, held at the ends (the edge pixel repeats)."""
|
||||
k = (n, d)
|
||||
if k not in self._idx:
|
||||
i = np.clip(np.arange(n) + d, 0, n - 1)
|
||||
self._idx[k] = self.torch.as_tensor(i, device=self.dev) if self.t else i
|
||||
return self._idx[k]
|
||||
|
||||
def sh(self, a, dy: int, dx: int):
|
||||
"""a sampled at (y + dy, x + dx), held at the borders."""
|
||||
if dy:
|
||||
a = a[self.index(a.shape[0], dy)]
|
||||
if dx:
|
||||
a = a[:, self.index(a.shape[1], dx)]
|
||||
return a
|
||||
|
||||
def where(self, c, a, b):
|
||||
return self.torch.where(c, a, b) if self.t else np.where(c, a, b)
|
||||
|
||||
def maximum(self, a, b):
|
||||
if self.t:
|
||||
return self.torch.maximum(a, b) if is_tensor(b) else a.clamp(min=b)
|
||||
return np.maximum(a, b)
|
||||
|
||||
def minimum(self, a, b):
|
||||
if self.t:
|
||||
return self.torch.minimum(a, b) if is_tensor(b) else a.clamp(max=b)
|
||||
return np.minimum(a, b)
|
||||
|
||||
def clip(self, a, lo: float, hi: float):
|
||||
return a.clamp(lo, hi) if self.t else np.clip(a, lo, hi)
|
||||
|
||||
def sqrt(self, a):
|
||||
return a.sqrt() if self.t else np.sqrt(a)
|
||||
|
||||
def cummax(self, a, axis: int):
|
||||
return self.torch.cummax(a, dim=axis).values if self.t else np.maximum.accumulate(a, axis=axis)
|
||||
|
||||
def flip(self, a, axis: int):
|
||||
return self.torch.flip(a, dims=(axis,)) if self.t else np.flip(a, axis=axis)
|
||||
|
||||
def take(self, a, idx, axis: int):
|
||||
return self.torch.gather(a, axis, idx) if self.t else np.take_along_axis(a, idx, axis=axis)
|
||||
|
||||
def fl(self, a):
|
||||
"""a as float32."""
|
||||
return a.float() if self.t else a.astype(np.float32)
|
||||
|
||||
def zeros_like(self, a):
|
||||
return self.torch.zeros_like(a) if self.t else np.zeros_like(a)
|
||||
|
||||
def full_like(self, a, v):
|
||||
return self.torch.full_like(a, v) if self.t else np.full_like(a, v)
|
||||
|
||||
def T(self, a):
|
||||
return a.transpose(0, 1) if self.t else a.T
|
||||
|
||||
def broadcast_x(self, a):
|
||||
"""Column indices, the shape of the 2-D array a."""
|
||||
x = self.arange(a.shape[1])
|
||||
return x.expand(a.shape[0], -1) if self.t else np.broadcast_to(x, a.shape)
|
||||
|
||||
|
||||
def _luma(c):
|
||||
"""c: HxWx3 float BGR."""
|
||||
return 0.114 * c[..., 0] + 0.587 * c[..., 1] + 0.299 * c[..., 2]
|
||||
|
||||
|
||||
def _lerp(o: _Ops, a, b, t):
|
||||
"""a + (b - a) * t, t per pixel."""
|
||||
return a + (b - a) * t[..., None]
|
||||
|
||||
|
||||
# ---- FXAA-style -------------------------------------------------------------------------------------------------
|
||||
def _fxaa(o: _Ops, c):
|
||||
L = _luma(c)
|
||||
N, S, W, E = o.sh(L, -1, 0), o.sh(L, 1, 0), o.sh(L, 0, -1), o.sh(L, 0, 1)
|
||||
NW, NE, SW, SE = o.sh(L, -1, -1), o.sh(L, -1, 1), o.sh(L, 1, -1), o.sh(L, 1, 1)
|
||||
mx = o.maximum(o.maximum(o.maximum(N, S), o.maximum(W, E)), L)
|
||||
mn = o.minimum(o.minimum(o.minimum(N, S), o.minimum(W, E)), L)
|
||||
rng = mx - mn
|
||||
active = rng >= o.maximum(mx * FXAA_EDGE, FXAA_EDGE_MIN)
|
||||
# sub-pixel: how far the pixel stands out from its 3x3 neighbourhood
|
||||
avg = (2.0 * (N + S + W + E) + NW + NE + SW + SE) / 12.0
|
||||
sub = o.clip(abs(avg - L) / o.maximum(rng, 1e-6), 0.0, 1.0)
|
||||
sub = (-2.0 * sub + 3.0) * sub * sub
|
||||
sub = sub * sub * FXAA_SUBPIX
|
||||
# direction: a horizontal edge has luma changing from row to row
|
||||
horz = abs(N + S - 2.0 * L) * 2.0 + abs(NE + SE - 2.0 * E) + abs(NW + SW - 2.0 * W)
|
||||
vert = abs(W + E - 2.0 * L) * 2.0 + abs(NW + NE - 2.0 * N) + abs(SW + SE - 2.0 * S)
|
||||
is_h = horz >= vert
|
||||
l1, l2 = o.where(is_h, N, W), o.where(is_h, S, E) # the two neighbours across the edge
|
||||
g1, g2 = abs(l1 - L), abs(l2 - L)
|
||||
first = g1 >= g2 # the edge is on the side of l1 (up, or left)
|
||||
nb = o.where(first, l1, l2)
|
||||
grad = o.maximum(g1, g2) * 0.25
|
||||
local = 0.5 * (L + nb)
|
||||
# luma halfway between the pixel's row (column) and its neighbour's, the line the search follows
|
||||
half = (0.5 * (L + N), 0.5 * (L + S), 0.5 * (L + W), 0.5 * (L + E))
|
||||
|
||||
def along(k: int):
|
||||
"""The half-way luma k pixels along the edge (for horizontal edges: x + k; vertical: y + k)."""
|
||||
hu, hd = o.sh(half[0], 0, k), o.sh(half[1], 0, k)
|
||||
vl, vr = o.sh(half[2], k, 0), o.sh(half[3], k, 0)
|
||||
return o.where(is_h, o.where(first, hu, hd), o.where(first, vl, vr))
|
||||
|
||||
ends = []
|
||||
for sign in (-1, 1):
|
||||
dist = o.full_like(L, FXAA_GUESS)
|
||||
delta = along(sign * FXAA_STEPS[-1]) - local
|
||||
found = o.zeros_like(L) > 1.0 # all False
|
||||
for k in FXAA_STEPS:
|
||||
d = along(sign * k) - local
|
||||
hit = (abs(d) >= grad) & ~found
|
||||
dist = o.where(hit, o.full_like(L, float(k)), dist)
|
||||
delta = o.where(hit, d, delta)
|
||||
found = found | hit
|
||||
ends.append((dist, delta))
|
||||
(dn, en), (dp, ep) = ends
|
||||
nearer_n = dn < dp
|
||||
d_min = o.minimum(dn, dp)
|
||||
end_delta = o.where(nearer_n, en, ep)
|
||||
good = (end_delta < 0) != ((L - local) < 0)
|
||||
off = o.where(good, 0.5 - d_min / (dn + dp), o.zeros_like(L))
|
||||
t = o.where(active, o.maximum(off, sub), o.zeros_like(L))
|
||||
cn = o.where(is_h[..., None], o.where(first[..., None], o.sh(c, -1, 0), o.sh(c, 1, 0)),
|
||||
o.where(first[..., None], o.sh(c, 0, -1), o.sh(c, 0, 1)))
|
||||
return _lerp(o, c, cn, t)
|
||||
|
||||
|
||||
# ---- SMAA/MLAA-style --------------------------------------------------------------------------------------------
|
||||
def _edges(o: _Ops, L):
|
||||
"""(left, top): whether there is an edge on the left (top) side of each pixel, after local contrast adaptation."""
|
||||
dl = abs(L - o.sh(L, 0, -1))
|
||||
dt = abs(L - o.sh(L, -1, 0))
|
||||
left = dl > SMAA_THRESHOLD
|
||||
top = dt > SMAA_THRESHOLD
|
||||
# an edge much weaker than one beside it is left alone (stops blurring next to strong edges)
|
||||
near_l = o.maximum(o.maximum(o.sh(dl, 0, -1), o.sh(dl, 0, 1)),
|
||||
o.maximum(o.maximum(dt, o.sh(dt, 1, 0)), o.maximum(o.sh(dt, 0, -1), o.sh(dt, 1, -1))))
|
||||
near_t = o.maximum(o.maximum(o.sh(dt, -1, 0), o.sh(dt, 1, 0)),
|
||||
o.maximum(o.maximum(dl, o.sh(dl, 0, 1)), o.maximum(o.sh(dl, -1, 0), o.sh(dl, -1, 1))))
|
||||
left = left & (dl * SMAA_ADAPT >= near_l)
|
||||
top = top & (dt * SMAA_ADAPT >= near_t)
|
||||
left = left & (o.broadcast_x(L) > 0) # nothing left of the first column, above the first row
|
||||
top = top & (o.T(o.broadcast_x(o.T(L))) > 0)
|
||||
return left, top
|
||||
|
||||
|
||||
def _line_weights(o: _Ops, line, cross):
|
||||
"""Edges that run along x: line[y, x] = an edge between rows y-1 and y at column x; cross[y, x] = an edge between
|
||||
columns x-1 and x in row y. Returns (up, down): how much pixel (y-1, x) takes of (y, x), and (y, x) of (y-1, x)."""
|
||||
H, W = line.shape
|
||||
x = o.broadcast_x(line)
|
||||
# how many edge pixels run on to the left and to the right of each one
|
||||
last_gap = o.cummax(o.where(line, o.full_like(x, -1), x), 1)
|
||||
dl = x - last_gap - 1
|
||||
xf = o.broadcast_x(line)
|
||||
last_gap_r = o.cummax(o.where(o.flip(line, 1), o.full_like(xf, -1), xf), 1)
|
||||
dr = o.flip(xf - last_gap_r - 1, 1)
|
||||
xl = o.clip(x - dl, 0, W - 1) # first pixel of the run (non-edge pixels: anything; masked out below)
|
||||
xr1 = o.clip(x + dr + 1, 0, W - 1) # just past the last one (held at the border)
|
||||
past_end = (x + dr + 1) >= W
|
||||
up_row, low_row = o.sh(cross, -1, 0), cross # the rows above and below the line
|
||||
ul, dl_ = o.take(up_row, xl, 1), o.take(low_row, xl, 1)
|
||||
ur, dr_ = o.take(up_row, xr1, 1) & ~past_end, o.take(low_row, xr1, 1) & ~past_end
|
||||
zero = o.fl(o.zeros_like(x))
|
||||
half = zero + 0.5
|
||||
hl = o.where(ul & ~dl_, half, o.where(dl_ & ~ul, -half, zero))
|
||||
hr = o.where(ur & ~dr_, half, o.where(dr_ & ~ur, -half, zero))
|
||||
n, p = o.fl(dl + dr + 1), o.fl(dl)
|
||||
mid = n * 0.5
|
||||
# the line from height hl at the run's start to 0 at its middle, then to hr at its end: its area over [p, p+1]
|
||||
a, b = p, o.minimum(p + 1.0, mid)
|
||||
left = o.where(b > a, hl * ((b - a) - (b * b - a * a) / (2.0 * mid)), zero)
|
||||
a, b = o.maximum(p, mid), p + 1.0
|
||||
right = o.where(b > a, hr * (((b * b - a * a) * 0.5 - mid * (b - a)) / mid), zero)
|
||||
up = o.where(line, o.maximum(left, 0.0) + o.maximum(right, 0.0), zero)
|
||||
down = o.where(line, -(o.minimum(left, 0.0) + o.minimum(right, 0.0)), zero)
|
||||
return up, down
|
||||
|
||||
|
||||
def _smaa(o: _Ops, c):
|
||||
L = _luma(c)
|
||||
left, top = _edges(o, L)
|
||||
up, down = _line_weights(o, top, left) # horizontal edges
|
||||
lft, rgt = _line_weights(o, o.T(left), o.T(top)) # vertical edges, as rows of the transposed picture
|
||||
lft, rgt = o.T(lft), o.T(rgt)
|
||||
# what each pixel takes from each neighbour
|
||||
w_t = down # its top edge: from the pixel above
|
||||
w_b = o.sh(up, 1, 0) * o.fl(o.T(o.broadcast_x(o.T(L))) < L.shape[0] - 1) # its bottom edge (the top of the one below)
|
||||
w_l = rgt # its left edge
|
||||
w_r = o.sh(lft, 0, 1) * o.fl(o.broadcast_x(L) < L.shape[1] - 1)
|
||||
total = w_t + w_b + w_l + w_r
|
||||
scale = o.where(total > 1.0, 1.0 / o.maximum(total, 1e-6), total * 0.0 + 1.0)
|
||||
w_t, w_b, w_l, w_r, total = w_t * scale, w_b * scale, w_l * scale, w_r * scale, total * scale
|
||||
out = c * (1.0 - total)[..., None]
|
||||
out = out + o.sh(c, -1, 0) * w_t[..., None] + o.sh(c, 1, 0) * w_b[..., None]
|
||||
out = out + o.sh(c, 0, -1) * w_l[..., None] + o.sh(c, 0, 1) * w_r[..., None]
|
||||
return out
|
||||
|
||||
|
||||
# ---- CAS-style sharpening ---------------------------------------------------------------------------------------
|
||||
def _cas(o: _Ops, c, sharpness: float = CAS_SHARPNESS):
|
||||
N, S, W, E = o.sh(c, -1, 0), o.sh(c, 1, 0), o.sh(c, 0, -1), o.sh(c, 0, 1)
|
||||
mn = o.minimum(o.minimum(o.minimum(N, S), o.minimum(W, E)), c)
|
||||
mx = o.maximum(o.maximum(o.maximum(N, S), o.maximum(W, E)), c)
|
||||
amp = o.sqrt(o.clip(o.minimum(mn, 1.0 - mx) / o.maximum(mx, 1e-6), 0.0, 1.0))
|
||||
peak = -1.0 / (8.0 - 3.0 * float(sharpness)) # 1/8 (gentle) .. 1/5 (strong)
|
||||
w = amp * peak
|
||||
return o.clip((c + w * (N + S + W + E)) / (1.0 + 4.0 * w), 0.0, 1.0)
|
||||
|
||||
|
||||
_FILTERS = {"fxaa": _fxaa, "smaa": _smaa, "cas": _cas}
|
||||
|
||||
|
||||
def apply(frame, mode: str):
|
||||
"""The frame with the filter applied ("off": the frame itself, untouched). frame: HxWx3 uint8 BGR, numpy or a
|
||||
torch tensor (any device); the result is the same kind."""
|
||||
if mode == "off" or mode not in _FILTERS:
|
||||
return frame
|
||||
o = _Ops(frame)
|
||||
if o.t:
|
||||
import torch
|
||||
with torch.no_grad():
|
||||
return o.u8(_FILTERS[mode](o, o.f32(frame)), frame)
|
||||
return o.u8(_FILTERS[mode](o, o.f32(frame)), frame)
|
||||
@@ -0,0 +1,476 @@
|
||||
"""Compare settings live ("part-screen rendering"): one picture cut into 2 to 4 strips, each strip drawn with a
|
||||
different choice of one setting, with its name and its measured cost on it, in step (the same game frame in every
|
||||
strip). The C key (or the Compare tab of the overlay) turns it on; Shift+C goes to the next thing to compare.
|
||||
|
||||
What can be compared (a "dimension") and its choices ("variants"):
|
||||
|
||||
- "aa", Anti-aliasing: Off, FXAA, SMAA-style, CAS sharpening (framegen/aa.py). Drawn at the game's size, before the
|
||||
upscaler, by the pipeline (Composer), like the setting itself.
|
||||
- "scaler", Upscaler: Off, Bilinear, AMD FSR 1 (at your sharpening, or at each of its levels), NVIDIA RTX VSR. Drawn
|
||||
by the video window (framegen/io.py), each variant on the whole picture, then its strip cut out.
|
||||
- "framegen", Frame generation: Off (the game's own frames, each held until the next) against On (your multiplier and
|
||||
model), or a smaller multiplier shown from the same run (every 2nd frame of a 4x run is a real 2x). Two AI models
|
||||
can't run at once: the one not running is shown as unavailable, with why.
|
||||
- "look", Look: Off against the look picked in the settings (framegen/looks.py), drawn by the video window.
|
||||
|
||||
A variant that can't run here (RTX VSR without NVIDIA's SDK, a model that isn't the one running) gets a black strip
|
||||
with its name and why: never another variant in its place.
|
||||
|
||||
This file holds the logic, without a GPU or a window: the choices and their names, what is available (why_not), the
|
||||
layouts and where the dividers go (rects, dividers), the label text and the timings (Timings), putting strips together
|
||||
(compose, for numpy and torch alike), the frame generation strips (FrameGenStrips) and the labels and dividers as
|
||||
images (overlay_items, drawn with framegen/ui_draw.py). The settings rows are in framegen/settings.py ("Compare").
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
DIMENSIONS = ("aa", "scaler", "framegen", "look")
|
||||
DIM_NAMES = {"aa": "Anti-aliasing", "scaler": "Upscaler", "framegen": "Frame generation", "look": "Look"}
|
||||
DIM_ALIASES = {"aa": "aa", "antialiasing": "aa", "anti-aliasing": "aa", "scaler": "scaler", "upscaler": "scaler",
|
||||
"upscaling": "scaler", "framegen": "framegen", "fg": "framegen", "frame-generation": "framegen",
|
||||
"interp": "framegen", "look": "look", "looks": "look"}
|
||||
|
||||
FSR_LEVELS = {"fsr-max": 0.0, "fsr-high": 0.25, "fsr-medium": 0.5, "fsr-low": 1.0, "fsr-minimal": 2.0}
|
||||
VARIANTS: dict[str, tuple[str, ...]] = {
|
||||
"aa": ("off", "fxaa", "smaa", "cas"),
|
||||
"scaler": ("off", "bilinear", "fsr", *FSR_LEVELS, "vsr"),
|
||||
"framegen": ("off", "on", "2x", "3x", "4x", "rife", "vfg"),
|
||||
"look": ("off", "on"),
|
||||
}
|
||||
NAMES: dict[str, dict[str, str]] = {
|
||||
"aa": {"off": "Off", "fxaa": "FXAA", "smaa": "SMAA-style", "cas": "CAS sharpen"},
|
||||
"scaler": {"off": "Off", "bilinear": "Bilinear", "fsr": "FSR 1", "fsr-max": "FSR 1 Max", "fsr-high": "FSR 1 High",
|
||||
"fsr-medium": "FSR 1 Medium", "fsr-low": "FSR 1 Low", "fsr-minimal": "FSR 1 Minimal",
|
||||
"vsr": "RTX VSR"},
|
||||
"framegen": {"off": "Off", "on": "On", "2x": "2x", "3x": "3x", "4x": "4x", "rife": "RIFE", "vfg": "NVIDIA VFG"},
|
||||
"look": {"off": "Off", "on": "Look"},
|
||||
}
|
||||
# the strips' choices before the player picks any (strip 1, 2, 3, 4)
|
||||
DEFAULTS = {"aa": ("off", "fxaa", "smaa", "cas"), "scaler": ("off", "bilinear", "fsr", "vsr"),
|
||||
"framegen": ("off", "on", "2x", "4x"), "look": ("off", "on", "off", "on")}
|
||||
MAX_STRIPS = {"aa": 4, "scaler": 4, "framegen": 4, "look": 2} # more would only repeat (Look: off and on)
|
||||
LAYOUTS = ("columns", "rows", "grid")
|
||||
LAYOUT_NAMES = {"columns": "Side by side", "rows": "Stacked", "grid": "2x2, same crop"}
|
||||
SOURCE_SIDE = ("aa", "framegen") # put together at the game's size by the pipeline; the others by the window
|
||||
WINDOW = 120 # frames the timings are taken over
|
||||
MODEL_NAMES = {"vfg": "NVIDIA VFG"} # others: RIFE <version>
|
||||
|
||||
|
||||
def strip_key(dim: str, i: int) -> str:
|
||||
"""The setting that holds strip i's choice (1-based) for this dimension."""
|
||||
return f"compare_{dim}_{i}"
|
||||
|
||||
|
||||
def parse(spec: str) -> tuple[str, list[str]]:
|
||||
"""--compare "<dimension>:<v1>,<v2>,...": ("aa", ["off", "fxaa"]). The dimension alone takes its defaults."""
|
||||
dim_s, _, rest = spec.strip().partition(":")
|
||||
dim = DIM_ALIASES.get(dim_s.strip().lower())
|
||||
if dim is None:
|
||||
raise ValueError(f"--compare: {dim_s!r} isn't something to compare: one of {', '.join(DIMENSIONS)}")
|
||||
picks = [v.strip().lower() for v in rest.split(",") if v.strip()] if rest.strip() else list(DEFAULTS[dim][:2])
|
||||
picks = ["off" if p == "none" else p for p in picks]
|
||||
bad = [p for p in picks if p not in VARIANTS[dim]]
|
||||
if bad:
|
||||
raise ValueError(f"--compare: {', '.join(bad)} isn't a choice for {DIM_NAMES[dim]}: "
|
||||
f"{', '.join(VARIANTS[dim])}")
|
||||
if not 2 <= len(picks) <= MAX_STRIPS[dim]:
|
||||
raise ValueError(f"--compare: {DIM_NAMES[dim]} takes 2 to {MAX_STRIPS[dim]} choices, not {len(picks)}")
|
||||
return dim, picks
|
||||
|
||||
|
||||
def settings_for(spec: str) -> dict:
|
||||
"""The settings --compare sets: Compare on, the dimension, the number of strips and each strip's choice."""
|
||||
dim, picks = parse(spec)
|
||||
out = {"compare": True, "compare_dim": dim, "compare_strips": len(picks)}
|
||||
out.update({strip_key(dim, i + 1): v for i, v in enumerate(picks)})
|
||||
return out
|
||||
|
||||
|
||||
# ---- what can run here -------------------------------------------------------------------------------------------
|
||||
@dataclass
|
||||
class Caps:
|
||||
"""What this machine and session can draw, for why_not. scalers: the upscalers the window has ("off", "bilinear",
|
||||
"fsr", "vsr"); scaler_why: why one isn't there. interp: frame generation on; model: the one running ("4.22.lite",
|
||||
"vfg"); multiplier: frames shown per game frame (2 = 2x); look: the look's name ("" = none can be drawn) and
|
||||
look_why. window: the upscaler and look comparisons need the video window (or devtools/compare_shot.py's GL)."""
|
||||
scalers: tuple = ("off", "bilinear", "fsr", "vsr")
|
||||
scaler_why: dict = field(default_factory=dict)
|
||||
interp: bool = True
|
||||
interp_why: str = ""
|
||||
model: str = "4.22.lite"
|
||||
models: tuple = ("4.22.lite", "vfg")
|
||||
multiplier: int = 2
|
||||
look: str = "Look"
|
||||
look_why: str = ""
|
||||
window: bool = True
|
||||
|
||||
|
||||
def model_name(model: str) -> str:
|
||||
return MODEL_NAMES.get(model, f"RIFE {model}")
|
||||
|
||||
|
||||
def multiplier_of(variant: str) -> int | None:
|
||||
return int(variant[:-1]) if variant.endswith("x") and variant[:-1].isdigit() else None
|
||||
|
||||
|
||||
def why_not(dim: str, variant: str, caps: Caps) -> str | None:
|
||||
"""Why this variant can't be shown here, or None when it can."""
|
||||
if dim in ("scaler", "look") and not caps.window:
|
||||
return "Needs the video window's OpenGL"
|
||||
if dim == "scaler":
|
||||
mode = "fsr" if variant in FSR_LEVELS else variant
|
||||
if mode not in caps.scalers:
|
||||
return caps.scaler_why.get(mode) or f"{NAMES['scaler'][variant]} isn't available here"
|
||||
return None
|
||||
if dim == "look":
|
||||
if variant == "on" and not caps.look:
|
||||
return caps.look_why or "No look can be drawn here"
|
||||
return None
|
||||
if dim == "framegen":
|
||||
if variant == "off":
|
||||
return None
|
||||
if not caps.interp:
|
||||
return caps.interp_why or "Frame generation is off: turn it on to compare"
|
||||
if variant in ("rife", "vfg"):
|
||||
running = "vfg" if caps.model == "vfg" else "rife"
|
||||
if variant != running:
|
||||
if variant == "vfg" and "vfg" not in caps.models:
|
||||
return "NVIDIA VFG isn't set up on this PC"
|
||||
return (f"One AI model runs at a time: this is {model_name(caps.model)}. "
|
||||
f"Pick {NAMES['framegen'][variant]} in Interpolation model to see it")
|
||||
return None
|
||||
m = multiplier_of(variant)
|
||||
if m is not None:
|
||||
if m > caps.multiplier:
|
||||
return f"Above the {caps.multiplier}x running now: raise the Frame multiplier to see it"
|
||||
if caps.multiplier % m:
|
||||
return f"Not a part of the {caps.multiplier}x running now (try {caps.multiplier}x or a divisor of it)"
|
||||
return None
|
||||
return None # aa: runs anywhere (GPU or the CPU fallback)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Strip:
|
||||
variant: str
|
||||
name: str
|
||||
why: str | None = None # unavailable: why
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Plan:
|
||||
dim: str
|
||||
strips: tuple[Strip, ...]
|
||||
layout: str = "columns"
|
||||
split: float = 0.5 # where the divider is, with 2 strips (0..1 across, or down)
|
||||
labels: bool = True
|
||||
timings: bool = True
|
||||
|
||||
@property
|
||||
def n(self) -> int:
|
||||
return len(self.strips)
|
||||
|
||||
|
||||
def plan(values: dict, caps: Caps, split: float = 0.5) -> Plan | None:
|
||||
"""The comparison the settings ask for (None: Compare is off)."""
|
||||
if not values.get("compare"):
|
||||
return None
|
||||
dim = values.get("compare_dim", "aa")
|
||||
if dim not in DIMENSIONS:
|
||||
dim = "aa"
|
||||
n = max(2, min(int(values.get("compare_strips", 2)), MAX_STRIPS[dim]))
|
||||
strips = []
|
||||
for i in range(n):
|
||||
v = values.get(strip_key(dim, i + 1), DEFAULTS[dim][i])
|
||||
if v not in VARIANTS[dim]:
|
||||
v = DEFAULTS[dim][i]
|
||||
strips.append(Strip(v, variant_name(dim, v, caps), why_not(dim, v, caps)))
|
||||
return Plan(dim, tuple(strips), values.get("compare_layout", "columns"), split,
|
||||
bool(values.get("compare_labels", True)), bool(values.get("compare_timings", True)))
|
||||
|
||||
|
||||
def variant_name(dim: str, variant: str, caps: Caps | None = None) -> str:
|
||||
"""The strip's title: "FXAA", "FSR 1 High", "2x", "On (3x RIFE 4.22.lite)"."""
|
||||
if dim == "framegen" and caps is not None and variant == "on":
|
||||
return f"{caps.multiplier}x {model_name(caps.model)}"
|
||||
if dim == "look" and caps is not None and variant == "on" and caps.look:
|
||||
return caps.look
|
||||
return NAMES[dim].get(variant, variant)
|
||||
|
||||
|
||||
# ---- where the strips go -----------------------------------------------------------------------------------------
|
||||
Rect = tuple[int, int, int, int] # x0, y0, x1, y1 in the picture's pixels, y down, x1/y1 not included
|
||||
|
||||
|
||||
def _cuts(n: int, size: int, split: float) -> list[int]:
|
||||
if n == 2:
|
||||
at = round(size * min(0.95, max(0.05, split)))
|
||||
return [0, at, size]
|
||||
return [round(size * i / n) for i in range(n + 1)]
|
||||
|
||||
|
||||
def rects(layout: str, n: int, w: int, h: int, split: float = 0.5) -> list[tuple[Rect, Rect]]:
|
||||
"""For each strip: (where it goes in the picture, which part of its variant's picture it shows). Side by side and
|
||||
stacked strips show their own part of the scene (the same place on screen); the grid shows the same crop of the
|
||||
picture's middle in each cell, pixel for pixel, for a close look."""
|
||||
if layout == "rows":
|
||||
ys = _cuts(n, h, split)
|
||||
return [((0, ys[i], w, ys[i + 1]),) * 2 for i in range(n)]
|
||||
if layout == "grid":
|
||||
if n == 2:
|
||||
cells = [(0, 0, w // 2, h), (w // 2, 0, w, h)]
|
||||
else:
|
||||
cells = [(0, 0, w // 2, h // 2), (w // 2, 0, w, h // 2), (0, h // 2, w // 2, h), (w // 2, h // 2, w, h)]
|
||||
out = []
|
||||
for x0, y0, x1, y1 in cells[:n]:
|
||||
cw, ch = x1 - x0, y1 - y0
|
||||
sx, sy = (w - cw) // 2, (h - ch) // 2
|
||||
out.append(((x0, y0, x1, y1), (sx, sy, sx + cw, sy + ch)))
|
||||
return out
|
||||
xs = _cuts(n, w, split)
|
||||
return [((xs[i], 0, xs[i + 1], h),) * 2 for i in range(n)]
|
||||
|
||||
|
||||
def dividers(layout: str, n: int, w: int, h: int, split: float = 0.5) -> list[Rect]:
|
||||
"""The lines between the strips, as (x0, y0, x1, y1) of zero width or height."""
|
||||
if layout == "rows":
|
||||
ys = _cuts(n, h, split)
|
||||
return [(0, y, w, y) for y in ys[1:-1]]
|
||||
if layout == "grid":
|
||||
if n == 2:
|
||||
return [(w // 2, 0, w // 2, h)]
|
||||
return [(w // 2, 0, w // 2, h), (0, h // 2, w, h // 2)]
|
||||
xs = _cuts(n, w, split)
|
||||
return [(x, 0, x, h) for x in xs[1:-1]]
|
||||
|
||||
|
||||
def drag_split(layout: str, x: float, y: float, w: int, h: int) -> float:
|
||||
"""The divider dragged to (x, y) in the picture: the new split (2 strips, side by side or stacked)."""
|
||||
t = (y / h) if layout == "rows" else (x / w)
|
||||
return min(0.95, max(0.05, t))
|
||||
|
||||
|
||||
def near_divider(p: Plan, x: float, y: float, w: int, h: int, reach: float) -> bool:
|
||||
"""Whether (x, y) is close enough to the one movable divider to grab it."""
|
||||
if p.n != 2 or p.layout == "grid":
|
||||
return False
|
||||
(x0, y0, x1, y1), = dividers(p.layout, 2, w, h, p.split)
|
||||
return abs((y - y0) if p.layout == "rows" else (x - x0)) <= reach
|
||||
|
||||
|
||||
def compose(images, r: list[tuple[Rect, Rect]], out=None):
|
||||
"""One picture from the strips: strip i's part of images[i] (None: left black). numpy arrays or torch tensors
|
||||
(HxWxC), all the same size; `out`, if given, is written into and returned (else a new one is made)."""
|
||||
first = next(im for im in images if im is not None)
|
||||
if out is None:
|
||||
out = first.clone() if hasattr(first, "clone") else first.copy()
|
||||
for im, ((dx0, dy0, dx1, dy1), (sx0, sy0, sx1, sy1)) in zip(images, r):
|
||||
if im is None:
|
||||
out[dy0:dy1, dx0:dx1] = 0
|
||||
else:
|
||||
out[dy0:dy1, dx0:dx1] = im[sy0:sy1, sx0:sx1]
|
||||
return out
|
||||
|
||||
|
||||
# ---- timings -----------------------------------------------------------------------------------------------------
|
||||
class Timings:
|
||||
"""Each variant's cost per frame, over the last WINDOW frames: average and worst, in ms."""
|
||||
|
||||
def __init__(self, n: int = WINDOW) -> None:
|
||||
self.n = n
|
||||
self._ms: dict[str, collections.deque] = {}
|
||||
|
||||
def add(self, key: str, ms: float) -> None:
|
||||
self._ms.setdefault(key, collections.deque(maxlen=self.n)).append(float(ms))
|
||||
|
||||
def stat(self, key: str) -> tuple[float, float] | None:
|
||||
d = self._ms.get(key)
|
||||
if not d:
|
||||
return None
|
||||
return sum(d) / len(d), max(d)
|
||||
|
||||
def text(self, key: str) -> str:
|
||||
s = self.stat(key)
|
||||
return "" if s is None else f"{s[0]:.2f} / {s[1]:.2f} ms"
|
||||
|
||||
def clear(self) -> None:
|
||||
self._ms.clear()
|
||||
|
||||
|
||||
def timing_key(dim: str, variant: str) -> str:
|
||||
return f"{dim}:{variant}"
|
||||
|
||||
|
||||
def labels(p: Plan, timings: Timings, rates: dict | None = None, caps: Caps | None = None) -> list[tuple[str, str]]:
|
||||
"""(title, second line) for each strip. The second line is the measured cost ("0.40 / 0.42 ms": average / worst
|
||||
over the last 120 frames), for frame generation the measured frame rate of each side and the AI's time per frame,
|
||||
or why the strip is unavailable. rates: {"game": fps, "shown": fps} as measured by the pipeline."""
|
||||
rates = rates or {}
|
||||
out = []
|
||||
for s in p.strips:
|
||||
if s.why:
|
||||
out.append((s.name, f"Unavailable: {s.why}"))
|
||||
continue
|
||||
if p.dim == "framegen":
|
||||
fps = strip_fps(s.variant, rates, caps)
|
||||
line = f"{fps:.0f} fps" if fps else ""
|
||||
if s.variant != "off" and p.timings:
|
||||
t = timings.text(timing_key("framegen", "ai"))
|
||||
if t:
|
||||
line = f"{line} · AI {t}" if line else f"AI {t}"
|
||||
out.append((s.name, line))
|
||||
continue
|
||||
out.append((s.name, timings.text(timing_key(p.dim, s.variant)) if p.timings and s.variant != "off" else ""))
|
||||
return out
|
||||
|
||||
|
||||
def strip_fps(variant: str, rates: dict, caps: Caps | None) -> float | None:
|
||||
"""The measured frame rate a frame generation strip shows: the game's for Off, the window's for On, a share of
|
||||
it for a smaller multiplier."""
|
||||
game, shown = rates.get("game"), rates.get("shown")
|
||||
if variant == "off":
|
||||
return game
|
||||
m = multiplier_of(variant)
|
||||
if m is not None and caps is not None and caps.multiplier and shown:
|
||||
return shown * m / caps.multiplier
|
||||
return shown
|
||||
|
||||
|
||||
# ---- frame generation strips -------------------------------------------------------------------------------------
|
||||
def _copy_into(dst, src):
|
||||
if dst is None or tuple(dst.shape) != tuple(src.shape) or type(dst) is not type(src) or (
|
||||
hasattr(src, "device") and getattr(dst, "device", None) != src.device):
|
||||
return src.clone() if hasattr(src, "clone") else src.copy()
|
||||
dst[...] = src
|
||||
return dst
|
||||
|
||||
|
||||
class FrameGenStrips:
|
||||
"""The frame generation comparison, fed every frame the window is about to show, in order. "Off" strips show
|
||||
the game's own frames only, each held until the next (as with frame generation off), from the same timeline as
|
||||
the generated ones, so both sides stay in step; "On" strips show every frame; a smaller multiplier (2x of a 4x
|
||||
run) shows every k-th frame, held. present() returns the picture to show."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._real = None # the game's latest frame shown so far (a copy)
|
||||
self._held: dict[int, object] = {} # strip -> its last frame (smaller multipliers)
|
||||
self._out = None
|
||||
self._count = 0
|
||||
|
||||
def reset(self) -> None:
|
||||
self._real, self._held, self._out, self._count = None, {}, None, 0
|
||||
|
||||
def real(self, frame) -> None:
|
||||
"""The game's own frame that the timeline has reached (call before present(), for real frames and for
|
||||
generated ones whose earlier real frame is new)."""
|
||||
self._real = _copy_into(self._real, frame)
|
||||
|
||||
def present(self, frame, p: Plan, multiplier: int, w: int, h: int):
|
||||
self._count += 1
|
||||
images = []
|
||||
for i, s in enumerate(p.strips):
|
||||
if s.why or s.variant == "off":
|
||||
images.append(None if s.why else (self._real if self._real is not None else frame))
|
||||
continue
|
||||
m = multiplier_of(s.variant)
|
||||
if m is not None and m < multiplier:
|
||||
k = multiplier // m
|
||||
if (self._count - 1) % k == 0 or i not in self._held:
|
||||
self._held[i] = _copy_into(self._held.get(i), frame)
|
||||
images.append(self._held[i])
|
||||
continue
|
||||
images.append(frame)
|
||||
if all(im is frame for im in images):
|
||||
return frame
|
||||
self._out = _copy_into(self._out, frame)
|
||||
return compose(images, rects(p.layout, p.n, w, h, p.split), self._out)
|
||||
|
||||
|
||||
# ---- anti-aliasing strips ----------------------------------------------------------------------------------------
|
||||
def _sync(frame) -> None:
|
||||
if hasattr(frame, "is_cuda") and frame.is_cuda:
|
||||
import torch
|
||||
torch.cuda.synchronize(frame.device)
|
||||
|
||||
|
||||
def aa_strips(frame, p: Plan, timings: Timings, out=None):
|
||||
"""The anti-aliasing comparison: each variant run on the whole frame (so its time is its real cost per frame),
|
||||
then its strip taken. Returns the picture to show."""
|
||||
from . import aa
|
||||
h, w = frame.shape[:2]
|
||||
images = []
|
||||
for s in p.strips:
|
||||
if s.why:
|
||||
images.append(None)
|
||||
continue
|
||||
if s.variant == "off":
|
||||
images.append(frame)
|
||||
continue
|
||||
_sync(frame)
|
||||
t0 = time.perf_counter()
|
||||
im = aa.apply(frame, s.variant)
|
||||
_sync(im)
|
||||
timings.add(timing_key("aa", s.variant), (time.perf_counter() - t0) * 1000)
|
||||
images.append(im)
|
||||
return compose(images, rects(p.layout, p.n, w, h, p.split), out)
|
||||
|
||||
|
||||
# ---- labels and dividers -----------------------------------------------------------------------------------------
|
||||
def overlay_items(p: Plan, texts: list[tuple[str, str]], w: int, h: int, ui: float = 1.0):
|
||||
"""The dividers and the labels over a w x h picture, as [(x, y, RGBA image)] (y down, the top-left corner of each
|
||||
image), drawn with framegen/ui_draw.py so they are crisp at any size. Labels sit at the top of each strip: the
|
||||
name, and under it the cost (or why it's unavailable)."""
|
||||
import numpy as np
|
||||
|
||||
from . import ui_draw as U
|
||||
items = []
|
||||
px = lambda v: max(1, int(round(v * ui))) # noqa: E731
|
||||
line = max(2, px(2))
|
||||
for x0, y0, x1, y1 in dividers(p.layout, p.n, w, h, p.split):
|
||||
if x0 == x1: # a vertical line: light, with a dark edge on each side so it shows on any picture
|
||||
img = np.zeros((y1 - y0, line + 2, 4), np.uint8)
|
||||
img[:, :, 3] = 255
|
||||
img[:, 1:-1, :3] = (235, 238, 245)
|
||||
img[:, [0, -1], 3] = 140
|
||||
items.append((x0 - img.shape[1] // 2, y0, img))
|
||||
else:
|
||||
img = np.zeros((line + 2, x1 - x0, 4), np.uint8)
|
||||
img[:, :, 3] = 255
|
||||
img[1:-1, :, :3] = (235, 238, 245)
|
||||
img[[0, -1], :, 3] = 140
|
||||
items.append((x0, y0 - img.shape[0] // 2, img))
|
||||
if not p.labels:
|
||||
return items
|
||||
f_title, f_sub = U.font(px(22), "semibold"), U.font(px(14))
|
||||
for (title, sub), ((x0, y0, x1, y1), _) in zip(texts, rects(p.layout, p.n, w, h, p.split)):
|
||||
room = max(px(60), (x1 - x0) - px(16))
|
||||
title = U.fit(title, f_title, room - px(24))
|
||||
subs = U.wrap(sub, f_sub, room - px(24), max_lines=3) if sub else []
|
||||
bw = min(room, px(24) + max([U.text_w(title, f_title)] + [U.text_w(s, f_sub) for s in subs]))
|
||||
bh = px(38) + px(19) * len(subs)
|
||||
c = U.Canvas(bw, bh, U.BG, px(8), border=U.BORDER)
|
||||
c.text(bw // 2, px(19), title, f_title, U.TIGHT if sub.startswith("Unavailable") else U.TEXT, anchor="mm")
|
||||
for k, s in enumerate(subs):
|
||||
c.text(bw // 2, px(38) + px(19) * k + px(6), s, f_sub, U.DIM, anchor="mm")
|
||||
items.append((x0 + ((x1 - x0) - bw) // 2, y0 + px(14), c.rgba(0.82)))
|
||||
return items
|
||||
|
||||
|
||||
def blend(img, items):
|
||||
"""The items drawn over img (HxWx3 BGR uint8, numpy; a copy is returned): for stills and clips."""
|
||||
import numpy as np
|
||||
out = img.copy()
|
||||
h, w = out.shape[:2]
|
||||
for x, y, rgba in items:
|
||||
ih, iw = rgba.shape[:2]
|
||||
ax0, ay0, ax1, ay1 = max(0, x), max(0, y), min(w, x + iw), min(h, y + ih)
|
||||
if ax1 <= ax0 or ay1 <= ay0:
|
||||
continue
|
||||
part = rgba[ay0 - y:ay1 - y, ax0 - x:ax1 - x].astype(np.float32)
|
||||
a = part[..., 3:4] / 255.0
|
||||
bgr = part[..., 2::-1]
|
||||
dst = out[ay0:ay1, ax0:ax1].astype(np.float32)
|
||||
out[ay0:ay1, ax0:ax1] = (dst * (1.0 - a) + bgr * a + 0.5).astype(np.uint8)
|
||||
return out
|
||||
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from . import fill, looks, oslayer
|
||||
from . import aa, compare, fill, looks, oslayer
|
||||
|
||||
DEFAULT_PATH = oslayer.config_dir() / "settings.json" # %APPDATA%\\framegen (Windows), ~/.config/smoovplay (Linux)
|
||||
|
||||
@@ -37,6 +37,7 @@ class Spec:
|
||||
sub: str = "" # a heading inside its section (the overlay draws one where it changes)
|
||||
quick: bool = False # one of the few big choices at the top of the launcher's Settings page
|
||||
applies: tuple = () # (key, values): only used, and only shown, while setting `key` is one of `values`
|
||||
also: tuple = () # (key, values): a second such condition (both must hold)
|
||||
later: str = "" # a note at the end of the launcher's dropdown, about choices that aren't offered yet
|
||||
hints: dict = field(default_factory=dict) # value -> a line under that choice in the launcher's dropdown (only
|
||||
# there, so no-break spaces keep "90 Hz" together; the in-video menu's font can't draw them, so help has none)
|
||||
@@ -63,7 +64,8 @@ class Spec:
|
||||
|
||||
def applies_to(self, values: dict) -> bool:
|
||||
"""Whether this setting is used with these values (e.g. VFG quality only while NVIDIA VFG is picked)."""
|
||||
return not self.applies or values.get(self.applies[0]) in self.applies[1]
|
||||
return ((not self.applies or values.get(self.applies[0]) in self.applies[1])
|
||||
and (not self.also or values.get(self.also[0]) in self.also[1]))
|
||||
|
||||
def unused_with(self, source: str) -> str | None:
|
||||
"""Why this setting isn't used with frames from `source` (a framegen/sources.py kind), or None if it is."""
|
||||
@@ -95,6 +97,43 @@ def valid_hz(value: Any) -> bool:
|
||||
|
||||
|
||||
ON_OFF = {True: "On", False: "Off"}
|
||||
|
||||
|
||||
def _compare_specs() -> tuple:
|
||||
"""The Compare tab (framegen/compare.py): Compare itself starts off each session; the rest is saved."""
|
||||
strips = []
|
||||
for d in compare.DIMENSIONS:
|
||||
for i in range(1, compare.MAX_STRIPS[d] + 1):
|
||||
where = ("left", "right") if i <= 2 else ("",)
|
||||
strips.append(Spec(
|
||||
compare.strip_key(d, i), f"Strip {i}", compare.VARIANTS[d], compare.DEFAULTS[d][i - 1],
|
||||
compare.NAMES[d], group="Compare", applies=("compare_dim", (d,)),
|
||||
also=("compare_strips", tuple(n for n in (2, 3, 4) if n >= i)),
|
||||
help=f"What strip {i} shows ({'from the ' + where[i - 1] if i <= 2 else 'counting from the left'}, "
|
||||
"or from the top when stacked). A choice this PC can't show gets a black strip saying why."))
|
||||
return (
|
||||
Spec("compare", "Compare", (False, True), False, ON_OFF, saved=False, group="Compare",
|
||||
help="Cuts the picture into strips, each drawn with a different choice of one setting, with its name "
|
||||
"and its measured cost per frame. Key: C (Shift+C: the next thing to compare). Starts off each "
|
||||
"session."),
|
||||
Spec("compare_dim", "What to compare", compare.DIMENSIONS, "aa", compare.DIM_NAMES, group="Compare",
|
||||
help="Anti-aliasing, the upscaler, frame generation (the game's own frames against generated ones, "
|
||||
"live, to see the smoothness) or the look."),
|
||||
Spec("compare_strips", "Strips", (2, 3, 4), 4, group="Compare",
|
||||
help="How many choices side by side. Look has two (off and on); a 2-strip divider can be dragged with "
|
||||
"the mouse."),
|
||||
*strips,
|
||||
Spec("compare_layout", "Layout", compare.LAYOUTS, "columns", compare.LAYOUT_NAMES, group="Compare",
|
||||
help="Side by side: vertical strips of one picture. Stacked: horizontal strips. 2x2: the same crop of "
|
||||
"the picture's middle in each cell, pixel for pixel, to look closely."),
|
||||
Spec("compare_labels", "Labels", (True, False), True, ON_OFF, group="Compare",
|
||||
help="Each strip's name at its top."),
|
||||
Spec("compare_timings", "Timings", (True, False), True, ON_OFF, group="Compare",
|
||||
help="Under each name: its measured cost per frame, average / worst over the last 120 frames, in ms."),
|
||||
Spec("compare_clips", "Compare in clips", (False, True), False, ON_OFF, group="Compare",
|
||||
help="Saved clips with the strips, labels and dividers burned in. Anti-aliasing and frame generation "
|
||||
"only: clips are saved at the game's size, before the upscaler and the look."),
|
||||
)
|
||||
OPACITY = (1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3) # menu and stats opacity choices
|
||||
PCT = {v: f"{round(v * 100)}%" for v in OPACITY}
|
||||
PCT_SIZE = {v: f"{round(v * 100)}%" for v in (0.6, 0.75, 0.9, 1.0, 1.25, 1.5, 2.0)}
|
||||
@@ -440,7 +479,18 @@ SPECS: tuple[Spec, ...] = (
|
||||
help="For testing with a 60 fps game: every other frame is left out, so it plays like a 30 fps game. At "
|
||||
"60 and 120 fps each AI frame is also scored against the real frame it replaced. This session "
|
||||
"only."),
|
||||
)
|
||||
# framegen/aa.py: at the game's size, before the upscaler; the pipeline applies it to every frame shown
|
||||
Spec("aa", "Anti-aliasing", aa.MODES, "off", aa.NAMES, group="Upscaling",
|
||||
hints={"off": "The game's picture as it comes. The default.",
|
||||
"fxaa": "Softens jagged edges: light and quick.",
|
||||
"smaa": "Smooths jagged edges by their shape, keeping more detail than FXAA.",
|
||||
"cas": "Not anti-aliasing: sharpens, more where the picture is soft."},
|
||||
help="Smooths jagged edges in the game's picture, before it is upscaled: FXAA (light), SMAA-style (keeps "
|
||||
"more detail) or CAS sharpening. Mostly for games and streams that come without anti-aliasing. Saved "
|
||||
"clips stay as the game sent them. Compare them side by side with the C key (Compare tab).",
|
||||
impact={"picture": "Softer, smoother edges (CAS: sharper).",
|
||||
"speed": "Runs on the graphics card for every frame shown; the Compare view measures it."}),
|
||||
) + _compare_specs()
|
||||
# Where each setting goes: (tab, heading, keys in order). The in-game overlay draws a tab for each, with the
|
||||
# headings inside; the launcher's Settings page uses the tabs as its sections. A setting not listed keeps its own.
|
||||
LAYOUT: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||||
@@ -448,6 +498,7 @@ LAYOUT: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||||
("Frame generation", "AI model", ("model", "vfg_quality", "motion", "engine")),
|
||||
("Frame generation", "Smoothing", ("even_out", "even_dips", "steady_hud")),
|
||||
("Upscaling", "Upscaler", ("scaler", "fsr_sharpness", "vsr_quality")),
|
||||
("Upscaling", "Anti-aliasing", ("aa",)),
|
||||
("Upscaling", "Output", ("output_res", "fill")),
|
||||
("Display", "Window", ("fullscreen", "vsync", "present")),
|
||||
("Display", "Colour and look", ("hdr", "look_on", "look")),
|
||||
@@ -460,6 +511,9 @@ LAYOUT: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||||
("Sources", "Capture card", ("capture_size",)),
|
||||
("Sources", "PS5 Remote Play", ("minimize_chiaki", "audio_sync")),
|
||||
("Sources", "Testing", ("simulate_30",)),
|
||||
("Compare", "Setup", ("compare", "compare_dim", "compare_strips",
|
||||
*(compare.strip_key(d, i) for d in compare.DIMENSIONS for i in range(1, 5)))),
|
||||
("Compare", "Show", ("compare_layout", "compare_labels", "compare_timings", "compare_clips")),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""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
|
||||
Reference in new issue
Block a user