#!/usr/bin/env python3 """Capture a COPIED original in a filesystem/network-isolated Wine environment. Requires project-local Wine and Xvfb plus bubblewrap and ImageMagick. Host mode does not execute Wine directly: only the game copy and generated prefix are writable inside the namespace, and the original directory is not mounted. """ import argparse import ctypes import json import os from pathlib import Path import shutil import subprocess import time def enter_key(): x = ctypes.CDLL('libX11.so.6') x.XOpenDisplay.argtypes = [ctypes.c_char_p] x.XOpenDisplay.restype = ctypes.c_void_p x.XKeysymToKeycode.argtypes = [ctypes.c_void_p, ctypes.c_ulong] x.XKeysymToKeycode.restype = ctypes.c_uint x.XFlush.argtypes = [ctypes.c_void_p] x.XCloseDisplay.argtypes = [ctypes.c_void_p] display = x.XOpenDisplay(None) if not display: return False test = ctypes.CDLL('libXtst.so.6') test.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong] key = x.XKeysymToKeycode(display, 0xff0d) test.XTestFakeKeyEvent(display, key, 1, 0) test.XTestFakeKeyEvent(display, key, 0, 0) x.XFlush(display) x.XCloseDisplay(display) return True def inside(args): work = Path('/work') with (work/'xvfb.log').open('w') as xlog, (work/'wine.log').open('w') as wlog: display = subprocess.Popen(['/native/usr/bin/Xvfb', ':89', '-screen', '0', '1024x768x24', '-nolisten', 'tcp'], stdout=xlog, stderr=xlog) wine = None try: for _ in range(30): if Path('/tmp/.X11-unix/X89').exists(): break if display.poll() is not None: raise RuntimeError('Xvfb failed; see xvfb.log') time.sleep(0.1) wine_env = dict(os.environ, LIBGL_DRIVERS_PATH='/native/usr/lib/i386-linux-gnu/dri') wine = subprocess.Popen(['/opt/wine-stable/bin/wine', args.game], cwd='/work/game', stdout=wlog, stderr=wlog, env=wine_env) captures = [] for index in range(3): time.sleep(args.seconds / 3) target = f'/work/frame-{index:02d}.png' image = subprocess.run(['import', '-display', ':89', '-window', 'root', target], timeout=10, capture_output=True) captures.append({'file': target, 'captureExit': image.returncode, 'wineExit': wine.poll()}) if args.enter: captures[-1]['sentReturn'] = enter_key() tree = subprocess.run(['xwininfo', '-root', '-tree'], capture_output=True, text=True) (work/'windows.txt').write_text(tree.stdout + tree.stderr) processes = [] for path in Path('/proc').glob('[0-9]*/cmdline'): try: processes.append(path.parent.name + ': ' + path.read_bytes().replace(b'\x00', b' ').decode('utf8', 'replace')) except OSError: pass (work/'processes.txt').write_text('\n'.join(processes)+'\n') (work/'capture.json').write_text(json.dumps({'game': args.game, 'captures': captures}, indent=2)+'\n') finally: subprocess.run(['/opt/wine-stable/bin/wineserver', '-k'], timeout=10, check=False) if wine and wine.poll() is None: wine.terminate() display.terminate() display.wait(timeout=5) def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--inside', action='store_true', help=argparse.SUPPRESS) p.add_argument('--game', choices=['Neutron.exe','NeutronNoCD.exe','NeutronSW.exe','NeutronHD.exe','NeutronHDnoCD.exe'], default='NeutronNoCD.exe') p.add_argument('--seconds', type=int, default=24) p.add_argument('--enter', action='store_true', help='Send Return after each screenshot') p.add_argument('--debug', action='store_true', help='Record Wine process and exception diagnostics') p.add_argument('--wine-renderer', choices=['gl','vulkan'], default='gl') p.add_argument('--output', type=Path) args = p.parse_args() if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120') if args.inside: return inside(args) project = Path(__file__).resolve().parents[2] source = project.parent/'Original' work = (args.output or project/'artifacts/reference').resolve() if work.is_relative_to(source.resolve()) or source.resolve().is_relative_to(work): p.error('Output must be separate from originals') work.mkdir(parents=True, exist_ok=True) if not (work/'game').exists(): shutil.copytree(source, work/'game') (work/'home').mkdir(exist_ok=True) (work/'home/.asoundrc').write_text('pcm.!default { type null }\nctl.!default { type hw card 0 }\n') (work/'alsa-null.conf').write_text('pcm.default { type null }\npcm.null { type null }\n') cmd = ['bwrap', '--unshare-all', '--new-session', '--die-with-parent', '--clearenv', '--ro-bind', '/usr', '/usr', '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64', '--symlink', 'usr/bin', '/bin', '--symlink', 'usr/sbin', '/sbin', '--ro-bind', '/etc', '/etc', '--ro-bind', '/sys', '/sys', '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', '--dir', '/tmp/.X11-unix', '--tmpfs', '/var', '--dir', '/var/tmp', '--dir', '/run', '--dir', '/home', '--bind', str(work), '/work', '--ro-bind', str(project/'.tools/wine/opt/wine-stable'), '/opt/wine-stable', '--ro-bind', str(project/'.tools/native'), '/native', '--ro-bind', str(Path(__file__).resolve()), '/capture.py'] for key,value in {'HOME':'/work/home', 'WINEPREFIX':'/work/prefix', 'WINEARCH':'win32', 'DISPLAY':':89', 'PATH':'/opt/wine-stable/bin:/usr/bin:/bin', 'LANG':'C.UTF-8', 'WINEDEBUG':'-all,err+all,warn+ddraw,warn+d3d,+seh' if args.debug else '-all', 'ALSA_CONFIG_PATH':'/work/alsa-null.conf', 'WINEDLLOVERRIDES':'mscoree,mshtml=', 'WINE_D3D_CONFIG':'renderer='+args.wine_renderer, 'LD_LIBRARY_PATH':'/native/usr/lib/x86_64-linux-gnu:/native/usr/lib/i386-linux-gnu', 'LIBGL_ALWAYS_SOFTWARE':'1', '__GLX_VENDOR_LIBRARY_NAME':'mesa', '__EGL_VENDOR_LIBRARY_FILENAMES':'/usr/share/glvnd/egl_vendor.d/50_mesa.json'}.items(): cmd += ['--setenv', key, value] if args.wine_renderer == 'vulkan': cmd += ['--setenv', 'VK_DRIVER_FILES', '/native/usr/share/vulkan/icd.d/lvp_icd.json'] cmd += ['/usr/bin/python3', '/capture.py', '--inside', '--game', args.game, '--seconds', str(args.seconds)] if args.enter: cmd += ['--enter'] print('Running copied original with no network and no original-directory mount:', work, flush=True) subprocess.run(cmd, check=True, timeout=args.seconds + 40) print('Capture metadata:', work/'capture.json') if __name__ == '__main__': main()