Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
327 lines (288 loc) · 16.9 KB
/
Copy pathrun.py
File metadata and controls
327 lines (288 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Prepares an Uncharted executable of the Nathan Drake Collection and starts bb-probe.exe.
BB_GAME_DIR the game folder (CUSA02343, CUSA02320, ...; the one with eboot.bin)
BB_GAME_DIR_U1 / _U2 / _U3 optional: the folder of a game that was dumped on its own; used for
that game instead of BB_GAME_DIR (its executable may be that folder's eboot.bin)
BB_EXE u1 / u2 / u3 or an executable name (default u1: eboot.bin, the collection menu)
BB_USER_DIR saves and shader caches (default user/ beside this script)
BB_SKIP_COLLECTION_MENU=1 u1 starts at Drake's Fortune's title, not the collection menu
Extra arguments go to bb-probe. When the game starts another executable of the collection
(sceSystemServiceLoadExec), that one is prepared and started in its place.
The in-game "Apply and restart" runs this script again through BB_RESTART_COMMAND;
`--after PID` waits for the previous game process to end first (its GPU device and memory).
"""
import ctypes
import os
from pathlib import Path
import subprocess
import sys
class _QuietStream:
"""stdout/stderr that never fail: started without a usable console (the launcher, Steam, a game switch
from the collection menu), a print raised OSError [Errno 22] and the game switch stopped (upstream #830)."""
def __init__(self, stream):
self.stream = stream
def write(self, text):
try:
return self.stream.write(text) if self.stream else len(text)
except (OSError, ValueError):
return len(text)
def flush(self):
try:
if self.stream:
self.stream.flush()
except (OSError, ValueError):
pass
def __getattr__(self, name):
return getattr(self.stream, name)
def __bool__(self):
return bool(self.stream)
# No stream at all (pythonw): left as None, which print() already skips and main()'s `if stream:` checks.
sys.stdout = _QuietStream(sys.stdout) if sys.stdout else sys.stdout
sys.stderr = _QuietStream(sys.stderr) if sys.stderr else sys.stderr
PORT = Path(__file__).resolve().parent
sys.path.insert(0, str(PORT / 'scripts'))
import cheats
from prepare import collection_folder
EXECUTABLES = {'u1': 'eboot.bin', 'u2': 'big2-ps4_Shipping.elf', 'u3': 'big3-ps4_Shipping.elf'}
LOADEXEC_EXIT = 101 # runtime_services.c: the game asked for another executable
def fail(message):
print(message, file=sys.stderr)
sys.exit(1)
def wait_for(pid):
kernel32 = ctypes.windll.kernel32
SYNCHRONIZE = 0x00100000
handle = kernel32.OpenProcess(SYNCHRONIZE, False, pid)
if handle:
kernel32.WaitForSingleObject(handle, 30000)
kernel32.CloseHandle(handle)
def no_console():
"""Started without a console (the launcher): console programs must not open their own."""
return 0 if ctypes.windll.kernel32.GetConsoleWindow() else subprocess.CREATE_NO_WINDOW
def run_script(name, *args):
# Inside the packaged executable (PyInstaller) the executable runs scripts itself.
script = ['--script'] if getattr(sys, 'frozen', False) else []
command = [sys.executable, *script, str(PORT / 'scripts' / name), *map(str, args)]
# stdin given: the output handles are passed explicitly (a windowed child would get none).
result = subprocess.run(command, stdin=subprocess.DEVNULL, creationflags=no_console())
if result.returncode:
sys.exit(result.returncode)
def find_executable(name):
"""bin/ (packaged), else out/ (built with build.sh)."""
for candidate in (PORT / 'bin' / name, PORT / 'out' / name):
if candidate.is_file():
return candidate
return None
def executable_name(value):
return EXECUTABLES.get(value.lower(), value) if value else EXECUTABLES['u1']
def locate(env, name):
"""(folder, executable file) for one of the collection's executables. A game dumped on its own
(BB_GAME_DIR_U1/U2/U3) comes from its folder, where the game may be that folder's eboot.bin."""
key = next((k for k, v in EXECUTABLES.items() if v == name), '')
own = env.get(f'BB_GAME_DIR_{key.upper()}', '') if key else ''
folder = own or env.get('BB_GAME_DIR', '')
if not folder:
return None, name
folder = Path(folder)
# Not in a collection folder: there eboot.bin is Uncharted 1, and an incomplete dump without
# big2/big3 started Uncharted 1 on half its files (a player's log, 2026-11-01).
if own and not (folder / name).is_file() and (folder / 'eboot.bin').is_file() \
and not collection_folder(folder):
name = 'eboot.bin'
return folder, name
def game_cheats(enabled, exe):
"""BB_CHEATS ("u1:health,u2:ammo") reduced to the running executable's own entries ("health")."""
key = next((k for k, name in EXECUTABLES.items() if name == exe), None)
return ','.join(c.split(':', 1)[1] for c in enabled.split(',') if key and c.startswith(f'{key}:'))
def prepare(game, exe, out):
"""boot-linked.bin for one executable, kept until the executable or the scripts change."""
out.mkdir(parents=True, exist_ok=True)
linked = out / 'boot-linked.bin'
# Which executable the files in out/ were made from: another folder (a per-game one) needs a new run.
stamp, source = out / 'source.txt', str(game / exe)
sources = [game / exe, *(PORT / 'scripts').glob('*.py'),
*(game / 'sce_module').glob('*.prx')]
if linked.is_file() and all(linked.stat().st_mtime >= s.stat().st_mtime for s in sources):
if not stamp.is_file():
stamp.write_text(source, encoding='utf-8')
if stamp.read_text(encoding='utf-8', errors='replace') == source:
return
print(f'Preparing {exe} ...')
run_script('prepare.py', game, '--out', out, '--exe', exe)
run_script('link_modules.py', game, '--out', out, '--exe', exe)
stamp.write_text(source, encoding='utf-8')
def isa_rewrite_args(probe, out):
"""['--isa-rewrite', table] when this CPU lacks instructions the game uses (Intel Sandy and Ivy Bridge:
BMI1, MOVBE, LZCNT, F16C), else []. bb-probe rewrites those instructions at load time from a table of
their places (scripts/isa_rewrite.py, needs the Python package iced-x86). BB_FORCE_LEGACY_CPU=1
does it on any CPU (tests)."""
check = subprocess.run([str(probe), '--cpu-features'], stdin=subprocess.DEVNULL, capture_output=True,
text=True, errors='replace', creationflags=no_console())
if check.returncode: # AVX, SSE4.2 or POPCNT missing: bb-probe has shown why
sys.stderr.write(check.stderr)
sys.exit(check.returncode)
missing = check.stdout.strip()
if not missing.startswith('CPU: missing'):
return []
print(f"{missing}; the game's instructions of those sets are rewritten at load time", flush=True)
table, linked = out / 'isa-rewrite.bin', out / 'boot-linked.bin'
if not table.is_file() or table.stat().st_mtime < max(linked.stat().st_mtime, (PORT / 'scripts' / 'isa_rewrite.py').stat().st_mtime):
try:
run_script('isa_rewrite.py', linked, '--out', out)
except SystemExit:
if missing == 'CPU: missing MOVBE' and not os.environ.get('BB_FORCE_LEGACY_CPU'):
return [] # AMD FX without iced-x86: bb-probe emulates its MOVBE in the fault handler, as before
fail(f'{missing}\nThe game needs its instructions rewritten for this processor, which needs the Python '
'package iced-x86 (pip install iced-x86) in the Python that runs this script.')
return ['--isa-rewrite', table]
def adopt_saves_cache(old, new):
"""Up to 0.3.6.31 the shader cache lived in the saves folder (old); now it lives in the install (new). Copy what
the install lacks from the saves folder once: the game folders (<title id>-<build>) and the shader locations
(shader_locations_<title id>.txt). Without them the first start rebuilds every shader and, with no saved
locations, may read all the game files (many minutes on a hard drive). The saves folder keeps its copy for
older versions. Each folder is copied aside and renamed, so a cut copy is redone next time."""
import shutil
try:
if not old.is_dir() or old.resolve() == new.resolve():
return
new.mkdir(parents=True, exist_ok=True)
for item in sorted(old.iterdir()):
target = new / item.name
if target.exists():
continue
if item.is_dir() and '.' not in item.name:
print(f'Shader cache: copying {item.name} from the saves folder ...', flush=True)
partial = new / f'{item.name}.copying'
shutil.rmtree(partial, ignore_errors=True)
shutil.copytree(item, partial)
partial.rename(target)
elif item.is_file() and item.name.startswith('shader_locations_') and item.suffix == '.txt':
shutil.copy2(item, target)
print(f'Shader cache: copied {item.name} from the saves folder', flush=True)
except OSError as error:
print(f'Shader cache: could not copy from the saves folder ({error}); the shaders are built again',
flush=True)
def main():
args = sys.argv[1:]
if len(args) >= 2 and args[0] == '--after':
wait_for(int(args[1]))
args = args[2:]
os.chdir(PORT)
# Paths and titles can hold characters the console code page (GBK, ...) lacks: never fail on a print.
# Pipes (the launcher reads them as UTF-8) get UTF-8; a real console keeps its own encoding.
for stream in (sys.stdout, sys.stderr):
if stream:
stream.reconfigure(errors='replace', **({} if stream.isatty() else {'encoding': 'utf-8'}))
env = os.environ
# Game titles carry "™": the scripts must not fall back to the Windows code page.
env['PYTHONUTF8'] = '1'
env['PYTHONIOENCODING'] = 'utf-8'
data = Path(env.get('BB_DATA_DIR', PORT))
out_root = data / 'out'
env.setdefault('BB_CONFIG', str(data / 'bbport.ini'))
# Keyboard, mouse and controller bindings (the launcher's Controls page).
env.setdefault('BB_INPUT_CONFIG', str(data / 'input.ini'))
# The collection's renderer (all three games): the camera velocity pass of the motion blur
# (its constants give the motion vectors), the compute pass after the scene is lit, before
# the post-processing, where DLSS/FSR/TAA and frame generation take it, and the pass that
# writes the finished picture before the UI (docs/upscaler.md).
env.setdefault('BB_VELOCITY_PS', 'f4b18264')
env.setdefault('BB_UPSCALE_BEFORE_CS', 'aec539f0')
env.setdefault('BB_HUDLESS_PS', '484cdbf5')
# Full-screen passes that rebuild positions from the jittered scene depth get the upscaler's
# jitter too: U1's sun shadow pass (kj2223's fork; without it its shadows flickered), U1's
# boat details and U3's London bar surfaces drawn against secondary scene depth (Alex,
# upstream 0.3.12; they flickered too).
env.setdefault('BB_JITTER_PS', 'f614041e,b2a42acf,1a08df2d')
if not env.get('BB_FSR411_DIR') and not (PORT / 'fsr4_411').is_dir() and (data / 'fsr4_411').is_dir():
env['BB_FSR411_DIR'] = str(data / 'fsr4_411')
probe = Path(env['BB_PROBE']) if env.get('BB_PROBE') else find_executable('bb-probe.exe')
if not probe or not probe.is_file():
fail('bb-probe.exe not found: build it with build.sh (MSYS2 CLANG64) or use a packaged build.')
# Development builds run from the MSYS2 tree: its CLANG64 DLLs (SDL3, FFmpeg, ...).
if not (probe.parent / 'SDL3.dll').is_file():
clang64 = Path(env.get('MSYS2_ROOT', r'C:\msys64')) / 'clang64' / 'bin'
if clang64.is_dir():
env['PATH'] = f'{clang64}{os.pathsep}{env.get("PATH", "")}'
exe = executable_name(env.get('BB_EXE', ''))
user_dir = Path(env.get('BB_USER_DIR', data / 'user')).resolve()
user_dir.mkdir(parents=True, exist_ok=True)
# GPU caches (shaders, pipelines) beside the saves; read before main(), so set here.
env.setdefault('BB_GPU_USER_DIR', str(user_dir))
# The shader cache stays beside this install even when the saves (BB_USER_DIR) are elsewhere: each version of the
# port keeps its own (BB_GPU_CACHE_DIR overrides).
if 'BB_GPU_CACHE_DIR' not in env:
env['BB_GPU_CACHE_DIR'] = str((data / 'user' / 'cache').resolve())
adopt_saves_cache(user_dir / 'cache', Path(env['BB_GPU_CACHE_DIR']))
env.setdefault('BB_VBLANK_HZ', '60')
loadexec = out_root / 'loadexec.txt'
env['BB_LOADEXEC_FILE'] = str(loadexec)
guest_argv = None
all_cheats = env.setdefault('BB_CHEATS_ALL', env.get('BB_CHEATS', ''))
while True:
game, file = locate(env, exe)
if not game:
fail('Set BB_GAME_DIR to the game folder (the one with eboot.bin).')
if not (game / file).is_file():
fail(f'No {file} in {game}: the game dump is incomplete (extract the game again) or the wrong folder '
'is chosen for this game.')
out = out_root / Path(exe).stem.split('-')[0]
prepare(game, file, out)
run_script('content_profile.py', game, '--out', out, '--sku', env.get('BB_CONTENT_SKU', 'full'))
# The trophy set of this game (its texts in the console language, the icons) for the runtime.
trophy_dir = out / 'trophy'
key = next((k for k, v in EXECUTABLES.items() if v == exe), '')
if key:
language = env.get('BB_LANGUAGE', '1')
run_script('trophies.py', game, '--out', trophy_dir, '--exe', key,
'--lang', language if language.isdigit() else '1',
*(['--own'] if env.get(f'BB_GAME_DIR_{key.upper()}') else []))
this = ['--run'] if getattr(sys, 'frozen', False) else [str(Path(__file__).resolve())]
env['BB_EXE'] = exe
env['BB_CHEATS'] = game_cheats(all_cheats, exe)
# Unlock all rewards (launcher Game page, BB_UNLOCK_REWARDS=1): every game, code patches + kept switches.
enabled = [c for c in env['BB_CHEATS'].split(',') if c] + (['rewards'] if env.get('BB_UNLOCK_REWARDS') == '1'
else [])
# Extra quality (launcher Display): Uncharted 2 and 3's full-resolution textures and hi-res local shadow switches
enabled += (['fullres'] if env.get('BB_FULL_RES_TEXTURES') == '1' else []) + (['hiresshadow'] if env.get('BB_HIRES_SHADOWS') == '1' else []) + (['nodof'] if env.get('BB_DOF') == '0' and env.get('BB_DOF_ENGINE', '1') != '0' else []) # Depth of field: Off everywhere
patches = cheats.build(game / exe, out, enabled)
env['BB_KEEP_BYTES'] = cheats.keep_bytes(game / exe, enabled)
# Developer mode: where its debug text switch is (F7 turns the text on and off, runtime_pad.c).
env['BB_DEV_TEXT_SWITCH'] = (cheats.dev_text_switch(game / exe)
if {'devmode', 'devmode_quiet'} & set(enabled) else '')
env['BB_RESTART_COMMAND'] = subprocess.list2cmdline([sys.executable, *this, '--after', str(os.getpid()), *args])
command = [str(probe), str(out / 'boot-linked.bin'), '--content-profile', str(out / 'content.bin'),
'--app0', str(game), '--user', str(user_dir), '--timeout', env.get('BB_TIMEOUT', '0')]
command += isa_rewrite_args(probe, out)
if patches:
command += ['--patches', str(patches)]
if guest_argv:
command += ['--guest-argv', str(guest_argv)]
if key and (trophy_dir / 'trophies.txt').is_file():
command += ['--trophies', str(trophy_dir)]
loadexec.unlink(missing_ok=True)
# No stdin: an inherited pipe (shells such as Git Bash) cost the game its console output.
code = subprocess.run([*command, *args], stdin=subprocess.DEVNULL, creationflags=no_console()).returncode
if code != LOADEXEC_EXIT or not loadexec.is_file():
return code
lines = loadexec.read_text(encoding='utf-8', errors='replace').splitlines()
target = Path(lines[0].replace('\\', '/')).name if lines else ''
if not target:
fail('The game asked for another executable without a name.')
print(f'Switching to {target}')
exe = target
# Back from U2/U3 the collection menu shows again (the skip is for the first start).
env.pop('BB_SKIP_COLLECTION_MENU', None)
# The window of the game the player picked takes the focus (window.cpp).
env['BB_RAISE_WINDOW'] = '1'
# The arguments given to sceSystemServiceLoadExec are the whole argv, argv[0] included
# (the collection menu passes "eboot.bin", "ispartofuccollection"). Put after the path, the
# program name became U2's and U3's first argument, which they load as a level: a white
# screen. Without arguments the path is argv[0].
guest_argv = out_root / 'guest-argv.txt'
guest_argv.write_text('\n'.join(lines[1:] or lines[:1]) + '\n', encoding='utf-8')
if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)