align_scan.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python3
  2. """Scores ours against the real-WE frames of an item after aligning the two timelines.
  3. align_scan.py <out dir> [ids or scene folders...] (REFS, LWE_WORKSHOP_DIR, LWE_ASSETS_DIR as for compare.py)
  4. phase_scan.py samples ours at fixed offsets, which is too coarse for a scene that changes fast (WE frames a second apart
  5. differing by 45) and cannot tell WE's own launch-to-launch offset (engine.runtime in WE includes the load time) from a
  6. real difference. This finds the frame of ours (fixed timestep, the WE rig's 15 fps, msaa x2, pointer at WE's position)
  7. that matches WE's first capture best, scanning coarsely and then a frame at a time around the minimum, and then scores
  8. the other WE frames at their capture times from there, taking the best of three neighbouring frames each. Items with a
  9. video texture also try the WE frames with red and blue exchanged (Wine draws some that way). An item that is the same in
  10. both engines ends at a few points or less; a larger value at the aligned frame is a real difference, whatever the diff
  11. looked like at other offsets.
  12. """
  13. import argparse
  14. import concurrent.futures
  15. import glob
  16. import json
  17. import os
  18. import re
  19. import shutil
  20. import sys
  21. import tempfile
  22. from pathlib import Path
  23. import numpy as np
  24. from PIL import Image
  25. HERE = Path(__file__).resolve().parent
  26. sys.path.insert(0, str(HERE.parent / 'regression'))
  27. import regress # noqa: E402
  28. REFS = os.environ.get('REFS', os.path.expanduser('~/.local/share/we_live/refs'))
  29. WORKSHOP = Path(os.environ.get('LWE_WORKSHOP_DIR', '/workspace/SteamLibrary/steamapps/workshop/content/431960'))
  30. ASSETS = Path(os.environ.get('LWE_ASSETS_DIR', '/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets'))
  31. FPS = 15
  32. def has_video_texture(item):
  33. path = Path(os.environ.get('LWE_LIBRARY_DIR', os.path.expanduser('~/.local/share/lwe-library'))) / 'features.json'
  34. try:
  35. return 'video-tex' in json.loads(path.read_text()).get(item, {}).get('features', {})
  36. except (OSError, ValueError):
  37. return False
  38. def load_we(item):
  39. files = sorted(glob.glob(f'{REFS}/{item}/f*.png'))
  40. times = [float(re.search(r'_(\d+(?:\.\d+)?)\.png$', os.path.basename(f)).group(1)) for f in files]
  41. return times, [np.asarray(Image.open(f).convert('RGB'))[30:1080, 4:1920].astype(np.float32) for f in files]
  42. class Renderer:
  43. def __init__(self, args, item, work):
  44. self.args, self.item, self.work, self.cache = args, item, work, {}
  45. def frame(self, number):
  46. if number in self.cache:
  47. return self.cache[number]
  48. ns = argparse.Namespace(binary = self.args.binary, width = 1920, height = 1058, frame = number, assets = ASSETS,
  49. timeout = 120, memory_limit = 8, step = 1 / FPS, clock = 0, gpu = 'auto', jobs = 1)
  50. env = regress.render_env(ns, '', None)
  51. env.pop('LWE_FIXED_CLOCK', None)
  52. env.pop('LD_PRELOAD', None)
  53. env['TZ'] = os.environ.get('TZ', 'Europe/Berlin')
  54. env['LWE_HEADLESS_CURSOR'] = '0.49792,0.51796'
  55. shot = self.work / f'{number}.png'
  56. status, _, _ = regress.render_once(ns, env, WORKSHOP / self.item, shot, self.work / f'{number}.log', [],
  57. ('--msaa', self.args.msaa, '--allow-parallax-overflow'))
  58. image = np.asarray(Image.open(shot).convert('RGB'))[0:1050, 0:1916].astype(np.float32) if status == 'ok' else None
  59. self.cache[number] = image
  60. return image
  61. def many(self, numbers, pool):
  62. todo = [n for n in numbers if n not in self.cache]
  63. list(pool.map(self.frame, todo))
  64. return {n: self.cache[n] for n in numbers}
  65. def score(we_frames, ours, swap):
  66. best = (1e9, False)
  67. for flipped in ((False, True) if swap else (False,)):
  68. target = we_frames[..., ::-1] if flipped else we_frames
  69. value = float(np.abs(target - ours).mean())
  70. best = min(best, (value, flipped))
  71. return best
  72. def scan_one(args, item, pool):
  73. key = Path(item).name
  74. times, frames = load_we(key)
  75. swap = has_video_texture(key)
  76. work = Path(tempfile.mkdtemp(prefix = 'align-', dir = args.out))
  77. renderer = Renderer(args, item, work)
  78. record = {'times': times}
  79. try:
  80. first = frames[0]
  81. coarse = renderer.many(list(range(args.first, args.last + 1, args.coarse)), pool)
  82. results = {n: score(first, img, swap)[0] for n, img in coarse.items() if img is not None}
  83. center = min(results, key = results.get)
  84. fine = renderer.many(list(range(max(center - args.coarse, 1), center + args.coarse + 1)), pool)
  85. results.update({n: score(first, img, swap)[0] for n, img in fine.items() if img is not None})
  86. start = min(results, key = results.get)
  87. record.update(align_frame = start, align_diff = round(results[start], 2),
  88. neighbours = {str(n): round(results[n], 1) for n in (start - 1, start + 1) if n in results})
  89. aligned = []
  90. for time, we in zip(times, frames):
  91. expected = start + round(time * FPS)
  92. near = renderer.many([expected - 1, expected, expected + 1], pool)
  93. best = min((score(we, img, swap) + (n,) for n, img in near.items() if img is not None), default = None)
  94. aligned.append({'t': time, 'diff': round(best[0], 2), 'swapped': best[1], 'frame': best[2]} if best else None)
  95. record['aligned'] = aligned
  96. record['mean_aligned'] = round(float(np.mean([a['diff'] for a in aligned if a])), 2)
  97. if args.keep and start in renderer.cache:
  98. pair = np.concatenate([first[..., ::-1] if swap and aligned[0] and aligned[0]['swapped'] else first,
  99. renderer.cache[start]], axis = 1)
  100. Image.fromarray(np.clip(pair, 0, 255).astype(np.uint8)).resize((1916, 525)).save(args.out / f'{key}.png')
  101. finally:
  102. shutil.rmtree(work, ignore_errors = True)
  103. return item, record
  104. def main():
  105. parser = argparse.ArgumentParser(description = __doc__.split('\n')[0])
  106. parser.add_argument('out', type = Path)
  107. parser.add_argument('ids', nargs = '*')
  108. parser.add_argument('--binary', type = Path, default = HERE.parent.parent / 'build/output/linux-wallpaperengine')
  109. parser.add_argument('--msaa', default = 'x2')
  110. parser.add_argument('--first', type = int, default = 30, help = 'first frame of the coarse scan (1/15 s each)')
  111. parser.add_argument('--last', type = int, default = 120)
  112. parser.add_argument('--coarse', type = int, default = 3)
  113. parser.add_argument('--jobs', type = int, default = 8)
  114. parser.add_argument('--keep', action = 'store_true', help = 'save the best aligned pair as <out>/<id>.png')
  115. args = parser.parse_args()
  116. args.out.mkdir(parents = True, exist_ok = True)
  117. path = args.out / 'align.json'
  118. results = json.loads(path.read_text()) if path.exists() else {}
  119. with concurrent.futures.ThreadPoolExecutor(args.jobs) as pool:
  120. for item in args.ids:
  121. if not glob.glob(f'{REFS}/{Path(item).name}/f*.png'):
  122. print(item, 'no WE frames')
  123. continue
  124. item, record = scan_one(args, item, pool)
  125. results[Path(item).name] = record
  126. print(Path(item).name, 'aligned frame', record.get('align_frame'), 'f000 diff', record.get('align_diff'), 'mean over frames',
  127. record.get('mean_aligned'), flush = True)
  128. path.write_text(json.dumps(results, indent = 1, sort_keys = True))
  129. if __name__ == '__main__':
  130. main()