diff --git a/README.md b/README.md index 40b5e5a2..9e507d91 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - Anisotropic texture filtering up to 16x, for sharp ground into the distance - In-game settings menu (F1) and performance overlay (F10) - Keyboard, mouse and gamepad with remapping, rumble and gyro -- Xbox button prompts: a layout that keeps the Switch button positions and shows the Xbox labels +- Xbox button prompts: LB, RB, LT, RT, Menu and View, and A, B, X and Y as labelled on the button to press, with either button layout - Shaders prepared at install instead of during play ## Planned diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 166969b5..78000227 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -11,6 +11,7 @@ Code copied or adapted from another project is listed here with its source, the | MacNativeGames TotK frame-rate patches: 60 fps present-interval controller, real-time frame step and its present sampling, hair and cloth clock, trampoline slow-motion check (instruction words and 1.2.1 sites), player position chain; quick-menu capture background RomFS overlay | https://github.com/ly05010419/MacNativeGames @ `ebe621de99bfc48f3c42f2d2aa73e04fbcc6eae2` (`games/totk/runtime/game_patches.c`, `game_version.h`, `world_survey.c`, `games/totk/scripts/make_romfs_patches.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/frame_rate.c`, `recomp/patches-v121.txt`, `tools/make_romfs_patches.py` | | MacNativeGames TotK 1.4.3 fade fix: the four distance / LOD and pre-actor fade sites, their instruction words and the floor of the fade step at 1 | https://github.com/ly05010419/MacNativeGames @ `3e9e7f67fdfdd3404134dcfa0f24969a9425a33f` (`games/totk/runtime/game_patches_v143.c` patch_fade_increment), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v143.txt` (set fade; the floor without flags, clz >> 5, as in pull request #78) | | MacNativeGames TotK aspect ratio: the camera and viewport sites that hand the perspective projection its aspect ratio, and the UI layout edits for a canvas wider than 16:9 | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/runtime/aspect_patch.h`, `aspect_math.h`, `game_patches_v143.c`, `games/totk/scripts/ultrawide_layout.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v143.txt` (set aspect), `tools/ultrawide_layout.py`, `tools/make_romfs_patches.py` (--aspect) | +| MacNativeGames TotK button icons: the Xbox controller's shoulder buttons, triggers, Menu, View and d-pad drawn with letters from the game's own text fonts, the .bfotf key, the button guide's images and their block-linear layout, the resource size table raised for the archives that grew | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/scripts/make_button_icons.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/button_icons.py`, `tools/make_romfs_patches.py` (--prompts) | | TOTK-Ultrawide, the community mod for emulators: the list of UI panes the ultrawide layout edits and the distances they move (data only, no code copied; the edit code is our own, and MacNativeGames' `ultrawide_layout.py` in the row above already carries the same values). The mod's repository URL and licence version are not recorded in this repository | TOTK-Ultrawide (community mod; URL not recorded here) | GPL (version not recorded here) | `tools/ultrawide_layout.py` (`KEEP_ROOT`, `edits`, `anim_edits`) | | MacNativeGames TotK virtual-core preemption: asynchronous preemption of an owner in top-level game code, priority inheritance through guest mutexes, the SDK's preemption-disable protocol (TLR+0x100/+0x102, SVC 0x36), the core-wait diagnostics | https://github.com/ly05010419/MacNativeGames @ `33e8fa83052ea1ae09a3583137008e9797e12950` (`games/totk/runtime/threads.c`, commits 8bf0893 and 19730cd), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/kernel.c` (SuspendThread and a register-saving stub replace SIGUSR2), `runtime/hostfn.c`, `runtime/svc.c` (host depth) | | MacNativeGames RomFS index builder (`TOTKRFS1` layout) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/scripts/prepare_romfs_backend.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/romfs_index.py` | @@ -68,7 +69,7 @@ These tools run on the developer's or player's machine during the build. They ar | Tcl/Tk 9.0.4, rebuilt with Xft for the Linux installer | https://github.com/tcltk/tcl and https://github.com/tcltk/tk, tag `core-9-0-4`; archives pinned by SHA-256 in `tools/make_release_linux.py` | Tcl/Tk licence (BSD-style) | `python/lib/`; licence texts in `licenses/tcl-license.terms` and `licenses/tk-license.terms` | | libXft 2 and libXrender 1, the sniper SDK sysroot's shared libraries, bundled beside the Xft Tk of the Linux installer; their Debian `copyright` files go into `licenses/` | https://repo.steampowered.com/steamrt-images-sniper/snapshots/3.0.20261021.266025/ | HPND (MIT-style) | `python/lib/`; `licenses/libXft-copyright.txt`, `licenses/libXrender-copyright.txt` | | CPython 3.14.9 embeddable package, with `tkinter` and Tcl/Tk 9.0.4 taken from the python.org 3.14.9 installer's component MSI (unpacked, never run); includes `vcruntime140*.dll` (Microsoft, redistributable with Python), OpenSSL, libffi, SQLite, zlib, libtommath | https://www.python.org/downloads/release/python-3149/ | PSF-2.0 (Tcl/Tk: Tcl/Tk licence, BSD-style) | `python/` | -| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, cryptography 50.0.2 (with its bundled OpenSSL), cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | BSD-3-Clause; lz4 BSD-3-Clause; cryptography Apache-2.0 OR BSD-3-Clause; cffi MIT; pycparser BSD-3-Clause | `python/Lib/site-packages/` | +| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, cryptography 50.0.2 (with its bundled OpenSSL), fontTools 4.68.0, cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | BSD-3-Clause; lz4 BSD-3-Clause; cryptography Apache-2.0 OR BSD-3-Clause; fontTools MIT; cffi MIT; pycparser BSD-3-Clause | `python/Lib/site-packages/` | | llvm-mingw 20261020 (LLVM/Clang/LLD 23, mingw-w64, libc++, libunwind, compiler-rt), x86_64 subset | https://github.com/mstorsjo/llvm-mingw/releases/tag/20261020 | Apache-2.0 with LLVM exception; mingw-w64 ZPL-2.1/BSD/public domain; libc++ and libunwind Apache-2.0 with LLVM exception and MIT/UIUC; winpthreads MIT | `llvm/` | | SDL 3.4.18 upstream Windows release (`SDL3.dll`) and mingw development package (headers, `libSDL3.dll.a`) | https://github.com/libsdl-org/SDL/releases/tag/release-3.4.18 | zlib | `bin/SDL3.dll`, `runtime/deps/` | | libopus 1.6.1 (MSYS2 `mingw-w64-ucrt-x86_64-opus` 1.6.1-2; `libopus-0.dll` imports only KERNEL32 and the UCRT api-ms-win-crt DLLs), headers and import library | https://repo.msys2.org/mingw/ucrt64/ | BSD-3-Clause | `bin/libopus-0.dll`, `runtime/deps/` | diff --git a/docs/building.md b/docs/building.md index 6be589f2..e63b60d3 100644 --- a/docs/building.md +++ b/docs/building.md @@ -107,9 +107,9 @@ of them. ``` `--patches` builds in the frame-rate, resolution and other patch sets, switchable at run time. The link copies `SDL3.dll`, `libiconv-2.dll` and `libopus-0.dll` next to the exe. - For Xbox button prompts, run `make_romfs_patches.py` once more with `--xbox-prompts`: it writes - `build\\romfs-patches-xbox` ([controls.md](controls.md), "Xbox button prompts"); `build_game.py` copies it next - to `totk.exe` like `romfs-patches`. + For Xbox button prompts, run `make_romfs_patches.py` twice more, with `--prompts xbox` and `--prompts xbox-label`: + they write `build\\romfs-patches-xbox` and `romfs-patches-xbox-label` ([controls.md](controls.md), "Xbox + button prompts"), which `build_game.py` copies next to `totk.exe` like `romfs-patches`. 6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`) for the shared shader list: @@ -194,6 +194,10 @@ Before a commit: `git config core.hooksPath .githooks` runs it before each local commit. - `build\\totk.exe --selftest`: layout, dispatch table and host-function registry, without game files. +A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes +`.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game +files); a change to the settings passes `totk.exe --probe-cfg`. + The lifter (`recomp/`) and the CPU headers (`runtime/cpu.h`, `runtime/simd.h`) are checked against Unicorn. Every lifter change passes these, all run with `.venv`: diff --git a/docs/controls.md b/docs/controls.md index 3cd4082c..c1c9cead 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -7,9 +7,8 @@ Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into - `nintendo`: by position, as on a Switch (the table below). - `xbox`: south A, east B, west X, north Y, as an Xbox pad labels them; on a PlayStation pad cross is A, circle B, square X, triangle Y. - `auto` (default): `nintendo` for a pad whose east button SDL reports labelled A (Switch Pro Controller, Nintendo-layout pads), `xbox` for the others. -- `xbox_prompts`: the buttons as `nintendo`, and the game's prompts name the Xbox labels (see Xbox button prompts below). -The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. With `nintendo`, `xbox` and `auto` the game's button prompts stay Switch letters; `xbox_prompts` changes them. +The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. Which controller's buttons the game's prompts show is `TOTK_PROMPTS` (see Xbox button prompts below). 0.1.9's `pad_layout = xbox_prompts` is read as `pad_layout = nintendo` with `prompts = xbox`, and the menu writes it that way. | Switch | Gamepad (by position, Nintendo layout) | Keyboard and mouse | Action in the world | |---|---|---|---| @@ -33,16 +32,29 @@ Esc is unbound in the game; it opens the settings menu and releases the mouse cu ## Xbox button prompts -`pad_layout = xbox_prompts` (*Xbox prompts (A right)* on the Controls tab) is for an Xbox pad played by position. The buttons work as with `nintendo`: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel). The letters the game shows are swapped to match the labels, A with B and X with Y, so each prompt names the button to press. The other layouts leave the prompts alone: with `xbox` the Switch letters already match the labels. +`TOTK_PROMPTS` (`prompts`, the *Button prompts* row on the Controls tab, read at start) picks the controller whose buttons the game's prompts show: `nintendo` (default) keeps the game's own, `xbox` shows an Xbox controller's. -The swapped letters are part of the game's textures, fonts and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the letter the game draws for it, and the prompt then names the wrong button. Use `xbox_prompts` with the default bindings. +- L, R, ZL, ZR, Plus and Minus become LB, RB, LT, RT, Menu and View, and the d-pad prompts a cross with an arrow for each direction meant. The letters on the keys are cut out in the game's own text font. +- A, B, X and Y name the label of the button the pad layout presses, so each prompt names the button to press. `pad_layout = nintendo` plays an Xbox pad by position: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel), so the prompts swap A with B and X with Y. `xbox` and `auto` put Switch A on the button labelled A, and the letters stay. -The buttons change at once, but the game reads its UI archive and fonts once at boot, so the prompts change at the next start (the menu says *prompts change after restart*). `xbox_prompts` loads `romfs-patches-xbox` next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`): the same 60 fps patches, with the swap made from the game's own files by `tools/make_romfs_patches.py --xbox-prompts`, which the setup runs next to the plain one: +| Switch | `nintendo` layout | `xbox` or `auto` layout | +|---|---|---| +| A, B, X, Y | B, A, Y, X | A, B, X, Y | +| L, R | LB, RB | LB, RB | +| ZL, ZR | LT, RT | LT, RT | +| Plus, Minus | Menu, View | Menu, View | +| D-pad | cross | cross | -- the action prompt (`DoCommand_00`) draws the letter images `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped, in a diamond that names the other face buttons. The diamond's letters are text the game takes from `LayoutMsg/DoCommand_00.msbt` of each language's `Mals` archive (and the layout's own text panes behind it); both are swapped. The diamond's shape shows the button's position and stays. -- every other prompt is text in the button font (`scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`, glyphs U+E040 to U+E043); the A and B, X and Y glyphs are swapped. +The action prompt (`DoCommand_00`) shows its button in a diamond whose shape gives the face buttons' positions as on a Switch, with the other three letters around it. With `nintendo` its letters are swapped with the rest and every one names the button in that place. With `xbox` and `auto` the letters are right but the diamond keeps the Switch positions: A shows on its right, while the button labelled A is at the bottom. The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations). -Without the folder (an install made by an older setup, or one where the setup could not prepare it and showed a warning) the menu says the files are missing, the log has `RomFS overlay: pad_layout = xbox_prompts, but ...`, and the Switch prompts stay; running the setup again on the install folder writes it. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version --xbox-prompts` writes `build\\romfs-patches-xbox`. +The prompts are part of the game's fonts, textures and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the prompt the game draws for it, which then names the wrong button. Use the Xbox prompts with the default bindings. + +The game reads its UI archive and fonts once at boot, so the prompts change at the next start, also after `pad_layout` changes between `nintendo` and the others (the menu says *prompts change after restart*); the buttons change at once. Under that note the menu offers *Restart now*: after a confirmation it writes `totk.ini`, closes the game as *Quit game* does and starts the game again with the same command line, which waits until the old process is gone before it opens the log and the saves (`runtime/gfx_present.c`, `gfx_window_closed`; `plat_restart` and `plat_restart_wait` in `runtime/platform/win32.c` and `linux.c`). Progress since the last save is lost, as with *Quit game*; while the game writes a save, the confirmation waits. With `prompts = xbox` the game loads `romfs-patches-xbox` (`pad_layout = nintendo`) or `romfs-patches-xbox-label` (`xbox`, `auto`) next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`; `runtime/input_map.c`, `input_prompts_folder`): the same 60 fps patches, with the prompts drawn from the game's own files by `tools/make_romfs_patches.py --prompts xbox` or `--prompts xbox-label` (`tools/button_icons.py`, after MacNativeGames' `make_button_icons.py`), which the setup runs next to the plain one: + +- every prompt but the button guide in play is text in the button font, `scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`: glyphs U+E040 to U+E043 (A B X Y), U+E044 to U+E047 (L R ZL ZR), U+E04B and U+E04C (Plus, Minus), U+E049 and U+E060 to U+E065 (the d-pad). fontTools writes the font again, so the archives grow and the folder also carries the resource size table (`System/Resource/ResourceSizeTable.Product....rsizetable.zs`) with their entries raised by as much; without that the game stops at start. +- the button guide in play draws L and ZL from the images `Nt_KeyTexL_00` and `Nt_KeyTexZL_00` of the Common archive's `timg/__Combined.bntx`, painted with the same icons. The action prompt draws its button from `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped for `nintendo`, and the diamond's letters are text the game takes from `LayoutMsg/DoCommand_00.msbt` of each language's `Mals` archive (and the layout's own text panes behind it), swapped the same way. + +The Switch prompts stay, with a note under *Button prompts* and a `RomFS overlay: ...` line in the log, when the folder is missing (an install made by an older setup, or one where the setup could not prepare it and showed a warning; running the setup again on the install folder writes it), when it fails its check, with a game resolution of another shape than 16:9 (its own UI layout wins; 16:10 and 21:9), and when the `romfs_mods` folder replaces one of its files: `romfs-patches` then loads in its place, where two overlays replacing one file would stop the game. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version --prompts xbox` (and `--prompts xbox-label`) writes `build\\romfs-patches-xbox` (`-label`); it needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`. ## Window keys diff --git a/docs/installer.md b/docs/installer.md index 77f789ba..fd7ba3b1 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -55,8 +55,9 @@ loads the saves 1.4.3 wrote. `totk.exe --prepare-shaders`) in the install folder, then fold the shader cache's loose files (four per shader, about 117,000) into `shader-cache/shader-cache.pack` (`tools/pack_shader_cache.py`). totk.exe reads the pack first and writes the translations it makes in play as loose files; running the tool again with the game closed folds those in. - The patches are written twice: `romfs-patches` and `romfs-patches-xbox` (`--xbox-prompts`, the A/B and X/Y prompts - swapped for `pad_layout = xbox_prompts`). + The patches are written three times: `romfs-patches`, and `romfs-patches-xbox` and `romfs-patches-xbox-label` + (`--prompts`: Xbox button prompts for `prompts = xbox`, the first for `pad_layout = nintendo`, the second for `xbox` + and `auto`). The two Xbox folders are optional: when one cannot be made, the setup warns and finishes. When the graphics driver crashes while building the shaders, `prepare_shaders.py` runs that part again without the variants it was building ([building.md](building.md), step 6), and the setup finishes with a warning that names how many were left out. diff --git a/installer/layout.py b/installer/layout.py index 902e54fc..0bd49839 100644 --- a/installer/layout.py +++ b/installer/layout.py @@ -92,6 +92,7 @@ class Layout: lib = self.runtime_lib_for(cpu) need = [self.python, self.tools / 'extract.py', self.tools / 'build_game.py', self.tools / 'prepare_shaders.py', self.tools / 'pack_shader_cache.py', self.tools / 'make_romfs_patches.py', self.tools / 'ultrawide_layout.py', + self.tools / 'button_icons.py', self.recomp / 'gen.py', self.clang, *((self.deps / 'include', self.deps / 'lib') if self.deps else ()), self.runtime, *([lib] if lib else ()), diff --git a/installer/steps.py b/installer/steps.py index aea9d5f7..2f38f351 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -6,8 +6,8 @@ tools/prepare_shaders.py, whose output goes to /logs/-.log and here: the host check is a small C program built with the bundled clang (hostcheck.c). Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, totk.exe and its DLLs, romfs-index.bin, -romfs-patches/, romfs-patches-xbox/, totk_xlate.exe, the shader state of totk.exe --prepare-shaders, totk.ini, -totk-install.json. +romfs-patches/, romfs-patches-xbox/, romfs-patches-xbox-label/, totk_xlate.exe, the shader state of totk.exe +--prepare-shaders, totk.ini, totk-install.json. Temp folder (/-): check/ (ExeFS of both inputs, the host check), gen/ (C), build/ (objects), logs/ (kept by the cleanup). """ @@ -679,7 +679,7 @@ class Prepare(Step): layout = ctx.layout xlate_id = layout.xlate.with_suffix('.id') tools = [layout.tools / n for n in ('prepare_shaders.py', 'shader_census.py', 'make_romfs_patches.py', - 'pack_shader_cache.py', 'ultrawide_layout.py')] + 'pack_shader_cache.py', 'ultrawide_layout.py', 'button_icons.py')] return fingerprint('prepare-1', ctx.keys['compile'], layout.xlate, xlate_id, shader_list_text(layout), *tools) def current(self, ctx, record): @@ -719,16 +719,23 @@ class Prepare(Step): dest / f'romfs-patches-{size}', '--aspect', size]) if code: raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log)) - # romfs-patches-xbox: the same with the A/B and X/Y prompts swapped, for pad_layout = xbox_prompts (written on - # every install, so the menu choice works without another run of the setup). Optional: when it fails, the game - # keeps the Switch prompts and the menu says the files are missing, so the setup warns and goes on. - remove(dest / 'romfs-patches-xbox') - code, log = run_tool(ctx, 'prepare-xbox', layout.tools / 'make_romfs_patches.py', - ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', - dest / 'romfs-patches-xbox', '--xbox-prompts']) - if code: - remove(dest / 'romfs-patches-xbox') - rep.warning('warn.xbox_prompts_failed', code=code, log=str(log)) + # The same with Xbox button icons in the prompts, for prompts = xbox (make_romfs_patches.py --prompts): + # romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label for xbox and auto (runtime/input_map.c + # input_prompts_folder). Both are written on every install, so the menu choices work without another run of + # the setup. Optional: when one fails, the game keeps the Switch prompts with that layout and the menu says the + # files are missing, so the setup warns once and goes on. + failed = None + for style in ('xbox', 'xbox-label'): + out = dest / f'romfs-patches-{style}' + remove(out) + code, log = run_tool(ctx, f'prepare-{style}', layout.tools / 'make_romfs_patches.py', + ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', out, + '--prompts', style]) + if code: + remove(out) + failed = failed or (code, log) + if failed: + rep.warning('warn.xbox_prompts_failed', code=failed[0], log=str(failed[1])) shader_list = layout.shader_list if not shader_list: diff --git a/runtime/cfg.c b/runtime/cfg.c index 436dbe89..b9763198 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -43,9 +43,9 @@ static const char *const known[] = { "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", - "PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC", + "PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC", "RENDER_SCALE", "REPLAY_ASYNC", - "REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", + "REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", "SHADER_MEMO", "SHADOW_RES", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", @@ -68,8 +68,8 @@ static const struct { const char *key, *section; } sections[] = { {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, - {"PAD_LAYOUT", "input"}, {"STICK_DEADZONE", "input"}, {"STICK_SENS", "input"}, {"MOUSE_SENS", "input"}, - {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "input"}, + {"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"STICK_SENS", "input"}, + {"MOUSE_SENS", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "input"}, {"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"}, {"BIND_RCLICK", "input"}, {"BIND_L", "input"}, {"BIND_R", "input"}, {"BIND_ZL", "input"}, {"BIND_ZR", "input"}, {"BIND_PLUS", "input"}, {"BIND_MINUS", "input"}, {"BIND_LEFT", "input"}, {"BIND_UP", "input"}, @@ -118,7 +118,8 @@ static const CfgMeta metas[] = { // Sound, Controls, Menu {"VOLUME", "100", "0..100", LIVE}, {"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE}, - {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox|xbox_prompts", LIVE}, + {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox", LIVE}, + {"PROMPTS", "nintendo", "nintendo|xbox", RESTART}, {"STICK_DEADZONE", "8", "0..50", LIVE}, {"STICK_SENS", "1", "0.1..3", RESTART}, {"MOUSE_SENS", "1", "0..10", LIVE}, {"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE}, @@ -189,6 +190,24 @@ static void add(char *key, char *value, int line) { entries[n_entries++] = (CfgEntry){strdup(key), strdup(value), 0, 0}; } +// 0.1.9 had the Xbox prompts as a pad layout: pad_layout = xbox_prompts is pad_layout = nintendo with prompts = xbox. +// Read as those two, which the menu shows and the next cfg_save writes; a prompts line of the file's own wins. The +// value still works from the environment (input_pad_layout_pick, input_prompts_pick). +static void migrate(void) { + CfgEntry *layout = NULL, *prompts = NULL; + for (int i = 0; i < n_entries; i++) { + if (!strcmp(entries[i].key, "PAD_LAYOUT")) layout = &entries[i]; + if (!strcmp(entries[i].key, "PROMPTS")) prompts = &entries[i]; + } + if (!layout || strcasecmp(layout->value, "xbox_prompts")) return; + free(layout->value); + layout->value = strdup("nintendo"); + layout->dirty = 1; + if (!prompts && n_entries < CFG_MAX_KEYS) entries[n_entries++] = (CfgEntry){strdup("PROMPTS"), strdup("xbox"), 1, 0}; + rt_log("cfg: totk.ini pad_layout = xbox_prompts is read as pad_layout = nintendo and prompts = %s", + prompts ? prompts->value : "xbox"); +} + int cfg_load(const char *path) { clear(); uint64_t size = 0; @@ -212,6 +231,7 @@ int cfg_load(const char *path) { p = eol + 1; } free(data); + migrate(); return 1; } diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index ca7449b2..9bf76bb2 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -279,7 +279,30 @@ int probe_cfg(void) { "pad layout: a set layout wins over the labels"); CHECK(input_pad_layout_pick("xbox_prompts", 0) == PAD_LAYOUT_NINTENDO && input_pad_layout_pick("Xbox_Prompts", 1) == PAD_LAYOUT_NINTENDO, - "pad layout: Xbox prompts keep the Nintendo positions (only the prompts change, romfs.c overlay_init)"); + "pad layout: 0.1.9's xbox_prompts keeps the Nintendo positions (only the prompts change, romfs.c overlay_init)"); + // Button prompts (input_map.c) + CHECK(input_prompts_pick(NULL, "auto") == PROMPTS_NINTENDO && input_prompts_pick("", "xbox") == PROMPTS_NINTENDO && + input_prompts_pick("Xbox", "nintendo") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox") == PROMPTS_NINTENDO, + "prompts: the game's own unless set to Xbox"); + CHECK(input_prompts_pick(NULL, "xbox_prompts") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox_prompts") == PROMPTS_NINTENDO, + "prompts: 0.1.9's pad_layout = xbox_prompts means Xbox while prompts is unset"); + CHECK(!input_prompts_folder(PROMPTS_NINTENDO, "nintendo") && !input_prompts_folder(PROMPTS_NINTENDO, "xbox"), + "prompts: the game's own need no folder"); + CHECK(EQ(input_prompts_folder(PROMPTS_XBOX, "nintendo"), "romfs-patches-xbox") && + EQ(input_prompts_folder(PROMPTS_XBOX, "xbox_prompts"), "romfs-patches-xbox") && + EQ(input_prompts_folder(PROMPTS_XBOX, "xbox"), "romfs-patches-xbox-label") && + EQ(input_prompts_folder(PROMPTS_XBOX, "auto"), "romfs-patches-xbox-label") && + EQ(input_prompts_folder(PROMPTS_XBOX, NULL), "romfs-patches-xbox-label"), + "prompts: the face buttons by position for the Nintendo layout, by label for xbox and auto"); + // romfs-patches-xbox shows A as B (tests/romfs_prompts_test.py checks the folders' contents). It is right exactly + // where the layout puts A on the east button, which an Xbox pad labels B. + input_map_reset(); + static const char *const layouts[] = {"nintendo", "xbox", "auto", "xbox_prompts"}; + for (int i = 0; i < 4; i++) { + int a_east = input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_EAST] = 1}, input_pad_layout_pick(layouts[i], 0)) == 1ull << B_A; + CHECK(a_east == EQ(input_prompts_folder(PROMPTS_XBOX, layouts[i]), "romfs-patches-xbox"), + "prompts: the folder names A as B exactly when the layout puts A on the button labelled B"); + } uint8_t pd[PAD_COUNT] = {0}; pd[PAD_SOUTH] = pd[PAD_NORTH] = 1; CHECK(input_map_pad_buttons(pd, PAD_LAYOUT_NINTENDO) == (1ull << B_B | 1ull << B_X) && @@ -370,6 +393,24 @@ int probe_cfg(void) { plat_setenv("TOTK_FREE_CORES", "1"); CHECK(cfg_bool("TOTK_FREE_CORES") == 1, "free_cores 1: on"); plat_setenv("TOTK_FREE_CORES", NULL); + // 0.1.9's pad_layout = xbox_prompts (cfg.c migrate): read as the Nintendo layout with the Xbox prompts, saved so + plat_setenv("TOTK_PAD_LAYOUT", NULL); + plat_setenv("TOTK_PROMPTS", NULL); + static const char old_layout[] = "[input]\r\npad_layout = xbox_prompts\r\n"; + CHECK(plat_file_write(path, old_layout, sizeof old_layout - 1) && cfg_load(path) == 1 && + EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "xbox"), + "0.1.9's pad_layout = xbox_prompts reads as nintendo with prompts = xbox"); + CHECK(cfg_save_to(path) == 1, "the read pad layout and prompts save"); + uint64_t saved_n = 0; + char *saved = (char *)plat_file_read(path, &saved_n); + CHECK(saved && strstr(saved, "pad_layout = nintendo") && strstr(saved, "prompts = xbox") && !strstr(saved, "xbox_prompts"), + "the next save writes the pad layout and the prompts"); + free(saved); + static const char old_layout_own[] = "[input]\r\npad_layout = xbox_prompts\r\nprompts = nintendo\r\n"; + CHECK(plat_file_write(path, old_layout_own, sizeof old_layout_own - 1) && cfg_load(path) == 1 && + EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "nintendo"), + "a prompts line of the file's own wins over 0.1.9's pad_layout = xbox_prompts"); + plat_file_delete(path); cfg_load("cfg-probe-missing.ini"); int listed = 0; for (int i = 0; cfg_meta_at(i); i++) { diff --git a/runtime/fs.h b/runtime/fs.h index a780e1e1..5c857e24 100644 --- a/runtime/fs.h +++ b/runtime/fs.h @@ -38,8 +38,14 @@ uint64_t romfs_file_count(void); // files in the index const char *romfs_entry(uint64_t i, uint64_t *offset, uint64_t *size); // path, image offset and size of index row i const char *romfs_image_path(void); // the romfs.bin path fs_init opened size_t romfs_overlay_count(void); -int romfs_xbox_prompts_ready(void); // romfs-patches-xbox was there at start -int romfs_xbox_prompts_active(void); // and was loaded (pad_layout = xbox_prompts at start) +// The button prompts (input_prompts_folder): the folder loaded at start, NULL for the game's own prompts; whether a +// folder had a manifest at start; and why the folder the settings asked for at start was not loaded (ROMFS_PROMPTS_OK +// for any other folder: it was not asked for). +enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROMPTS_SHAPE, ROMFS_PROMPTS_MODS, + ROMFS_PROMPTS_PATCHES }; +const char *romfs_prompts(void); +int romfs_prompts_ready(const char *folder); +int romfs_prompts_off(const char *folder); const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added); // RomFS path of overlay k void fs_trace(const char *what, const char *path); // TOTK_TRACE=fs: one line per open diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index cb8e7189..aa919494 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -23,9 +23,9 @@ #include "gfx.h" #include "gfx_wsys.h" #include "nvn_api.h" +#include "platform/platform.h" #include "ui/menu.h" #include "vk.h" -#include "platform/platform.h" #define FRAMES 2 #define MAX_IMAGES 16 @@ -40,6 +40,7 @@ void vk_queue_unlock(void) { plat_rmutex_unlock(&g_ql); } // ---- window state shared with the back end static VkSurfaceKHR g_surface; static volatile int32_t g_dirty; // the window was resized; swapchain stale +static volatile int32_t g_restart; // gfx_window_request_restart: closing the window starts the game again static volatile int32_t g_focused = 1; static volatile int32_t g_focus_msgs; static PlatRMutex g_start_lock; // gfx_window_start / vsync start @@ -63,15 +64,27 @@ void gfx_window_focus_changed(int in) { } // The window was closed: the process ends with it, as in MNG, once a save Commit still running in the background is -// done. +// done. After gfx_window_request_restart the executable then starts again with the same command line and environment +// (plat_restart), and the new process waits until this one is gone (main.c) before it moves the log and opens the +// RomFS and the saves. void gfx_window_closed(void) { - rt_log("gfx: window closed; exiting"); + int restart = plat_cas32(&g_restart, 0, 0) != 0; + rt_log("gfx: window closed; %s", restart ? "restarting" : "exiting"); fs_save_flush(); vk_pipeline_save(); prof_write(); // plat_exit runs no atexit handlers + if (restart) { + plat_setenv("TOTK_REEXEC", NULL); // the new process counts its own address-space retries (memory.c) + if (!plat_restart()) rt_log("gfx: the restart could not start the game again"); + } plat_exit(0); } +void gfx_window_request_restart(void) { + plat_xchg32(&g_restart, 1); + gfx_window_request_close(); +} + // TOTK_FULLSCREEN=1: borderless window over the monitor. TOTK_WINDOW_SIZE=x: client area of the window (the // swapchain follows the window; the game image is scaled to it). int gfx_cfg_fullscreen(void) { return cfg_bool("TOTK_FULLSCREEN"); } diff --git a/runtime/input_map.c b/runtime/input_map.c index 49220eac..5bce90ef 100644 --- a/runtime/input_map.c +++ b/runtime/input_map.c @@ -288,6 +288,18 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) { return east_labelled_a ? PAD_LAYOUT_NINTENDO : PAD_LAYOUT_XBOX; } +int input_prompts_pick(const char *prompts, const char *pad_layout) { + if (prompts && *prompts) return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : PROMPTS_NINTENDO; + return pad_layout && !strcasecmp(pad_layout, "xbox_prompts") ? PROMPTS_XBOX : PROMPTS_NINTENDO; +} + +const char *input_prompts_folder(int prompts, const char *pad_layout) { + if (prompts != PROMPTS_XBOX) return NULL; + // The folders are read at start, before a pad is open: auto counts as Xbox, as for a pad without Nintendo labels. + // A Nintendo-labelled pad under auto plays by label too (its A is on the button labelled A), so it matches as well. + return input_pad_layout_pick(pad_layout, 0) == PAD_LAYOUT_NINTENDO ? "romfs-patches-xbox" : "romfs-patches-xbox-label"; +} + uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout) { const PadBinding *t = input_map.pads[layout]; uint64_t b = 0; diff --git a/runtime/input_map.h b/runtime/input_map.h index 6e66b4ab..545eae89 100644 --- a/runtime/input_map.h +++ b/runtime/input_map.h @@ -80,11 +80,23 @@ int input_map_bind(const char *button, const char *list); // Applies the TOTK_BIND_ settings (cfg_get) over the defaults: at start, and again when one of them changes. void input_map_configure(void); -// The layout for a TOTK_PAD_LAYOUT value: "nintendo" or "xbox" (any case); "xbox_prompts" is the Nintendo layout with -// the A/B and X/Y prompts swapped (runtime/romfs.c overlay_init), so the buttons map as "nintendo". Anything else -// ("auto", NULL) picks Nintendo when the pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox -// otherwise. +// The layout for a TOTK_PAD_LAYOUT value: "nintendo" or "xbox" (any case); "xbox_prompts", 0.1.9's name for the Nintendo +// layout with the Xbox prompts, maps the buttons as "nintendo". Anything else ("auto", NULL) picks Nintendo when the +// pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox otherwise. int input_pad_layout_pick(const char *setting, int east_labelled_a); + +// Button prompts (TOTK_PROMPTS): the controller whose buttons the game's prompts show. Nintendo: the game's own. Xbox: +// LB RB LT RT, Menu, View and a d-pad cross for the other buttons, and the face buttons named by the label of the +// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). +enum { PROMPTS_NINTENDO, PROMPTS_XBOX }; +// The prompts for a TOTK_PROMPTS value ("nintendo" or "xbox", any case). Unset or empty: Xbox while the pad layout +// setting is "xbox_prompts", else Nintendo. +int input_prompts_pick(const char *prompts, const char *pad_layout); +// The folder next to romfs-index.bin that holds those prompts for a TOTK_PAD_LAYOUT value, NULL for the game's own. The +// Nintendo layout plays an Xbox pad by position, so its folder names the face buttons the other way round +// (romfs-patches-xbox: the right button does A and is labelled B); xbox and auto put every Switch button on the button +// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. +const char *input_prompts_folder(int prompts, const char *pad_layout); // down[pad] != 0 for the gamepad inputs held. Returns the Switch button bits (0..15) the layout's pad table presses. uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout); diff --git a/runtime/main.c b/runtime/main.c index 3fa4b9cb..9bd1009a 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -480,6 +480,9 @@ static void portable_paths(RtConfig *c) { int main(int argc, char **argv) { mem_init(); // first: claim the guest address space before anything else can land there; reads totk.ini + // A restart from the settings menu (gfx_present.c gfx_window_closed) starts this process while the one it replaces + // is still exiting: its log, RomFS and saves are free once it is gone. + if (plat_restart_wait(30000) < 0) rt_log("restart: the previous process still runs after 30 s; starting anyway"); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); plat_crash_hook(crash_handler); diff --git a/runtime/platform/linux.c b/runtime/platform/linux.c index 136b43c4..690ecb44 100644 --- a/runtime/platform/linux.c +++ b/runtime/platform/linux.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1650,3 +1651,85 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) { while (k < 0 && errno == EINTR); return (long)k; } + +// ---- restart +// TOTK_RESTART_WAIT names the process that called plat_restart, as its id and start time (field 22 of /proc//stat, +// clock ticks after boot): a process that has only reused the id is not waited for. Waiting keeps the new process off +// the old one's files (the log it moves at start, the saves) until the old one is gone. The new process gets no +// descriptor past stderr (glibc 2.34's closefrom file action), and the default signal mask and dispositions, whatever +// the calling thread had. +#define RESTART_WAIT "TOTK_RESTART_WAIT" + +// The start time of process pid (field 22 of its /proc stat line), 0 when it is gone. +static unsigned long long process_start(int pid) { + char path[64], buf[1024]; + snprintf(path, sizeof path, "/proc/%d/stat", pid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + size_t n = fread(buf, 1, sizeof buf - 1, f); + fclose(f); + buf[n] = 0; + char *p = strrchr(buf, ')'); // the command name may hold spaces + unsigned long long start = 0; + if (!p || sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %*d %*d %llu", + &start) != 1) + return 0; + return start; +} + +int plat_restart(void) { + // the arguments, NUL-separated, from /proc/self/cmdline + static char args[16384]; + char *argv[256]; + int argc = 0; + FILE *f = fopen("/proc/self/cmdline", "rb"); + size_t n = f ? fread(args, 1, sizeof args - 1, f) : 0; + if (f) fclose(f); + args[n] = 0; + for (size_t i = 0; i < n && argc < 255; i += strlen(args + i) + 1) argv[argc++] = args + i; + argv[argc] = NULL; + char exe[PATH_MAX], wait[64]; + if (!argc || !plat_exe_path(exe, sizeof exe)) return 0; + snprintf(wait, sizeof wait, "%d.%llu", (int)getpid(), process_start((int)getpid())); + posix_spawn_file_actions_t fa; + posix_spawn_file_actions_init(&fa); + posix_spawn_file_actions_addclosefrom_np(&fa, 3); + posix_spawnattr_t at; + posix_spawnattr_init(&at); + sigset_t none, all; + sigemptyset(&none); + sigfillset(&all); + posix_spawnattr_setsigmask(&at, &none); + posix_spawnattr_setsigdefault(&at, &all); + posix_spawnattr_setflags(&at, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF); + setenv(RESTART_WAIT, wait, 1); + pid_t pid; + int e = posix_spawn(&pid, exe, &fa, &at, argv, environ); + unsetenv(RESTART_WAIT); + posix_spawnattr_destroy(&at); + posix_spawn_file_actions_destroy(&fa); + return e == 0; +} + +int plat_restart_wait(uint32_t timeout_ms) { + const char *v = getenv(RESTART_WAIT); + if (!v) return 0; + int pid = 0; + unsigned long long start = 0; + int ok = sscanf(v, "%d.%llu", &pid, &start) == 2 && pid > 0 && start; + unsetenv(RESTART_WAIT); // the processes this one starts do not wait again + if (!ok) return 0; + // The descriptor is taken first: a start time that still matches then proves it is that process, not a new one with + // the id. It reads as ready once the process has exited, reaped or not. + int fd = (int)syscall(SYS_pidfd_open, pid, 0); + if (fd < 0) return 0; // already gone + int r = 0; + if (process_start(pid) == start) { + struct pollfd p = {fd, POLLIN, 0}; + do r = poll(&p, 1, (int)timeout_ms); + while (r < 0 && errno == EINTR); + r = r > 0 ? 1 : -1; + } + close(fd); + return r; +} diff --git a/runtime/platform/platform.h b/runtime/platform/platform.h index 66ac1870..70249095 100644 --- a/runtime/platform/platform.h +++ b/runtime/platform/platform.h @@ -411,3 +411,11 @@ PlatChild *plat_child_start(const char *exe, const char *arg, uint32_t *err); void plat_child_stop(PlatChild *c); // kills the child and frees c int plat_child_write(PlatChild *c, const void *data, size_t n); // 1 when all n bytes were written long plat_child_read(PlatChild *c, void *buf, size_t cap); // bytes read (at least 1); 0 or negative: pipe broke + +// ---- restart: this program again, in a new process that starts once this one is gone +// Starts this executable again with the same command line, environment and working folder, and no handle of this +// process. 1 when it started; the caller then exits. +int plat_restart(void); +// In a process plat_restart started: waits, at most timeout_ms, until the process that started it has exited. 1 after +// the wait, -1 on timeout, 0 when there is nothing to wait for (not started by plat_restart, or that process is gone). +int plat_restart_wait(uint32_t timeout_ms); diff --git a/runtime/platform/win32.c b/runtime/platform/win32.c index b32c644d..096ef9ec 100644 --- a/runtime/platform/win32.c +++ b/runtime/platform/win32.c @@ -1526,3 +1526,44 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) { if (!ReadFile(c->out, buf, (DWORD)cap, &got, NULL)) return -1; return (long)got; } + +// ---- restart +// TOTK_RESTART_WAIT names the process that called plat_restart, as its id and creation time: a process that has only +// reused the id is not waited for. Waiting keeps the new process off the old one's files (the log it moves at start, +// the saves) until the old one is gone; no handle is inherited, so none of them stays open in the new one either. +#define RESTART_WAIT "TOTK_RESTART_WAIT" + +static uint64_t process_created(HANDLE h) { + FILETIME c, e, k, u; + return GetProcessTimes(h, &c, &e, &k, &u) ? ft64(c) : 0; +} + +int plat_restart(void) { + char wait[48]; + snprintf(wait, sizeof wait, "%lu.%llu", GetCurrentProcessId(), (unsigned long long)process_created(GetCurrentProcess())); + plat_setenv(RESTART_WAIT, wait); + STARTUPINFOW si = {.cb = sizeof si}; + PROCESS_INFORMATION pi; + wchar_t *cmd = _wcsdup(GetCommandLineW()); // CreateProcessW may write its command line + BOOL ok = cmd && CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); + free(cmd); + plat_setenv(RESTART_WAIT, NULL); + if (!ok) return 0; + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return 1; +} + +int plat_restart_wait(uint32_t timeout_ms) { + char v[48]; + if (!plat_getenv(RESTART_WAIT, v, sizeof v)) return 0; + plat_setenv(RESTART_WAIT, NULL); // the processes this one starts do not wait again + unsigned long pid = 0; + unsigned long long created = 0; + if (sscanf(v, "%lu.%llu", &pid, &created) != 2) return 0; + HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!h) return 0; // already gone + int r = process_created(h) != created ? 0 : WaitForSingleObject(h, timeout_ms) == WAIT_OBJECT_0 ? 1 : -1; + CloseHandle(h); + return r; +} diff --git a/runtime/romfs.c b/runtime/romfs.c index 4f356ced..a389593f 100644 --- a/runtime/romfs.c +++ b/runtime/romfs.c @@ -24,6 +24,7 @@ #include "cfg.h" #include "fs.h" #include "host.h" +#include "input_map.h" #include "romfs_config.h" #include "romfs_path.h" #include "platform/platform.h" @@ -412,23 +413,56 @@ static void camera_overlay(void) { if (ok && serve_generated(CAMPACK, base, out, out_n, "camera", "camera speed", keeps)) cam_pack_served(); } -static int xbox_prompts_ready; // romfs-patches-xbox/manifest.tsv was next to romfs-index.bin at start -static int xbox_prompts_active; // and overlay_init loaded it +// The button prompts' folders (input_prompts_folder) and whether each had a manifest next to romfs-index.bin at start; +// the one the settings asked for at start, the one overlay_init loaded (NULL: the game's own prompts) and why the first +// did not load (ROMFS_PROMPTS_*). The menu compares them with the settings in effect (ui/menu.cpp prompts_note). +static struct { const char *name; int ready; } prompts_folders[2]; +static const char *prompts_wanted, *prompts_loaded; +static int prompts_off; -int romfs_xbox_prompts_ready(void) { return xbox_prompts_ready; } -int romfs_xbox_prompts_active(void) { return xbox_prompts_active; } +const char *romfs_prompts(void) { return prompts_loaded; } + +int romfs_prompts_ready(const char *folder) { + for (int i = 0; i < 2; i++) + if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready; + return 0; +} + +int romfs_prompts_off(const char *folder) { + return folder && prompts_wanted && !strcmp(folder, prompts_wanted) ? prompts_off : ROMFS_PROMPTS_OK; +} + +// The first RomFS file that the overlays [a, b) and [c, d) both replace, or NULL. +static const char *overlay_clash(size_t a, size_t b, size_t c, size_t d) { + for (size_t i = a; i < b; i++) + for (size_t j = c; j < d; j++) + if (overlays[i].index != ADDED && overlays[i].index == overlays[j].index) return overlays[i].name; + return NULL; +} + +// Drops the overlays [a, b), the ones after them moving down. +static void overlay_drop(size_t a, size_t b) { + for (size_t k = a; k < b; k++) { + free((void *)overlays[k].path); + free((void *)overlays[k].name); + } + memmove(overlays + a, overlays + b, (noverlay - b) * sizeof *overlays); + noverlay -= b - a; +} static void overlay_init(void) { // TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py). // A game resolution that is not 16:9 takes romfs-patches-x instead when it is there: the same overlay with // the UI laid out for that shape (make_romfs_patches.py --aspect), when the game version has the camera aspect patch // the layout goes with (res_wants_wide_overlay). - // With pad_layout = xbox_prompts, romfs-patches-xbox in its place: the same patches with the A/B and X/Y prompts - // swapped (make_romfs_patches.py --xbox-prompts). The game reads the archives once at boot, so the prompts stay - // until restart even though the layout itself changes live. Each folder replaces romfs-patches as a whole and the - // setup builds no wide folder with Xbox prompts, so a wide game resolution keeps the Switch prompts. - char def[2100], xbox[2100]; - const char *patches = cfg_get("TOTK_ROMFS_PATCHES"); + // With prompts = xbox, the Xbox prompts' folder for the pad layout in its place (input_prompts_folder): the same + // patches with Xbox button icons (make_romfs_patches.py --prompts). The game reads the archives once at boot, so + // the prompts stay until restart even though the layout itself changes live. Each folder replaces romfs-patches as + // a whole and the setup builds no folder of another shape with Xbox prompts, so a game resolution that is not 16:9 + // keeps the Switch prompts. So does a RomFS mod that replaces one of the prompts' files (the fonts, the resource + // size table): romfs-patches loads in their place, where two overlays replacing one file would stop the game. + char def[2100], path[2100]; + const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS"); int wide = 0; unsigned out[2]; res_wanted(out); @@ -442,29 +476,54 @@ static void overlay_init(void) { "(tools/make_romfs_patches.py --aspect %ux%u)", out[0], out[1], out[0], out[1]); } } - xbox_prompts_ready = - snprintf(xbox, sizeof xbox, "%s/romfs-patches-xbox/manifest.tsv", index_dir) < (int)sizeof xbox && - plat_file_exists(xbox); - int want_xbox = !strcasecmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts"); - if (!patches && want_xbox && xbox_prompts_ready) { - xbox[strlen(xbox) - strlen("/manifest.tsv")] = 0; - xbox_prompts_active = overlay_load(xbox, 1); - if (xbox_prompts_active) rt_log("RomFS overlay: Xbox button prompts (%s)", xbox); - else rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", xbox); - } else if (want_xbox) { - rt_log("RomFS overlay: pad_layout = xbox_prompts, but %s; Switch prompts stay", - wide ? "the game resolution takes the wide UI layout" - : patches ? "TOTK_ROMFS_PATCHES is set" - : "romfs-patches-xbox has no manifest.tsv (run the setup again)"); + static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each folder + for (int i = 0; i < 2; i++) { + prompts_folders[i].name = input_prompts_folder(PROMPTS_XBOX, layouts[i]); + prompts_folders[i].ready = + snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, prompts_folders[i].name) < (int)sizeof path && + plat_file_exists(path); } - if (!patches && !xbox_prompts_active && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def && - plat_file_exists(def)) { - def[strlen(def) - strlen("/manifest.tsv")] = 0; - patches = def; + const char *layout = cfg_value("TOTK_PAD_LAYOUT"); + prompts_wanted = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout); + prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK + : wide ? ROMFS_PROMPTS_SHAPE + : patches ? ROMFS_PROMPTS_PATCHES + : !romfs_prompts_ready(prompts_wanted) ? ROMFS_PROMPTS_MISSING + : ROMFS_PROMPTS_OK; + size_t first = noverlay; + if (prompts_wanted && prompts_off == ROMFS_PROMPTS_OK) { + snprintf(path, sizeof path, "%s/%s", index_dir, prompts_wanted); // fits: its manifest path did + if (overlay_load(path, 1)) { + prompts_loaded = prompts_wanted; + rt_log("RomFS overlay: Xbox button prompts (%s)", path); + } else { + prompts_off = ROMFS_PROMPTS_FAILED; + rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", path); + } + } else if (prompts_wanted) { + rt_log("RomFS overlay: prompts = xbox, but %s; Switch prompts stay", + prompts_off == ROMFS_PROMPTS_SHAPE ? "the game resolution takes its own UI layout" + : prompts_off == ROMFS_PROMPTS_PATCHES ? "TOTK_ROMFS_PATCHES is set" + : "their folder has no manifest.tsv (run the setup again)"); + } + size_t prompts_end = noverlay; + char plain[2100]; // romfs-patches, when it has a manifest + int plain_ok = snprintf(plain, sizeof plain, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof plain && + plat_file_exists(plain); + if (plain_ok) plain[strlen(plain) - strlen("/manifest.tsv")] = 0; + if (!patches && !prompts_loaded && plain_ok) patches = plain; + if (patches && *patches && strcmp(patches, "0")) overlay_load(patches, 0); + size_t mods_first = noverlay; + if (mods && *mods && strcmp(mods, "0")) overlay_load(mods, 0); + const char *clash = prompts_loaded ? overlay_clash(first, prompts_end, mods_first, noverlay) : NULL; + if (clash) { + rt_log("RomFS overlay: the RomFS mods folder replaces %s, which the Xbox prompts change too; Switch prompts stay", + clash); + overlay_drop(first, prompts_end); + prompts_loaded = NULL; + prompts_off = ROMFS_PROMPTS_MODS; + if (plain_ok) overlay_load(plain, 0); } - const char *dirs[2] = {patches, cfg_get("TOTK_ROMFS_MODS")}; - for (int i = 0; i < 2; i++) - if (dirs[i] && *dirs[i] && strcmp(dirs[i], "0")) overlay_load(dirs[i], 0); heapdef_overlay(); camera_overlay(); added_init(); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index f2860fd9..b5925de2 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -35,6 +35,7 @@ static int g_font_bad; extern "C" { #include "cfg.h" +#include "fs.h" #include "input.h" #include "input_map.h" #include "perfmon.h" @@ -49,9 +50,6 @@ void vk_queue_unlock(void); void res_sizes(unsigned out[2], unsigned scene[2]); double frame_step_limit_hz(void); extern const int rt_game_version; -// fs.h (romfs.c): romfs-patches-xbox was next to romfs-index.bin at start, and was loaded. -int romfs_xbox_prompts_ready(void); -int romfs_xbox_prompts_active(void); extern const char rt_port_version[]; } @@ -673,14 +671,11 @@ static void tab_sound(float scale) { opt_end(); } -// The note under the layout. Xbox prompts (the Nintendo layout with the A/B and X/Y prompts swapped, romfs.c -// overlay_init) change the buttons at once but the prompts only at the next start: "files missing" without -// romfs-patches-xbox, "prompts change after restart" while the prompts in use differ from the choice. Automatic with a -// gamepad connected: "in use: Xbox". NULL otherwise. +// A confirmation is open (Controls: restart, Advanced: reset): B and Esc close it, not the menu; L / R stay on the page. +static bool g_modal; + +// The note under the layout: Automatic with a gamepad connected, the layout it picked ("in use: Xbox"). NULL otherwise. static const char *pad_layout_note(void) { - bool want = !strcasecmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts"); - if (want && !romfs_xbox_prompts_ready()) return menu_text(UI_MENU_PAD_LAYOUT_PROMPTS_MISSING); - if (want != (romfs_xbox_prompts_active() != 0)) return menu_text(UI_MENU_PAD_LAYOUT_PROMPTS_RESTART); int got = input_pad_layout(); if (got < 0 || strcmp(cfg_value("TOTK_PAD_LAYOUT"), "auto")) return nullptr; static char note[96]; @@ -724,11 +719,70 @@ static void row_walk_key(void) { -1, n); } +// The note under the prompts. The settings name a folder of prompts (input_prompts_folder: the prompts and the pad +// layout, as a layout that puts A on the right button needs the face buttons named the other way round), but the game +// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: "files +// missing" when the setup did not write the one asked for, why it was left out at start (damaged, a game resolution +// that is not 16:9, a RomFS mod with the same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then +// *restart is set: a restart would bring the prompts asked for. NULL when they match. +static const char *prompts_note(bool *restart) { + *restart = false; + const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts(); + const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout); + if (want == used || (want && used && !strcmp(want, used))) return nullptr; + if (want && !romfs_prompts_ready(want)) return menu_text(UI_MENU_PROMPTS_MISSING); + switch (romfs_prompts_off(want)) { + case ROMFS_PROMPTS_FAILED: return menu_text(UI_MENU_PROMPTS_FAILED); + case ROMFS_PROMPTS_SHAPE: return menu_text(UI_MENU_PROMPTS_OFF_SHAPE); + case ROMFS_PROMPTS_MODS: return menu_text(UI_MENU_PROMPTS_OFF_MODS); + case ROMFS_PROMPTS_PATCHES: return menu_text(UI_MENU_PROMPTS_OFF_PATCHES); + default: *restart = true; return menu_text(UI_MENU_PROMPTS_RESTART); + } +} + +// The confirmation of "Restart now", over the menu; Cancel has the cursor first. Restart writes totk.ini, then closes +// the game as Quit does and starts it again (gfx_window_request_restart). It waits while the game writes a save, and +// the game stays when totk.ini cannot be written, as the new prompts would not come back. +static void restart_confirm(void) { + g_modal = false; + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + if (!ImGui::BeginPopupModal("##restart_confirm", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize)) + return; + g_modal = true; + ImGui::TextUnformatted(menu_text(UI_MENU_RESTART_CONFIRM)); + bool saving = fs_save_busy() != 0; + if (saving || !cfg_last_save_ok()) + ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", + menu_text(saving ? UI_MENU_RESTART_SAVING : UI_MENU_SAVE_FAILED)); + ImGui::Spacing(); + const char *yes = menu_text(UI_MENU_RESTART_YES), *no = menu_text(UI_MENU_RESET_NO); + const ImGuiStyle &st = ImGui::GetStyle(); + float bw = fmaxf(ImGui::CalcTextSize(yes).x, ImGui::CalcTextSize(no).x) + st.FramePadding.x * 4; + bool close = ImGui::Button(no, ImVec2(bw, 0)); + if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + ImGui::BeginDisabled(saving); + if (ImGui::Button(yes, ImVec2(bw, 0)) && cfg_save()) gfx_window_request_restart(); + ImGui::EndDisabled(); + if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) + close = true; + if (close) { + ImGui::CloseCurrentPopup(); + opt_focus_key("##restart"); // back on the row it came from + } + ImGui::EndPopup(); +} + static void tab_controls(float scale) { opt_begin("##controls", scale); - static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX, - UI_MENU_PAD_LAYOUT_XBOX_PROMPTS}; - opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 4, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note()); + static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX}; + opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 3, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note()); + static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX}; + bool restart; + const char *note = prompts_note(&restart); + opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 2, UI_MENU_PROMPTS_DESC, note); + bool ask = restart && opt_button("##restart", UI_MENU_RESTART, UI_MENU_RESTART_DESC); opt_toggle("TOTK_MOTION", UI_MENU_MOTION, UI_MENU_MOTION_DESC); opt_slider("TOTK_RUMBLE_STRENGTH", UI_MENU_RUMBLE_STRENGTH, 0, 300, UI_MENU_RUMBLE_STRENGTH_DESC, 10, "%.0f %%"); opt_slider("TOTK_RUMBLE_CURVE", UI_MENU_RUMBLE_CURVE, 0.2f, 1.5f, UI_MENU_RUMBLE_CURVE_DESC, 0.05f, "%.2f"); @@ -741,6 +795,8 @@ static void tab_controls(float scale) { binds_rows(scale); opt_end(); binds_after_page(); + if (ask) ImGui::OpenPopup("##restart_confirm"); // at the level BeginPopupModal looks it up + restart_confirm(); } static void tab_menu(float scale) { @@ -752,7 +808,6 @@ static void tab_menu(float scale) { } // ---- Advanced: the testing and troubleshooting keys, the bug report helpers and the reset of every setting -static bool g_modal; // the reset confirmation is open: B and Esc close it, not the menu; L / R stay on the page // A thread count with no fixed default: Automatic (unset), then the common counts. static void row_threads(const char *key, UiTextId label, UiTextId desc) { @@ -984,7 +1039,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { ImGui::SameLine(); if (ImGui::Button(quit, ImVec2(bw, 0))) gfx_window_request_close(); bool was_modal = g_modal || binds_modal(); - if (g_tab != TAB_ADVANCED) g_modal = false; + if (g_tab != TAB_ADVANCED && g_tab != TAB_CONTROLS) g_modal = false; if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))) set_open(0); ImGui::End(); diff --git a/runtime/ui/menu.h b/runtime/ui/menu.h index ae24384b..a1d5202b 100644 --- a/runtime/ui/menu.h +++ b/runtime/ui/menu.h @@ -60,6 +60,7 @@ int menu_font_check(void); // ---- what the menu asks of the platform side (gfx_window_win.c, gfx_window_sdl.c) void gfx_window_apply_settings(void); // TOTK_FULLSCREEN or TOTK_WINDOW_SIZE changed: the window follows void gfx_window_request_close(void); // as the window's close button: the process ends +void gfx_window_request_restart(void); // the same, then totk.exe starts again with the same command line int gfx_window_monitor_size(int *w, int *h); // pixels of the monitor the window is on; 0 when unknown double gfx_window_refresh_hz(void); // its refresh rate (TOTK_FPS_LIMIT=display); 0 when unknown unsigned gfx_window_dpi(void); // the window's DPI (96 at 100% display scale); any thread diff --git a/runtime/ui_text.c b/runtime/ui_text.c index f4d57136..fa63fd65 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -133,15 +133,31 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT] = "Button layout", [UI_MENU_PAD_LAYOUT_DESC] = "Which button is A. Nintendo: the right one, as on a Switch. Xbox: the bottom one, as " "labelled on an Xbox controller (cross on a PlayStation controller). Automatic picks " - "Nintendo for controllers with Nintendo labels and Xbox for the others. Xbox prompts: " - "A is the right one as with Nintendo, and the game shows the Xbox labels (B for A, A " - "for B, Y for X, X for Y); the prompts change after a restart. The letters are part of the " - "game's files, so a button you remap in Controls keeps the old letter on screen.", + "Nintendo for controllers with Nintendo labels and Xbox for the others. Which " + "controller the game's prompts show is set under Button prompts.", [UI_MENU_PAD_LAYOUT_AUTO] = "Automatic", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A right)", - [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Xbox prompts (A right)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s", - [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "prompt files missing: run the setup again", - [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "prompts change after restart", + [UI_MENU_PROMPTS] = "Button prompts", + [UI_MENU_PROMPTS_DESC] = "Which controller's buttons the game's prompts show. Nintendo: the game's own. Xbox: LB, " + "RB, LT, RT, Menu, View and a d-pad cross, and A, B, X and Y as labelled on the button " + "the layout above presses (with Nintendo (A right) the right button is labelled B, so the " + "prompts for A show B). The game reads its prompts at start, so they change after a " + "restart. They are part of the game's files, so a button you remap in Controls keeps its " + "old prompt on screen.", + [UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", + [UI_MENU_PROMPTS_MISSING] = "prompt files missing: run the setup again", + [UI_MENU_PROMPTS_FAILED] = "prompt files damaged: run the setup again", + [UI_MENU_PROMPTS_RESTART] = "prompts change after restart", + [UI_MENU_PROMPTS_OFF_SHAPE] = "off at a game resolution not 16:9", + [UI_MENU_PROMPTS_OFF_MODS] = "off: a RomFS mod replaces their files", + [UI_MENU_PROMPTS_OFF_PATCHES] = "off while TOTK_ROMFS_PATCHES is set", + [UI_MENU_RESTART] = "Restart now", + [UI_MENU_RESTART_DESC] = "Closes the game and starts it again with the new prompts. Progress since your last save " + "is lost.", + [UI_MENU_RESTART_CONFIRM] = "Restart the game now? Progress since your last save is lost.", + [UI_MENU_RESTART_YES] = "Restart", + [UI_MENU_RESTART_SAVING] = "The game is saving: Restart is possible in a moment.", [UI_MENU_STICK_DEADZONE] = "Stick dead zone", [UI_MENU_STICK_DEADZONE_DESC] = "How far a gamepad stick moves before the game sees it. Raise it if the character or the camera moves on its own.", [UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity", @@ -412,16 +428,31 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT] = "Раскладка кнопок", [UI_MENU_PAD_LAYOUT_DESC] = "Какая кнопка работает как A. Nintendo: правая, как на Switch. Xbox: нижняя, как " "подписано на контроллере Xbox (крест на контроллере PlayStation). Автоматически: " - "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных. Подсказки Xbox: " - "A справа, как в Nintendo, а игра показывает надписи Xbox (B вместо A, A вместо B, Y " - "вместо X, X вместо Y); подсказки меняются после перезапуска. Буквы записаны в файлах " - "игры, поэтому у кнопки, переназначенной на вкладке управления, на экране остаётся " - "прежняя буква.", + "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных. Кнопки какого " + "контроллера показывают подсказки игры, задаётся в строке «Подсказки кнопок».", [UI_MENU_PAD_LAYOUT_AUTO] = "Автоматически", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A справа)", - [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Подсказки Xbox (A справа)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", - [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова", - [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "подсказки сменятся после перезапуска", + [UI_MENU_PROMPTS] = "Подсказки кнопок", + [UI_MENU_PROMPTS_DESC] = "Кнопки какого контроллера показывают подсказки игры. Nintendo: как в самой игре. Xbox: " + "LB, RB, LT, RT, Menu, View и крестовина, а A, B, X и Y подписаны так же, как кнопка, " + "которую нажимает раскладка выше (в Nintendo (A справа) правая кнопка подписана B, и " + "подсказки A показывают B). Игра читает подсказки при запуске, так что они меняются после " + "перезапуска. Подсказки записаны в файлах игры, поэтому у кнопки, переназначенной на " + "вкладке управления, на экране остаётся прежняя подсказка.", + [UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", + [UI_MENU_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова", + [UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова", + [UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска", + [UI_MENU_PROMPTS_OFF_SHAPE] = "выкл. при разрешении игры не 16:9", + [UI_MENU_PROMPTS_OFF_MODS] = "выкл.: мод RomFS заменяет их файлы", + [UI_MENU_PROMPTS_OFF_PATCHES] = "выкл., пока задан TOTK_ROMFS_PATCHES", + [UI_MENU_RESTART] = "Перезапустить сейчас", + [UI_MENU_RESTART_DESC] = "Закрывает игру и запускает её снова с новыми подсказками. Прогресс после последнего " + "сохранения будет потерян.", + [UI_MENU_RESTART_CONFIRM] = "Перезапустить игру сейчас? Прогресс после последнего сохранения будет потерян.", + [UI_MENU_RESTART_YES] = "Перезапустить", + [UI_MENU_RESTART_SAVING] = "Игра сохраняется: перезапуск будет доступен через мгновение.", [UI_MENU_STICK_DEADZONE] = "Мёртвая зона стиков", [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами.", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", @@ -679,10 +710,8 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { "reiniciar. As letras fazem parte dos arquivos do jogo, então um botão remapeado em " "Controles continua com a letra antiga na tela.", [UI_MENU_PAD_LAYOUT_AUTO] = "Automático", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A à direita)", - [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A embaixo)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Ícones de Xbox (A à direita)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A embaixo)", [UI_MENU_PAD_LAYOUT_IN_USE] = "em uso: %s", - [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "faltam os arquivos dos ícones: execute a instalação de novo", - [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "os ícones mudam após reiniciar", [UI_MENU_STICK_DEADZONE] = "Zona morta dos analógicos", [UI_MENU_STICK_DEADZONE_DESC] = "Quanto um analógico do controle precisa se mover antes que o jogo perceba. Aumente se o personagem ou a câmera se moverem sozinhos.", [UI_MENU_MOUSE_SENS] = "Sensibilidade da câmera no mouse", @@ -985,10 +1014,7 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT_AUTO] = "自动", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo(A 在右)", [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox(A 在下)", - [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Xbox 按键提示(A 在右)", [UI_MENU_PAD_LAYOUT_IN_USE] = "使用中:%s", - [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "缺少按键提示文件:请重新运行安装程序", - [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "按键提示重启后生效", [UI_MENU_STICK_DEADZONE] = "摇杆死区", [UI_MENU_STICK_DEADZONE_DESC] = "手柄摇杆要推动多远游戏才会响应。如果角色或视角会自己移动," "请调高此值。", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 361b2837..6b71b6ab 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -67,8 +67,13 @@ typedef enum { UI_MENU_RUMBLE_CURVE, UI_MENU_RUMBLE_CURVE_DESC, UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC, UI_MENU_PAD_LAYOUT, UI_MENU_PAD_LAYOUT_DESC, UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, - UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_XBOX_PROMPTS, UI_MENU_PAD_LAYOUT_IN_USE, - UI_MENU_PAD_LAYOUT_PROMPTS_MISSING, UI_MENU_PAD_LAYOUT_PROMPTS_RESTART, + UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_IN_USE, + UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, + // the notes under the prompts: their files are missing or damaged, they change after restart, or why they are off + UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE, + UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES, + // "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO) + UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING, UI_MENU_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC, UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, UI_MENU_WALK_KEY, UI_MENU_WALK_KEY_DESC, UI_MENU_WALK_KEY_TAKEN, UI_MENU_WALK_SCALE, UI_MENU_WALK_SCALE_DESC, diff --git a/tests/romfs_prompts_test.py b/tests/romfs_prompts_test.py new file mode 100644 index 00000000..dca0d054 --- /dev/null +++ b/tests/romfs_prompts_test.py @@ -0,0 +1,539 @@ +"""tools/make_romfs_patches.py --prompts and tools/button_icons.py on a RomFS made here, with no game files: each prompt +names the label of the Xbox button that the pad layout presses, the shoulder buttons, triggers, Plus, Minus and the +d-pad are drawn as on an Xbox controller, the resource size table grows with the fonts, every other file and member +stays byte for byte, the same input gives the same output, and a RomFS the tool does not recognise fails before it +writes anything. Both game versions: 1.2.1 (Common.Product.110, 72x72 button guide images) and 1.4.3 +(Common.Product.140, 108x108). + +Run: .venv-py314\\Scripts\\python tests\\romfs_prompts_test.py +""" +import compression.zstd as zstd +import hashlib +import importlib.util +import io +import json +import random +import struct +import subprocess +import sys +import tempfile +import unittest +import zlib +from pathlib import Path + +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.recordingPen import RecordingPen +from fontTools.pens.t2CharStringPen import T2CharStringPen +from fontTools.ttLib import TTFont + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / 'tools' / 'make_romfs_patches.py' +spec = importlib.util.spec_from_file_location('button_icons', ROOT / 'tools' / 'button_icons.py') +icons = importlib.util.module_from_spec(spec) +spec.loader.exec_module(icons) + +# The face button each Switch button is in a pad layout (docs/controls.md, runtime/input_map.c), the label an Xbox pad +# prints on it, and the layout each overlay is made for (runtime/input_map.c input_prompts_folder). +POSITION = {'nintendo': {'A': 'east', 'B': 'south', 'X': 'north', 'Y': 'west'}, + 'xbox': {'A': 'south', 'B': 'east', 'X': 'west', 'Y': 'north'}} +XBOX_LABEL = {'south': 'A', 'east': 'B', 'west': 'X', 'north': 'Y'} +STYLE_LAYOUT = {'xbox': 'nintendo', 'xbox-label': 'xbox'} +FACE = {'A': 0xE040, 'B': 0xE041, 'X': 0xE042, 'Y': 0xE043} +# The glyphs drawn as Xbox icons, with their advance: LB RB LT RT, Menu and View, the d-pad. +DRAWN = {0xE044: 820, 0xE045: 820, 0xE046: 760, 0xE047: 760, 0xE04B: 640, 0xE04C: 640, 0xE049: 640, + **{cp: 640 for cp in range(0xE060, 0xE066)}} + +# restbl: the resource size table's name after its version, in both forms the tool takes. +VERSIONS = {'v121': dict(common='110', size=72, newest=121, restbl='Nin_NX_NVN.rsizetable.zs'), + 'v143': dict(common='140', size=108, newest=143, restbl='rsizetable.zs')} +DEFAULT_FONT, REGIONAL_FONT = 'Font/Font.Nin_NX_NVN.bfarc.zs', 'Font/Font_KRko.Nin_NX_NVN.bfarc.zs' +PANES = {'T_A_00': 'A', 'T_B_00': 'B', 'T_X_00': 'X', 'T_Y_00': 'Y', 'T_Name_00': 'A'} +MESSAGES = {**PANES, 'Greeting': 'Hello'} +R8_UNORM, BC1 = 0x201, 0x1a01 +IMAGE = 16384 # an R8 square up to 128 rows, two GOBs wide, block height 16: the size of the game's key images + + +# ---- the formats, written here from their layout so the tools' readers are checked against an independent writer +def sarc(members, align=0x80): + names, sfnt, name_at = list(members), b'', {} + for name in names: + name_at[name] = len(sfnt) // 4 + sfnt += name.encode() + b'\0' + sfnt += bytes(-len(sfnt) % 4) + head = 0x14 + 12 + 16 * len(names) + 8 + len(sfnt) + start = head + -head % align + data, nodes = b'', b'' + for name in names: + data += bytes(-len(data) % align) + nodes += struct.pack('<4I', zlib.crc32(name.encode()), 0x01000000 | name_at[name], len(data), len(data) + len(members[name])) + data += members[name] + out = (b'SARC' + struct.pack(' [(frame, value)] of a FLAN made by bflan().""" + pos, out = 0x14, {} + count, table = struct.unpack_from(' (format, size, image).""" + out = bytearray(0x30) + out[0:4], out[0x20:0x24] = b'BNTX', b'NX ' + table = len(out) + out += bytes(8 * len(textures)) + struct.pack_into(' (format, size, image) of a BNTX made by bntx().""" + count, table = struct.unpack_from(' text) after a pan1 section.""" + sections = b'pan1' + struct.pack(' text).""" + labels = b''.join(bytes([len(name)]) + name.encode() + struct.pack(' size).""" + crcs = sorted((zlib.crc32(path.removesuffix('.zs').encode()), size) for path, size in entries.items()) + return b'RESTBL' + struct.pack(' (advance, draw(pen)).""" + names = {cp: f'uni{cp:04X}' for cp in glyphs} + fb = FontBuilder(1000, isTTF=False) + fb.setupGlyphOrder(['.notdef'] + list(names.values())) + fb.setupCharacterMap(names) + charstrings, metrics = {}, {} + for gname, (advance, draw) in [('.notdef', (500, lambda pen: rect(pen, 50, 0, 450, 700)))] + \ + [(names[cp], glyphs[cp]) for cp in glyphs]: + pen = T2CharStringPen(advance, None) + draw(pen) + charstrings[gname], metrics[gname] = pen.getCharString(), (advance, 0) + fb.setupCFF(name, {'FullName': name}, charstrings, {}) + fb.setupHorizontalMetrics(metrics) + fb.setupHorizontalHeader(ascent=800, descent=-200) + fb.setupNameTable({'familyName': name, 'styleName': 'Regular'}) + fb.setupOS2(sTypoAscender=800, usWinAscent=800, usWinDescent=200) + fb.setupPost() + out = io.BytesIO() + fb.save(out) + return out.getvalue() + + +# A distinct rectangle and advance for every button glyph, so a glyph that moved is found by its outline. +BUTTONS = {cp: (600 + 4 * (cp - 0xE040), lambda pen, i=cp - 0xE040: rect(pen, 20 + 5 * i, 20, 300 + 5 * i, 400 + 3 * i)) + for cp in range(0xE040, 0xE069)} +LETTERS_1 = {ord('L'): (560, polygon((60, 0), (480, 0), (480, 100), (160, 100), (160, 700), (60, 700))), + ord('B'): (560, lambda pen: [rect(pen, 60, 0, 460, 700), rect(pen, 160, 100, 360, 300, True), + rect(pen, 160, 400, 360, 600, True)]), + ord('R'): (560, lambda pen: [rect(pen, 60, 0, 460, 700), rect(pen, 160, 400, 360, 600, True)])} +LETTERS_2 = {ord('T'): (560, polygon((230, 0), (330, 0), (330, 600), (520, 600), (520, 700), (40, 700), (40, 600), (230, 600)))} + + +class Romfs: + """A RomFS (romfs.bin, index.json) holding the files make_romfs_patches.py reads, the originals kept to compare.""" + + def __init__(self, folder, version, text_fonts=True, restbl_skips=(), l_format=R8_UNORM): + v, rnd = VERSIONS[version], random.Random(version) + words = [b'Layout', b'Pane', b'Font', b'Msg', b'Texture', b'Anim', b'Group', b'Text', b'Base', b'Key'] + samples = [b' '.join(rnd.choice(words) + str(rnd.randrange(999)).encode() for _ in range(rnd.randrange(20, 80))) + for _ in range(400)] + self.dictionary = zstd.train_dict(samples, 4096) + self.common = f'UI/LayoutArchive/Common.Product.{v["common"]}.Nin_NX_NVN.blarc.zs' + self.mals = [f'Mals/EUen.Product.{v["newest"]}.sarc.zs', f'Mals/USen.Product.{v["newest"]}.sarc.zs'] + self.old_mals = 'Mals/USen.Product.110.sarc.zs' + self.restbl = f'System/Resource/ResourceSizeTable.Product.{v["newest"]}.{v["restbl"]}' + self.old_restbl = f'System/Resource/ResourceSizeTable.Product.100.{v["restbl"]}' # an older version's: left alone + size = v['size'] + images = {f'Nt_KeyTex{b}_00': (R8_UNORM, size, rnd.randbytes(IMAGE)) for b in 'ABXY'} + images.update({'Nt_KeyTexL_00^z': (l_format, size, rnd.randbytes(IMAGE)), + 'Nt_KeyTexZL_00': (R8_UNORM, size, rnd.randbytes(IMAGE)), + 'Nt_KeyTexLSt_00': (R8_UNORM, size, rnd.randbytes(IMAGE))}) + self.text_fonts = [bfotf(cff_font('Text1', LETTERS_1), 0x01020304), bfotf(cff_font('Text2', LETTERS_2), 0x0a0b0c0d)] + default = {'scft/External.bfotf': bfotf(cff_font('External', BUTTONS), 0x5a17c3e9), 'fnt/rest.bin': rnd.randbytes(700)} + if text_fonts: + default.update(zip(icons.TEXT_FONTS, self.text_fonts)) + mals = sarc({'LayoutMsg/DoCommand_00.msbt': msbt(MESSAGES), 'LayoutMsg/Other_00.msbt': msbt({'T_A_00': 'A'})}) + self.contents = { # RomFS path -> contents before compression + self.common: sarc({'anim/ShortCutBG_00_In.bflan': bflan(('C_CaptureBG_00', 'C_CaptureClearBG_00', + 'P_CaptureClearBG_00', 'N_Other_00')), + 'anim/AutoBuilder_00_In.bflan': bflan(('C_CaptureBG_00',)), + 'blyt/DoCommand_00.bflyt': bflyt(PANES), + 'blyt/Title_00.bflyt': bflyt({'N_Title_00': 'Z'}), + 'timg/__Combined.bntx': bntx(images)}), + DEFAULT_FONT: sarc(default), + # The same font under another key: drawn once, stored under each archive's own key. + REGIONAL_FONT: sarc({'scft/External.bfotf': bfotf(cff_font('External', BUTTONS), 0x77777777), + 'fnt/rest.bin': rnd.randbytes(500)}), + **{path: mals for path in self.mals + [self.old_mals]}, + } + sizes = {path: len(data) + 256 for path, data in self.contents.items() if path not in restbl_skips} + self.contents[self.restbl] = restbl({**sizes, **{f'Other/{i}.bin': 1000 + i for i in range(20)}}) + self.contents[self.old_restbl] = restbl({DEFAULT_FONT: 1}) + plain = (REGIONAL_FONT, self.restbl, self.old_restbl) # stored without a dictionary + self.files = {'Pack/ZsDic.pack.zs': zstd.compress(sarc({'zs.zsdic': self.dictionary.dict_content}))} + self.files.update({path: zstd.compress(data, zstd_dict=None if path in plain else self.dictionary) + for path, data in self.contents.items()}) + self.files['Other/file.bin'] = rnd.randbytes(100) + image, entries = bytearray(), [] + for path, data in self.files.items(): + image += bytes(-len(image) % 16) + entries.append(dict(path=path, offset=len(image), size=len(data))) + image += data + folder.mkdir(parents=True) + (folder / 'romfs.bin').write_bytes(image) + (folder / 'index.json').write_text(json.dumps(dict(status='pass', files=entries))) + self.folder, self.version = folder, version + + def run(self, out, *flags): + return subprocess.run([sys.executable, '-I', str(TOOL), '--version', self.version, '--romfs', str(self.folder), + '--out', str(out), *flags], capture_output=True, text=True, encoding='utf-8') + + def read(self, out, path): + """The overlay's file, decompressed.""" + raw = (out / path).read_bytes() + return zstd.decompress(raw, zstd_dict=self.dictionary if zstd.get_frame_info(raw).dictionary_id else None) + + +def font(blob): + return TTFont(io.BytesIO(unbfotf(blob))) + + +def glyph(f, cp): + """(outline, advance) of the glyph of code point cp.""" + name = f.getBestCmap()[cp] + pen = RecordingPen() + f.getGlyphSet()[name].draw(pen) + return pen.value, f['hmtx'][name][0] + + +def manifest(out): + return {line.split('\t')[0]: line.split('\t')[1:] for line in (out / 'manifest.tsv').read_text().splitlines() + if not line.startswith('#')} + + +class PromptsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory(prefix='totk-prompts-') + cls.base = Path(cls.tmp.name) + cls.romfs = {v: Romfs(cls.base / v / 'romfs', v) for v in VERSIONS} + cls.outs = {} + for v, romfs in cls.romfs.items(): + for style in ('plain', 'xbox', 'xbox-label'): + out = cls.base / v / style + proc = romfs.run(out, *(() if style == 'plain' else ('--prompts', style))) + assert proc.returncode == 0, proc.stderr + cls.outs[v, style] = (out, json.loads(proc.stdout.strip().splitlines()[-1])) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def each(self, styles=('xbox', 'xbox-label')): + """(RomFS, style, overlay folder, summary) of every run of these styles.""" + return [(self.romfs[v], style, out, summary) for (v, style), (out, summary) in self.outs.items() + if style in styles] + + def test_plain_overlay_has_only_the_frame_rate_patch(self): + for romfs, _, out, summary in self.each(('plain',)): + with self.subTest(version=romfs.version, style="plain"): + self.assertEqual(set(manifest(out)), {romfs.common}) + self.assertIsNone(summary['prompts']) + keys = visibility(sarc_files(romfs.read(out, romfs.common))['anim/ShortCutBG_00_In.bflan']) + self.assertEqual(keys['C_CaptureBG_00'], [(0.0, 0), (0.0, 1)]) + self.assertEqual(keys['N_Other_00'], [(0.0, 0), (1.0, 1)]) + + def test_face_buttons_name_the_xbox_label_of_the_button_pressed(self): + for romfs, style, out, _ in self.each(): + with self.subTest(version=romfs.version, style=style): + layout = STYLE_LAYOUT[style] + label = {b: XBOX_LABEL[POSITION[layout][b]] for b in FACE} # Switch button -> the label of its button + before, after = sarc_files(romfs.contents[romfs.common]), sarc_files(romfs.read(out, romfs.common)) + old, new = bntx_images(before['timg/__Combined.bntx']), bntx_images(after['timg/__Combined.bntx']) + panes, messages = pane_texts(after['blyt/DoCommand_00.bflyt']), {} + for path in romfs.mals if layout == 'nintendo' else []: + messages[path] = message_texts(sarc_files(romfs.read(out, path))['LayoutMsg/DoCommand_00.msbt']) + original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf']) + for path in (DEFAULT_FONT, REGIONAL_FONT): + drawn = font(sarc_files(romfs.read(out, path))['scft/External.bfotf']) + for b, cp in FACE.items(): + self.assertEqual(glyph(drawn, cp), glyph(original, FACE[label[b]]), f'{path}: glyph of {b}') + for b in FACE: + self.assertEqual(new[f'Nt_KeyTex{b}_00'], old[f'Nt_KeyTex{label[b]}_00'], f'action prompt image of {b}') + self.assertEqual(panes[f'T_{b}_00'], label[b], f'diamond letter of {b}') + for path, texts in messages.items(): + self.assertEqual(texts[f'T_{b}_00'], label[b], f'{path}: diamond message of {b}') + # Text that only looks like a letter pane, and every other message, stays. + self.assertEqual((panes['T_Name_00'], pane_texts(after['blyt/Title_00.bflyt'])), ('A', {'N_Title_00': 'Z'})) + for path, texts in messages.items(): + self.assertEqual((texts['T_Name_00'], texts['Greeting']), ('A', 'Hello')) + self.assertEqual(sarc_files(romfs.read(out, path))['LayoutMsg/Other_00.msbt'], msbt({'T_A_00': 'A'})) + + def test_other_buttons_are_drawn_as_xbox_icons(self): + for romfs, style, out, _ in self.each(): + with self.subTest(version=romfs.version, style=style): + original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf']) + default = sarc_files(romfs.read(out, DEFAULT_FONT)) + drawn = font(default['scft/External.bfotf']) + for cp in range(0xE040, 0xE069): + outline, advance = glyph(drawn, cp) + if cp in DRAWN: + self.assertNotEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} drawn') + self.assertEqual(advance, DRAWN[cp], f'U+{cp:04X} advance') + elif cp not in FACE.values(): + self.assertEqual((outline, advance), glyph(original, cp), f'U+{cp:04X} kept') + # The letters are holes in the key: LB is the key, L, and B with its two counters. + moves = sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE044)[0]) + self.assertEqual(moves, 5) + self.assertEqual(sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE047)[0]), 1 + 1 + 1 + 1) # RT: key, R + counter, T + self.assertEqual(sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE060)[0]), 2) # d-pad up: cross, arrow + # The text fonts and the archives' other members stay byte for byte; both archives hold the same font. + before = sarc_files(romfs.contents[DEFAULT_FONT]) + self.assertEqual({k: v for k, v in default.items() if k != 'scft/External.bfotf'}, + {k: v for k, v in before.items() if k != 'scft/External.bfotf'}) + regional = sarc_files(romfs.read(out, REGIONAL_FONT)) + self.assertEqual(regional['fnt/rest.bin'], sarc_files(romfs.contents[REGIONAL_FONT])['fnt/rest.bin']) + self.assertEqual(unbfotf(regional['scft/External.bfotf']), unbfotf(default['scft/External.bfotf'])) + self.assertEqual(struct.unpack_from(' 0 and grown[REGIONAL_FONT] > 0, grown) + self.assertEqual(summary['prompts']['grown'], {p: g for p, g in grown.items() if g > 0}) + for crc, entry in original.items(): + paths = [p for p in grown if zlib.crc32(p.removesuffix('.zs').encode()) == crc and grown[p] > 0] + self.assertEqual(table[crc], entry + (grown[paths[0]] if paths else 0)) + self.assertEqual(set(table), set(original)) + + def test_manifest_lists_what_changed_with_both_hashes(self): + for romfs, style, out, _ in self.each(('plain', 'xbox', 'xbox-label')): + with self.subTest(version=romfs.version, style=style): + expect = {romfs.common} + if style != 'plain': + expect |= {DEFAULT_FONT, REGIONAL_FONT, romfs.restbl} | (set(romfs.mals) if style == 'xbox' else set()) + lines = manifest(out) + self.assertEqual(set(lines), expect) + for path, (size, sha, original) in lines.items(): + data = (out / path).read_bytes() + self.assertEqual((int(size), sha), (len(data), hashlib.sha256(data).hexdigest()), path) + self.assertEqual(original, hashlib.sha256(romfs.files[path]).hexdigest(), path) + + def test_same_input_same_output_and_the_older_flag(self): + romfs = self.romfs['v121'] + for flags in (('--prompts', 'xbox'), ('--xbox-prompts',)): + out = self.base / 'again' / '-'.join(flags) + proc = romfs.run(out, *flags) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual((out / 'manifest.tsv').read_bytes(), (self.outs['v121', 'xbox'][0] / 'manifest.tsv').read_bytes()) + + def test_unrecognised_romfs_fails_before_writing(self): + cases = {'no text fonts': (dict(text_fonts=False), icons.TEXT_FONTS[0]), + 'no size entry': (dict(restbl_skips=(REGIONAL_FONT,)), 'has no entry in the resource size table'), + 'compressed L image': (dict(l_format=BC1), 'Nt_KeyTexL_00: format')} + for i, (case, (options, message)) in enumerate(cases.items()): + with self.subTest(case): + romfs = Romfs(self.base / 'bad' / str(i) / 'romfs', 'v121', **options) + out = self.base / 'bad' / str(i) / 'out' + proc = romfs.run(out, '--prompts', 'xbox-label') + self.assertNotEqual(proc.returncode, 0) + self.assertIn(message, proc.stderr) + self.assertFalse(out.exists(), 'a failed run writes nothing') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/build_game.py b/tools/build_game.py index a0c26673..ef55110c 100644 --- a/tools/build_game.py +++ b/tools/build_game.py @@ -240,9 +240,10 @@ def write_if_changed(path, text): def copy_romfs_patches(version, out): """totk.exe loads romfs-patches beside romfs-index.bin (runtime/romfs.c overlay_init). tools/make_romfs_patches.py writes them into build/ only, so a build in another directory ran without the 60 fps overlay (the quick - menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox (the same with - the A/B and X/Y prompts swapped, pad_layout = xbox_prompts) the same way when it was made.""" - for name in ('romfs-patches', 'romfs-patches-xbox'): + menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox and + romfs-patches-xbox-label (the same with Xbox button prompts, make_romfs_patches.py --prompts) the same way when they + were made.""" + for name in ('romfs-patches', 'romfs-patches-xbox', 'romfs-patches-xbox-label'): src = ROOT / 'build' / version / name dst = out / name if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file(): diff --git a/tools/button_icons.py b/tools/button_icons.py new file mode 100644 index 00000000..c062080e --- /dev/null +++ b/tools/button_icons.py @@ -0,0 +1,319 @@ +# Adapted from MacNativeGames games/totk/scripts/make_button_icons.py @ 933b6a0 (MIT, Copyright (c) 2026 +# MacNativeGames contributors). +"""Xbox button icons for the game's prompts, drawn on the player's machine for tools/make_romfs_patches.py --prompts. +The outlines are our own shapes with letters cut out of them in the game's own text fonts: nothing of the game is in +the repository. + +Every prompt except the button guide in play is text in the button font, scft/External.bfotf of each +Font/Font*.Nin_NX_NVN.bfarc.zs: private-use code points from U+E040 (A, B, X, Y, then L, R, ZL, ZR, the d-pad, Plus and +Minus, the sticks). A .bfotf is an OpenType (CFF) font after an 8-byte header; from offset 4 on, every byte is XORed +with a 4-byte key, which the size in the header's second word gives away (bfotf_decode). redraw_font draws the shoulder +buttons, the triggers, Plus, Minus and the d-pad as an Xbox controller names them (LB RB, LT RT, Menu and View, a +cross), can swap the glyphs of the face buttons (A with B, X with Y), and has fontTools write the font again. The +archive then grows by a kilobyte or two, more than the game's resource size table allows it: grow_restbl raises those +entries (without it the game stops at start, MacNativeGames found). + +The button guide in play (bottom right) draws L and ZL from images of the common layout archive instead +(timg/__Combined.bntx, Nt_KeyTexL_00 and Nt_KeyTexZL_00): bntx_redraw paints the same icons into them, the size +unchanged. The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations). + +Needs fontTools (tools/requirements-installer.txt, tools/requirements-py314.txt). +""" +import io +import struct +import zlib + +from fontTools.pens.basePen import BasePen +from fontTools.pens.boundsPen import BoundsPen +from fontTools.pens.recordingPen import RecordingPen +from fontTools.pens.reverseContourPen import ReverseContourPen +from fontTools.pens.t2CharStringPen import T2CharStringPen +from fontTools.pens.transformPen import TransformPen +from fontTools.ttLib import TTFont + +FONT = 'scft/External.bfotf' +# The letters on the keys come from the text fonts of the default archive; the regional archives lack them. +TEXT_ARCHIVE = 'Font/Font.Nin_NX_NVN.bfarc.zs' +TEXT_FONTS = ('scft/ninP_RodinNTLG-B_DH_003_subset.bfotf', 'scft/nintendo_NTLG-DB_DH_002.bfotf') +# The button guide's images and the glyph each one shows. +HUD_TEXTURES = {'Nt_KeyTexL_00': 0xE044, 'Nt_KeyTexZL_00': 0xE046} + + +def xor(data, key): + """data with byte i XORed with key[i % 4].""" + pad = (key * (len(data) // 4 + 1))[:len(data)] + return (int.from_bytes(data, 'little') ^ int.from_bytes(pad, 'little')).to_bytes(len(data), 'little') + + +def bfotf_decode(blob): + """(OpenType font, key) of a .bfotf (the module docstring). The font fills the rest of the file.""" + key = xor(blob[4:8], struct.pack('>I', len(blob) - 8)) + otf = xor(blob[8:], key) + assert otf[:4] == b'OTTO', 'not a CFF OpenType font' + return otf, key + + +def bfotf_encode(otf, key, head): + """The .bfotf of otf: head (the original's first word) and the size, the rest XORed with key as bfotf_decode reads + it. The size field holds the whole font, so its length has to be a multiple of 4 (fontTools pads its tables).""" + assert len(otf) % 4 == 0, len(otf) + return head[:4] + xor(struct.pack('>I', len(otf)) + otf, key) + + +# ---- drawing, in units of the font's 1000-unit em; the round A/B/X/Y icons fill y 20..585 +Y0, Y1 = 20, 585 +CY, R = (Y0 + Y1) / 2, (Y1 - Y0) / 2 +K = 0.5523 # control point distance of a quarter circle drawn with one cubic curve, per unit of radius + + +class Glyphs: + """Outlines of letters from the game's own text fonts, drawn as holes in a shape.""" + def __init__(self, fonts): + self.fonts = fonts + + def outline(self, ch): + for font in self.fonts: + cmap = font.getBestCmap() + if ord(ch) in cmap: + glyphs = font.getGlyphSet(); g = glyphs[cmap[ord(ch)]] + rec = RecordingPen(); g.draw(rec); box = BoundsPen(glyphs); g.draw(box) + return rec, box.bounds, font['head'].unitsPerEm, g.width + raise KeyError(f'no text font has {ch!r}') + + def hole(self, pen, text, cx, cy, cap, max_width): + """text centred on (cx, cy), at most cap high and max_width wide, its contours reversed so they cut holes.""" + parts, x, ink = [], 0.0, [1e9, 1e9, -1e9, -1e9] + for ch in text: + rec, b, upm, advance = self.outline(ch); k = 1000 / upm + parts.append((rec, k, x)) + ink = [min(ink[0], x + b[0] * k), min(ink[1], b[1] * k), max(ink[2], x + b[2] * k), max(ink[3], b[3] * k)] + x += advance * k * 0.96 + width, height = ink[2] - ink[0], ink[3] - ink[1] + scale = min(cap / height, max_width / width) + ox, oy = cx - (ink[0] + width / 2) * scale, cy - (ink[1] + height / 2) * scale + reverse = ReverseContourPen(pen) + for rec, k, x in parts: + rec.replay(TransformPen(reverse, (scale * k, 0, 0, scale * k, ox + x * scale, oy))) + + +def text_glyphs(blobs): + """Glyphs over the text fonts in blobs (.bfotf files), the first that has a letter giving it.""" + return Glyphs([TTFont(io.BytesIO(bfotf_decode(blob)[0])) for blob in blobs]) + + +def circle(pen, cx, cy, r): + k = K * r + pen.moveTo((cx + r, cy)) + pen.curveTo((cx + r, cy + k), (cx + k, cy + r), (cx, cy + r)) + pen.curveTo((cx - k, cy + r), (cx - r, cy + k), (cx - r, cy)) + pen.curveTo((cx - r, cy - k), (cx - k, cy - r), (cx, cy - r)) + pen.curveTo((cx + k, cy - r), (cx + r, cy - k), (cx + r, cy)) + pen.closePath() + + +def rounded(pen, x0, y0, x1, y1, bottom, top=None): + """Counter-clockwise rounded rectangle (bottom and top corner radii).""" + top = bottom if top is None else top + kb, kt = K * bottom, K * top + pen.moveTo((x0 + bottom, y0)); pen.lineTo((x1 - bottom, y0)) + pen.curveTo((x1 - bottom + kb, y0), (x1, y0 + bottom - kb), (x1, y0 + bottom)); pen.lineTo((x1, y1 - top)) + pen.curveTo((x1, y1 - top + kt), (x1 - top + kt, y1), (x1 - top, y1)); pen.lineTo((x0 + top, y1)) + pen.curveTo((x0 + top - kt, y1), (x0, y1 - top + kt), (x0, y1 - top)); pen.lineTo((x0, y0 + bottom)) + pen.curveTo((x0, y0 + bottom - kb), (x0 + bottom - kb, y0), (x0 + bottom, y0)); pen.closePath() + + +def polygon(pen, points): + pen.moveTo(points[0]) + for p in points[1:]: + pen.lineTo(p) + pen.closePath() + + +def xbox_icons(g): + """Code point -> (advance, draw(pen)) for the buttons an Xbox controller names differently from a Switch: L R = LB + RB, ZL ZR = LT RT, Plus and Minus = Menu and View, the d-pad as a cross. g: Glyphs for the letters. The face + buttons keep the game's own glyphs (redraw_font swaps them for the Nintendo layout).""" + def bumper(label, advance=820): + def draw(pen): + rounded(pen, 40, Y0 + 70, advance - 40, Y1 - 70, 70, 150); g.hole(pen, label, advance / 2, CY, 230, advance - 200) + return advance, draw + + def trigger(label, advance=760): + def draw(pen): + rounded(pen, 60, Y0, advance - 60, Y1, 60, 230); g.hole(pen, label, advance / 2, CY - 20, 230, advance - 220) + return advance, draw + + def menu(advance=640): # three bars, as on the Menu button + def draw(pen): + circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen) + for dy in (-115, 0, 115): + rounded(reverse, advance / 2 - 150, CY + dy - 38, advance / 2 + 150, CY + dy + 38, 38) + return advance, draw + + def view(advance=640): # two overlapping windows, as on the View button + def draw(pen): + circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen); s = 150 + rounded(reverse, advance / 2 - s - 15, CY + 15, advance / 2 - 15, CY + s + 15, 16) + rounded(reverse, advance / 2 + 15, CY - s - 15, advance / 2 + s + 15, CY - 15, 16) + return advance, draw + + def dpad(*lit, advance=640): # a cross with an arrow cut into each direction the prompt means + def draw(pen): + cx, length, arm = advance / 2, R, R * 0.40 + polygon(pen, [(cx + length, CY - arm), (cx + length, CY + arm), (cx + arm, CY + arm), (cx + arm, CY + length), + (cx - arm, CY + length), (cx - arm, CY + arm), (cx - length, CY + arm), (cx - length, CY - arm), + (cx - arm, CY - arm), (cx - arm, CY - length), (cx + arm, CY - length), (cx + arm, CY - arm)]) + m, t, h = (length + arm) / 2, arm * 0.72, arm * 0.80 # arm centre, half base and height of the arrow + heads = {'up': [(cx - t, CY + m - h / 2), (cx, CY + m + h / 2), (cx + t, CY + m - h / 2)], + 'down': [(cx + t, CY - m + h / 2), (cx, CY - m - h / 2), (cx - t, CY - m + h / 2)], + 'left': [(cx - m + h / 2, CY - t), (cx - m - h / 2, CY), (cx - m + h / 2, CY + t)], + 'right': [(cx + m - h / 2, CY + t), (cx + m + h / 2, CY), (cx + m - h / 2, CY - t)]} + for d in lit: + polygon(pen, heads[d]) # already clockwise: a hole + return advance, draw + + return { + 0xE044: bumper('LB'), 0xE045: bumper('RB'), 0xE046: trigger('LT'), 0xE047: trigger('RT'), + 0xE04B: menu(), 0xE04C: view(), + 0xE049: dpad('up', 'down', 'left', 'right'), 0xE060: dpad('up'), 0xE061: dpad('down'), + 0xE062: dpad('left'), 0xE063: dpad('right'), 0xE064: dpad('up', 'down'), 0xE065: dpad('left', 'right'), + } + + +def redraw_font(otf, icons, swaps=()): + """The OpenType font otf with the glyphs of each (code point, code point) pair of swaps trading places (outlines and + horizontal metrics), then every code point of icons (code point -> (advance, draw)) drawn anew, written again by + fontTools. The timestamps stay, so the same input gives the same bytes.""" + font = TTFont(io.BytesIO(otf), recalcTimestamp=False) + assert font['head'].unitsPerEm == 1000, f'em of {font["head"].unitsPerEm} units, the drawings assume 1000' + cff = font['CFF '].cff + top = cff.topDictIndex[0] + assert not hasattr(top, 'ROS'), 'CID-keyed CFF' # its glyphs can use different private dictionaries + charstrings, private, hmtx, cmap = top.CharStrings, top.Private, font['hmtx'], font.getBestCmap() + nominal = getattr(private, 'nominalWidthX', 0) + for a, b in swaps: + ga, gb = cmap[a], cmap[b] + outline_a, outline_b = charstrings[ga], charstrings[gb] + charstrings[ga], charstrings[gb] = outline_b, outline_a + hmtx[ga], hmtx[gb] = hmtx[gb], hmtx[ga] + for cp, (advance, draw) in icons.items(): + pen = T2CharStringPen(advance - nominal, None); draw(pen) # the width operand is relative to nominalWidthX + charstrings[cmap[cp]] = pen.getCharString(private=private, globalSubrs=cff.GlobalSubrs) + glyphs = font.getGlyphSet() + for cp, (advance, _) in icons.items(): + box = BoundsPen(glyphs); glyphs[cmap[cp]].draw(box) + hmtx[cmap[cp]] = (advance, int(round(box.bounds[0]))) + out = io.BytesIO(); font.save(out) + return out.getvalue() + + +# ---- the button guide's images: square R8_UNORM masks (white key, black letter), one mip, block-linear, 72x72 up to +# 1.2.1 and 108x108 in 1.4.3. Each is drawn from the icon of the same Switch button, fitted into the square. +R8_UNORM, HUD_MARGIN, SUPERSAMPLE = 0x201, 4, 4 + + +def gob_offset(x, y, width_gobs, block_height): + """Byte offset of (x, y) in a Tegra block-linear surface of 1 byte per pixel (GOBs of 64 bytes x 8 rows).""" + return ((y // (8 * block_height)) * 512 * block_height * width_gobs + (x // 64) * 512 * block_height + + ((y % (8 * block_height)) // 8) * 512 + ((x % 64) // 32) * 256 + ((y % 8) // 2) * 64 + + ((x % 32) // 16) * 32 + (y % 2) * 16 + (x % 16)) + + +class PolygonPen(BasePen): + """Outlines flattened to closed polygons.""" + def __init__(self): + super().__init__(None); self.polygons = [] + + def _moveTo(self, pt): + self.polygons.append([pt]) + + def _lineTo(self, pt): + self.polygons[-1].append(pt) + + def _curveToOne(self, pt1, pt2, pt3): + p0 = self.polygons[-1][-1] + for i in range(1, 17): + t = i / 16; u = 1 - t + self.polygons[-1].append(tuple(u ** 3 * p0[k] + 3 * u * u * t * pt1[k] + 3 * u * t * t * pt2[k] + t ** 3 * pt3[k] + for k in (0, 1))) + + def _qCurveToOne(self, pt1, pt2): + p0 = self.polygons[-1][-1] + for i in range(1, 17): + t = i / 16; u = 1 - t + self.polygons[-1].append(tuple(u * u * p0[k] + 2 * u * t * pt1[k] + t * t * pt2[k] for k in (0, 1))) + + +def rasterize(draw, size): + """A size x size coverage mask (0..255, rows top down) of draw's outline, fitted into the square, nonzero winding.""" + rec = RecordingPen(); draw(rec) + box = BoundsPen(None); rec.replay(box); x0, y0, x1, y1 = box.bounds + inner = size - 2 * HUD_MARGIN; scale = inner / max(x1 - x0, y1 - y0) + ox = HUD_MARGIN + (inner - (x1 - x0) * scale) / 2 - x0 * scale + oy = HUD_MARGIN + (inner - (y1 - y0) * scale) / 2 - y0 * scale + flat = PolygonPen(); rec.replay(TransformPen(flat, (scale, 0, 0, -scale, ox, size - oy))) # font y up -> rows down + edges = [(a, b) for poly in flat.polygons for a, b in zip(poly, poly[1:] + poly[:1]) if a[1] != b[1]] + n = size * SUPERSAMPLE; cover = [0] * (size * size) + for row in range(n): + y = (row + 0.5) / SUPERSAMPLE + crossings = sorted((a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]), 1 if b[1] > a[1] else -1) + for a, b in edges if min(a[1], b[1]) <= y < max(a[1], b[1])) + winding, start = 0, None + for x, d in crossings: + if winding == 0: + start = x + winding += d + if winding == 0: + for col in range(max(0, round(start * SUPERSAMPLE)), min(n, round(x * SUPERSAMPLE))): + cover[(row // SUPERSAMPLE) * size + col // SUPERSAMPLE] += 1 + return bytes(min(255, c * 255 // (SUPERSAMPLE * SUPERSAMPLE)) for c in cover) + + +def bntx_redraw(data, base, textures, icons): + """Paint the icon of each texture of textures (name without the ^ suffix -> code point; icons: code point -> + (advance, draw)) over its image in the BNTX at data[base:] (a bytearray), in place. Returns the names painted.""" + assert data[base:base + 4] == b'BNTX' and data[base + 0x20:base + 0x24] == b'NX ' + count, table = struct.unpack_from('.Nin_NX_NVN.rsizetable.zs, a RESTBL whose +# entries are keyed by the CRC32 of the RomFS path without .zs. The game sizes the buffer it loads a file into from its +# entry, so an archive that grew needs its entry raised by as much. +def restbl_offsets(table): + """CRC32 of a path -> offset of its size in the RESTBL table.""" + assert table[:6] == b'RESTBL', 'not a RESTBL' + count = struct.unpack_from(' bytes it grew) raised by that much.""" + at, out = restbl_offsets(table), bytearray(table) + for path, extra in growth.items(): + h = zlib.crc32(path.removesuffix('.zs').encode()) + assert h in at, f'{path} has no entry in the resource size table' + struct.pack_into('x when the game resolution is that size (runtime/romfs.c overlay_init); the camera's side of it is the patch set aspect (recomp/patches-v121.txt, patches-v143.txt). ---xbox-prompts: the same overlay with the A and B, and the X and Y button prompts swapped, for pad_layout = xbox_prompts -(runtime/romfs.c overlay_init loads romfs-patches-xbox in place of romfs-patches). That layout plays an Xbox pad by -position, as nintendo does: the button that does Switch A is labelled B, and the prompts then name the label. Built from -the game's own images and glyphs, nothing added: -- the action prompt (blyt/DoCommand_00.bflyt) draws the letter images Nt_KeyTexA/B/X/Y_00 of timg/__Combined.bntx in - the Common archive: their image data is swapped (same format, size and tiling). Around it, a diamond names the - other face buttons with one-letter text panes (T_B_00, T_X_00, ...). The game fills them from the messages of the - same name in LayoutMsg/DoCommand_00.msbt of each Mals/ archive, over the layout's own text: both have - their letters swapped the same way. The diamond's shape (Nt_KeyBtnSubBase*) shows the button's position, which - stays right. -- every other prompt is text: the button glyphs U+E040 A, U+E041 B, U+E042 X, U+E043 Y of scft/External.bfotf, the - same font in each Font/Font*.Nin_NX_NVN.bfarc.zs. Their CFF outlines and horizontal metrics are swapped. +--prompts xbox | xbox-label: the same overlay with Xbox button icons in the game's prompts, for prompts = xbox +(runtime/romfs.c overlay_init loads romfs-patches-xbox or romfs-patches-xbox-label in place of romfs-patches). Drawn +from the game's own files on the player's machine, nothing added (tools/button_icons.py, which needs fontTools): +- both: L, R, ZL, ZR, Plus, Minus and the d-pad become LB, RB, LT, RT, Menu, View and a cross in the button font + (scft/External.bfotf, the same font in each Font/Font*.Nin_NX_NVN.bfarc.zs), and L and ZL in the button guide's images + (Nt_KeyTexL_00 and Nt_KeyTexZL_00 of timg/__Combined.bntx in the Common archive). The fonts grow, so the overlay also + carries the resource size table (System/Resource/ResourceSizeTable.Product....rsizetable.zs) with their entries + raised by as much. +- xbox, for pad_layout = nintendo. That layout plays an Xbox pad by position: the button that does Switch A is + labelled B, so the face buttons' prompts are swapped to name the labels, A with B and X with Y: + - the action prompt (blyt/DoCommand_00.bflyt) draws the letter images Nt_KeyTexA/B/X/Y_00 of timg/__Combined.bntx in + the Common archive: their image data is swapped (same format, size and tiling). Around it, a diamond names the + other face buttons with one-letter text panes (T_B_00, T_X_00, ...). The game fills them from the messages of the + same name in LayoutMsg/DoCommand_00.msbt of each Mals/ archive, over the layout's own text: both have + their letters swapped the same way. The diamond's shape (Nt_KeyBtnSubBase*) shows the button's position, which + stays right. + - every other prompt: the glyphs U+E040 A, U+E041 B, U+E042 X, U+E043 Y of the button font trade places. +- xbox-label, for pad_layout = xbox and auto. Those layouts put Switch A on the button labelled A (auto picks xbox for + every pad not labelled the Nintendo way), so the face buttons keep their letters; the action prompt's diamond keeps + the Switch positions (A on the right). +--xbox-prompts is the older name of --prompts xbox. Input: build/extracted//romfs (romfs.bin and index.json, verified by tools/extract.py). Output: -build//romfs-patches/ by default (romfs-patches-xbox with --xbox-prompts), and /manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314. +build//romfs-patches/ by default (romfs-patches-