regress.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. #!/usr/bin/env python3
  2. """Wallpaper regression runs: render every installed scene wallpaper headlessly with a build,
  3. then compare two runs (usually the last good build against the one being tested).
  4. tools/regression/regress.py run /path/to/old/linux-wallpaperengine runs/base --repeat 2
  5. tools/regression/regress.py run build/output/linux-wallpaperengine runs/new
  6. tools/regression/regress.py compare runs/base runs/new --report runs/report
  7. Runs are reproducible: animation time advances by a fixed step per frame (LWE_FIXED_TIMESTEP),
  8. particles are seeded per object, the wall clock is pinned (fixed_clock.c) and audio input is
  9. off. Each worker gets its own Xvfb display, nothing touches the real screen.
  10. --gpu renders on the GPU instead (the engine's headless EGL driver, XDG_SESSION_TYPE=headless),
  11. no Xvfb and many times faster than llvmpipe. GPU and llvmpipe pixels differ slightly, so compare
  12. runs made the same way; the binary needs the headless driver for this.
  13. compare looks at four things per wallpaper: whether it still renders (crash/timeout), error
  14. lines that appear or disappear in the log, how much of the screenshot changed, and whether gif
  15. and video textures still move (wallpapers shipping them get a second render a few frames later,
  16. a hidden or frozen one shows up as less motion). Video textures play in real time and never
  17. render the same twice, --repeat 2 on the base run marks those pixels so compare ignores them.
  18. It writes an HTML report with side-by-sides of everything flagged and exits 1 if anything
  19. regressed. Both builds need LWE_FIXED_TIMESTEP support, older ones render every run differently.
  20. Needs Xvfb, gcc and Pillow (tools/requirements.txt).
  21. """
  22. import argparse
  23. import atexit
  24. import concurrent.futures
  25. import html
  26. import json
  27. import os
  28. import queue
  29. import re
  30. import resource
  31. import shutil
  32. import signal
  33. import subprocess
  34. import sys
  35. import tempfile
  36. import time
  37. from pathlib import Path
  38. HERE = Path (__file__).resolve ().parent
  39. TOOLS = HERE.parent
  40. DEFAULT_WORKSHOP = Path.home () / '.local/share/Steam/steamapps/workshop/content/431960'
  41. DEFAULT_ASSETS = Path.home () / '.local/share/Steam/steamapps/common/wallpaper_engine/assets'
  42. # lines worth tracking between builds; everything else in the log is chatter
  43. ERROR_LINE = re.compile (
  44. r'error|exception|failed|cannot|can\'t|unsupported|not supported|typeerror|referenceerror|'
  45. r'syntaxerror|abort|segmentation|falling back',
  46. re.IGNORECASE
  47. )
  48. # driver/X noise that shows up on some machines and says nothing about the engine
  49. IGNORED_LINE = re.compile (r'amdgpu|_XSERVTrans|MESA-LOADER|libEGL warning|ALSA lib|Puppet draw result')
  50. # mpv announcing a video stream, those textures play in real time and never render the same twice
  51. VIDEO_LINE = re.compile (r'^\W*Video\s+--vid=', re.MULTILINE)
  52. def env_path (name, fallback):
  53. value = os.environ.get (name)
  54. return Path (value) if value else fallback
  55. def read_project (folder):
  56. try:
  57. with open (folder / 'project.json', encoding = 'utf-8-sig') as f:
  58. return json.load (f)
  59. except (OSError, ValueError):
  60. return None
  61. def read_sized (f):
  62. size = int.from_bytes (f.read (4), 'little')
  63. return f.read (size).decode ('utf-8', 'replace')
  64. def texture_kinds (header):
  65. """'gif' for animated (sprite sheet) textures, 'video' for mp4 ones, from a .tex header."""
  66. if header[:8] != b'TEXV0005' or len (header) < 26:
  67. return set ()
  68. flags = int.from_bytes (header[22:26], 'little')
  69. return ({'gif'} if flags & 4 else set ()) | ({'video'} if flags & 32 else set ())
  70. def animated_textures (folder):
  71. """What kind of animated textures a wallpaper ships, loose or inside its .pkg files."""
  72. kinds = set ()
  73. for path in folder.rglob ('*'):
  74. if path.suffix == '.mp4':
  75. kinds.add ('video')
  76. elif path.suffix == '.tex':
  77. with open (path, 'rb') as f:
  78. kinds |= texture_kinds (f.read (64))
  79. elif path.suffix == '.pkg':
  80. try:
  81. with open (path, 'rb') as f:
  82. read_sized (f)
  83. entries = []
  84. for _ in range (int.from_bytes (f.read (4), 'little')):
  85. name = read_sized (f)
  86. offset = int.from_bytes (f.read (4), 'little')
  87. f.read (4)
  88. entries.append ((name, offset))
  89. base = f.tell ()
  90. for name, offset in entries:
  91. if name.endswith ('.mp4'):
  92. kinds.add ('video')
  93. elif name.endswith ('.tex'):
  94. f.seek (base + offset)
  95. kinds |= texture_kinds (f.read (64))
  96. except (OSError, ValueError):
  97. pass
  98. return kinds
  99. def find_wallpapers (workshop, types, ids, variants):
  100. """(name, folder, title, properties) per render; variants add renders of the same wallpaper
  101. with user properties set, named <id>@<variant>."""
  102. found = []
  103. for folder in sorted (workshop.iterdir ()):
  104. if not folder.is_dir () or (ids and folder.name not in ids):
  105. continue
  106. project = read_project (folder)
  107. kind = str ((project or {}).get ('type', '')).lower ()
  108. if kind in types:
  109. title = (project or {}).get ('title', '')
  110. found.append ((folder.name, folder, title, []))
  111. for variant, properties in variants.get (folder.name, {}).items ():
  112. found.append ((f'{folder.name}@{variant}', folder, f'{title} [{variant}]', properties))
  113. return found
  114. def build_shims (out):
  115. shims = out / '.shims'
  116. shims.mkdir (parents = True, exist_ok = True)
  117. built = []
  118. for source in (TOOLS / 'dbus_noop_shim.c', HERE / 'fixed_clock.c'):
  119. target = shims / (source.stem + '.so')
  120. if not target.exists () or source.stat ().st_mtime > target.stat ().st_mtime:
  121. subprocess.run (['gcc', '-shared', '-fPIC', '-O2', '-o', str (target), str (source), '-ldl'], check = True)
  122. built.append (str (target))
  123. return ':'.join (built)
  124. def x_sockets ():
  125. """Display numbers with a listening X socket, abstract ones included (some sandboxes can't
  126. write /tmp/.X11-unix, Xvfb then only has the abstract socket)."""
  127. numbers = set ()
  128. with open ('/proc/net/unix') as f:
  129. for line in f:
  130. match = re.search (r'/tmp/\.X11-unix/X(\d+)$', line.strip ())
  131. if match:
  132. numbers.add (int (match.group (1)))
  133. return numbers
  134. class Display:
  135. """One Xvfb server per worker so renders can run side by side."""
  136. process = None
  137. def __init__ (self, first, width, height):
  138. number = first
  139. while True:
  140. while number in x_sockets () or Path (f'/tmp/.X11-unix/X{number}').exists ():
  141. number += 1
  142. self.name = f':{number}'
  143. self.number = number
  144. self.process = subprocess.Popen (
  145. ['Xvfb', self.name, '-screen', '0', f'{width}x{height}x24', '-nolisten', 'tcp'],
  146. stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
  147. )
  148. for _ in range (100):
  149. if number in x_sockets ():
  150. return
  151. if self.process.poll () is not None:
  152. break
  153. time.sleep (0.05)
  154. self.close ()
  155. number += 1
  156. if number > first + 50:
  157. raise RuntimeError ('could not start Xvfb')
  158. def close (self):
  159. if self.process is None:
  160. return
  161. self.process.terminate ()
  162. try:
  163. self.process.wait (5)
  164. except subprocess.TimeoutExpired:
  165. self.process.kill ()
  166. def stop (process):
  167. if process.poll () is not None:
  168. return
  169. os.killpg (process.pid, signal.SIGTERM)
  170. try:
  171. process.wait (5)
  172. except subprocess.TimeoutExpired:
  173. os.killpg (process.pid, signal.SIGKILL)
  174. process.wait ()
  175. def limit_process (memory_gb):
  176. resource.setrlimit (resource.RLIMIT_CORE, (0, 0))
  177. # RLIMIT_DATA, V8 and the GPU driver reserve far more address space than they use
  178. if memory_gb:
  179. limit = int (memory_gb * 1024 ** 3)
  180. resource.setrlimit (resource.RLIMIT_DATA, (limit, limit))
  181. def render_once (args, env, folder, shot, log_path, properties, extra = ()):
  182. command = [
  183. str (args.binary), '--window', f'0x0x{args.width}x{args.height}', '--fps', '1000',
  184. '--silent', '--no-audio-processing', '--screenshot', str (shot), '--screenshot-delay', str (args.frame),
  185. '--assets-dir', str (args.assets),
  186. ]
  187. for value in properties:
  188. command += ['--set-property', value]
  189. command += list (extra)
  190. command.append (str (folder))
  191. # private session bus per render unless the caller already gave one
  192. if 'DBUS_SESSION_BUS_ADDRESS' not in env and shutil.which ('dbus-run-session'):
  193. command = ['dbus-run-session', '--'] + command
  194. started = time.monotonic ()
  195. status = 'timeout'
  196. with open (log_path, 'wb') as log:
  197. process = subprocess.Popen (
  198. command, env = env, stdin = subprocess.DEVNULL, stdout = log, stderr = subprocess.STDOUT, start_new_session = True,
  199. # no core files: the sandbox shares the desktop's user and its crash handler picks them up
  200. preexec_fn = lambda: limit_process (getattr (args, 'memory_limit', None))
  201. )
  202. last_size = -1
  203. while time.monotonic () - started < args.timeout:
  204. code = process.poll ()
  205. size = shot.stat ().st_size if shot.exists () else 0
  206. # the engine keeps running after the screenshot, stop it once the file is complete
  207. if size > 0 and size == last_size:
  208. status = 'ok'
  209. break
  210. if code is not None:
  211. status = 'ok' if size > 0 else ('crash' if code < 0 else 'noshot')
  212. break
  213. last_size = size
  214. time.sleep (0.25)
  215. stop (process)
  216. return status, process.returncode, time.monotonic () - started
  217. def render_env (args, preload, display):
  218. env = dict (os.environ)
  219. env.pop ('WAYLAND_DISPLAY', None)
  220. env.pop ('WAYLAND_SOCKET', None)
  221. env.pop ('DISPLAY', None)
  222. # nothing may reach the desktop session: libwayland and D-Bus fall back to sockets in XDG_RUNTIME_DIR, so a
  223. # build without the headless driver would open a window on the real desktop
  224. for name in ('DBUS_SESSION_BUS_ADDRESS', 'KDE_FULL_SESSION', 'KDE_SESSION_VERSION', 'DESKTOP_SESSION',
  225. 'XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP'):
  226. env.pop (name, None)
  227. runtime_dir = tempfile.mkdtemp (prefix = 'lwe-regress-run-')
  228. atexit.register (shutil.rmtree, runtime_dir, True)
  229. env.update ({
  230. 'XDG_RUNTIME_DIR': runtime_dir,
  231. 'XDG_SESSION_TYPE': 'x11',
  232. 'LD_LIBRARY_PATH': ':'.join (filter (None, [str (args.binary.parent), os.environ.get ('LD_LIBRARY_PATH')])),
  233. 'LD_PRELOAD': preload,
  234. 'LWE_FIXED_TIMESTEP': str (args.step),
  235. 'LWE_FIXED_CLOCK': str (args.clock),
  236. 'TZ': 'UTC',
  237. # no audio server: whatever the machine is playing would otherwise feed the audio visualizers
  238. 'PULSE_SERVER': 'unix:/nonexistent-pulse',
  239. 'PIPEWIRE_REMOTE': '/nonexistent-pipewire',
  240. })
  241. if args.gpu:
  242. env['XDG_SESSION_TYPE'] = 'headless'
  243. if args.gpu != 'auto':
  244. env['LWE_HEADLESS_DEVICE'] = args.gpu
  245. else:
  246. env['DISPLAY'] = display.name
  247. # software rendering (llvmpipe) starts a thread per core in every instance, which just
  248. # thrashes when several renders run at once
  249. env.setdefault ('LP_NUM_THREADS', str (max (1, (os.cpu_count () or 1) // args.jobs)))
  250. return env
  251. def render (args, preload, display, wallpaper):
  252. wallpaper_id, folder, title, properties = wallpaper
  253. target = args.out / wallpaper_id
  254. shutil.rmtree (target, ignore_errors = True)
  255. target.mkdir (parents = True)
  256. env = render_env (args, preload, display)
  257. status, code, seconds = render_once (args, env, folder, target / 'shot.png', target / 'log.txt', properties)
  258. # extra renders of the same build show what isn't reproducible (video textures play in real
  259. # time), compare ignores those pixels
  260. if status == 'ok':
  261. for repeat in range (2, args.repeat + 1):
  262. render_once (args, env, folder, target / f'shot{repeat}.png', target / f'log{repeat}.txt', properties)
  263. # animated textures have to keep moving: a second, later frame shows whether a gif or video
  264. # is still drawn and still playing (a hidden or frozen one leaves its area static)
  265. animated = sorted (animated_textures (folder))
  266. motion = None
  267. if status == 'ok' and animated and args.motion_gap > 0:
  268. later = target / 'shot_motion.png'
  269. args_later = argparse.Namespace (**{**vars (args), 'frame': args.frame + args.motion_gap})
  270. if render_once (args_later, env, folder, later, target / 'log_motion.txt', properties)[0] == 'ok':
  271. motion = changed_fraction (target / 'shot.png', later, 16)
  272. log = (target / 'log.txt').read_text (errors = 'replace')
  273. result = {
  274. 'id': wallpaper_id,
  275. 'title': title,
  276. 'status': status,
  277. 'exit': code,
  278. 'seconds': round (seconds, 1),
  279. 'video': bool (VIDEO_LINE.search (log)),
  280. 'animated': animated,
  281. 'motion': motion,
  282. }
  283. (target / 'result.json').write_text (json.dumps (result, ensure_ascii = False, indent = 1))
  284. return result
  285. def cmd_run (args):
  286. if args.jobs is None:
  287. cores = os.cpu_count () or 2
  288. args.jobs = max (1, cores // 2 if args.gpu else min (8, cores // 4))
  289. args.binary = args.binary.resolve ()
  290. args.out = args.out.resolve ()
  291. args.out.mkdir (parents = True, exist_ok = True)
  292. variants = {}
  293. if args.variants.exists ():
  294. variants = {k: v for k, v in json.loads (args.variants.read_text ()).items () if not k.startswith ('_')}
  295. wallpapers = find_wallpapers (args.workshop, set (args.types.split (',')), set (args.ids or []), variants)
  296. if not wallpapers:
  297. sys.exit (f'no wallpapers found in {args.workshop}')
  298. preload = build_shims (args.out)
  299. displays = queue.Queue ()
  300. opened = []
  301. try:
  302. for _ in range (args.jobs):
  303. if args.gpu:
  304. displays.put (None)
  305. continue
  306. display = Display (opened[-1].number + 1 if opened else 90, args.width, args.height)
  307. opened.append (display)
  308. displays.put (display)
  309. def job (wallpaper):
  310. display = displays.get ()
  311. try:
  312. return render (args, preload, display, wallpaper)
  313. finally:
  314. displays.put (display)
  315. (args.out / 'run.json').write_text (json.dumps ({
  316. 'binary': str (args.binary),
  317. 'frame': args.frame,
  318. 'step': args.step,
  319. 'clock': args.clock,
  320. 'size': [args.width, args.height],
  321. 'repeat': args.repeat,
  322. 'renderer': 'gpu' if args.gpu else 'llvmpipe',
  323. 'started': time.strftime ('%Y-%m-%d %H:%M:%S'),
  324. }, indent = 1))
  325. done = 0
  326. with concurrent.futures.ThreadPoolExecutor (args.jobs) as pool:
  327. for result in pool.map (job, wallpapers):
  328. done += 1
  329. print (f'[{done}/{len (wallpapers)}] {result["id"]} {result["status"]} {result["seconds"]}s', flush = True)
  330. finally:
  331. for display in opened:
  332. display.close ()
  333. def error_lines (log):
  334. if not log.exists ():
  335. return set ()
  336. lines = set ()
  337. for line in log.read_text (errors = 'replace').splitlines ():
  338. if ERROR_LINE.search (line) and not IGNORED_LINE.search (line):
  339. # numbers, pointers and temp paths change between runs, the message doesn't
  340. line = re.sub (r'0x[0-9a-fA-F]+', 'X', line)
  341. line = re.sub (r'\d+', 'N', line)
  342. lines.add (line.strip ()[:300])
  343. return lines
  344. def strongest_difference (a, b):
  345. from PIL import ImageChops
  346. if a.size != b.size:
  347. b = b.resize (a.size)
  348. # per pixel, the largest channel difference
  349. channels = ImageChops.difference (a, b).split ()
  350. return ImageChops.lighter (ImageChops.lighter (channels[0], channels[1]), channels[2])
  351. def changed_fraction (first, second, threshold):
  352. from PIL import Image
  353. a = Image.open (first).convert ('RGB')
  354. histogram = strongest_difference (a, Image.open (second).convert ('RGB')).histogram ()
  355. return sum (histogram[threshold + 1:]) / (a.size[0] * a.size[1])
  356. def noise_mask (shots, threshold):
  357. """Pixels that already differ between repeated renders of the same build."""
  358. from PIL import Image, ImageChops
  359. images = [Image.open (shot).convert ('RGB') for shot in shots]
  360. mask = None
  361. for other in images[1:]:
  362. changed = strongest_difference (images[0], other).point (lambda v: 255 if v > threshold else 0)
  363. mask = changed if mask is None else ImageChops.lighter (mask, changed)
  364. return mask
  365. def image_diff (base, new, threshold, heatmap, noise):
  366. from PIL import Image, ImageChops
  367. a = Image.open (base).convert ('RGB')
  368. b = Image.open (new).convert ('RGB')
  369. changed_mask = strongest_difference (a, b).point (lambda v: 255 if v > threshold else 0)
  370. total = a.size[0] * a.size[1]
  371. ignored = 0
  372. if noise is not None:
  373. noise = noise.resize (a.size)
  374. ignored = noise.histogram ()[255] / total
  375. changed_mask = ImageChops.subtract (changed_mask, noise)
  376. changed = changed_mask.histogram ()[255] / total
  377. if changed > 0 or ignored > 0:
  378. dim = a.convert ('L').convert ('RGB').point (lambda v: v // 3)
  379. if noise is not None:
  380. dim = Image.composite (Image.new ('RGB', a.size, (60, 60, 110)), dim, noise)
  381. Image.composite (Image.new ('RGB', a.size, (255, 40, 40)), dim, changed_mask).save (heatmap, quality = 85)
  382. return changed, ignored
  383. def thumbnail (source, target, width = 640):
  384. from PIL import Image
  385. image = Image.open (source).convert ('RGB')
  386. image.thumbnail ((width, width))
  387. image.save (target, quality = 85)
  388. def load_result (folder):
  389. try:
  390. return json.loads ((folder / 'result.json').read_text ())
  391. except (OSError, ValueError):
  392. return None
  393. def renderer (folder):
  394. try:
  395. return json.loads ((folder / 'run.json').read_text ()).get ('renderer', 'llvmpipe')
  396. except (OSError, ValueError):
  397. return '?'
  398. def cmd_compare (args):
  399. if renderer (args.base) != renderer (args.new):
  400. print (f'warning: base was rendered with {renderer (args.base)} and new with {renderer (args.new)}, '
  401. 'expect small differences everywhere', file = sys.stderr)
  402. report = args.report.resolve ()
  403. shutil.rmtree (report, ignore_errors = True)
  404. (report / 'img').mkdir (parents = True)
  405. ids = sorted ({p.name for p in args.base.iterdir () if (p / 'result.json').exists ()}
  406. | {p.name for p in args.new.iterdir () if (p / 'result.json').exists ()})
  407. rows = []
  408. for wallpaper_id in ids:
  409. base = load_result (args.base / wallpaper_id)
  410. new = load_result (args.new / wallpaper_id)
  411. row = {
  412. 'id': wallpaper_id,
  413. 'title': (new or base or {}).get ('title', ''),
  414. 'base': base['status'] if base else 'missing',
  415. 'new': new['status'] if new else 'missing',
  416. 'added_errors': [],
  417. 'fixed_errors': [],
  418. 'changed': None,
  419. 'verdict': 'same',
  420. }
  421. if base and new:
  422. base_errors = error_lines (args.base / wallpaper_id / 'log.txt')
  423. new_errors = error_lines (args.new / wallpaper_id / 'log.txt')
  424. row['added_errors'] = sorted (new_errors - base_errors)
  425. row['fixed_errors'] = sorted (base_errors - new_errors)
  426. base_shot = args.base / wallpaper_id / 'shot.png'
  427. new_shot = args.new / wallpaper_id / 'shot.png'
  428. row['video'] = bool ((base or {}).get ('video') or (new or {}).get ('video'))
  429. row['ignored'] = 0
  430. if base and new and base_shot.exists () and new_shot.exists ():
  431. heatmap = report / 'img' / f'{wallpaper_id}_diff.jpg'
  432. repeats = sorted ((args.base / wallpaper_id).glob ('shot[0-9]*.png'))
  433. repeats += sorted ((args.new / wallpaper_id).glob ('shot[0-9]*.png'))
  434. noise = None
  435. if repeats:
  436. noise = noise_mask ([base_shot] + [r for r in repeats if r.parent == base_shot.parent], args.threshold)
  437. new_repeats = [r for r in repeats if r.parent == new_shot.parent]
  438. if new_repeats:
  439. from PIL import ImageChops
  440. extra = noise_mask ([new_shot] + new_repeats, args.threshold)
  441. noise = extra if noise is None else ImageChops.lighter (noise, extra.resize (noise.size))
  442. row['changed'], row['ignored'] = image_diff (base_shot, new_shot, args.threshold, heatmap, noise)
  443. row['animated'] = (new or base or {}).get ('animated', [])
  444. row['motion'] = [(base or {}).get ('motion'), (new or {}).get ('motion')]
  445. base_motion, new_motion = row['motion']
  446. # the second frame moved noticeably less than with the base build
  447. # runs made before the motion check have no "motion" key at all, None means the later render failed
  448. less_motion = ('motion' in (new or {}) and base_motion is not None and base_motion * 100 >= args.motion_min
  449. and (new_motion or 0) < base_motion * 0.5)
  450. if row['new'] == 'missing':
  451. row['verdict'] = 'not run'
  452. elif row['base'] == 'missing':
  453. row['verdict'] = 'new wallpaper'
  454. elif row['new'] != 'ok' and row['base'] == 'ok':
  455. row['verdict'] = 'broken'
  456. elif row['new'] == 'ok' and row['base'] not in ('ok', 'missing'):
  457. row['verdict'] = 'fixed'
  458. elif row['added_errors']:
  459. row['verdict'] = 'new errors'
  460. elif less_motion:
  461. row['verdict'] = 'less motion'
  462. elif row['changed'] is not None and row['changed'] * 100 > (args.video_tolerance if row['video'] else args.tolerance):
  463. row['verdict'] = 'changed'
  464. elif row['fixed_errors']:
  465. row['verdict'] = 'fewer errors'
  466. if row['verdict'] not in ('same', 'not run'):
  467. for side, shot in (('base', base_shot), ('new', new_shot),
  468. ('base_motion', args.base / wallpaper_id / 'shot_motion.png'),
  469. ('new_motion', args.new / wallpaper_id / 'shot_motion.png')):
  470. if shot.exists ():
  471. thumbnail (shot, report / 'img' / f'{wallpaper_id}_{side}.jpg')
  472. rows.append (row)
  473. order = {'broken': 0, 'new errors': 1, 'less motion': 2, 'changed': 3, 'fixed': 4, 'fewer errors': 5,
  474. 'new wallpaper': 6, 'same': 7, 'not run': 8}
  475. rows.sort (key = lambda r: (order[r['verdict']], -(r['changed'] or 0)))
  476. (report / 'summary.json').write_text (json.dumps (rows, ensure_ascii = False, indent = 1))
  477. write_html (report, args, rows)
  478. counts = {}
  479. for row in rows:
  480. counts[row['verdict']] = counts.get (row['verdict'], 0) + 1
  481. print (', '.join (f'{count} {verdict}' for verdict, count in sorted (counts.items (), key = lambda c: order[c[0]])))
  482. for row in rows:
  483. if row['verdict'] not in ('same', 'not run'):
  484. changed = f' {row["changed"] * 100:.2f}% of pixels' if row['changed'] else ''
  485. print (f' {row["verdict"]:12} {row["id"]} {row["title"][:50]}{changed}')
  486. print (f'report: {report / "index.html"}')
  487. regressed = any (r['verdict'] in ('broken', 'new errors', 'less motion', 'changed') for r in rows)
  488. sys.exit (1 if regressed else 0)
  489. def write_html (report, args, rows):
  490. def esc (value):
  491. return html.escape (str (value))
  492. def run_info (folder):
  493. try:
  494. return json.loads ((folder / 'run.json').read_text ())
  495. except (OSError, ValueError):
  496. return {}
  497. base_info = run_info (args.base)
  498. new_info = run_info (args.new)
  499. parts = [f'''<!doctype html><html><head><meta charset="utf-8"><title>Wallpaper regressions</title>
  500. <style>
  501. body {{ font: 14px system-ui, sans-serif; margin: 24px; background: #16161a; color: #ddd; }}
  502. a {{ color: #8ab4f8; }} h2 {{ margin-top: 40px; }}
  503. table {{ border-collapse: collapse; }} td, th {{ padding: 4px 10px; border-bottom: 1px solid #333; text-align: left; }}
  504. .broken, .new-errors {{ color: #ff6b6b; }} .changed {{ color: #ffb86b; }} .fixed, .fewer-errors {{ color: #7ee787; }}
  505. .pair {{ display: flex; gap: 8px; flex-wrap: wrap; }} .pair figure {{ margin: 0; }} .pair img {{ max-width: 420px; display: block; }}
  506. figcaption {{ color: #999; font-size: 12px; }} pre {{ background: #222; padding: 8px; overflow-x: auto; }}
  507. </style></head><body>
  508. <h1>Wallpaper regressions</h1>
  509. <p>base: {esc (args.base)} ({esc (base_info.get ('binary', '?'))}, {esc (base_info.get ('started', ''))})<br>
  510. new: {esc (args.new)} ({esc (new_info.get ('binary', '?'))}, {esc (new_info.get ('started', ''))})<br>
  511. frame {esc (new_info.get ('frame', '?'))} at {esc (new_info.get ('step', '?'))}s per frame, pixel threshold {args.threshold},
  512. changed above {args.tolerance}% of pixels ({args.video_tolerance}% with video textures)</p>
  513. <p>Heatmaps: red is changed, blue is ignored because it already differs between repeated renders of one build
  514. (<code>run --repeat 2</code>), grey is unchanged.</p>
  515. <table><tr><th>verdict</th><th>id</th><th>title</th><th>base</th><th>new</th><th>pixels changed</th><th>ignored</th><th>motion base / new</th></tr>''']
  516. for row in rows:
  517. css = row['verdict'].replace (' ', '-')
  518. changed = f'{row["changed"] * 100:.2f}%' if row['changed'] is not None else '-'
  519. ignored = f'{row["ignored"] * 100:.1f}%' if row['ignored'] else ''
  520. title = esc (row['title']) + (' <small>(video texture)</small>' if row['video'] else '')
  521. detailed = row['verdict'] not in ('same', 'not run')
  522. link = f'<a href="#w{esc (row["id"])}">{esc (row["id"])}</a>' if detailed else esc (row['id'])
  523. motion = ' / '.join ('-' if m is None else f'{m * 100:.2f}%' for m in row['motion']) if row['animated'] else ''
  524. if row['animated']:
  525. title += f' <small>({", ".join (row["animated"])})</small>'
  526. parts.append (f'<tr><td class="{css}">{esc (row["verdict"])}</td><td>{link}</td><td>{title}</td>'
  527. f'<td>{esc (row["base"])}</td><td>{esc (row["new"])}</td><td>{changed}</td><td>{ignored}</td><td>{motion}</td></tr>')
  528. parts.append ('</table>')
  529. for row in rows:
  530. if row['verdict'] in ('same', 'not run'):
  531. continue
  532. parts.append (f'<h2 id="w{esc (row["id"])}" class="{row["verdict"].replace (" ", "-")}">'
  533. f'{esc (row["id"])} - {esc (row["title"])} ({esc (row["verdict"])})</h2><div class="pair">')
  534. for name, caption in (('base', 'base'), ('new', 'new'), ('diff', 'changed pixels'),
  535. ('base_motion', 'base, a few frames later'), ('new_motion', 'new, a few frames later')):
  536. image = report / 'img' / f'{row["id"]}_{name}.jpg'
  537. if image.exists ():
  538. parts.append (f'<figure><img src="img/{image.name}"><figcaption>{caption}</figcaption></figure>')
  539. parts.append ('</div>')
  540. if row['added_errors']:
  541. parts.append ('<p>new in the log:</p><pre>' + esc ('\n'.join (row['added_errors'])) + '</pre>')
  542. if row['fixed_errors']:
  543. parts.append ('<p>gone from the log:</p><pre>' + esc ('\n'.join (row['fixed_errors'])) + '</pre>')
  544. parts.append ('</body></html>')
  545. (report / 'index.html').write_text ('\n'.join (parts))
  546. def main ():
  547. parser = argparse.ArgumentParser (description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter)
  548. commands = parser.add_subparsers (dest = 'command', required = True)
  549. run = commands.add_parser ('run', help = 'render every wallpaper with one build')
  550. run.add_argument ('binary', type = Path, help = 'the linux-wallpaperengine executable to test')
  551. run.add_argument ('out', type = Path, help = 'folder for the screenshots and logs')
  552. run.add_argument ('--workshop', type = Path, default = env_path ('LWE_WORKSHOP_DIR', DEFAULT_WORKSHOP))
  553. run.add_argument ('--assets', type = Path, default = env_path ('LWE_ASSETS_DIR', DEFAULT_ASSETS))
  554. run.add_argument ('--ids', nargs = '*', help = 'only these workshop ids')
  555. run.add_argument ('--variants', type = Path, default = HERE / 'variants.json',
  556. help = 'extra renders with user properties set (default: variants.json next to this script)')
  557. run.add_argument ('--types', default = 'scene', help = 'project types to include, comma separated (default: scene)')
  558. run.add_argument ('--jobs', type = int, help = 'renders at once (default: cores/4 up to 8, cores/2 with --gpu)')
  559. run.add_argument ('--gpu', nargs = '?', const = 'auto', metavar = 'RENDER_NODE',
  560. help = 'render on the GPU without Xvfb, optionally on this /dev/dri/renderD* node')
  561. run.add_argument ('--frame', type = int, default = 30, help = 'frame to screenshot (default: 30)')
  562. run.add_argument ('--step', type = float, default = 0.1, help = 'animation seconds per frame (default: 0.1)')
  563. run.add_argument ('--clock', type = int, default = 1767268800, help = 'pinned wall clock, unix seconds')
  564. run.add_argument ('--width', type = int, default = 1280)
  565. run.add_argument ('--height', type = int, default = 720)
  566. run.add_argument ('--repeat', type = int, default = 1,
  567. help = 'renders per wallpaper; use 2+ for the base run so compare can ignore noise')
  568. run.add_argument ('--motion-gap', type = int, default = 5,
  569. help = 'frames between the two renders of wallpapers with gif/video textures (0 disables)')
  570. run.add_argument ('--timeout', type = float, default = 300, help = 'seconds per wallpaper')
  571. run.add_argument ('--memory-limit', type = float, default = 4, help = 'GB of data per engine (RLIMIT_DATA)')
  572. run.set_defaults (func = cmd_run)
  573. compare = commands.add_parser ('compare', help = 'compare two runs and write a report')
  574. compare.add_argument ('base', type = Path)
  575. compare.add_argument ('new', type = Path)
  576. compare.add_argument ('--report', type = Path, default = Path ('regression-report'))
  577. compare.add_argument ('--threshold', type = int, default = 16, help = 'per-channel difference that counts as changed')
  578. compare.add_argument ('--video-tolerance', type = float, default = 5,
  579. help = 'percent of changed pixels allowed with video textures, the motion check covers those')
  580. compare.add_argument ('--motion-min', type = float, default = 0.05,
  581. help = 'percent of pixels that must move in the base run for the motion check to apply')
  582. compare.add_argument ('--tolerance', type = float, default = 0.1, help = 'percent of changed pixels allowed')
  583. compare.set_defaults (func = cmd_compare)
  584. args = parser.parse_args ()
  585. args.func (args)
  586. if __name__ == '__main__':
  587. main ()