Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
476 lines (438 loc) · 21.3 KB
/
Copy pathrun.py
File metadata and controls
476 lines (438 loc) · 21.3 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Prepares the game image and starts the native probe (Windows and Linux; run.sh wraps it on Linux).
Environment variables (THEORDER_GAME_DIR, THEORDER_DATA_DIR,
THEORDER_PATCHES, THEORDER_MODS_* / THEORDER_MODS_*, THEORDER_USER_DIR, ...).
Extra arguments go to the game probe.
The in-game "Apply and restart" runs this script again through THEORDER_RESTART_COMMAND;
`--after PID` waits for the previous game process to end first (its GPU device and memory).
"""
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import time
WINDOWS = sys.platform == 'win32'
EXE_SUFFIX = '.exe' if WINDOWS else ''
if WINDOWS:
import ctypes
PORT = Path(__file__).resolve().parent
def fail(message):
print(message, file=sys.stderr)
sys.exit(1)
def wait_for(pid):
if not WINDOWS:
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
os.kill(pid, 0)
except ProcessLookupError:
return
except PermissionError:
pass
time.sleep(0.1)
return
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."""
if not WINDOWS:
return 0
return 0 if ctypes.windll.kernel32.GetConsoleWindow() else subprocess.CREATE_NO_WINDOW
def parse_cpu_features(output):
"""Instruction sets `theorder-probe --cpu-features` reports missing ([] when complete)."""
for line in output.splitlines():
if line.startswith('CPU: missing '):
return [name.strip() for name in line[len('CPU: missing '):].split(',') if name.strip()]
return []
def isa_rewrite_wanted(missing, env):
"""THEORDER_ISA_REWRITE=1 forces the ISA rewrite table, 0 disables it; otherwise the CPU decides."""
policy = get_env(env, 'ISA_REWRITE')
if policy in ('0', '1'):
return policy == '1'
return bool(missing)
def run_script(name, *args, capture=False, check=True):
# Inside the packaged launcher 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)]
env = {**os.environ, 'PYTHONIOENCODING': 'utf-8'}
if capture:
result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True,
encoding='utf-8', env=env, creationflags=no_console())
if not check:
return result.returncode, result.stdout
if result.returncode:
sys.exit(result.returncode)
return result.stdout
# stdin given: the output handles are passed explicitly (a windowed launcher child would
# get none otherwise).
result = subprocess.run(command, stdin=subprocess.DEVNULL, env=env, creationflags=no_console())
if result.returncode:
sys.exit(result.returncode)
return None
def launch_prefix(env):
"""Linux integrations chosen in the launcher: MangoHud is its Vulkan layer (an environment
variable), GameMode a command that starts the game."""
if WINDOWS:
return []
if get_env(env, 'MANGOHUD') == '1':
env.setdefault('MANGOHUD', '1')
if get_env(env, 'GAMEMODE') == '1':
if gamemode := shutil.which('gamemoderun'):
return [gamemode]
print('GameMode: gamemoderun not found, starting without it', flush=True)
return []
def get_env(env, key, default=None):
"""The environment variable THEORDER_<key>, or default."""
return env.get(f'THEORDER_{key}', default)
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
PS4_TO_ENGINE_LANG = {
0: 18, 1: 0, 2: 2, 3: 5, 4: 4, 5: 3, 6: 6, 7: 7, 8: 8,
9: 19, 10: 21, 11: 20, 12: 12, 13: 10, 14: 13, 15: 11,
16: 9, 17: 17, 18: 1, 19: 15, 20: 16
}
LANG_CODE_TO_PS4 = {
'ja': 0, 'japanese': 0,
'en': 1, 'en-us': 1, 'us': 1, 'english': 1,
'fr': 2, 'french': 2,
'es': 3, 'es-es': 3, 'spanish': 3,
'de': 4, 'german': 4,
'it': 5, 'italian': 5,
'nl': 6, 'dutch': 6,
'pt-pt': 7,
'ru': 8, 'russian': 8,
'ko': 9, 'korean': 9,
'zh-hant': 10, 'zh-hans': 11,
'fi': 12, 'finnish': 12,
'sv': 13, 'swedish': 13,
'da': 14, 'danish': 14,
'no': 15, 'norwegian': 15,
'pl': 16, 'polish': 16,
'pt': 17, 'pt-br': 17, 'br': 17, 'portuguese': 17,
'en-gb': 18, 'uk': 18,
'tr': 19, 'turkish': 19,
'es-419': 20, 'es-la': 20, 'la': 20,
'ar': 21, 'arabic': 21
}
def resolve_language(cli_lang, env, ini_path, graphics_options=None):
for candidate in (cli_lang, get_env(env, 'LANGUAGE')):
if candidate is not None:
val = str(candidate).strip().lower()
if val in LANG_CODE_TO_PS4:
return LANG_CODE_TO_PS4[val]
if val.isdigit():
return int(val)
if graphics_options:
ini_vals = graphics_options.read_ini(ini_path)
if 'language' in ini_vals:
val = str(ini_vals['language']).strip().lower()
if val in LANG_CODE_TO_PS4:
return LANG_CODE_TO_PS4[val]
if val.isdigit():
return int(val)
try:
appdata = os.environ.get('APPDATA')
if appdata:
s_file = Path(appdata) / 'theorder1886-launcher' / 'settings.json'
if s_file.is_file():
s_data = json.loads(s_file.read_text(encoding='utf-8'))
if 'language' in s_data:
val = str(s_data['language']).strip().lower()
if val in LANG_CODE_TO_PS4:
return LANG_CODE_TO_PS4[val]
if val.isdigit():
return int(val)
except Exception:
pass
try:
import locale
loc = (locale.getdefaultlocale()[0] or '').lower()
if any(p in loc for p in ('pt', 'brazil', 'portuguese')):
return 17
if any(p in loc for p in ('es', 'spanish')):
return 20
if any(p in loc for p in ('fr', 'french')):
return 2
if any(p in loc for p in ('de', 'german')):
return 4
if any(p in loc for p in ('it', 'italian')):
return 5
if any(p in loc for p in ('ru', 'russian')):
return 8
if any(p in loc for p in ('pl', 'polish')):
return 16
except Exception:
pass
return 1
def find_probe_executable():
"""Finds the probe executable (theorder-probe)."""
return find_executable('theorder-probe' + EXE_SUFFIX)
def main():
args = sys.argv[1:]
if len(args) >= 2 and args[0] == '--after':
wait_for(int(args[1]))
args = args[2:]
cli_lang = None
cli_costume = None
translated_args = []
i = 0
while i < len(args):
if args[i] in ('--startlevel', '--level') and i + 1 < len(args):
translated_args.extend(['--guest-arg', '-startlevel', '--guest-arg', args[i + 1]])
i += 2
elif args[i] in ('--startcheckpoint', '--checkpoint') and i + 1 < len(args):
translated_args.extend(['--guest-arg', '-startcheckpoint', '--guest-arg', args[i + 1]])
i += 2
elif args[i] in ('--no-cloth', '--disablecloth'):
translated_args.extend(['--guest-arg', '-disablecloth'])
i += 1
elif args[i] in ('--no-cam-springs', '--nocamsprings'):
translated_args.extend(['--guest-arg', '-nocamsprings'])
i += 1
elif args[i] in ('--no-cam-additive', '--nocamadditive'):
translated_args.extend(['--guest-arg', '-nocamadditive'])
i += 1
elif args[i] == '--msaa' and i + 1 < len(args):
translated_args.extend(['--guest-arg', '-msaa', '--guest-arg', args[i + 1]])
i += 2
elif args[i] == '--frontend':
translated_args.extend(['--guest-arg', '-frontend'])
i += 1
elif args[i] == '--perf':
translated_args.extend(['--guest-arg', '-disablecloth', '--guest-arg', '-nocamsprings', '--guest-arg', '-nocamadditive', '--guest-arg', '-msaa', '--guest-arg', '1'])
i += 1
elif args[i] in ('--language', '--lang', '-l') and i + 1 < len(args):
cli_lang = args[i + 1]
i += 2
elif args[i] in ('--costume', '--dlc-costume') and i + 1 < len(args):
cli_costume = args[i + 1]
i += 2
else:
translated_args.append(args[i])
i += 1
args = translated_args
# As run.sh: relative paths (THEORDER_GAME_DIR, etc.) are from the port.
os.chdir(PORT)
env = os.environ
data = Path(get_env(env, 'DATA_DIR', PORT))
out = data / 'out'
out.mkdir(parents=True, exist_ok=True)
config_default = data / 'theorder.ini'
# The settings of releases up to 0.2.0 (gow3.ini) move to theorder.ini once.
if not config_default.exists() and (data / 'gow3.ini').is_file():
try:
(data / 'gow3.ini').replace(config_default)
except OSError:
config_default = data / 'gow3.ini'
env.setdefault('THEORDER_CONFIG', get_env(env, 'CONFIG', str(config_default)))
# Values this script derived on the previous start ("Apply and restart" inherits them) are
# derived again from the new options.
for key in env.pop('THEORDER_DERIVED', '').split(','):
env.pop(key, None)
derived = []
sys.path.insert(0, str(PORT / 'scripts'))
import graphics_options
graphics, reverted = graphics_options.prepare(env['THEORDER_CONFIG'], out / 'graphics_state.json')
if reverted:
print('Graphics: the last restart never reached the game; previous options restored', flush=True)
env.update(graphics_options.environment(graphics))
if not get_env(env, 'FSR411_DIR') and not (PORT / 'fsr4_411').is_dir() and (data / 'fsr4_411').is_dir():
env['THEORDER_FSR411_DIR'] = str(data / 'fsr4_411')
probe_env = get_env(env, 'PROBE')
probe = Path(probe_env) if probe_env else find_probe_executable()
if not probe or not probe.is_file():
fail(f'theorder-probe{EXE_SUFFIX} / theorder-probe{EXE_SUFFIX} not found: build it with build.sh or use a packaged build.')
# Development builds run from the MSYS2 tree: its CLANG64 DLLs (SDL3, FFmpeg, ...).
if WINDOWS and 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", "")}'
# Instruction sets this CPU lacks (MOVBE, BMI1, LZCNT): the ISA rewrite covers them; exit 20
# is a set nothing covers.
features = subprocess.run([str(probe), '--cpu-features'], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
text=True, creationflags=no_console())
if features.returncode == 20:
print(features.stdout, end='', flush=True)
sys.exit(20)
missing = parse_cpu_features(features.stdout)
candidates = [
get_env(env, 'GAME_DIR'),
r'C:\Users\Mateus\Downloads\games\CUSA00035',
PORT.parent / 'CUSA00035',
]
game = None
for c in candidates:
if c and (Path(c) / 'eboot.bin').is_file():
game = Path(c)
break
if not game:
game = Path(get_env(env, 'GAME_DIR', PORT.parent / 'CUSA00035'))
if not (game / 'eboot.bin').is_file():
fail(f'No eboot.bin in {game} (set THEORDER_GAME_DIR).')
update_view = None
patch_dir = get_env(env, 'PATCH_DIR')
if patch_dir:
import game_update
try:
update_view = game_update.create_view(game, patch_dir, out)
except (ValueError, OSError) as error:
fail(str(error))
game = update_view
print(f'Game and update combined from {patch_dir}', flush=True)
original_game = game.resolve()
game = Path(run_script('mods.py', game, '--out', out,
'--mods-dir', get_env(env, 'MODS_DIR', str(data / 'mods')),
'--config', get_env(env, 'MODS_CONFIG', str(data / 'mods.json')),
'--enabled', get_env(env, 'MODS_ENABLED', '1'), capture=True).strip())
mod_view = game if game.resolve() != original_game else None
try:
run_script('prepare.py', game, '--out', out)
run_script('link_libc.py', game, '--out', out)
run_script('link_modules.py', game, '--out', out)
# A failed rewrite prints its reason and the game starts without the table.
isa_args = []
if isa_rewrite_wanted(missing, env):
code, output = run_script('isa_rewrite.py', out / 'boot-linked.bin', '--out', out,
capture=True, check=False)
print(output, end='', flush=True)
if code == 0:
isa_args = ['--isa-rewrite', str(out / 'isa-rewrite.bin')]
run_script('content_profile.py', game, '--out', out, '--sku', get_env(env, 'CONTENT_SKU', 'full'))
import patches
from patches import game_profile_for, patch_requirements, patch_status, selected_patches
profile = game_profile_for(game)
engine_fps, fps_patched = 60, False
# The window shows the game's icon (BMP: the format SDL loads without extra libraries); on
# Linux the launcher's own icon (the AppImage ships the one chosen when it was built) and
# an application id the desktop entry matches, so the shell shows the same icon.
icon_file = game / 'sce_sys' / 'icon0.png'
if not WINDOWS:
env.setdefault('SDL_APP_ID', 'theorder')
if (PORT / 'launcher' / 'theorder.png').is_file():
icon_file = PORT / 'launcher' / 'theorder.png'
try:
from PIL import Image
with Image.open(icon_file) as icon:
icon.convert('RGBA').resize((64, 64), Image.LANCZOS).save(out / 'window_icon.bmp')
env.setdefault('THEORDER_WINDOW_ICON', str(out / 'window_icon.bmp'))
except (ImportError, OSError):
pass
# The temporal upscalers and motion vectors are not calibrated for this game yet: they stay
# off unless the launcher's experimental switch is on; linear image readbacks fix textures.
if get_env(env, 'EXPERIMENTAL_UPSCALER') != '1':
env.setdefault('THEORDER_UPSCALER', 'none')
env.setdefault('THEORDER_READBACK_LINEAR', '0')
env.setdefault('THEORDER_FACE_DEPTH_FIX', '1')
env.setdefault('THEORDER_FACE_SECONDARY_FIX', '1')
env.setdefault('THEORDER_PARTICLE_SRT_FIX', '1')
env.setdefault('THEORDER_EVSM_HTILE', '1')
patches_val = get_env(env, 'PATCHES', '')
patches_only = get_env(env, 'PATCHES_ONLY') == '1'
if profile:
names = selected_patches(profile[1], profile[2], patches_val, patches_only)
names = graphics_options.patch_names(names, graphics)
names = graphics_options.restrict_to_available(names, patches.available_patches(profile[1], profile[2]))
env['THEORDER_PATCHES'] = ';'.join(names)
env['THEORDER_PATCHES_ONLY'] = '1'
(out / 'patch_status.json').unlink(missing_ok=True)
run_script('patches.py', '--out', out, '--extra', get_env(env, 'PATCHES', ''), '--game-dir', game,
'--patches-dir', get_env(env, 'PATCHES_DIR', str(data / 'patches')),
'--patches-config', get_env(env, 'PATCHES_CONFIG', str(data / 'patches.json')))
if profile:
# Only the patches found in this eboot.bin count: a frame rate patch that was skipped
# leaves the engine at 60 FPS, and the notes' memory and VBlank needs follow the same list.
status = patch_status(out) or {}
applied = status.get('applied', [])
# The in-game menu's field of view writes these constants (probe.c set_fov_sites).
env['THEORDER_FOV_SITES'] = ' '.join(hex(site) for site in status.get('fov_sites', []))
engine_fps = graphics_options.applied_engine_fps(applied)
fps_patched = any(n.startswith(f'{graphics_options.FPS_PREFIX} - ') for n in applied)
dmem, vblank = patch_requirements(profile[1], applied, profile[2])
# The Order presents at 30 Hz (flip rate 1) and steps 33.3 ms per frame. Its 60 FPS patch
# halves the step, so the presentation has to follow (every vblank, at most 60 FPS) or
# the game runs in slow motion. Derived like the values below, so a restart back to 30 FPS
# drops them (flip rate 0 without the patch doubles the game's speed).
if profile[3] == 'The Order 1886' and f'{graphics_options.FPS_PREFIX} - 60 FPS' in applied:
for key, value in (('FLIP_RATE', '0'), ('FPS_LIMIT', '60')):
if not get_env(env, key):
env[f'THEORDER_{key}'] = value
derived.append(f'THEORDER_{key}')
print('The Order 60 FPS patch: presenting every vblank, at most 60 FPS', flush=True)
for key, value in (('DMEM_MB', dmem), ('VBLANK_HZ', vblank)):
if value and not get_env(env, key):
env[f'THEORDER_{key}'] = str(value)
derived.append(f'THEORDER_{key}')
if not get_env(env, 'VBLANK_HZ'):
env['THEORDER_VBLANK_HZ'] = '60'
derived.append('THEORDER_VBLANK_HZ')
# Without the frame rate patch the engine steps 1/60 s per frame: the present thread must
# not flip faster, or the game speeds up.
env['THEORDER_ENGINE_FPS'] = str(engine_fps)
derived.append('THEORDER_ENGINE_FPS')
# The Order runs at half its engine setting: 30 FPS at 60, 60 with the frame rate patch.
print(f'Game frame rate: {engine_fps // 2} FPS'
+ ('' if fps_patched or graphics['engine_fps'] == '60' else
' (the frame rate patch was not found in this eboot.bin)'), flush=True)
env['THEORDER_DERIVED'] = ','.join(derived)
# The guest memory pool is committed in full at start: a resolution patch above 1080p
# can need more than 16 GB of RAM, and the game then closes when the page file cannot grow.
import guest_memory
if warning := guest_memory.memory_warning(get_env(env, 'DMEM_MB'), guest_memory.physical_memory_mb(),
get_env(env, 'STREAM_MEMORY', 'cached')):
print(warning, flush=True)
# The in-game restart starts this script again once this process is gone.
# GPU caches (shaders, pipelines) beside the saves; read before main(), so set here.
user_dir = Path(get_env(env, 'USER_DIR', str(data / 'user'))).resolve()
user_dir.mkdir(parents=True, exist_ok=True)
env.setdefault('THEORDER_GPU_USER_DIR', str(user_dir))
from save_backup import backup
try:
if made := backup(user_dir):
print(f'Saves backed up to {made}', flush=True)
except OSError as error:
print(f'Save backup failed, starting anyway: {error}', flush=True)
this = ['--run'] if getattr(sys, 'frozen', False) else [str(Path(__file__).resolve())]
# Windows: the probe starts the new launch and ends, so it waits for this process. Linux:
# the probe replaces itself with the new launch while this process still waits for it.
after = ['--after', str(os.getpid())] if WINDOWS else []
restart = [sys.executable, *this, *after, *args]
restart_cmd = subprocess.list2cmdline(restart) if WINDOWS else shlex.join(restart)
env['THEORDER_RESTART_COMMAND'] = restart_cmd
# Resolve language & pass guest arguments
ps4_lang = resolve_language(cli_lang, env, env['THEORDER_CONFIG'], graphics_options)
engine_lang = PS4_TO_ENGINE_LANG.get(ps4_lang, ps4_lang)
env['THEORDER_LANGUAGE'] = str(ps4_lang)
print(f'Language: PS4 id {ps4_lang} -> engine id {engine_lang}', flush=True)
guest_lang_args = []
if '-language' not in args:
guest_lang_args.extend(['--guest-arg', '-language', '--guest-arg', str(engine_lang)])
if '-enablesubtitles' not in args:
guest_lang_args.extend(['--guest-arg', '-enablesubtitles'])
timeout_val = get_env(env, 'TIMEOUT', '0')
command = [*launch_prefix(env), str(probe), str(out / 'boot-linked.bin'), '--content-profile', str(out / 'content.bin'),
'--patches', str(out / 'patches.bin'), '--app0', str(game),
'--user', str(user_dir),
'--timeout', timeout_val, *isa_args, *guest_lang_args, *args]
# No stdin: an inherited pipe (shells such as Git Bash) cost the game its console output.
return subprocess.run(command, stdin=subprocess.DEVNULL, creationflags=no_console()).returncode
finally:
if mod_view:
shutil.rmtree(mod_view, ignore_errors=True)
if update_view:
game_update.remove_view(update_view)
if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)