Add keyboard and mouse button prompts (prompts = pc)

The Button prompts row gets a third choice, PC: every button glyph of the game's button font and every image of the
button guide is drawn as the key or mouse button the keyboard defaults press it with (E, Shift, Space, left click, Q,
R, right click, F, Tab, M, 1 to 4, W A S D, Ctrl, C) and the right stick as the mouse, whatever the pad layout. The
setup writes romfs-patches-pc next to the Xbox folders (make_romfs_patches.py --prompts pc, button_icons.py pc_icons);
--binds <totk.ini> draws the keys of its bind_ lines instead. At a game resolution of another shape the game takes
romfs-patches-pc-<w>x<h> (--prompts pc --aspect) in place of romfs-patches-<w>x<h> when it is there.

(cherry picked from commit 3f81cf02be664100bd9c569c53588d620d90b527)
This commit is contained in:
Wintego authored and Valiantsin Dzerakh committed 2026-11-04 08:36:28 +03:00
1 parent 56b3cd1246
commit cb628b08b7
22 files changed
+386 -84

No files matched your search

+2 -1
View File
@@ -115,7 +115,8 @@ of them.
`SDL3.dll`, `libiconv-2.dll` and `libopus-0.dll` next to the exe.
For Xbox button prompts, run `make_romfs_patches.py` twice more, with `--prompts xbox` and `--prompts xbox-label`:
they write `build\<ver>\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`.
button prompts"), which `build_game.py` copies next to `totk.exe` like `romfs-patches`. `--prompts pc` writes
`romfs-patches-pc`, the keyboard and mouse prompts ([controls.md](controls.md), "PC button prompts").
6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`)
for the shared shader list:
+19 -1
View File
@@ -33,7 +33,7 @@ Esc is unbound in the game; it opens the settings menu and releases the mouse cu
## Xbox button prompts
`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.
`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, `pc` the keyboard and mouse (PC button prompts, below).
- 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.
@@ -57,6 +57,24 @@ The game reads its UI archive and fonts once at boot, so the prompts change at t
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 <ver> --prompts xbox` (and `--prompts xbox-label`) writes `build\<ver>\romfs-patches-xbox` (`-label`); it needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`.
## PC button prompts
`prompts = pc` (*PC* on the *Button prompts* row) shows the key or mouse button the default keyboard bindings press each Switch button with, whatever the pad layout. The game loads `romfs-patches-pc` in place of `romfs-patches`, written by `tools/make_romfs_patches.py --prompts pc` (`button_icons.py`, `pc_icons`), which the setup runs next to the Xbox ones:
| Switch | Prompt |
|---|---|
| A, B, X, Y | E, Shift, Space, left click |
| L, R, ZL, ZR | Q, R, right click, F |
| Plus, Minus | Tab, M |
| D-pad | 1 (left), 2 (up), 3 (right), 4 (down), as a cross or the keys of the directions meant |
| Left stick, its press | W A S D (or the keys of the directions meant), Ctrl |
| Right stick, its press | the mouse, with an arrow for each direction meant, C |
- The glyphs keep the width of the game's own, so the right-aligned guides do not run into their text. A key is a rounded square with its label cut out in the game's own text fonts; a mouse button is a mouse with that button filled and the others hollow.
- The button guide in play draws every button from images of the Common archive (`Nt_KeyTexA/B/X/Y/L/ZL_00`, `Nt_KeyTexLSt_00` and `_01`, the stick tilted and pressed): all of them are painted with the same icons. The letters of the action prompt's diamond are one character of the Normal font each: E, an arrow for Shift, a bar for Space, L and R for the mouse buttons.
- Like the Xbox prompts they follow the defaults and not the bindings. `--binds <totk.ini>` draws the first key of each `bind_` line of that file instead, for a folder made by hand.
- At a game resolution of another shape than 16:9 the game loads `romfs-patches-pc-<w>x<h>` in place of `romfs-patches-<w>x<h>` when it is there: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts pc --aspect <w>x<h> --out <install>\romfs-patches-pc-<w>x<h>`. The setup does not write those, so without one the Switch prompts stay (*off at a game resolution not 16:9*).
## Window keys
| Key | Gamepad | Action |
+3 -2
View File
@@ -67,9 +67,10 @@ 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 three times: `romfs-patches`, and `romfs-patches-xbox` and `romfs-patches-xbox-label`
The patches are written four times: `romfs-patches`, `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.
and `auto`), and `romfs-patches-pc` (keyboard and mouse prompts for `prompts = pc`). The three prompt 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.
+5 -3
View File
@@ -7,7 +7,8 @@ recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and tools/prepar
with the bundled clang (hostcheck.c).
Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ (Chinese and Korean text), totk.exe
and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/, romfs-patches-xbox-label/, totk_xlate.exe, the
and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/,
romfs-patches-xbox-label/, romfs-patches-pc/, totk_xlate.exe, the
shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json.
Temp folder (<temp>/<dest name>-<hash>): check/ (ExeFS of both inputs, the host check), unpacked/ (the NSP of an NSZ
or XCZ input until the extraction is done), gen/ (C), build/ (objects), logs/. The cleanup keeps gen/, build/ and
@@ -1067,9 +1068,10 @@ class Prepare(Step):
# 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.
# files are missing, so the setup warns once and goes on. romfs-patches-pc likewise, with keyboard and mouse
# prompts for prompts = pc (16:9 only: another shape takes make_romfs_patches.py --prompts pc --aspect).
failed = None
for style in ('xbox', 'xbox-label'):
for style in ('xbox', 'xbox-label', 'pc'):
out = dest / f'romfs-patches-{style}'
remove(out)
code, log = run_tool(ctx, f'prepare-{style}', layout.tools / 'make_romfs_patches.py',
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.",
"warn.cheats_skipped": "The cheats of the mods folder that change the game's code could not be built; the game installs without them. Details: {log}",
"warn.exefs_skipped": "The mods' ExeFS patches (.ips, .pchtxt) could not be built; the game installs without them. Details: {log}",
"warn.xbox_prompts_failed": "The Xbox button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
"warn.xbox_prompts_failed": "The Xbox or PC button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
"warn.shaders_skipped": "The graphics driver crashed while building some shaders, so {count} were left out of the preparation. The game builds them when it first needs them, and the driver may crash there too; a driver update may fix it. Details: {log}",
"warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.",
"warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.",
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.cheats_skipped": "Não foi possível compilar os cheats da pasta de mods que alteram o código do jogo; o jogo é instalado sem eles. Detalhes: {log}",
"warn.exefs_skipped": "Não foi possível compilar os patches ExeFS dos mods (.ips, .pchtxt); o jogo é instalado sem eles. Detalhes: {log}",
"warn.npdm_differs": "O main.npdm difere do dump de referência da versão {version}; só os módulos de código são usados.",
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox ou do PC (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
"warn.shaders_skipped": "O driver gráfico travou ao compilar alguns shaders, então {count} ficaram fora da preparação. O jogo os compila quando precisar deles pela primeira vez, e o driver pode travar ali também; uma atualização do driver pode resolver. Detalhes: {log}",
"warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.",
"warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.",
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.",
"warn.cheats_skipped": "Не удалось собрать читы из папки модов, меняющие код игры; игра установится без них. Подробности: {log}",
"warn.exefs_skipped": "Не удалось собрать ExeFS-патчи модов (.ips, .pchtxt); игра установится без них. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox или PC (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
"warn.shaders_skipped": "Графический драйвер аварийно завершился при сборке части шейдеров, поэтому {count} из них пропущены при подготовке. Игра соберёт их, когда они впервые понадобятся, и драйвер может упасть и там; обновление драйвера может это исправить. Подробности: {log}",
"warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.",
"warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.",
+1 -1
View File
@@ -103,7 +103,7 @@
"warn.cheats_skipped": "无法构建 mods 文件夹中修改游戏代码的金手指;游戏将不含它们进行安装。详情:{log}",
"warn.exefs_skipped": "无法构建模组的 ExeFS 补丁(.ips、.pchtxt);游戏将不含它们进行安装。详情:{log}",
"warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。",
"warn.xbox_prompts_failed": "无法准备 Xbox 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.xbox_prompts_failed": "无法准备 Xbox 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.shaders_skipped": "显卡驱动在编译部分着色器时崩溃,因此有 {count} 个着色器未被预先准备。游戏会在首次需要时编译它们,驱动在那时也可能崩溃;更新驱动可能会解决。详情:{log}",
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
+1 -1
View File
@@ -145,7 +145,7 @@ static const CfgMeta metas[] = {
{"VOLUME", "100", "0..100", LIVE}, {"AUDIO_CHANNELS", "stereo", "auto|stereo|5.1", RESTART},
{"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},
{"PROMPTS", "nintendo", "nintendo|xbox", RESTART},
{"PROMPTS", "nintendo", "nintendo|xbox|pc", RESTART},
{"STICK_DEADZONE", "8", "0..50", LIVE}, {"STICK_SENS", "1", "0.1..3", RESTART},
{"LSTICK_DEADZONE", "", "0..50", LIVE}, {"RSTICK_DEADZONE", "", "0..50", LIVE},
{"MOUSE_MODE", "direct", "stick|direct", LIVE},
+5
View File
@@ -305,6 +305,11 @@ int probe_cfg(void) {
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("PC", "nintendo") == PROMPTS_PC && input_prompts_pick("pc", "xbox_prompts") == PROMPTS_PC &&
EQ(input_prompts_folder(PROMPTS_PC, "nintendo"), "romfs-patches-pc") &&
EQ(input_prompts_folder(PROMPTS_PC, "xbox"), "romfs-patches-pc") &&
EQ(input_prompts_folder(PROMPTS_PC, NULL), "romfs-patches-pc"),
"prompts: pc shows the keyboard and mouse whatever the pad layout");
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"),
+2 -1
View File
@@ -41,7 +41,8 @@ size_t romfs_overlay_count(void);
int romfs_patches_loaded(void); // a romfs-patches manifest gave at least one file
// 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).
// for any other folder: it was not asked for). romfs-patches-pc goes by that name also where romfs-patches-pc-<w>x<h>
// stands in for it (romfs.c overlay_init).
enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROMPTS_SHAPE, ROMFS_PROMPTS_MODS,
ROMFS_PROMPTS_PATCHES };
const char *romfs_prompts(void);
+3 -1
View File
@@ -289,11 +289,13 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) {
}
int input_prompts_pick(const char *prompts, const char *pad_layout) {
if (prompts && *prompts) return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : PROMPTS_NINTENDO;
if (prompts && *prompts)
return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : !strcasecmp(prompts, "pc") ? PROMPTS_PC : 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_PC) return "romfs-patches-pc";
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.
+8 -5
View File
@@ -89,15 +89,18 @@ 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.
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). PC: the key or
// mouse button the keyboard defaults press each button with, the mouse for the right stick.
enum { PROMPTS_NINTENDO, PROMPTS_XBOX, PROMPTS_PC };
// The prompts for a TOTK_PROMPTS value ("nintendo", "xbox" or "pc", 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.
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. The PC
// prompts follow no pad: romfs-patches-pc whatever the layout (romfs.c overlay_init serves romfs-patches-pc-<w>x<h>
// under that name at a game resolution of another shape).
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);
+37 -17
View File
@@ -750,14 +750,17 @@ static void camera_overlay(void) {
// 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];
// romfs-patches-pc keeps that name, but at a game resolution of another shape than 16:9 its files come from pc_dir,
// romfs-patches-pc-<w>x<h> (overlay_init).
static struct { const char *name; int ready; } prompts_folders[3];
static const char *prompts_wanted, *prompts_loaded;
static int prompts_off;
static char pc_dir[64];
const char *romfs_prompts(void) { return prompts_loaded; }
int romfs_prompts_ready(const char *folder) {
for (int i = 0; i < 2; i++)
for (int i = 0; i < 3; i++)
if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready;
return 0;
}
@@ -798,6 +801,9 @@ static void overlay_init(void) {
// keeps the Switch prompts. So does a RomFS mod (the TOTK_ROMFS_MODS manifest or a player mod) that replaces one of
// the prompts' fonts: romfs-patches loads in their place, so the mod's file is not served beside prompts files made
// for the game's own. A mod's resource size table is no clash: restbl_overlay merges it with the prompts' one.
// prompts = pc takes romfs-patches-pc whatever the pad layout, and at a game resolution of another shape
// romfs-patches-pc-<w>x<h> (make_romfs_patches.py --prompts pc --aspect): it carries that shape's UI layout too, so
// it replaces romfs-patches-<w>x<h> as romfs-patches-pc replaces romfs-patches.
char def[2100], path[2100];
const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS");
int wide = 0;
@@ -813,34 +819,46 @@ static void overlay_init(void) {
"(tools/make_romfs_patches.py --aspect %ux%u)", out[0], out[1], out[0], out[1]);
}
}
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]);
static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each Xbox folder, then the PC one
for (int i = 0; i < 3; i++) {
const char *name = i < 2 ? input_prompts_folder(PROMPTS_XBOX, layouts[i]) : input_prompts_folder(PROMPTS_PC, 0);
const char *dir = name;
if (i == 2) {
if (wide) snprintf(pc_dir, sizeof pc_dir, "%s-%ux%u", name, out[0], out[1]);
else snprintf(pc_dir, sizeof pc_dir, "%s", name);
dir = pc_dir;
}
prompts_folders[i].name = name;
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);
snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, dir) < (int)sizeof path && plat_file_exists(path);
}
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
prompts_wanted = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
int pick = input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), shaped = wide && pick == PROMPTS_PC;
const char *style = pick == PROMPTS_PC ? "keyboard and mouse" : "Xbox";
prompts_wanted = input_prompts_folder(pick, layout);
prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK
: wide ? ROMFS_PROMPTS_SHAPE
: patches ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? ROMFS_PROMPTS_MISSING
: wide && !shaped ? ROMFS_PROMPTS_SHAPE
: patches && !wide ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? (shaped ? ROMFS_PROMPTS_SHAPE : ROMFS_PROMPTS_MISSING)
: ROMFS_PROMPTS_OK;
restbl_find();
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
// fits: its manifest path did
snprintf(path, sizeof path, "%s/%s", index_dir, shaped ? pc_dir : prompts_wanted);
if (overlay_load(path, 1, 0)) {
prompts_loaded = prompts_wanted;
rt_log("RomFS overlay: Xbox button prompts (%s)", path);
rt_log("RomFS overlay: %s button prompts (%s)", style, path);
if (shaped) patches = NULL; // in place of romfs-patches-<w>x<h>, whose UI layout it carries
} 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"
rt_log("RomFS overlay: prompts = %s, but %s; Switch prompts stay", pick == PROMPTS_PC ? "pc" : "xbox",
prompts_off == ROMFS_PROMPTS_SHAPE ? (shaped ? "the game resolution has no romfs-patches-pc-<w>x<h> "
"(tools/make_romfs_patches.py --prompts pc --aspect)"
: "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)");
}
@@ -856,11 +874,13 @@ static void overlay_init(void) {
mods_overlay_init();
const char *clash = prompts_loaded ? overlay_clash(first, prompts_end, mods_first, noverlay) : NULL;
if (clash) {
rt_log("RomFS overlay: a RomFS mod replaces %s, which the Xbox prompts change too; Switch prompts stay", clash);
rt_log("RomFS overlay: a RomFS mod replaces %s, which the %s prompts change too; Switch prompts stay", clash,
style);
overlay_drop(first, prompts_end);
prompts_loaded = NULL;
prompts_off = ROMFS_PROMPTS_MODS;
if (plain_ok) overlay_load(plain, 0, 0);
if (shaped) overlay_load(def, 0, 0);
else if (plain_ok) overlay_load(plain, 0, 0);
}
restbl_collect();
overlay_contest();
+7 -4
View File
@@ -773,8 +773,11 @@ static const char *prompts_note(bool *restart) {
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)) {
// A game resolution of another shape needs a folder of its own for the PC prompts (romfs-patches-pc-<w>x<h>), which
// the setup does not write: the shape is the reason then, not the setup.
int off = romfs_prompts_off(want);
if (want && !romfs_prompts_ready(want) && off != ROMFS_PROMPTS_SHAPE) return menu_text(UI_MENU_PROMPTS_MISSING);
switch (off) {
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);
@@ -827,10 +830,10 @@ 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 prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX};
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC};
bool restart;
const char *note = prompts_note(&restart);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 2, UI_MENU_PROMPTS_DESC, note);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 3, 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 %%");
+19 -12
View File
@@ -241,10 +241,11 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[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",
"prompts for A show B). PC: the keys and mouse buttons of the keyboard's default layout "
"(E, Shift, Space, left click...) and the mouse for the camera. 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_PC] = "PC",
[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",
@@ -701,10 +702,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[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",
"подсказки A показывают B). PC: клавиши и кнопки мыши стандартной раскладки клавиатуры "
"(E, Shift, пробел, левый клик...) и мышь для камеры. Игра читает подсказки при запуске, "
"так что они меняются после перезапуска. Подсказки записаны в файлах игры, поэтому у "
"кнопки, переназначенной на вкладке управления, на экране остаётся прежняя подсказка.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", [UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова",
[UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова",
[UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска",
@@ -1338,11 +1340,14 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_DESC] = "Os botões de qual controle os ícones do jogo mostram. Nintendo: os do próprio jogo. "
"Xbox: LB, RB, LT, RT, Menu, Exibir e uma cruz direcional, e A, B, X e Y com a letra do "
"botão que o layout acima aperta (com Nintendo (A à direita) o botão da direita tem a "
"letra B, então os ícones de A mostram B). O jogo lê os ícones ao iniciar, então eles "
"mudam depois de reiniciar. Eles fazem parte dos arquivos do jogo, então um botão "
"remapeado em Controles continua com o ícone antigo na tela.",
"letra B, então os ícones de A mostram B). PC: as teclas e os botões do mouse do layout "
"padrão do teclado (E, Shift, Espaço, clique esquerdo...) e o mouse para a câmera. O jogo "
"lê os ícones ao iniciar, então eles mudam depois de reiniciar. Eles fazem parte dos "
"arquivos do jogo, então um botão remapeado em Controles continua com o ícone antigo na "
"tela.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
[UI_MENU_PROMPTS_XBOX] = "Xbox",
[UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_MOUSE_MODE] = "Câmera com o mouse",
[UI_MENU_MOUSE_MODE_DESC] = "Direta: a câmera gira o quanto o mouse se move, como num jogo de PC, sem zona morta nem curva do analógico (jogo 1.4.3; as outras versões usam a emulação do analógico). Emulação do analógico: o mouse age como o analógico direito.",
[UI_MENU_MOUSE_STICK] = "Emulação do analógico",
@@ -1944,9 +1949,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS] = "按键提示",
[UI_MENU_PROMPTS_DESC] = "游戏的按键提示显示哪种手柄的按键。Nintendo:游戏原有的提示。Xbox:LB、RB、LT、RT、Menu、View 和十字键,以及上方布局所按下的按键上标注的 "
"A、B、X、Y(使用 Nintendo(A 在右)时右侧按键标为 B,因此 A 的提示显示 "
"B)。游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。",
"B)。PC:键盘默认布局的按键和鼠标按键(E、Shift、空格、左键……),镜头用鼠标。"
"游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
[UI_MENU_PROMPTS_XBOX] = "Xbox",
[UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_MOUSE_MODE] = "鼠标视角",
[UI_MENU_MOUSE_MODE_DESC] = "直接:镜头按鼠标移动的距离转动,与电脑游戏相同,没有摇杆死区和响应曲线(游戏 1.4.3;其他版本使用摇杆模拟)。摇杆模拟:鼠标相当于右摇杆。",
[UI_MENU_MOUSE_STICK] = "摇杆模拟",
+1 -1
View File
@@ -99,7 +99,7 @@ typedef enum {
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_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX,
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC,
// 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,
+59 -8
View File
@@ -1,8 +1,8 @@
"""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
d-pad are drawn as on an Xbox controller, the PC prompts draw every button as its key or mouse button (the defaults or
a totk.ini's bind_ lines), 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
@@ -296,6 +296,11 @@ LETTERS_1 = {ord('L'): (560, polygon((60, 0), (480, 0), (480, 100), (160, 100),
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)))}
# The other characters the PC prompts' keys show (button_icons.PC_LABELS of the defaults): a block with a counter, each
# its own size.
LETTERS_2.update({ord(ch): (560, lambda pen, i=i: [rect(pen, 60, 0, 300 + 10 * i, 700), rect(pen, 120, 100, 240, 600, True)])
for i, ch in enumerate('ACDEFMQSW1234⇧')})
PC_PANES = {'A': 'E', 'B': '↑', 'X': '▬', 'Y': 'L'} # the diamond's letters with the default keys
class Romfs:
@@ -316,7 +321,8 @@ class Romfs:
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))})
'Nt_KeyTexLSt_00': (R8_UNORM, size, rnd.randbytes(IMAGE)),
'Nt_KeyTexLSt_01': (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:
@@ -388,7 +394,7 @@ class PromptsTest(unittest.TestCase):
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'):
for style in ('plain', 'xbox', 'xbox-label', 'pc'):
out = cls.base / v / style
proc = romfs.run(out, *(() if style == 'plain' else ('--prompts', style)))
assert proc.returncode == 0, proc.stderr
@@ -485,7 +491,7 @@ class PromptsTest(unittest.TestCase):
self.assertEqual(after[member], before[member], member)
def test_resource_size_table_grows_with_the_fonts(self):
for romfs, style, out, summary in self.each():
for romfs, style, out, summary in self.each(('xbox', 'xbox-label', 'pc')):
with self.subTest(version=romfs.version, style=style):
table = restbl_sizes(romfs.read(out, romfs.restbl))
original = restbl_sizes(romfs.contents[romfs.restbl])
@@ -501,11 +507,12 @@ class PromptsTest(unittest.TestCase):
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')):
for romfs, style, out, _ in self.each(('plain', 'xbox', 'xbox-label', 'pc')):
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())
expect |= {DEFAULT_FONT, REGIONAL_FONT, romfs.restbl}
expect |= set(romfs.mals) if style in ('xbox', 'pc') else set()
lines = manifest(out)
self.assertEqual(set(lines), expect)
for path, (size, sha, original) in lines.items():
@@ -513,6 +520,50 @@ class PromptsTest(unittest.TestCase):
self.assertEqual((int(size), sha), (len(data), hashlib.sha256(data).hexdigest()), path)
self.assertEqual(original, hashlib.sha256(romfs.files[path]).hexdigest(), path)
def test_pc_prompts_draw_every_button_as_its_key(self):
for romfs, _, out, _ in self.each(('pc',)):
with self.subTest(version=romfs.version):
original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
drawn = font(sarc_files(romfs.read(out, DEFAULT_FONT))['scft/External.bfotf'])
advances = icons.font_advances(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
pc = icons.pc_icons(icons.text_glyphs(romfs.text_fonts), advances)
self.assertIn(0xE05E, pc) # the left stick's W A S D
for cp in range(0xE040, 0xE069):
outline, advance = glyph(drawn, cp)
if cp in pc:
self.assertNotEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} drawn')
else:
self.assertEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} kept')
self.assertEqual(advance, glyph(original, cp)[1], f'U+{cp:04X} keeps its advance')
# The key's label is a hole: E is the key, the block and its counter.
self.assertEqual(sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE040)[0]), 3)
after = sarc_files(romfs.read(out, romfs.common))
new = bntx_images(after['timg/__Combined.bntx'])
size = VERSIONS[romfs.version]['size']
for name, cp in icons.PC_HUD_TEXTURES.items():
image = new[name][2]
pixels = bytes(image[icons.gob_offset(x, y, (size + 63) // 64, 16)] for y in range(size) for x in range(size))
self.assertEqual(pixels, icons.rasterize(pc[cp][1], size), name)
panes = pane_texts(after['blyt/DoCommand_00.bflyt'])
for b, letter in PC_PANES.items():
self.assertEqual(panes[f'T_{b}_00'], letter, f'diamond letter of {b}')
for path in romfs.mals:
texts = message_texts(sarc_files(romfs.read(out, path))['LayoutMsg/DoCommand_00.msbt'])
self.assertEqual((texts[f'T_{b}_00'], texts['T_Name_00']), (letter, 'A'), path)
def test_pc_prompts_follow_the_bind_lines(self):
romfs = self.romfs['v143']
ini = self.base / 'binds' / 'totk.ini'
ini.parent.mkdir(parents=True)
ini.write_text('[input]\n# bind_A = key:q\nbind_A = pad:east, key:F\nbind_B = pad:south\nbind_X = key:default\n',
encoding='utf-8')
out = self.base / 'binds' / 'out'
proc = romfs.run(out, '--prompts', 'pc', '--binds', str(ini))
self.assertEqual(proc.returncode, 0, proc.stderr)
panes = pane_texts(sarc_files(romfs.read(out, romfs.common))['blyt/DoCommand_00.bflyt'])
self.assertEqual({b: panes[f'T_{b}_00'] for b in PC_PANES}, {**PC_PANES, 'A': 'F'})
self.assertEqual(icons.pc_binds(ini.read_text(encoding='utf-8')), {**icons.PC_BINDS, 'A': 'f'})
def test_same_input_same_output_and_the_older_flag(self):
romfs = self.romfs['v121']
for flags in (('--prompts', 'xbox'), ('--xbox-prompts',)):
+4 -4
View File
@@ -241,10 +241,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/<version> 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 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'):
menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox,
romfs-patches-xbox-label and romfs-patches-pc (the same with Xbox or keyboard and mouse 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', 'romfs-patches-pc'):
src = ROOT / 'build' / version / name
dst = out / name
if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file():
+176 -7
View File
@@ -1,6 +1,7 @@
# 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.
"""Xbox and keyboard-and-mouse 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.
@@ -9,13 +10,15 @@ Font/Font*.Nin_NX_NVN.bfarc.zs: private-use code points from U+E040 (A, B, X, Y,
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).
cross), or every button as the key or mouse button the keyboard presses it with (pc_icons), 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).
The button guide in play (bottom right) draws its buttons, L and ZL among them, 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 Xbox prompts redraw L and ZL, the keyboard and mouse ones every image (PC_HUD_TEXTURES: A, B, X,
Y, L, ZL and the stick's two). Prompts drawn as fixed images (some tutorial animations) keep the Switch icons.
Needs fontTools (tools/requirements-installer.txt, tools/requirements-py314.txt).
"""
@@ -180,6 +183,172 @@ def xbox_icons(g):
}
# ---- keyboard and mouse prompts (--prompts pc): every button the keyboard drives, drawn as the key or mouse button
# bound to it, in the same filled-shape style. Each glyph keeps the advance of the game's own (a wider glyph runs into
# the text of a right-aligned guide).
# The keyboard defaults of runtime/input_map.c (input_map_reset; the totk.ini bind_ lines apply on top, pc_binds). The
# right stick is the camera, which the mouse drives.
PC_BINDS = {
'A': 'e', 'B': 'lshift', 'X': 'space', 'Y': 'mouse_l', 'L': 'q', 'R': 'r', 'ZL': 'mouse_r', 'ZR': 'f',
'PLUS': 'tab', 'MINUS': 'm', 'LEFT': '1', 'UP': '2', 'RIGHT': '3', 'DOWN': '4', 'LCLICK': 'lctrl', 'RCLICK': 'c',
'LSTICK_UP': 'w', 'LSTICK_LEFT': 'a', 'LSTICK_DOWN': 's', 'LSTICK_RIGHT': 'd',
}
# What a key shows: its letter, a symbol or a short name (key names as in totk.ini; the rest show their name).
PC_LABELS = {
'lshift': '⇧', 'rshift': '⇧', 'lctrl': 'CTRL', 'rctrl': 'CTRL', 'lalt': 'ALT', 'tab': 'TAB',
'enter': 'ENT', 'backspace': 'BKSP', 'capslock': 'CAPS', 'insert': 'INS', 'delete': 'DEL', 'home': 'HOME',
'end': 'END', 'pageup': 'PGUP', 'pagedown': 'PGDN', 'up': '↑', 'down': '↓', 'left': '←',
'right': '→', 'num_add': '+', 'num_sub': '-', 'num_mul': '*', 'num_div': '/', 'num_decimal': '.',
'minus': '-', 'equals': '=', 'lbracket': '[', 'rbracket': ']', 'semicolon': ';', 'apostrophe': "'", 'comma': ',',
'period': '.', 'slash': '/', 'backslash': '\\', 'grave': '`', 'mouse_x1': 'M4', 'mouse_x2': 'M5',
}
# The one-letter panes around the action prompt (T_A_00 ...) are in the Normal font (Rodin B and Symbol): one character
# of it per key.
PC_LETTER_LABELS = {'lshift': '↑', 'rshift': '↑', 'space': '▬', 'mouse_l': 'L', 'mouse_r': 'R',
'mouse_m': 'M', 'lctrl': 'C', 'rctrl': 'C', 'tab': 'T'}
# The button guide's images in the pc style: every symbol mask of the action prompt (LSt_00 the stick tilted, LSt_01
# the stick pressed).
PC_HUD_TEXTURES = {'Nt_KeyTexA_00': 0xE040, 'Nt_KeyTexB_00': 0xE041, 'Nt_KeyTexX_00': 0xE042, 'Nt_KeyTexY_00': 0xE043,
'Nt_KeyTexL_00': 0xE044, 'Nt_KeyTexZL_00': 0xE046, 'Nt_KeyTexLSt_00': 0xE05E,
'Nt_KeyTexLSt_01': 0xE056}
PC_MOUSE = ('mouse_l', 'mouse_r', 'mouse_m')
def pc_binds(ini_text=None):
"""PC_BINDS with the first key of each bind_<action> line of a totk.ini text over it (a line without a key entry,
or with key:default, keeps the default)."""
binds = dict(PC_BINDS)
for line in (ini_text or '').splitlines():
line = line.split('#')[0].split(';')[0].strip()
if not line.lower().startswith('bind_') or '=' not in line:
continue
action, value = (s.strip() for s in line.split('=', 1))
keys = [e.strip()[4:].strip().lower() for e in value.split(',') if e.strip().lower().startswith('key:')]
keys = [k for k in keys if k != 'default']
if keys and action[5:].upper() in binds:
binds[action[5:].upper()] = keys[0]
return binds
def font_advances(blob):
"""Code point -> advance of every glyph of the button font (a .bfotf)."""
font = TTFont(io.BytesIO(bfotf_decode(blob)[0]))
return {cp: font['hmtx'][name][0] for cp, name in font.getBestCmap().items()}
def pc_letter(key):
"""The one character the panes around the action prompt show for key."""
if key in PC_LETTER_LABELS:
return PC_LETTER_LABELS[key]
return PC_LABELS.get(key, key.upper())[0]
def pc_icons(g, adv, binds=PC_BINDS):
"""Code point -> (advance, draw(pen)) for every button glyph but Home and Capture, drawn as the key or mouse button
binds puts on it. g: Glyphs for the key labels; adv: the game's advance of each glyph (font_advances), which each
drawing keeps."""
def mouse_body(pen, cx, y0, y1, lit=None):
"""A mouse seen from above; lit ('l', 'r', 'm' or None) its pressed button, filled, the others hollow."""
h = y1 - y0; r = h * 0.33; t = h * 0.07; gap = h * 0.035
x0, x1, mid = cx - r, cx + r, y0 + h * 0.52
rounded(pen, x0, y0, x1, y1, r * 0.9, r)
reverse = ReverseContourPen(pen) # holes; they never overlap each other or leave the body
ri = r - t
if lit in ('l', 'r'): # the seams around the pressed button
sx0, sx1 = (x0 + t, cx - gap) if lit == 'l' else (cx + gap, x1 - t)
polygon(reverse, [(sx0, mid - gap), (sx1, mid - gap), (sx1, mid + gap), (sx0, mid + gap)])
polygon(reverse, [(cx - gap, mid + gap), (cx + gap, mid + gap), (cx + gap, y1 - t), (cx - gap, y1 - t)])
if lit != 'l': # hollow left button, its outer top corner following the body
ix0, ix1 = x0 + t, cx - gap
reverse.moveTo((ix1, mid + gap)); reverse.lineTo((ix1, y1 - t)); reverse.lineTo((ix0 + ri, y1 - t))
reverse.curveTo((ix0 + ri - K * ri, y1 - t), (ix0, y1 - t - ri + K * ri), (ix0, y1 - t - ri))
reverse.lineTo((ix0, mid + gap)); reverse.closePath()
if lit != 'r':
ix0, ix1 = cx + gap, x1 - t
reverse.moveTo((ix0, mid + gap)); reverse.lineTo((ix1, mid + gap)); reverse.lineTo((ix1, y1 - t - ri))
reverse.curveTo((ix1, y1 - t - ri + K * ri), (ix1 - ri + K * ri, y1 - t), (ix1 - ri, y1 - t))
reverse.lineTo((ix0, y1 - t)); reverse.closePath()
if lit == 'm': # the wheel, filled over the gap between the hollow buttons
rounded(pen, cx - h * 0.06, mid + h * 0.12, cx + h * 0.06, mid + h * 0.36, h * 0.06)
def key_cap(pen, x0, y0, x1, y1, key):
"""A key: a rounded square with its label cut out; a mouse button draws the mouse."""
if key in PC_MOUSE:
mouse_body(pen, (x0 + x1) / 2, y0, y1, key[6:])
return
w, h = x1 - x0, y1 - y0
rounded(pen, x0, y0, x1, y1, min(w, h) * 0.18)
if key == 'space': # an open bracket lying on its back
t = h * 0.09
bx0, bx1, by0, by1 = x0 + w * 0.22, x1 - w * 0.22, y0 + h * 0.36, y0 + h * 0.60
polygon(ReverseContourPen(pen), [(bx0, by0), (bx1, by0), (bx1, by1), (bx1 - t, by1), (bx1 - t, by0 + t),
(bx0 + t, by0 + t), (bx0 + t, by1), (bx0, by1)])
return
label = PC_LABELS.get(key, key.upper())
cap = h * (0.52 if len(label) == 1 else 0.36 if len(label) == 2 else 0.26)
g.hole(pen, label, (x0 + x1) / 2, (y0 + y1) / 2, cap, w * 0.74)
def arrow(pen, cx, cy, d, s):
"""A filled arrowhead pointing d, s its half size."""
polygon(pen, {'up': [(cx - s, cy - s * 0.6), (cx + s, cy - s * 0.6), (cx, cy + s * 0.8)],
'down': [(cx + s, cy + s * 0.6), (cx - s, cy + s * 0.6), (cx, cy - s * 0.8)],
'left': [(cx + s * 0.6, cy - s), (cx + s * 0.6, cy + s), (cx - s * 0.8, cy)],
'right': [(cx - s * 0.6, cy + s), (cx - s * 0.6, cy - s), (cx + s * 0.8, cy)]}[d])
def one(key, advance):
def draw(pen):
side = min(advance - 80, Y1 - Y0)
key_cap(pen, (advance - side) / 2, Y0, (advance + side) / 2, Y1, key)
return advance, draw
def grid(cells, advance):
"""Small keys in a grid: cells = [(key, column, row)], row 0 on top."""
def draw(pen):
cols, rows = max(c for _, c, _ in cells) + 1, max(r for _, _, r in cells) + 1
gap = 24; size = min((advance - 60 - gap * (cols - 1)) / cols, (Y1 - Y0 - gap * (rows - 1)) / rows)
left, top = (advance - cols * size - gap * (cols - 1)) / 2, CY + (rows * size + gap * (rows - 1)) / 2
for key, c, r in cells:
x, y = left + c * (size + gap), top - (r + 1) * size - r * gap
key_cap(pen, x, y, x + size, y + size, key)
return advance, draw
def mouse_move(advance, *dirs):
"""The mouse, no button pressed, with an arrow for each direction the prompt means."""
def draw(pen):
mouse_body(pen, advance / 2, Y0 + 30, Y1 - 30)
off = (Y1 - Y0 - 60) * 0.33 + 70
spots = {'up': (advance / 2 + off, CY + 110), 'down': (advance / 2 + off, CY - 110),
'left': (advance / 2 - off, CY), 'right': (advance / 2 + off, CY)}
for d in dirs:
arrow(pen, *spots[d], d, 52)
return advance, draw
b = binds
up, left, down, right = b['LSTICK_UP'], b['LSTICK_LEFT'], b['LSTICK_DOWN'], b['LSTICK_RIGHT']
du, dl, dd, dr = b['UP'], b['LEFT'], b['DOWN'], b['RIGHT']
return {
**{cp: one(b[name], adv[cp]) for cp, name in ((0xE040, 'A'), (0xE041, 'B'), (0xE042, 'X'), (0xE043, 'Y'),
(0xE044, 'L'), (0xE045, 'R'), (0xE046, 'ZL'), (0xE047, 'ZR'),
(0xE04B, 'PLUS'), (0xE04C, 'MINUS'), (0xE056, 'LCLICK'),
(0xE057, 'RCLICK'))},
# the d-pad: its four keys as a cross (up on top), or the keys of the directions the prompt means
0xE049: grid([(du, 1, 0), (dl, 0, 1), (dd, 1, 1), (dr, 2, 1)], adv[0xE049]),
0xE060: one(du, adv[0xE060]), 0xE061: one(dd, adv[0xE061]), 0xE062: one(dl, adv[0xE062]),
0xE063: one(dr, adv[0xE063]), 0xE064: grid([(du, 0, 0), (dd, 0, 1)], adv[0xE064]),
0xE065: grid([(dl, 0, 0), (dr, 1, 0)], adv[0xE065]),
# the left stick: its keys (W A S D)
0xE05E: grid([(up, 1, 0), (left, 0, 1), (down, 1, 1), (right, 2, 1)], adv[0xE05E]),
0xE052: one(up, adv[0xE052]), 0xE050: one(down, adv[0xE050]), 0xE05A: one(left, adv[0xE05A]),
0xE058: one(right, adv[0xE058]), 0xE05C: grid([(up, 0, 0), (down, 0, 1)], adv[0xE05C]),
0xE054: grid([(left, 0, 0), (right, 1, 0)], adv[0xE054]),
# the right stick: the mouse
0xE05F: mouse_move(adv[0xE05F]), 0xE053: mouse_move(adv[0xE053], 'up'),
0xE051: mouse_move(adv[0xE051], 'down'), 0xE05B: mouse_move(adv[0xE05B], 'left'),
0xE059: mouse_move(adv[0xE059], 'right'), 0xE05D: mouse_move(adv[0xE05D], 'up', 'down'),
0xE055: mouse_move(adv[0xE055], 'left', 'right'), 0xE068: mouse_move(adv[0xE068], '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
+27 -10
View File
@@ -38,6 +38,11 @@ from the game's own files on the player's machine, nothing added (tools/button_i
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.
--prompts pc: keyboard and mouse prompts, for prompts = pc (romfs-patches-pc, or romfs-patches-pc-<w>x<h> with
--aspect): every button of the button font is drawn as the key or mouse button the keyboard defaults put on it
(button_icons.pc_icons; --binds <totk.ini> takes the first key of its bind_ lines instead), and so are the button
guide's images (A, B, X, Y, L, ZL and the stick's two). The one-letter panes around the action prompt name the keys
with one character of the Normal font (E, an arrow for Shift, a bar for Space, L and R for the mouse buttons).
Input: build/extracted/<version>/romfs (romfs.bin and index.json, verified by tools/extract.py). Output:
build/<version>/romfs-patches/<path> by default (romfs-patches-<style> with --prompts), and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
@@ -58,9 +63,11 @@ ap.add_argument('--romfs', type=Path, help='default build/extracted/<version>/ro
ap.add_argument('--out', type=Path,
help='default build/<version>/romfs-patches (romfs-patches-<style> with --prompts)')
ap.add_argument('--aspect', help='<w>x<h> of a game resolution of another shape than 16:9: also lay the UI out for it')
ap.add_argument('--prompts', choices=('xbox', 'xbox-label'),
ap.add_argument('--prompts', choices=('xbox', 'xbox-label', 'pc'),
help='Xbox button icons in the prompts: xbox for pad_layout = nintendo (A shown as B, X as Y), '
'xbox-label for pad_layout = xbox or auto (the face buttons keep their letters)')
'xbox-label for pad_layout = xbox or auto (the face buttons keep their letters), '
'pc for the keyboard and mouse')
ap.add_argument('--binds', type=Path, help='--prompts pc: a totk.ini whose bind_ lines the key icons follow')
ap.add_argument('--xbox-prompts', dest='prompts', action='store_const', const='xbox', help='the same as --prompts xbox')
args = ap.parse_args()
args.romfs = args.romfs or root / 'build/extracted' / args.version / 'romfs'
@@ -231,9 +238,11 @@ LAYOUT_MSG = 'LayoutMsg/DoCommand_00.msbt'
RESTBL = max((p for p in files if p.startswith('System/Resource/ResourceSizeTable.') and p.endswith('.rsizetable.zs')),
key=lambda p: int((re.search(r'\.(\d+)\.', p) or [0, 0])[1]), default=None)
by_position = args.prompts == 'xbox' # the face buttons' prompts swapped to the labels (pad_layout = nintendo)
pc = args.prompts == 'pc'
letter_panes = by_position or pc # the one-letter panes around the action prompt change
if args.prompts:
assert FONTS, 'no Font/Font*.Nin_NX_NVN.bfarc.zs in the RomFS'
assert MALS or not by_position, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
assert MALS or not letter_panes, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
assert RESTBL, 'no System/Resource/ResourceSizeTable.Product.<n>...rsizetable.zs in the RomFS'
spec = importlib.util.spec_from_file_location('button_icons', Path(__file__).with_name('button_icons.py'))
icons = importlib.util.module_from_spec(spec)
@@ -252,7 +261,7 @@ 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
prompt_files = (FONTS + (MALS if by_position else []) + [RESTBL]) if args.prompts else []
prompt_files = (FONTS + (MALS if letter_panes else []) + [RESTBL]) if args.prompts else []
originals = {path: read(path) for path in [ARCHIVE] + prompt_files}
raw = originals[ARCHIVE]
info = zstd.get_frame_info(raw)
@@ -297,19 +306,27 @@ if args.prompts:
text = sarc_members(archives[icons.TEXT_ARCHIVE])
missing = [name for name in icons.TEXT_FONTS if name not in text]
assert not missing, f'no {", ".join(missing)} in {icons.TEXT_ARCHIVE}'
drawn = icons.xbox_icons(icons.text_glyphs(archives[icons.TEXT_ARCHIVE][slice(*text[name])]
for name in icons.TEXT_FONTS))
glyphs = icons.text_glyphs(archives[icons.TEXT_ARCHIVE][slice(*text[name])] for name in icons.TEXT_FONTS)
if pc:
binds = icons.pc_binds(args.binds.read_text(encoding='utf-8', errors='replace') if args.binds else None)
advances = icons.font_advances(archives[icons.TEXT_ARCHIVE][slice(*text[icons.FONT])])
drawn = icons.pc_icons(glyphs, advances, binds)
pane_letters = {letter: icons.pc_letter(binds[letter]) for letter in 'ABXY'}
else:
drawn = icons.xbox_icons(glyphs)
pane_letters = KEY_LETTERS
bntx = members['timg/__Combined.bntx'][0]
letters = {}
if by_position:
bntx_swap(blarc, bntx, KEY_TEXTURES)
if letter_panes:
for member, (lo, hi) in members.items():
if member.endswith('.bflyt'):
changed = bflyt_letters(blarc, lo, hi, KEY_LETTERS)
changed = bflyt_letters(blarc, lo, hi, pane_letters)
if changed:
letters[member] = changed
assert 'blyt/DoCommand_00.bflyt' in letters, 'no letter panes in blyt/DoCommand_00.bflyt'
hud = icons.bntx_redraw(blarc, bntx, icons.HUD_TEXTURES, drawn)
hud = icons.bntx_redraw(blarc, bntx, icons.PC_HUD_TEXTURES if pc else icons.HUD_TEXTURES, drawn)
outputs[ARCHIVE] = bytes(blarc)
fonts = {} # each distinct font is drawn once (1.4.3's four archives hold the same one)
for path, bfarc in archives.items():
@@ -319,11 +336,11 @@ if args.prompts:
fonts[otf] = icons.redraw_font(otf, drawn, KEY_GLYPHS if by_position else ())
outputs[path] = sarc_replace(bfarc, {icons.FONT: icons.bfotf_encode(fonts[otf], key, bfarc[lo:hi])})
messages = {}
for path in MALS if by_position else []:
for path in MALS if letter_panes else []:
mals = bytearray(unpack(path))
lo, hi = sarc_members(mals)[LAYOUT_MSG]
msbt = bytearray(mals[lo:hi])
changed = msbt_letters(msbt, KEY_LETTERS)
changed = msbt_letters(msbt, pane_letters)
assert len(changed) == sum(len(v) for v in letters.values()), (path, changed)
mals[lo:hi] = msbt
outputs[path] = bytes(mals)
+4 -2
View File
@@ -283,9 +283,11 @@
# labels, xbox for the others). The bind_ lines below apply on top. Changes while the game runs take effect at once.
# 0.1.9's xbox_prompts is read as nintendo with prompts = xbox.
# pad_layout = auto
# The buttons the game's prompts show: nintendo (the game's own) or xbox (LB RB LT RT, Menu, View and a d-pad cross,
# The 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 Y as labelled on the button pad_layout presses: with nintendo, A shows as B and X as Y). Read at start
# (docs/controls.md, "Xbox button prompts").
# (docs/controls.md, "Xbox button prompts"). pc: the key or mouse button the keyboard defaults press each button with
# (E, Shift, Space, left click, Q, R, right click, F, Tab, M, 1 to 4, W A S D, Ctrl, C) and the mouse for the right
# stick, whatever pad_layout (docs/controls.md, "PC button prompts").
# prompts = nintendo
# 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.