phase_scan.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python3
  2. """Scores our render at many time offsets against every real-WE frame of an item.
  3. phase_scan.py <out dir> [ids...] (REFS, LWE_WORKSHOP_DIR, LWE_ASSETS_DIR as for compare.py)
  4. WE animates and its frames are taken a few seconds after the load, so one frame of ours says little when the two are at
  5. different points of a loop. This renders ours with a fixed timestep (1/30 s per frame) at --frames offsets, scores every
  6. render against every WE frame with compare.py's metric (mean absolute difference of the window crop) and keeps the best
  7. pair as <out>/<id>.png (WE | ours) with the whole table in <out>/phase.json. An item that is the same in both engines
  8. reaches the noise floor at some offset; one that stays high at every offset differs for a real reason.
  9. Clock and time zone are not pinned: WE under Wine reads the real clock too.
  10. """
  11. import argparse
  12. import concurrent.futures
  13. import glob
  14. import json
  15. import os
  16. import shutil
  17. import sys
  18. import tempfile
  19. from pathlib import Path
  20. import numpy as np
  21. from PIL import Image
  22. HERE = Path(__file__).resolve().parent
  23. sys.path.insert(0, str(HERE.parent / 'regression'))
  24. import regress # noqa: E402
  25. REFS = os.environ.get('REFS', os.path.expanduser('~/.local/share/we_live/refs'))
  26. WORKSHOP = Path(os.environ.get('LWE_WORKSHOP_DIR', '/workspace/SteamLibrary/steamapps/workshop/content/431960'))
  27. ASSETS = Path(os.environ.get('LWE_ASSETS_DIR', '/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets'))
  28. def has_video_texture(item):
  29. path = Path(os.environ.get('LWE_LIBRARY_DIR', os.path.expanduser('~/.local/share/lwe-library'))) / 'features.json'
  30. try:
  31. return 'video-tex' in json.loads(path.read_text()).get(item, {}).get('features', {})
  32. except (OSError, ValueError):
  33. return False
  34. def load_we(item, try_swap):
  35. """WE frames, plus the same frames with red and blue exchanged for items with a video texture: live WE under Wine
  36. draws some of those swapped (not all, 3155776049's are right), scan_one keeps whichever fits better."""
  37. frames = [np.asarray(Image.open(f).convert('RGB'))[30:1080, 4:1920].astype(np.float32)
  38. for f in sorted(glob.glob(f'{REFS}/{item}/f*.png'))]
  39. if try_swap and has_video_texture(item):
  40. return frames + [f[..., ::-1] for f in frames]
  41. return frames
  42. def scan_one(args, item, we):
  43. work = Path(tempfile.mkdtemp(prefix = 'phase-', dir = args.out))
  44. table = []
  45. best = (1e9, None, None, None)
  46. half = len(glob.glob(f'{REFS}/{item}/f*.png'))
  47. try:
  48. for frame in args.frames:
  49. ns = argparse.Namespace(binary = args.binary, width = 1920, height = 1058, frame = frame, assets = ASSETS,
  50. timeout = 120, memory_limit = 8, step = 1 / 30, clock = 0, gpu = 'auto', jobs = args.jobs)
  51. env = regress.render_env(ns, '', None)
  52. env.pop('LWE_FIXED_CLOCK', None)
  53. env.pop('LD_PRELOAD', None)
  54. env['TZ'] = os.environ.get('TZ', 'Europe/Berlin')
  55. env['LWE_HEADLESS_CURSOR'] = '0.49792,0.51796'
  56. shot = work / f'{frame}.png'
  57. status, _, _ = regress.render_once(ns, env, WORKSHOP / item, shot, work / f'{frame}.log', [], ('--msaa', args.msaa, '--allow-parallax-overflow'))
  58. if status != 'ok':
  59. table.append({'frame': frame, 'status': status})
  60. continue
  61. ours = np.asarray(Image.open(shot).convert('RGB'))[0:1050, 0:1916].astype(np.float32)
  62. diffs = [float(np.abs(w - ours).mean()) for w in we]
  63. k = int(np.argmin(diffs))
  64. table.append({'frame': frame, 'best_we': k % half, 'swapped': k >= half, 'diff': round(diffs[k], 2)})
  65. if diffs[k] < best[0]:
  66. best = (diffs[k], frame, k, ours)
  67. record = {'we_frames': len(we), 'table': table}
  68. if best[3] is not None:
  69. record.update(best_diff = round(best[0], 2), best_frame = best[1], best_we = best[2] % half, swapped = best[2] >= half)
  70. pair = np.concatenate([we[best[2]], best[3]], axis = 1)
  71. Image.fromarray(np.clip(pair, 0, 255).astype(np.uint8)).resize((1916, 525)).save(args.out / f'{item}.png')
  72. finally:
  73. shutil.rmtree(work, ignore_errors = True)
  74. return item, record
  75. def main():
  76. parser = argparse.ArgumentParser(description = __doc__.split('\n')[0])
  77. parser.add_argument('out', type = Path)
  78. parser.add_argument('ids', nargs = '*')
  79. parser.add_argument('--binary', type = Path, default = HERE.parent.parent / 'build/output/linux-wallpaperengine')
  80. parser.add_argument('--frames', type = lambda s: [int(x) for x in s.split(',')],
  81. default = list(range(15, 601, 15)), help = 'comma separated frame counts (default 15..600 step 15)')
  82. parser.add_argument('--jobs', type = int, default = 8)
  83. parser.add_argument('--msaa', default = 'x2', help = "anti-aliasing of the render, the rig's WE config has x2 (alpha to coverage sprites go black without it)")
  84. parser.add_argument('--swap-rb-video', action = 'store_true',
  85. help = 'also try the WE frames of video texture items with red and blue exchanged (Wine draws some that way)')
  86. args = parser.parse_args()
  87. args.out.mkdir(parents = True, exist_ok = True)
  88. ids = args.ids or sorted(p.name for p in Path(REFS).iterdir() if glob.glob(f'{p}/f*.png'))
  89. path = args.out / 'phase.json'
  90. results = json.loads(path.read_text()) if path.exists() else {}
  91. with concurrent.futures.ThreadPoolExecutor(args.jobs) as pool:
  92. futures = []
  93. for item in ids:
  94. we = load_we(item, args.swap_rb_video)
  95. if we and (WORKSHOP / item / 'project.json').exists():
  96. futures.append(pool.submit(scan_one, args, item, we))
  97. for done in concurrent.futures.as_completed(futures):
  98. item, record = done.result()
  99. results[item] = record
  100. print(item, record.get('best_diff'), 'frame', record.get('best_frame'), flush = True)
  101. path.write_text(json.dumps(results, indent = 1, sort_keys = True))
  102. if __name__ == '__main__':
  103. main()