render_we.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #!/usr/bin/env python3
  2. """Real Wallpaper Engine reference frames under Wine, a fresh WE instance per item.
  3. render_we.py [ids...] (default: every item in the scan.py database)
  4. render_we.py <dir|scene.json|scene.pkg> ... test scenes, frames go to $REFS/<dir name>
  5. Writes $REFS/<id>/f*.png (default ~/.local/share/we_live/refs; full :98 screen, window at +4+30) + we.log.
  6. Items that already have frames are skipped unless FORCE=1. Instead of fixed sleeps it waits until the window
  7. isn't a flat colour any more (the first rendered frame), then SETTLE seconds, then FRAMES frames INTERVAL
  8. seconds apart (env overrides). -control openWallpaper sent to a running instance doesn't switch wallpapers under
  9. Wine (it only brings the UI window back), hence one instance per item.
  10. Audio is pointed at dead sockets, see README.md. Setup of the Wine prefix: README.md.
  11. """
  12. import os, subprocess, sys, time
  13. import resource
  14. import numpy as np
  15. import mss
  16. from PIL import Image
  17. from Xlib import display as xdisplay
  18. S = os.environ.get('WE_LIVE_DIR', os.path.expanduser('~/.local/share/we_live'))
  19. HERE = os.path.dirname(os.path.abspath(__file__)) + '/wine'
  20. W = os.environ.get('LWE_WORKSHOP_DIR', '/workspace/SteamLibrary/steamapps/workshop/content/431960')
  21. LIB = os.environ.get('LWE_LIBRARY_DIR', os.path.expanduser('~/.local/share/lwe-library'))
  22. REFS = os.environ.get('REFS', S + '/refs')
  23. D = ':98'
  24. FRAMES = int(os.environ.get('FRAMES', 5))
  25. INTERVAL = float(os.environ.get('INTERVAL', 1.0))
  26. SETTLE = float(os.environ.get('SETTLE', 4.0))
  27. TIMEOUT = float(os.environ.get('SWITCH_TIMEOUT', 30))
  28. RETRIES = int(os.environ.get('RETRIES', 3))
  29. # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
  30. env = {k: v for k, v in os.environ.items() if k not in ('WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'DBUS_SESSION_BUS_ADDRESS')}
  31. env = dict(env, XDG_RUNTIME_DIR=S + '/run', WINEPREFIX=S + '/wineprefix', DISPLAY=D, WINEDEBUG='-all', DXVK_LOG_PATH=S,
  32. PULSE_SERVER=f'unix:{S}/run/no-pulse', PIPEWIRE_REMOTE=f'{S}/run/no-pipewire', ALSA_CONFIG_PATH=S + '/run/asound-null.conf')
  33. WINE = '/usr/lib/wine/wine64'
  34. we_proc = None
  35. log = None
  36. # no core files: the sandbox shares the desktop's user and its crash handler picks them up
  37. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  38. def winpath(p):
  39. return 'Z:' + p.replace('/', '\\')
  40. def grab(m):
  41. s = m.grab({'left': 0, 'top': 0, 'width': 1920, 'height': 1080})
  42. return Image.frombytes('RGB', s.size, s.rgb)
  43. def small(img):
  44. return np.asarray(img.crop((4, 30, 1920, 1080)).resize((240, 131))).astype(np.float32)
  45. def hide_ui():
  46. d = xdisplay.Display(D)
  47. root = d.screen().root
  48. def walk(w):
  49. # windows can disappear while walking the tree
  50. try:
  51. children = w.query_tree().children
  52. except Exception:
  53. return
  54. for c in children:
  55. yield c
  56. yield from walk(c)
  57. for w in walk(root):
  58. try:
  59. if w.get_wm_name() == 'Wallpaper UI':
  60. w.unmap()
  61. except Exception:
  62. pass
  63. try:
  64. top = root.query_tree().children
  65. except Exception:
  66. top = []
  67. for w in top:
  68. try:
  69. g = w.get_geometry()
  70. if w.get_attributes().map_state == 2 and min(g.width, g.height) <= 20 and (g.width, g.height) != (1, 1):
  71. w.unmap()
  72. except Exception:
  73. pass
  74. d.sync()
  75. d.close()
  76. def start_we(first):
  77. global we_proc, log
  78. subprocess.run(['/usr/lib/wine/wineserver', '-k'], env=env, stderr=subprocess.DEVNULL)
  79. time.sleep(1)
  80. log = open(S + '/we_run_last.log', 'w')
  81. we_proc = subprocess.Popen([WINE, 'wallpaper64.exe', '-control', 'openWallpaper', '-file', winpath(first),
  82. '-monitor', '0', '-playInWindow', '-silent'], cwd=S + '/we28', env=env,
  83. stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True)
  84. def wait_rendered(m, t0, timeout):
  85. """until the window isn't a flat colour any more, or timeout"""
  86. while time.time() - t0 < timeout:
  87. hide_ui()
  88. if small(grab(m)).std() > 3:
  89. return True
  90. time.sleep(0.3)
  91. return False
  92. def item_file(id_, info):
  93. if info.get('type') == 'scene':
  94. # "file" is scene.json, or gifscene.json for gif scenes, packed into the .pkg of the same name
  95. name = info.get('file') or 'scene.json'
  96. pkg = os.path.join(W, id_, os.path.splitext(name)[0] + '.pkg')
  97. return pkg if os.path.exists(pkg) else os.path.join(W, id_, name)
  98. return os.path.join(W, id_, 'project.json')
  99. def main():
  100. import json, glob
  101. db = json.load(open(LIB + '/features.json'))
  102. ids = sys.argv[1:] or sorted(db)
  103. if not os.environ.get('FORCE'):
  104. ids = [i for i in ids if os.path.exists(i) or not glob.glob(f'{REFS}/{i}/f*.png')]
  105. out_root = REFS
  106. files = []
  107. for n, i in enumerate(ids):
  108. if os.path.exists(i):
  109. path = os.path.abspath(i)
  110. files.append(path + '/scene.json' if os.path.isdir(path) else path)
  111. ids[n] = os.path.basename(path if os.path.isdir(path) else os.path.dirname(path))
  112. else:
  113. files.append(item_file(i, db.get(i, {}).get('info', {})))
  114. subprocess.run(['bash', HERE + '/we_display.sh'], stdout=subprocess.DEVNULL, check=True)
  115. with mss.MSS(display=D) as m:
  116. for n, f in enumerate(files):
  117. id_ = ids[n]
  118. out = os.path.join(out_root, id_)
  119. os.makedirs(out, exist_ok=True)
  120. for old in os.listdir(out):
  121. os.remove(os.path.join(out, old))
  122. t0 = time.time()
  123. # scenes with video textures sometimes never get past a flat first frame under Wine, a new
  124. # instance usually does
  125. for attempt in range(RETRIES):
  126. start = time.time()
  127. start_we(f)
  128. # the killed instance's window must be gone before "not flat" means anything
  129. while time.time() - start < 10 and small(grab(m)).std() > 3:
  130. time.sleep(0.2)
  131. ok = wait_rendered(m, start, TIMEOUT)
  132. if ok:
  133. break
  134. time.sleep(SETTLE)
  135. hide_ui()
  136. t1 = time.time()
  137. last = None
  138. for i in range(FRAMES):
  139. last = grab(m)
  140. last.save('%s/f%03d_%.1f.png' % (out, i, time.time() - t1))
  141. time.sleep(INTERVAL)
  142. log.flush()
  143. try:
  144. with open(S + '/we_run_last.log', errors='replace') as src, open(out + '/we.log', 'w') as dst:
  145. dst.write(src.read()[-20000:])
  146. except OSError:
  147. pass
  148. print(f'we {id_} {FRAMES} frames{"" if ok else " (still flat)"} {time.time() - t0:.1f}s', flush=True)
  149. subprocess.run(['/usr/lib/wine/wineserver', '-k'], env=env, stderr=subprocess.DEVNULL)
  150. if __name__ == '__main__':
  151. main()