From bb85bc8a80300a7f3e5f9c33e72859b51c4c8a6f Mon Sep 17 00:00:00 2001 From: mrtink125792 <350481146+mrtink125792@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:10:20 +0000 Subject: [PATCH 1/4] Add an Xbox prompts button layout: Switch positions with the A/B and X/Y prompts swapped to the Xbox labels With pad_layout = nintendo on an Xbox pad the right button does Switch A but is labelled B, the bottom one does B but is labelled A, and the game's prompts still name the Switch buttons. A fourth Button layout choice, Xbox prompts (A right) (pad_layout = xbox_prompts), maps the buttons as nintendo and swaps the prompts to the labels, so each prompt names the button to press. Automatic, Nintendo and Xbox are unchanged and keep the game's own prompts. The buttons change at once; the prompts at the next start, as the game reads its UI archive and fonts at boot (the menu says so). At start, xbox_prompts loads romfs-patches-xbox in place of romfs-patches (runtime/romfs.c overlay_init). tools/make_romfs_patches.py --xbox-prompts writes it from the player's own RomFS, with the 60 fps patches; nothing from the game or a mod is added to the repository. It swaps A with B and X with Y in: - the letter images Nt_KeyTexA/B/X/Y_00 of the action prompt (DoCommand_00), in the Common archive's __Combined.bntx (same format, size and tiling, so the image data trades places); - the action prompt's diamond of the other face buttons: one-letter text panes the game fills from LayoutMsg/DoCommand_00.msbt in each language's Mals archive (both the messages and the layout's own text); - the button glyphs U+E040 to U+E043 of scft/External.bfotf in each Font/Font*.bfarc, which every other prompt uses (CFF outlines and metrics in the deobfuscated OpenType font, then its checksums). The diamond's shape shows the button's position and stays. The setup writes both folders; the menu notes when the Xbox prompt files are missing and when the prompts in use differ from the choice until a restart. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/building.md | 3 + docs/controls.md | 14 +- docs/installer.md | 2 + installer/steps.py | 19 ++- runtime/cfg.c | 2 +- runtime/cfg_probe.c | 3 + runtime/fs.h | 2 + runtime/input_map.c | 2 +- runtime/input_map.h | 6 +- runtime/romfs.c | 24 ++- runtime/ui/menu.cpp | 16 +- runtime/ui_text.c | 18 ++- runtime/ui_text.h | 3 +- tools/build_game.py | 22 +-- tools/make_romfs_patches.py | 309 +++++++++++++++++++++++++++++++++--- tools/package_build.py | 2 + totk.ini.example | 4 +- 18 files changed, 402 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 13e75988..ec8f1979 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling - 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 - Shaders prepared at install instead of during play ## Planned diff --git a/docs/building.md b/docs/building.md index 30ebfd21..3718d083 100644 --- a/docs/building.md +++ b/docs/building.md @@ -87,6 +87,9 @@ From the repository root, in PowerShell. Every step that depends on the game ver ``` Lifting takes about 15 s, a clean compile about 200 s on 24 threads; later builds recompile only what changed. + 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`. `--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. diff --git a/docs/controls.md b/docs/controls.md index 0cceb44a..295e655c 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -7,8 +7,20 @@ 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*. The game's button prompts stay Switch letters either way. +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. + +## 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. + +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: + +- 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. + +Without the folder (an install made by an older setup) 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`. | Switch | Gamepad (by position, Nintendo layout) | Keyboard and mouse | Action in the world | |---|---|---|---| diff --git a/docs/installer.md b/docs/installer.md index a3158d28..e6ad004c 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -53,6 +53,8 @@ keeps `profile/`. Saves carry over both ways: 1.4.3 converts a 1.2.1 save on loa `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`). 6. **Clean up** the temp folder (generated C and objects, about 1.3 GB). A cancelled or failed setup resumes from the last finished step (`totk-install.json`). diff --git a/installer/steps.py b/installer/steps.py index b2109fa1..364625d9 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -6,7 +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/, totk_xlate.exe, the shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json. +romfs-patches/, romfs-patches-xbox/, 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). """ @@ -595,6 +596,7 @@ class Prepare(Step): dest = ctx.dest xlate = dest / ctx.layout.xlate.name return ((dest / 'shader-prepared.bin').is_file() and (dest / 'romfs-patches' / 'manifest.tsv').is_file() + and (dest / 'romfs-patches-xbox' / 'manifest.tsv').is_file() and xlate.is_file() and file_sha256(xlate) == record.get('xlate_sha256')) def run(self, ctx): @@ -612,12 +614,15 @@ class Prepare(Step): remove(xlate.with_suffix('.id')) rep.progress('prepare', 'romfs_patches', force=True) - remove(dest / 'romfs-patches') - code, log = run_tool(ctx, 'prepare', layout.tools / 'make_romfs_patches.py', - ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', - dest / 'romfs-patches']) - 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 (always written, + # so the menu setting works without another run of the setup). + for name, extra in (('romfs-patches', []), ('romfs-patches-xbox', ['--xbox-prompts'])): + remove(dest / name) + code, log = run_tool(ctx, 'prepare', layout.tools / 'make_romfs_patches.py', + ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', + dest / name] + extra) + if code: + raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log)) shader_list = layout.shader_list if not shader_list: diff --git a/runtime/cfg.c b/runtime/cfg.c index 417513e0..4ebd4e35 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -103,7 +103,7 @@ 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", LIVE}, + {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox|xbox_prompts", LIVE}, {"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, {"MENU_LANG", "", "en|ru", LIVE}, // Advanced: scheduling diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index 608d5f24..c1318ce0 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -277,6 +277,9 @@ int probe_cfg(void) { "pad layout: automatic is Nintendo for an east button labelled A, Xbox otherwise"); CHECK(input_pad_layout_pick("Xbox", 1) == PAD_LAYOUT_XBOX && input_pad_layout_pick("nintendo", 0) == PAD_LAYOUT_NINTENDO, "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)"); 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) && diff --git a/runtime/fs.h b/runtime/fs.h index 07cfe7a0..8584959b 100644 --- a/runtime/fs.h +++ b/runtime/fs.h @@ -38,6 +38,8 @@ 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) 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/input_map.c b/runtime/input_map.c index b0951a2e..1ae7e4a3 100644 --- a/runtime/input_map.c +++ b/runtime/input_map.c @@ -283,7 +283,7 @@ void input_map_line(const InputMap *m, int action, char *out, size_t n) { } int input_pad_layout_pick(const char *setting, int east_labelled_a) { - if (setting && !_stricmp(setting, "nintendo")) return PAD_LAYOUT_NINTENDO; + if (setting && (!_stricmp(setting, "nintendo") || !_stricmp(setting, "xbox_prompts"))) return PAD_LAYOUT_NINTENDO; if (setting && !_stricmp(setting, "xbox")) return PAD_LAYOUT_XBOX; return east_labelled_a ? PAD_LAYOUT_NINTENDO : PAD_LAYOUT_XBOX; } diff --git a/runtime/input_map.h b/runtime/input_map.h index bcfb42d1..6e66b4ab 100644 --- a/runtime/input_map.h +++ b/runtime/input_map.h @@ -80,8 +80,10 @@ 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); 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" 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. int input_pad_layout_pick(const char *setting, int east_labelled_a); // 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/romfs.c b/runtime/romfs.c index 0d7aee5b..bd7eb2c1 100644 --- a/runtime/romfs.c +++ b/runtime/romfs.c @@ -407,10 +407,32 @@ static void heapdef_overlay(void) { res_heapdef_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 + +int romfs_xbox_prompts_ready(void) { return xbox_prompts_ready; } +int romfs_xbox_prompts_active(void) { return xbox_prompts_active; } + 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) - char def[2100]; + // 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. + char def[2100], xbox[2100]; const char *patches = cfg_get("TOTK_ROMFS_PATCHES"); + xbox_prompts_ready = + snprintf(xbox, sizeof xbox, "%s/romfs-patches-xbox/manifest.tsv", index_dir) < (int)sizeof xbox && + GetFileAttributesA(xbox) != INVALID_FILE_ATTRIBUTES; + int want_xbox = !_stricmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts"); + if (!patches && want_xbox && xbox_prompts_ready) { + xbox[strlen(xbox) - strlen("/manifest.tsv")] = 0; + patches = xbox; + xbox_prompts_active = 1; + rt_log("RomFS overlay: Xbox button prompts (%s)", xbox); + } else if (want_xbox) { + rt_log("RomFS overlay: pad_layout = xbox_prompts, but %s; Switch prompts stay", + patches ? "TOTK_ROMFS_PATCHES is set" : "romfs-patches-xbox has no manifest.tsv (run the setup again)"); + } if (!patches && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def && GetFileAttributesA(def) != INVALID_FILE_ATTRIBUTES) { def[strlen(def) - strlen("/manifest.tsv")] = 0; diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 45c4428e..0a014722 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -38,6 +38,9 @@ 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[]; } @@ -555,8 +558,14 @@ static void tab_sound(float scale) { opt_end(); } -// "in use: Xbox" under the layout when it is Automatic and a gamepad is connected; NULL otherwise. +// 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. static const char *pad_layout_note(void) { + bool want = !_stricmp(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]; @@ -567,8 +576,9 @@ static const char *pad_layout_note(void) { 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}; - opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 3, 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, + 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()); 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"); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 33be5f0c..cb41a2e5 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -94,9 +94,14 @@ 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.", + "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.", [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_IN_USE] = "in use: %s", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Xbox prompts (A right)", + [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_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", @@ -317,9 +322,14 @@ 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 для остальных.", + "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных. Подсказки Xbox: " + "A справа, как в Nintendo, а игра показывает надписи Xbox (B вместо A, A вместо B, Y " + "вместо X, X вместо Y); подсказки меняются после перезапуска.", [UI_MENU_PAD_LAYOUT_AUTO] = "Автоматически", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A справа)", - [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", + [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] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами.", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 8df6ff0f..14fd10f2 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -56,7 +56,8 @@ 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_IN_USE, + 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_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, diff --git a/tools/build_game.py b/tools/build_game.py index 990c2072..22eb9581 100644 --- a/tools/build_game.py +++ b/tools/build_game.py @@ -174,16 +174,18 @@ 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.""" - src = ROOT / 'build' / version / 'romfs-patches' - dst = out / 'romfs-patches' - if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file(): - return - if (dst / 'manifest.tsv').is_file() and (dst / 'manifest.tsv').read_bytes() == (src / 'manifest.tsv').read_bytes(): - return - shutil.rmtree(dst, ignore_errors=True) - shutil.copytree(src, dst) - print(f'romfs patches: copied from {src}') + 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'): + src = ROOT / 'build' / version / name + dst = out / name + if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file(): + continue + if (dst / 'manifest.tsv').is_file() and (dst / 'manifest.tsv').read_bytes() == (src / 'manifest.tsv').read_bytes(): + continue + shutil.rmtree(dst, ignore_errors=True) + shutil.copytree(src, dst) + print(f'romfs patches: copied {name} from {src}') def c_string(s): diff --git a/tools/make_romfs_patches.py b/tools/make_romfs_patches.py index 21ddefff..ef5bd7aa 100644 --- a/tools/make_romfs_patches.py +++ b/tools/make_romfs_patches.py @@ -11,13 +11,27 @@ captured at once (upstream checked weapon, shield, material and ability wheel at The game-over flow fix of the same upstream script is 1.0.0 only (1.2.1 and 1.4.3 run DmF_SY_GameOver.110) and is left out. +--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. + Input: build/extracted//romfs (romfs.bin and index.json, verified by tools/extract.py). Output: -build//romfs-patches/ by default, 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-xbox with --xbox-prompts), and /manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314. """ import argparse import compression.zstd as zstd import hashlib import json +import re import struct from pathlib import Path @@ -25,17 +39,19 @@ root = Path(__file__).resolve().parents[1] ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument('--version', choices=('v121', 'v143'), default='v121') ap.add_argument('--romfs', type=Path, help='default build/extracted//romfs') -ap.add_argument('--out', type=Path, help='default build//romfs-patches') +ap.add_argument('--out', type=Path, + help='default build//romfs-patches (romfs-patches-xbox with --xbox-prompts)') +ap.add_argument('--xbox-prompts', action='store_true', help='swap the A/B and X/Y button prompts as well') args = ap.parse_args() args.romfs = args.romfs or root / 'build/extracted' / args.version / 'romfs' -args.out = args.out or root / 'build' / args.version / 'romfs-patches' +args.out = args.out or root / 'build' / args.version / ('romfs-patches-xbox' if args.xbox_prompts else 'romfs-patches') index = json.loads((args.romfs / 'index.json').read_text()) assert index['status'] == 'pass' files = {f['path']: f for f in index['files']} -def sarc_members(data): - """name -> (absolute start, end) of every SARC member.""" +def sarc_nodes(data): + """(name, node offset, absolute start, end) of every SARC member, in SFAT order.""" assert data[:4] == b'SARC' and data[6:8] == b'\xff\xfe' header, size, start = struct.unpack_from(' (absolute start, end) of every SARC member.""" + return {name: (lo, hi) for name, _, lo, hi in sarc_nodes(data)} + + def flvi_keys(data, base): """(pane name, absolute key offset, keys) of every FLVI (visibility) step track in the BFLAN at data[base:].""" assert data[base:base + 4] == b'FLAN' and data[base + 4:base + 6] == b'\xff\xfe' @@ -77,12 +99,226 @@ def flvi_keys(data, base): return out +def bntx_swap(data, base, pairs): + """Swap the image data of each (name, name) pair of textures in the BNTX at data[base:] (names without the ^ + suffix). Both of a pair must have the same header from flags to layout (format, size, tiling, mips) and image + size, so the bytes of one are a valid image of the other.""" + assert data[base:base + 4] == b'BNTX' and data[base + 0x20:base + 0x24] == b'NX ' + count, table = struct.unpack_from('_ (A, B, X or Y) in the BFLYT at data[base:end] by + swap (letter -> letter); the names of the panes changed. Same length (one UTF-16 letter and its terminator).""" + assert data[base:base + 4] == b'FLYT' + pos, changed = base + struct.unpack_from(' pos else '' + if letter in swap and re.fullmatch(r'T_[ABXY]_\d+', name): + data[at:at + 2] = swap[letter].encode('utf-16-le') + changed.append(name) + if not size: + break + pos += size + return changed + + +def msbt_letters(data, swap): + """Swap the one-letter messages labelled T__ (A, B, X or Y) in the UTF-16 MSBT data (a bytearray) by + swap; the labels changed. The game sets a layout's text panes from the messages of the same name in + Mals//LayoutMsg/.msbt, over the text stored in the layout.""" + assert data[:8] == b'MsgStdBn' and data[0x0c] == 1, 'not a UTF-16 MSBT' + sections, pos = {}, 0x20 + for _ in range(struct.unpack_from('H', data, pos)[0] + if not count: + return [], 0, pos + 2 + size = data[pos + 2] + offsets = [int.from_bytes(data[pos + 3 + i * size:pos + 3 + (i + 1) * size], 'big') for i in range(count + 1)] + first = pos + 2 + (count + 1) * size + return [(first + offsets[i], first + offsets[i + 1]) for i in range(count)], size, first + offsets[-1] + + +def cff_charstrings(data, cff): + """The offset (from the CFF table) of the CharStrings INDEX: operator 17 of the Top DICT. CID-keyed fonts (ROS, + operator 12 30) are refused: their glyphs can use different private dictionaries.""" + _, _, pos = cff_index(data, cff + data[cff + 2]) # Name INDEX after the header + top, _, _ = cff_index(data, pos) + (pos, end), operands, found = top[0], [], None + while pos < end: + b = data[pos] + if b <= 21: + op = (12, data[pos + 1]) if b == 12 else b + pos += 2 if b == 12 else 1 + assert op != (12, 30), 'CID-keyed CFF' + if op == 17: + found = operands[-1] + operands = [] + elif b == 28: + operands.append(struct.unpack_from('>h', data, pos + 1)[0]); pos += 3 + elif b == 29: + operands.append(struct.unpack_from('>i', data, pos + 1)[0]); pos += 5 + elif b == 30: # real number: nibbles up to an 0xf + pos += 1 + while data[pos] & 0x0f != 0x0f and data[pos] & 0xf0 != 0xf0: + pos += 1 + pos += 1 + operands.append(0) + elif b <= 246: + operands.append(b - 139); pos += 1 + elif b <= 250: + operands.append((b - 247) * 256 + data[pos + 1] + 108); pos += 2 + else: + operands.append(-(b - 251) * 256 - data[pos + 1] - 108); pos += 2 + assert found is not None, 'no CharStrings in the Top DICT' + return found + + +def otf_glyph(data, cmap, code): + """The glyph id of a code point in the format 4 (platform 3 encoding 1) subtable of the cmap at data[cmap:].""" + for k in range(struct.unpack_from('>H', data, cmap + 2)[0]): + platform, encoding, offset = struct.unpack_from('>HHI', data, cmap + 4 + 8 * k) + p = cmap + offset + if (platform, encoding) != (3, 1) or struct.unpack_from('>H', data, p)[0] != 4: + continue + seg = struct.unpack_from('>H', data, p + 6)[0] // 2 + for s in range(seg): + end = struct.unpack_from('>H', data, p + 14 + 2 * s)[0] + start = struct.unpack_from('>H', data, p + 16 + 2 * seg + 2 * s)[0] + if not start <= code <= end: + continue + delta = struct.unpack_from('>h', data, p + 16 + 4 * seg + 2 * s)[0] + at = p + 16 + 6 * seg + 2 * s + ro = struct.unpack_from('>H', data, at)[0] + glyph = code if not ro else struct.unpack_from('>H', data, at + ro + 2 * (code - start))[0] + return (glyph + delta) & 0xffff if glyph else 0 + raise AssertionError(f'U+{code:04X} is not in the font') + + +def otf_checksum(data): + data = bytes(data) + bytes(-len(data) % 4) + return sum(struct.unpack(f'>{len(data) // 4}I', data)) & 0xffffffff + + +def bfotf_swap(data, pairs): + """The BFOTF data with the glyphs of each (code point, code point) pair swapped: CFF outlines and horizontal + metrics, then the table checksums. A BFOTF is an OpenType font after an 8-byte header; from offset 4 on, every + 4-byte word is XORed with one key, which the size field gives away (it holds the font's length).""" + key = bytes(x ^ y for x, y in zip(data[4:8], struct.pack('>I', len(data) - 8))) + plain = bytearray(data[:4]) + bytearray(x ^ key[i % 4] for i, x in enumerate(data[4:])) + font = plain[8:] + assert font[:4] == b'OTTO', 'not a CFF OpenType font' + tables = {} + for k in range(struct.unpack_from('>H', font, 4)[0]): + tag, _, offset, length = struct.unpack_from('>4sIII', font, 12 + 16 * k) + tables[tag] = (12 + 16 * k, offset, length) + cff = tables[b'CFF '][1] + strings, size, end = cff_index(font, cff + cff_charstrings(font, cff)) + hmtx, metrics = tables[b'hmtx'][1], struct.unpack_from('>H', font, tables[b'hhea'][1] + 34)[0] + order = list(range(len(strings))) + for a, b in pairs: + ga, gb = otf_glyph(font, tables[b'cmap'][1], a), otf_glyph(font, tables[b'cmap'][1], b) + assert 0 < ga < len(strings) and 0 < gb < len(strings) and ga < metrics and gb < metrics, (a, b, ga, gb) + order[ga], order[gb] = order[gb], order[ga] + ma, mb = hmtx + 4 * ga, hmtx + 4 * gb + font[ma:ma + 4], font[mb:mb + 4] = font[mb:mb + 4], font[ma:ma + 4] + # The CharStrings INDEX again with the items in the new order: the same length, so nothing after it moves. + body = b''.join(bytes(font[slice(*strings[g])]) for g in order) + first = strings[0][0] + assert first + len(body) == end + font[first:end] = body + at, base = first - (len(strings) + 1) * size, 1 # the offset array ends where the first item starts + for i, g in enumerate(order + [None]): + font[at + i * size:at + (i + 1) * size] = base.to_bytes(size, 'big') + if g is not None: + base += strings[g][1] - strings[g][0] + head = tables[b'head'][1] + struct.pack_into('>I', font, head + 8, 0) + for entry, offset, length in tables.values(): + struct.pack_into('>I', font, entry + 4, otf_checksum(font[offset:offset + length])) + struct.pack_into('>I', font, head + 8, (0xb1b0afba - otf_checksum(font)) & 0xffffffff) + plain[8:] = font + return bytes(plain[:4]) + bytes(x ^ key[i % 4] for i, x in enumerate(plain[4:])) + + +def sarc_replace(data, new): + """The SARC data with the members named in new (name -> bytes) replaced. The header, SFAT and SFNT stay; the + members are laid out again in their old order, each at an offset with at least the alignment its old one had.""" + start = struct.unpack_from(' MALS.get(m[1], (0, ''))[0]: + MALS[m[1]] = (int(m[2]), p) +MALS = sorted(p for _, p in MALS.values()) +LAYOUT_MSG = 'LayoutMsg/DoCommand_00.msbt' with (args.romfs / 'romfs.bin').open('rb') as image: def read(path): @@ -96,7 +332,8 @@ with (args.romfs / 'romfs.bin').open('rb') as image: for name, (lo, hi) in sarc_members(pack).items(): d = zstd.ZstdDict(pack[lo:hi]) dictionaries[d.dict_id] = d - raw = read(ARCHIVE) + originals = {path: read(path) for path in [ARCHIVE] + (FONTS + MALS if args.xbox_prompts else [])} +raw = originals[ARCHIVE] info = zstd.get_frame_info(raw) dictionary = dictionaries[info.dictionary_id] original = zstd.decompress(raw, zstd_dict=dictionary) @@ -117,13 +354,49 @@ for member, panes in MEMBERS.items(): patched[member] = changed diff = [i for i in range(len(original)) if original[i] != blarc[i]] assert diff and all(any(lo <= i < hi for lo, hi in (members[m] for m in MEMBERS)) for i in diff), diff -data = zstd.compress(bytes(blarc), level=19, zstd_dict=dictionary) -assert zstd.decompress(data, zstd_dict=dictionary) == bytes(blarc) -assert zstd.get_frame_info(data).dictionary_id == info.dictionary_id -target = args.out / ARCHIVE -target.parent.mkdir(parents=True, exist_ok=True) -target.write_bytes(data) -line = '\t'.join([ARCHIVE, str(len(data)), hashlib.sha256(data).hexdigest(), hashlib.sha256(raw).hexdigest()]) +outputs = {ARCHIVE: bytes(blarc)} # RomFS path -> new contents (before compression) +if args.xbox_prompts: + bntx_swap(blarc, members['timg/__Combined.bntx'][0], KEY_TEXTURES) + letters = {} + for member, (lo, hi) in members.items(): + if member.endswith('.bflyt'): + changed = bflyt_letters(blarc, lo, hi, KEY_LETTERS) + if changed: + letters[member] = changed + assert 'blyt/DoCommand_00.bflyt' in letters, 'no letter panes in blyt/DoCommand_00.bflyt' + outputs[ARCHIVE] = bytes(blarc) + assert FONTS, 'no Font/Font*.Nin_NX_NVN.bfarc.zs in the RomFS' + for path in FONTS: + frame = zstd.get_frame_info(originals[path]) + bfarc = zstd.decompress(originals[path], zstd_dict=dictionaries.get(frame.dictionary_id)) + lo, hi = sarc_members(bfarc)['scft/External.bfotf'] + outputs[path] = sarc_replace(bfarc, {'scft/External.bfotf': bfotf_swap(bfarc[lo:hi], KEY_GLYPHS)}) + assert MALS, 'no Mals/.Product..sarc.zs in the RomFS' + messages = {} + for path in MALS: + frame = zstd.get_frame_info(originals[path]) + mals = bytearray(zstd.decompress(originals[path], zstd_dict=dictionaries.get(frame.dictionary_id))) + lo, hi = sarc_members(mals)[LAYOUT_MSG] + msbt = bytearray(mals[lo:hi]) + changed = msbt_letters(msbt, KEY_LETTERS) + assert len(changed) == sum(len(v) for v in letters.values()), (path, changed) + mals[lo:hi] = msbt + outputs[path] = bytes(mals) + messages[path] = len(changed) + +lines = [] +for path, contents in outputs.items(): + raw = originals[path] + dictionary = dictionaries.get(zstd.get_frame_info(raw).dictionary_id) + data = zstd.compress(contents, level=19, zstd_dict=dictionary) + assert zstd.decompress(data, zstd_dict=dictionary) == contents + assert zstd.get_frame_info(data).dictionary_id == zstd.get_frame_info(raw).dictionary_id + target = args.out / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + lines.append('\t'.join([path, str(len(data)), hashlib.sha256(data).hexdigest(), hashlib.sha256(raw).hexdigest()])) (args.out / 'manifest.tsv').write_text('# path\tsize\tsha256\toriginal_sha256 (tools/make_romfs_patches.py)\n' - + line + '\n') -print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, size=len(data), changed_bytes=len(diff)))) + + ''.join(line + '\n' for line in lines)) +print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, changed_bytes=len(diff), + xbox_prompts=dict(textures=KEY_TEXTURES, letters=letters, messages=messages, fonts=FONTS) + if args.xbox_prompts else None))) diff --git a/tools/package_build.py b/tools/package_build.py index 302075e0..c2071ba0 100644 --- a/tools/package_build.py +++ b/tools/package_build.py @@ -91,6 +91,8 @@ def main(): else: print(f'package_build: {f} not in {build}, skipped') n = copy_tree(build / 'romfs-patches', out / 'romfs-patches') + if (build / 'romfs-patches-xbox').is_dir(): # pad_layout = xbox_prompts (make_romfs_patches.py --xbox-prompts) + n += copy_tree(build / 'romfs-patches-xbox', out / 'romfs-patches-xbox') n += copy_tree(exefs, out / 'exefs') n += copy_tree(fonts, out / 'shared-fonts') if not a.no_shader_cache and (build / 'shader-cache').is_dir(): diff --git a/totk.ini.example b/totk.ini.example index 93e21dcd..663c27af 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -148,7 +148,9 @@ # rumble_triggers = 0 # Which gamepad button is Switch A: nintendo (by position: east A, south B, west Y, north X), xbox (south A, east B, # west X, north Y, as an Xbox pad labels them; cross A on a PlayStation pad) or auto (nintendo for a pad with Nintendo -# labels, xbox for the others). The bind_ lines below apply on top. Changes while the game runs take effect at once. +# labels, xbox for the others). xbox_prompts: the buttons as nintendo, and the game's prompts swapped to the Xbox +# labels (A with B, X with Y; it loads romfs-patches-xbox, docs/controls.md, "Xbox button prompts"). The bind_ lines +# below apply on top. Changes while the game runs take effect at once; the xbox_prompts prompts at the next start. # pad_layout = auto # Gamepad stick dead zone in percent of full deflection (0 to 50). Raise it for a stick that drifts: inside the circle # the stick reads centred, and the rest of its travel is scaled to start there. From 7923e2da6e83688ffdcb720079f8184336ae3b51 Mon Sep 17 00:00:00 2001 From: mrtink125792 <350481146+mrtink125792@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:27:04 +0000 Subject: [PATCH 2/4] Let the setup go on without the Xbox prompts, and put the Xbox prompts docs below the controls table romfs-patches-xbox is optional: when make_romfs_patches.py --xbox-prompts fails (a game update whose prompts it does not recognise), the setup removes the partial folder, warns (warn.xbox_prompts_failed) and finishes, where it stopped the whole install before. The game then keeps the Switch prompts and the menu says the files are missing. Its log is prepare-xbox-make_romfs_patches.log, so it no longer replaces the 60 fps run's log, and Prepare no longer counts the folder as part of a finished step. The Xbox button prompts section of docs/controls.md sat between the layout list and the controls table it introduces; it now follows the table. The building.md note follows the paragraph it interrupted. Co-Authored-By: Claude Opus 5.5 --- docs/building.md | 4 ++-- docs/controls.md | 22 +++++++++++----------- installer/steps.py | 26 ++++++++++++++++---------- installer/text/en.json | 1 + installer/text/ru.json | 1 + 5 files changed, 31 insertions(+), 23 deletions(-) diff --git a/docs/building.md b/docs/building.md index 3718d083..44216cc0 100644 --- a/docs/building.md +++ b/docs/building.md @@ -87,11 +87,11 @@ From the repository root, in PowerShell. Every step that depends on the game ver ``` Lifting takes about 15 s, a clean compile about 200 s on 24 threads; later builds recompile only what changed. + `--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`. - `--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. 6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`) for the shared shader list: diff --git a/docs/controls.md b/docs/controls.md index 295e655c..df57d17e 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -11,17 +11,6 @@ Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into 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. -## 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. - -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: - -- 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. - -Without the folder (an install made by an older setup) 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`. - | Switch | Gamepad (by position, Nintendo layout) | Keyboard and mouse | Action in the world | |---|---|---|---| | Left stick | left stick | W A S D | move | @@ -42,6 +31,17 @@ Without the folder (an install made by an older setup) the menu says the files a Esc is unbound in the game; it opens the settings menu and releases the mouse cursor (see Mouse camera). Z and X duplicate ZL and ZR so menu pages turn with two neighbouring keys; the menu tabs (L, R) are Q and R. The mouse wheel is unbound. The bindings are the tables of `input_map` in `runtime/input_map.c`: the keys (platform-neutral key ids) and one gamepad table per layout (gamepad inputs by position); `runtime/input_win.c` translates Win32 virtual keys and SDL buttons. +## 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. + +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: + +- 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. + +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`. + ## Window keys | Key | Gamepad | Action | diff --git a/installer/steps.py b/installer/steps.py index 364625d9..07f9f917 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -596,7 +596,6 @@ class Prepare(Step): dest = ctx.dest xlate = dest / ctx.layout.xlate.name return ((dest / 'shader-prepared.bin').is_file() and (dest / 'romfs-patches' / 'manifest.tsv').is_file() - and (dest / 'romfs-patches-xbox' / 'manifest.tsv').is_file() and xlate.is_file() and file_sha256(xlate) == record.get('xlate_sha256')) def run(self, ctx): @@ -614,15 +613,22 @@ class Prepare(Step): remove(xlate.with_suffix('.id')) rep.progress('prepare', 'romfs_patches', force=True) - # romfs-patches-xbox: the same with the A/B and X/Y prompts swapped, for pad_layout = xbox_prompts (always written, - # so the menu setting works without another run of the setup). - for name, extra in (('romfs-patches', []), ('romfs-patches-xbox', ['--xbox-prompts'])): - remove(dest / name) - code, log = run_tool(ctx, 'prepare', layout.tools / 'make_romfs_patches.py', - ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', - dest / name] + extra) - if code: - raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log)) + remove(dest / 'romfs-patches') + code, log = run_tool(ctx, 'prepare', layout.tools / 'make_romfs_patches.py', + ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', + dest / 'romfs-patches']) + 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)) shader_list = layout.shader_list if not shader_list: diff --git a/installer/text/en.json b/installer/text/en.json index 5e8a5912..c30ea40c 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -82,6 +82,7 @@ "warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts, which the installer does not extract; some text may not show.", "warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.", + "warn.xbox_prompts_failed": "The Xbox button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}", "ui.title": "TotK Setup", "ui.version": "version {version}", diff --git a/installer/text/ru.json b/installer/text/ru.json index fa4d3a76..3a325526 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -82,6 +82,7 @@ "warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch, которые установка не извлекает; часть текста может не отображаться.", "warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.", + "warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}", "ui.title": "Установка TotK", "ui.version": "версия {version}", From 301fc19aa368b1b4a24cdc12d23964c62396dc09 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sat, 31 Oct 2026 07:52:41 +0300 Subject: [PATCH 3/4] Fall back to romfs-patches when romfs-patches-xbox fails its check at boot The Xbox prompts folder is optional, so a manifest that no longer matches the RomFS logs the reason and drops that folder instead of stopping the game. The main romfs-patches and the mods folder keep their fatal checks. Co-Authored-By: Claude Opus 5.5 --- runtime/romfs.c | 50 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/runtime/romfs.c b/runtime/romfs.c index bd7eb2c1..69fa0fae 100644 --- a/runtime/romfs.c +++ b/runtime/romfs.c @@ -244,7 +244,11 @@ static uint32_t overlay_slot(uint64_t i) { } // ---- overlays -static void overlay_load(const char *dir) { +// Loads and checks one overlay folder. A failed check stops the game, except with optional set (the Xbox prompts +// folder): the folder is dropped, the reason logged, and 0 returned. Returns 1 when the folder is loaded or has no +// manifest. +static int overlay_load(const char *dir, int optional) { +#define BAD(...) do { if (!optional) rt_fatal(__VA_ARGS__); rt_log(__VA_ARGS__); goto bad; } while (0) char path[2100]; need(snprintf(path, sizeof path, "%s/manifest.tsv", dir) < (int)sizeof path, "overlay path"); wchar_t *w = fs_wide(path); @@ -252,7 +256,7 @@ static void overlay_load(const char *dir) { free(w); if (!m) { rt_log("RomFS overlay: none (%s)", path); - return; + return 1; } char line[8192]; size_t first = noverlay; @@ -268,30 +272,32 @@ static void overlay_load(const char *dir) { uint64_t i = lower(name); int known = i < file_count && !strcmp(entry_name(entry(i)), name), add = !strcmp(orig, "-"); if (!known && !add) - rt_fatal("RomFS overlay: %s/manifest.tsv names %s, which the RomFS lacks; a new file has \"-\" as its " - "original's SHA-256", dir, name); + BAD("RomFS overlay: %s/manifest.tsv names %s, which the RomFS lacks; a new file has \"-\" as its " + "original's SHA-256", dir, name); if (known && add) - rt_fatal("RomFS overlay: %s/manifest.tsv adds %s, which the RomFS already has; give its original's SHA-256", - dir, name); + BAD("RomFS overlay: %s/manifest.tsv adds %s, which the RomFS already has; give its original's SHA-256", + dir, name); Entry e = {0}; if (known) { e = entry(i); sha_range(image, e.offset, e.size, hex, 0); - if (strcmp(hex, orig)) rt_fatal("RomFS overlay: the original of %s has SHA-256 %s, %s/manifest.tsv says %s", - name, hex, dir, orig); + if (strcmp(hex, orig)) BAD("RomFS overlay: the original of %s has SHA-256 %s, %s/manifest.tsv says %s", + name, hex, dir, orig); } else { i = ADDED; } char file[8200]; need(snprintf(file, sizeof file, "%s/%s", dir, name) < (int)sizeof file, "overlay file path"); HANDLE f = open_read(file, 1); - if (f == INVALID_HANDLE_VALUE) rt_fatal("RomFS overlay: %s missing", file); + if (f == INVALID_HANDLE_VALUE) BAD("RomFS overlay: %s missing", file); Identity id = identity_of(f); - if (id.size != size) rt_fatal("RomFS overlay: %s has %llu bytes, its manifest says %llu", file, - (unsigned long long)id.size, size); + if (id.size != size) { + CloseHandle(f); + BAD("RomFS overlay: %s has %llu bytes, its manifest says %llu", file, (unsigned long long)id.size, size); + } sha_range(f, 0, size, hex, 0); CloseHandle(f); - if (strcmp(hex, sha)) rt_fatal("RomFS overlay: %s has SHA-256 %s, its manifest says %s", file, hex, sha); + if (strcmp(hex, sha)) BAD("RomFS overlay: %s has SHA-256 %s, its manifest says %s", file, hex, sha); hashed += e.size + size; if (noverlay == overlay_cap) { overlay_cap = overlay_cap ? overlay_cap * 2 : 16; @@ -309,6 +315,16 @@ static void overlay_load(const char *dir) { noverlay - first - 16); if (noverlay > first) rt_log("RomFS overlay: %s checked, %zu files, %.1f MiB hashed in %.2f s", dir, noverlay - first, hashed / 1048576.0, now_s() - t0); + return 1; +bad: + fclose(m); + for (size_t k = first; k < noverlay; k++) { + free((void *)overlays[k].path); + free((void *)overlays[k].name); + } + noverlay = first; + return 0; +#undef BAD } static int overlay_order(const void *a, const void *b) { @@ -426,21 +442,21 @@ static void overlay_init(void) { int want_xbox = !_stricmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts"); if (!patches && want_xbox && xbox_prompts_ready) { xbox[strlen(xbox) - strlen("/manifest.tsv")] = 0; - patches = xbox; - xbox_prompts_active = 1; - rt_log("RomFS overlay: Xbox button prompts (%s)", xbox); + 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", patches ? "TOTK_ROMFS_PATCHES is set" : "romfs-patches-xbox has no manifest.tsv (run the setup again)"); } - if (!patches && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def && + if (!patches && !xbox_prompts_active && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def && GetFileAttributesA(def) != INVALID_FILE_ATTRIBUTES) { def[strlen(def) - strlen("/manifest.tsv")] = 0; patches = def; } 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]); + if (dirs[i] && *dirs[i] && strcmp(dirs[i], "0")) overlay_load(dirs[i], 0); heapdef_overlay(); added_init(); if (noverlay) qsort(overlays, noverlay, sizeof *overlays, overlay_order); From 61dccff1a0be1736813a9f4d19ad30ec79d8cea2 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Sat, 31 Oct 2026 07:52:59 +0300 Subject: [PATCH 4/4] Say that the Xbox prompts do not follow remapped buttons The swapped letters are baked into the game's textures, fonts and messages, so a button remapped with a bind_ line or on the Controls tab keeps the old letter on screen. The menu description (English and Russian) and docs/controls.md now say so. Co-Authored-By: Claude Opus 5.5 --- docs/controls.md | 2 ++ runtime/ui_text.c | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/controls.md b/docs/controls.md index df57d17e..29f53f0d 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -35,6 +35,8 @@ Esc is unbound in the game; it opens the settings menu and releases the mouse cu `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. +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. + 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: - 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. diff --git a/runtime/ui_text.c b/runtime/ui_text.c index cb41a2e5..7313a396 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -96,7 +96,8 @@ static const char *const text_en[UI_TEXT_COUNT] = { "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.", + "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.", [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_IN_USE] = "in use: %s", @@ -324,7 +325,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { "подписано на контроллере Xbox (крест на контроллере PlayStation). Автоматически: " "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных. Подсказки Xbox: " "A справа, как в Nintendo, а игра показывает надписи Xbox (B вместо A, A вместо B, Y " - "вместо X, X вместо Y); подсказки меняются после перезапуска.", + "вместо X, X вместо Y); подсказки меняются после перезапуска. Буквы записаны в файлах " + "игры, поэтому у кнопки, переназначенной на вкладке управления, на экране остаётся " + "прежняя буква.", [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",