Files
Neutron/tools/recon/reference_capture.py
T

144 lines
8.4 KiB
Python

#!/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')
application = ['/opt/wine-stable/bin/wine', args.game]
if args.port_smoke:
application = ['/opt/wine-stable/bin/wine', r'Z:\port\GamePort.exe',
'--assets', r'Z:\port\assets', '--scene', r'Z:\port\scenes\level1b\scene.json',
'--level', 'gam/level1b.gam', '--original-camera', '--with-player',
'--headless', '--frames', '2', '--time', '0.05', '--no-validation',
'--screenshot', r'Z:\work\port-frame.ppm']
wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/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()
if args.port_smoke and wine.poll() is not None: break
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': 'GamePort.exe' if args.port_smoke else 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('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation')
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/windows-smoke' if args.port_smoke else '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 args.port_smoke and 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']
if args.port_smoke:
cmd += ['--ro-bind', str(project/'dist/win-x64'), '/port']
for key,value in {'HOME':'/work/home', 'WINEPREFIX':'/work/prefix', 'WINEARCH':'win64' if args.port_smoke else '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=b;mshtml=' if args.port_smoke else '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.port_smoke:
cmd += ['--setenv', 'VK_DRIVER_FILES', '/usr/share/vulkan/icd.d/lvp_icd.json']
elif 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']
if args.port_smoke: cmd += ['--port-smoke']
print('Running isolated Windows port' if args.port_smoke else '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 args.port_smoke:
result = json.loads((work/'capture.json').read_text())
if result['captures'][-1]['wineExit'] != 0 or not (work/'port-frame.ppm').is_file():
raise SystemExit('Windows port smoke did not pass; inspect wine.log (native Windows remains unverified)')
print('Windows port rendered under Wine; native Windows validation is still required')
if __name__ == '__main__': main()