Merge task/psp: PlayStation button prompts from #741 (fabiomode2), and the game makes a missing layout or prompts folder itself after a resolution or prompts change (#180, #378)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-18 19:14:27 +03:00
commit ebce67b367
32 files changed
+1048 -359

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- Setup and in-game menu in English, Russian, Brazilian Portuguese and Simplified Chinese
- Keyboard, mouse and gamepad with remapping, rumble and gyro
- Stereo or 5.1 surround sound output
- Xbox button prompts: LB, RB, LT, RT, Menu and View, and A, B, X and Y as labelled on the button to press, with either button layout
- Xbox and PlayStation button prompts: Xbox's LB, RB, LT, RT, Menu, View and A, B, X, Y, or PlayStation's ○ × △ □, L1, R1, L2, R2, Options and Share, as labelled on the button to press, with either button layout
- Shaders prepared at install instead of during play
- Mods made for emulators: unpack a mod into the `mods` folder next to `totk.exe`; switch and order them in the menu. RomFS
mods, TKMM's merged output and ExeFS code patches (`.ips`, `.pchtxt`) work; the game rebuilds itself for code patches
+9 -5
View File
@@ -122,10 +122,12 @@ of them.
reason, and `--full-build` compiles everything.
`--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` 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`. `--prompts pc` writes
`romfs-patches-pc`, the keyboard and mouse prompts ([controls.md](controls.md), "PC button prompts").
For Xbox and PlayStation button prompts, run `make_romfs_patches.py` twice more for each, with `--prompts xbox`,
`--prompts xbox-label`, `--prompts playstation` and `--prompts playstation-xbox`: they write
`build\<ver>\romfs-patches-xbox`, `-xbox-label`, `-playstation` and `-playstation-xbox`
([controls.md](controls.md), "Xbox and PlayStation 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").
`--aspect <w>x<h>` writes the UI laid out for a game resolution of another shape; with `--hud 16:9` or `--hud 21:9`
(a screen wider than that) the HUD stays within the middle 16:9 or 21:9 instead of the screen's corners. The default
`--out` then is `build\<ver>\romfs-patches-<w>x<h>-hud16x9` (`-hud21x9`), which the game loads for `hud_width = 16:9`
@@ -239,7 +241,9 @@ HUD pane/animation and generator naming regressions run with Python 3.14+: `test
Set `HUD_TEST_ROMFS` to a verified extracted RomFS directory to include a real-archive comparison against the
pre-port layout generator; all game-derived temporary data stays under `build/`.
`python tests/romfs_shapes_check.py --cc <clang>` compiles the production folder-selection and preparation helpers
to check canonical aliases, capped/full fallback, prompt arguments and generation deduplication without game files.
to check canonical aliases, capped/full fallback, prompt arguments, the missing 16:9 prompts and generation
deduplication without game files. `tests/romfs_prompts_test.py` checks that two `--background` runs for one folder
publish it once and that a folder with a manifest is kept.
A change to the mods' ExeFS patches
(`tools/exefs_patches.py`, `runtime/mods.c`, the `folded.txt` of `recomp/gen.py`) passes
`.venv\Scripts\python tests\exefs_patches_test.py`, which makes its own modules and runs `gen.py` on one with a jump
+24 -6
View File
@@ -8,7 +8,7 @@ Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into
- `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.
The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. Which controller's buttons the game's prompts show is `TOTK_PROMPTS` (see Xbox button prompts below). 0.1.9's `pad_layout = xbox_prompts` is read as `pad_layout = nintendo` with `prompts = xbox`, and the menu writes it that way.
The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. Which controller's buttons the game's prompts show is `TOTK_PROMPTS` (see Button prompts below). 0.1.9's `pad_layout = xbox_prompts` is read as `pad_layout = nintendo` with `prompts = xbox`, and the menu writes it that way.
| Switch | Gamepad (by position, Nintendo layout) | Keyboard and mouse | Action in the world |
|---|---|---|---|
@@ -31,9 +31,9 @@ The log names the layout in effect (`input: gamepad layout ...`); the menu shows
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. T duplicates Y for the game's menus, where the left mouse button is A while the pointer is shown (sort the inventory with T). The mouse wheel zooms the Purah Pad's map and its camera, steps the game's menus and the d-pad strips (see Mouse in the game's menus), and is unbound elsewhere. 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
## Xbox and PlayStation 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, `pc` the keyboard and mouse (PC button prompts, below).
`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, `playstation` a PlayStation 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.
@@ -48,16 +48,34 @@ Esc is unbound in the game; it opens the settings menu and releases the mouse cu
The action prompt (`DoCommand_00`) shows its button in a diamond whose shape gives the face buttons' positions as on a Switch, with the other three letters around it. With `nintendo` its letters are swapped with the rest and every one names the button in that place. With `xbox` and `auto` the letters stay and the diamond is laid out as an Xbox pad: A at the bottom, B on the right, X on the left and Y at the top, the button the prompt names lit in its place, its bar reaching left from X and right from the others (`tools/make_romfs_patches.py`, `bflyt_xbox_diamond`: the panes of `blyt/DoCommand_00.bflyt` take their partner's place, A's of B and X's of Y). The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations).
The prompts are part of the game's fonts, textures and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the prompt the game draws for it, which then names the wrong button. Use the Xbox prompts with the default bindings.
### PlayStation
`prompts = playstation` shows a PlayStation pad's buttons: the face buttons as ○ (circle), × (cross), △ (triangle) and □ (square), L1, R1, L2 and R2 on the shoulders and triggers, Options and Share on Plus and Minus, and the d-pad as a cross. Each prompt names the button to press, so the shapes follow `pad_layout`:
| Switch | `nintendo` layout | `xbox` or `auto` layout |
|---|---|---|
| A, B, X, Y | ○, ×, △, □ | ×, ○, □, △ |
| L, R | L1, R1 | L1, R1 |
| ZL, ZR | L2, R2 | L2, R2 |
| Plus, Minus | Options, Share | Options, Share |
| D-pad | cross | cross |
The game's text fonts already have the four shapes (U+25CB, U+00D7, U+25B3 and U+25A1), so the action prompt's diamond uses them as text; the action prompt's button image and the button guide's images are drawn with the same shapes. The game loads `romfs-patches-playstation` (`pad_layout = nintendo`) or `romfs-patches-playstation-xbox` (`xbox`, `auto`) in place of `romfs-patches`; the setup writes both with `tools/make_romfs_patches.py --prompts playstation` and `--prompts playstation-xbox` (`tools/button_icons.py`, `playstation_icons`). With `xbox` and `auto` the diamond is laid out as for the Xbox prompts: × at the bottom, ○ on the right, □ on the left and △ at the top. At a game resolution of another shape the prompts follow the shape's UI layout as the Xbox ones do (below).
The prompts are part of the game's fonts, textures and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the prompt the game draws for it, which then names the wrong button. Use the Xbox or PlayStation prompts with the default bindings.
The game reads its UI archive and fonts once at boot, so the prompts change at the next start, also after `pad_layout` changes between `nintendo` and the others (the menu says *prompts change after restart*); the buttons change at once. Under that note the menu offers *Restart now*: after a confirmation it writes `totk.ini`, closes the game as *Quit game* does and starts the game again with the same command line, which waits until the old process is gone before it opens the log and the saves (`runtime/gfx_present.c`, `gfx_window_closed`; `plat_restart` and `plat_restart_wait` in `runtime/platform/win32.c` and `linux.c`). Progress since the last save is lost, as with *Quit game*; while the game writes a save, the confirmation waits. With `prompts = xbox` the game loads `romfs-patches-xbox` (`pad_layout = nintendo`) or `romfs-patches-xbox-label` (`xbox`, `auto`) next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`; `runtime/input_map.c`, `input_prompts_folder`): the same 60 fps patches, with the prompts drawn from the game's own files by `tools/make_romfs_patches.py --prompts xbox` or `--prompts xbox-label` (`tools/button_icons.py`, after MacNativeGames' `make_button_icons.py`), which the setup runs next to the plain one:
- every prompt but the button guide in play is text in the button font, `scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`: glyphs U+E040 to U+E043 (A B X Y), U+E044 to U+E047 (L R ZL ZR), U+E04B and U+E04C (Plus, Minus), U+E049 and U+E060 to U+E065 (the d-pad). fontTools writes the font again, so the archives grow and the folder also carries the resource size table (`System/Resource/ResourceSizeTable.Product.<n>...rsizetable.zs`) with their entries raised by as much; without that the game stops at start.
- the button guide in play draws L and ZL from the images `Nt_KeyTexL_00` and `Nt_KeyTexZL_00` of the Common archive's `timg/__Combined.bntx`, painted with the same icons. The action prompt draws its button from `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped for `nintendo`, and the diamond's letters are text the game takes from `LayoutMsg/DoCommand_00.msbt` of each language's `Mals` archive (and the layout's own text panes behind it), swapped the same way.
The Switch prompts stay, with a note under *Button prompts* and a `RomFS overlay: ...` line in the log, when the folder is missing (an install made by an older setup, or one where the setup could not prepare it and showed a warning; running the setup again on the install folder writes it), when it fails its check, with a game resolution of another shape than 16:9 that has no folder of its own (below), 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`.
With `prompts = playstation` the game loads `romfs-patches-playstation` (`pad_layout = nintendo`) or `romfs-patches-playstation-xbox` (`xbox`, `auto`) the same way, written by `tools/make_romfs_patches.py --prompts playstation` and `--prompts playstation-xbox`: the same 60 fps patches, with the face buttons' images and the diamond's letters drawn as ○ × △ □, the shoulders and triggers as L1 R1 L2 R2, Options and Share, and the button guide's L and ZL images. The game's text fonts already have the four shapes, so the diamond's panes and messages hold those characters instead of the letters.
At a game resolution of another shape than 16:9 the game loads `romfs-patches-xbox-<w>x<h>` (or `romfs-patches-xbox-label-<w>x<h>`) in place of `romfs-patches-<w>x<h>`: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts xbox --aspect <w>x<h> --reuse <install>\romfs-patches-xbox --out <install>\romfs-patches-xbox-<w>x<h>`. The setup writes both for each of the fifteen sizes it lays the UI out for, as for the PC prompts below, so on a display of one of those shapes the game resolution follows the display with these prompts too. At another size, without that folder, the Switch prompts stay (*off at this game resolution*).
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; an install whose setup's tools sit next to the game makes it itself, see below), when it fails its check, with a game resolution of another shape than 16:9 that has no folder of its own (below), 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`); `--prompts playstation` and `--prompts playstation-xbox` write `build\<ver>\romfs-patches-playstation` and `-playstation-xbox` the same way. It needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`.
A missing prompts folder, at 16:9 or of a game resolution's shape, is made by the game itself on an install whose setup left its tools next to the game (`build-cache/rebuild.txt`): choosing those prompts or a pad layout that needs it, or starting the game with them selected, starts `make_romfs_patches.py --background` for it (`runtime/romfs.c`, `romfs_folders_prepare`; `runtime/ui/menu.cpp`, `folders_tick`, once the choice has stayed for 1.5 seconds). The note says *prompt files being made in the background; used at the next start*; when the tools did not start it says so and *Try again* starts them again. A source build has no `rebuild.txt` and keeps the notes above.
At a game resolution of another shape than 16:9 the game loads `romfs-patches-<style>-<w>x<h>` (`romfs-patches-xbox-<w>x<h>`, `-xbox-label-`, `-playstation-` or `-playstation-xbox-`) in place of `romfs-patches-<w>x<h>`: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts <style> --aspect <w>x<h> --reuse <install>\romfs-patches-<style> --out <install>\romfs-patches-<style>-<w>x<h>`. The setup writes it for the shapes of the connected displays and `output_res`, for the selected prompts only (installer Shapes step), as for the PC prompts below. At another size, without that folder, the Switch prompts stay (*off at this game resolution*) until the game has made it in the background (above).
## PC button prompts
+12 -6
View File
@@ -90,12 +90,14 @@ 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`, `romfs-patches-xbox` and `romfs-patches-xbox-label`
The patches are written five 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 prompt folders are optional: when one cannot be made, the setup warns and finishes.
and `auto`), `romfs-patches-playstation` and `romfs-patches-playstation-xbox` (PlayStation prompts for
`prompts = playstation`, the same split). The prompt folders are optional: when one cannot be made, the setup warns
and finishes.
**PC prompts** (step `pc_prompts`): `romfs-patches-pc`, the keyboard and mouse prompts for `prompts = pc`, drawn
from the `bind_` lines of `totk.ini` (`--binds`). Its key holds those lines, so a setup run after a change of the
bindings draws only these again. Optional like the Xbox prompts. All four 16:9 folders are always written, so a
bindings draws only these again. Optional like the Xbox prompts. All six 16:9 folders are always written, so a
switch of the prompts style at 16:9 needs no setup run.
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
@@ -108,9 +110,13 @@ loads the saves 1.4.3 wrote.
`output_res` (`installer/screens.py`). One folder per shape, named after the shape's size in `ASPECT_SIZES` (the
closest within 1%; `5120x2160` uses `2560x1080`); `runtime/romfs.c` `overlay_init` maps the game resolution the
same way, and a folder of the exact size from an older setup still wins. A 16:9 player gets none. The step runs
again when the displays, the prompts or the patches change; at a game resolution whose shape has no folder the
game draws 16:9 with bars, and the settings menu marks such sizes and can write the shape's folders in the
background for the next start.
again when the displays, the prompts or the patches change. At a game resolution whose shape has no folder the
game draws 16:9 with bars and starts the generator itself, in the background, for the next start: at start and
when the settings menu changes the resolution, the HUD width, the prompts or the pad layout
(`runtime/romfs.c`, `romfs_folders_prepare`, with the Python and tools that `build-cache/rebuild.txt` names; a
missing 16:9 prompts folder too). Those runs use `--background`: below-normal priority, and a folder that has a
manifest is never written into. Every `make_romfs_patches.py` run writes `<folder>.part-<pid>` and renames it into
place when complete; the clean-up step removes the `.part` folders of stopped runs once they are an hour old.
9. **DLSS** (the window's tick box, on by default, or `--dlss`; Windows with an NVIDIA RTX GPU): download
`nvngx_dlss.dll` from NVIDIA's own DLSS SDK repository (github.com/NVIDIA/DLSS, a pinned tag, NVIDIA RTX SDK
license) into the install folder and check its size and SHA-256 (`steps.py`, `Dlss`). The release does not ship
+1 -1
View File
@@ -18,7 +18,7 @@ Many rows below are developer tools that only act together with another setting
| Setting | What it does | Effect of changing it | Safety |
| --- | --- | --- | --- |
| `hud_width` (default `full`) | `full` places the HUD at the screen's edges; `21:9` or `16:9` constrains it to that centered area on a wider game resolution. A cap that is not narrower than the screen, and 16:9 or taller output, keep the full layout. | Read at start. The Shapes installer step builds the selected cap only for needed screen shapes and button prompts. Changing it in the Screen tab may require preparing the layout there or rerunning setup before restarting. If a capped folder is missing the full layout loads with a log message. Explicit overlay overrides and player UI mods keep their precedence. | Safe |
| `hud_width` (default `full`) | `full` places the HUD at the screen's edges; `21:9` or `16:9` constrains it to that centered area on a wider game resolution. A cap that is not narrower than the screen, and 16:9 or taller output, keep the full layout. | Read at start. The Shapes installer step builds the selected cap only for needed screen shapes and button prompts. After a change in the Screen tab an install makes a missing layout in the background; it loads at the next start. If a capped folder is missing the full layout loads with a log message. Explicit overlay overrides and player UI mods keep their precedence. | Safe |
## Diagnostics and logging
+16 -6
View File
@@ -140,16 +140,26 @@ def ini_value(text, name):
return value
# The pad prompts' folder suffixes (make_romfs_patches.py --prompts), each written at 16:9 on every install
# (steps.Prepare): the Xbox and PlayStation ones, for the Nintendo pad layout and for xbox and auto
PAD_PROMPTS = ('xbox', 'xbox-label', 'playstation', 'playstation-xbox')
# Every prompts folder suffix: the pad ones and the keyboard and mouse one (steps.PcPrompts)
PROMPTS_STYLES = PAD_PROMPTS + ('pc',)
def prompts_style(text):
"""The prompts' folder suffix the settings select, as runtime/input_map.c input_prompts_pick and
input_prompts_folder pick it at start: 'pc', 'xbox' (Nintendo pad layout), 'xbox-label' (any other) or None for the
game's own prompts, the default without a totk.ini."""
p, layout = ini_value(text, 'prompts'), (ini_value(text, 'pad_layout') or '').lower()
if p and p.lower() == 'pc':
input_prompts_folder pick it at start: 'pc', 'xbox' or 'playstation' (Nintendo pad layout), 'xbox-label' or
'playstation-xbox' (any other), or None for the game's own prompts, the default without a totk.ini."""
p, layout = (ini_value(text, 'prompts') or '').lower(), (ini_value(text, 'pad_layout') or '').lower()
if p == 'pc':
return 'pc'
if not (p.lower() == 'xbox' if p else layout == 'xbox_prompts'):
nintendo = layout in ('nintendo', 'xbox_prompts')
if p in ('playstation', 'ps'):
return 'playstation' if nintendo else 'playstation-xbox'
if not (p == 'xbox' if p else layout == 'xbox_prompts'):
return None
return 'xbox' if layout in ('nintendo', 'xbox_prompts') else 'xbox-label'
return 'xbox' if nintendo else 'xbox-label'
def wanted(dest, screens=None):
+35 -9
View File
@@ -1303,14 +1303,15 @@ class Prepare(Step):
dest / 'romfs-patches'])
if code:
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
# The same with Xbox button icons in the prompts, for prompts = xbox (make_romfs_patches.py --prompts):
# romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label for xbox and auto (runtime/input_map.c
# input_prompts_folder). Both are written on every install, so the menu choices work without another run of
# The same with Xbox and PlayStation button icons in the prompts, for prompts = xbox and playstation
# (make_romfs_patches.py --prompts): romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label
# for xbox and auto, and romfs-patches-playstation / -playstation-xbox likewise (runtime/input_map.c
# input_prompts_folder). All 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. The keyboard and mouse prompts are the PcPrompts
# step's: they follow totk.ini's bindings.
failed = None
for style in ('xbox', 'xbox-label'):
for style in screens.PAD_PROMPTS:
out = dest / f'romfs-patches-{style}'
remove(out)
code, log = run_tool(ctx, f'prepare-{style}', layout.tools / 'make_romfs_patches.py',
@@ -1407,7 +1408,30 @@ class PcPrompts(Step):
# ---- 6b. screen shapes
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-xbox|-xbox-label|-pc)?-\d+x\d+(?:-hud(?:16|21)x9)?$')
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-(?:%s))?-\d+x\d+(?:-hud(?:16|21)x9)?$'
% '|'.join(map(re.escape, screens.PROMPTS_STYLES)))
# make_romfs_patches.py writes <folder>.part-<pid> and renames it to <folder> when it is complete. A run that was
# stopped (the PC turned off under a generator the game started, runtime/romfs.c romfs_folders_prepare) leaves its
# folder behind: one whose files did not change for PART_STALE_S is such a leftover, a younger one may belong to a
# generator running now. SHAPED_FOLDER matches neither.
PART_FOLDER = re.compile(r'^romfs-patches[\w.-]*\.part-[\w-]+$')
PART_STALE_S = 3600
def stale_parts(dest, now=None):
"""The leftover .part folders of make_romfs_patches.py runs in dest."""
now = time.time() if now is None else now
found = []
for folder in dest.iterdir() if dest.is_dir() else ():
if not (folder.is_dir() and not folder.is_symlink() and PART_FOLDER.match(folder.name)):
continue
try:
newest = max([folder.stat().st_mtime] + [f.stat().st_mtime for f in folder.rglob('*')])
except OSError:
continue
if now - newest > PART_STALE_S:
found.append(folder)
return found
def hud_width(dest):
@@ -1428,13 +1452,15 @@ def shape_hud(size, hud):
class Shapes(Step):
"""romfs-patches-<w>x<h> (the UI laid out for a shape, make_romfs_patches.py --aspect) and, with Xbox or PC prompts
"""romfs-patches-<w>x<h> (the UI laid out for a shape, make_romfs_patches.py --aspect) and, with Xbox, PlayStation or
PC prompts
in totk.ini, romfs-patches-<style>-<w>x<h> (that layout with those prompts), for the shapes this player needs:
those of the connected displays and of the totk.ini output_res, one folder per shape (installer/screens.py; the
game maps its resolution to the folder in runtime/romfs.c overlay_init). A setup before this step wrote all 15
sizes for every prompts style, 64 folders. The key holds the shapes, prompts style and selected HUD width, so a run after a
monitor or settings change (or its rebuild mode) writes only these again; the game's settings menu can also start
the generator for the shape in use (runtime/ui/menu.cpp row_output_res)."""
monitor or settings change (or its rebuild mode) writes only these again; the game also starts the generator for a
folder its settings need and the install lacks, at start and from its menu (runtime/romfs.c romfs_folders_prepare,
make_romfs_patches.py --background), whose unfinished .part folders the clean-up below leaves alone."""
id = 'shapes'
@@ -1593,7 +1619,7 @@ class Cleanup(Step):
ctx.state['lang'] = ctx.lang
(dest / 'profile').mkdir(exist_ok=True)
rep.progress('cleanup', 'temp', force=True)
for stale in dest.glob('update-merge-*'):
for stale in [*dest.glob('update-merge-*'), *stale_parts(dest)]:
remove(stale)
for name in ('check', 'unpacked', 'shader_list.tsv', 'shared-fonts'): # gen/ and build/ stay for the next rebuild
remove(ctx.temp / name)
+1 -1
View File
@@ -113,7 +113,7 @@
"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.plugins_skipped": "The mods' code plugins (exefs subsdk) could not be built; the game installs without them. 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.xbox_prompts_failed": "The Xbox, PlayStation 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
@@ -113,7 +113,7 @@
"warn.exefs_skipped": "Não foi possível compilar os patches ExeFS dos mods (.ips, .pchtxt); o jogo é instalado sem eles. Detalhes: {log}",
"warn.plugins_skipped": "Não foi possível compilar os plugins de código dos mods (exefs subsdk); 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 ou do PC (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, do PlayStation 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
@@ -113,7 +113,7 @@
"warn.cheats_skipped": "Не удалось собрать читы из папки модов, меняющие код игры; игра установится без них. Подробности: {log}",
"warn.exefs_skipped": "Не удалось собрать ExeFS-патчи модов (.ips, .pchtxt); игра установится без них. Подробности: {log}",
"warn.plugins_skipped": "Не удалось собрать плагины кода модов (exefs subsdk); игра установится без них. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox или PC (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox, PlayStation или 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
@@ -113,7 +113,7 @@
"warn.exefs_skipped": "无法构建模组的 ExeFS 补丁(.ips、.pchtxt);游戏将不含它们进行安装。详情:{log}",
"warn.plugins_skipped": "无法构建模组的代码插件(exefs subsdk);游戏将不含它们进行安装。详情:{log}",
"warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。",
"warn.xbox_prompts_failed": "无法准备 Xbox 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.xbox_prompts_failed": "无法准备 Xbox、PlayStation 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
"warn.shaders_skipped": "显卡驱动在编译部分着色器时崩溃,因此有 {count} 个着色器未被预先准备。游戏会在首次需要时编译它们,驱动在那时也可能崩溃;更新驱动可能会解决。详情:{log}",
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
+25 -18
View File
@@ -14,6 +14,7 @@
#include "cfg.h"
#include "host.h"
#include "input_map.h"
#include "platform/platform.h"
#define PREFIX "TOTK_"
@@ -177,7 +178,7 @@ static const CfgMeta metas[] = {
{"GYRO_BIAS_X", "", NULL, RESTART}, {"GYRO_BIAS_Y", "", NULL, RESTART}, {"GYRO_BIAS_Z", "", NULL, RESTART},
{"GYRO_BIAS_PAD", "", NULL, RESTART},
{"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox", LIVE},
{"PROMPTS", "nintendo", "nintendo|xbox|pc", RESTART},
{"PROMPTS", "nintendo", "nintendo|xbox|playstation|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},
@@ -391,8 +392,8 @@ static const char *raw_get(const char *name) {
// picture between black bars. The sizes are the ones the installer lays the HUD out for (installer/steps.py
// ASPECT_SIZES, ui/menu.cpp row_output_res): of the display's shape within 1%, the smallest at least 1080 high that fits
// the display, else the largest that fits. A 16:9 display, an unknown one or one of another shape keeps 1920x1080.
// Xbox and keyboard prompts need their folder for that size's shape too (romfs-patches-xbox-<w>x<h>, -xbox-label-,
// -pc-, written by installer/steps.py Shapes for the style totk.ini selects and the connected displays' shapes): they
// Xbox, PlayStation and keyboard prompts need their folder for that size's shape too (romfs-patches-<style>-<w>x<h>,
// written by installer/steps.py Shapes for the style totk.ini selects and the connected displays' shapes): they
// keep 1920x1080 when it is missing, as in a source build without make_romfs_patches.py --prompts <style> --aspect or
// after a switch of prompts in the menu, where a default of another shape would trade the prompts the player chose for
// the Switch ones.
@@ -422,22 +423,21 @@ int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]) {
}
static char screen_res[16]; // set once by cfg_init, "" for none
// romfs-patches-xbox-, romfs-patches-xbox-label- and romfs-patches-pc-<screen_res> have a manifest (set once by
// cfg_init)
static const char *const screen_folders[3] = {"romfs-patches-xbox", "romfs-patches-xbox-label", "romfs-patches-pc"};
static int screen_prompts[3];
// Which pad and keyboard prompts' folders have a manifest at screen_res's shape (<folder>-<screen_res>; set once by
// cfg_init): the folders input_map.c input_prompts_folder names
static const char *const screen_folders[5] = {"romfs-patches-xbox", "romfs-patches-xbox-label",
"romfs-patches-playstation", "romfs-patches-playstation-xbox",
"romfs-patches-pc"};
static int screen_prompts[5];
// Whether the prompts in effect have their folder at screen_res. The same picks as input_map.c input_prompts_pick and
// input_prompts_folder: an unknown or empty value is the Nintendo prompts, an unset one Xbox while the pad layout is
// "xbox_prompts"; the Xbox prompts take romfs-patches-xbox with the Nintendo pad layout (or "xbox_prompts") and
// romfs-patches-xbox-label with any other.
// Whether the prompts in effect have their folder at screen_res: the folder input_map.c input_prompts_pick and
// input_prompts_folder pick at start. The game's own prompts need none.
static int shape_keeps_prompts(void) {
const char *p = raw_get(PREFIX "PROMPTS"), *l = raw_get(PREFIX "PAD_LAYOUT");
if (p && *p && !strcasecmp(p, "pc")) return screen_prompts[2];
int xbox = p && *p ? !strcasecmp(p, "xbox") : l && !strcasecmp(l, "xbox_prompts");
if (!xbox) return 1;
int by_position = l && (!strcasecmp(l, "nintendo") || !strcasecmp(l, "xbox_prompts"));
return screen_prompts[by_position ? 0 : 1];
const char *layout = raw_get(PREFIX "PAD_LAYOUT");
const char *want = input_prompts_folder(input_prompts_pick(raw_get(PREFIX "PROMPTS"), layout), layout);
for (int i = 0; want && i < 5; i++)
if (!strcmp(screen_folders[i], want)) return screen_prompts[i];
return 1;
}
static void screen_default(void) {
@@ -455,13 +455,20 @@ static void screen_default(void) {
if (best < 0) best = fit;
if (best < 0) return;
snprintf(screen_res, sizeof screen_res, "%ux%u", SHAPED[best][0], SHAPED[best][1]);
for (int i = 0; i < 3; i++)
for (int i = 0; i < 5; i++)
screen_prompts[i] = romfs_shaped_prompts_ready(screen_folders[i], SHAPED[best][0], SHAPED[best][1]);
if (!raw_get(PREFIX "OUTPUT_RES") && shape_keeps_prompts())
rt_log("cfg: the display is %dx%d: output_res defaults to %s, its shape (totk.ini output_res sets another)", sw,
sh, screen_res);
}
int cfg_screen_size(unsigned out[2]) {
unsigned w = 0, h = 0;
if (raw_get(PREFIX "OUTPUT_RES") || !screen_res[0] || sscanf(screen_res, "%ux%u", &w, &h) != 2) return 0;
out[0] = w, out[1] = h;
return 1;
}
const char *cfg_get(const char *name) {
const char *v = raw_get(name);
if (v || strncmp(name, PREFIX, PREFIX_LEN)) return v;
+6
View File
@@ -26,6 +26,12 @@ int cfg_is_set(const char *name);
// The folder size of w x h's shape (cfg.c SHAPED: the closest aspect ratio within 1%, the first of equal ones), the
// one romfs-patches-<w>x<h> the setup writes for it. 0 for 16:9 and for a shape without a UI layout.
int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]);
// The size output_res defaults to on this display (its shape, cfg.c screen_default) while the player set no
// output_res, also when the default stays 1920x1080 because that shape lacks the prompts' folder. The generator the game
// starts for missing folders (romfs.c romfs_folders_prepare) makes them for this size, so after a prompts change the
// next start takes the display's shape again. 0 when the player set output_res, a device profile is in use or the
// display is 16:9.
int cfg_screen_size(unsigned out[2]);
// The device profile in use, "deck" or "desktop" (TOTK_DEVICE_PROFILE, else what the machine is).
const char *cfg_device_profile(void);
// Writes the keys cfg_set changed since the last save into totk.ini next to totk.exe (cfg_save_to: the file at path).
+40 -7
View File
@@ -334,14 +334,27 @@ int probe_cfg(void) {
EQ(input_prompts_folder(PROMPTS_XBOX, "auto"), "romfs-patches-xbox-label") &&
EQ(input_prompts_folder(PROMPTS_XBOX, NULL), "romfs-patches-xbox-label"),
"prompts: the face buttons by position for the Nintendo layout, by label for xbox and auto");
CHECK(input_prompts_pick("PlayStation", "nintendo") == PROMPTS_PLAYSTATION &&
input_prompts_pick("playstation", "xbox") == PROMPTS_PLAYSTATION &&
input_prompts_pick("ps", "auto") == PROMPTS_PLAYSTATION,
"prompts: PlayStation, any case");
CHECK(EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "nintendo"), "romfs-patches-playstation") &&
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "xbox_prompts"), "romfs-patches-playstation") &&
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "xbox"), "romfs-patches-playstation-xbox") &&
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "auto"), "romfs-patches-playstation-xbox") &&
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, NULL), "romfs-patches-playstation-xbox"),
"prompts: the PlayStation shapes by position for the Nintendo layout, by label for xbox and auto");
// romfs-patches-xbox shows A as B (tests/romfs_prompts_test.py checks the folders' contents). It is right exactly
// where the layout puts A on the east button, which an Xbox pad labels B.
// where the layout puts A on the east button, which an Xbox pad labels B. The PlayStation folder shows A as the
// circle there, so its name follows the same split.
input_map_reset();
static const char *const layouts[] = {"nintendo", "xbox", "auto", "xbox_prompts"};
for (int i = 0; i < 4; i++) {
int a_east = input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_EAST] = 1}, input_pad_layout_pick(layouts[i], 0)) == 1ull << B_A;
CHECK(a_east == EQ(input_prompts_folder(PROMPTS_XBOX, layouts[i]), "romfs-patches-xbox"),
"prompts: the folder names A as B exactly when the layout puts A on the button labelled B");
CHECK(a_east == EQ(input_prompts_folder(PROMPTS_PLAYSTATION, layouts[i]), "romfs-patches-playstation"),
"prompts: the PlayStation folder puts A on the circle exactly when the layout puts A on the east button");
}
// One folder per screen shape (cfg.c cfg_shape_size, installer/screens.py shape_size): the closest aspect ratio of
// SHAPED within 1%, the first of equal ones; 16:9 and unlisted shapes have none.
@@ -383,7 +396,7 @@ int probe_cfg(void) {
!romfs_shaped_prompts_ready("romfs-patches-pc", 5120, 2160),
"shape: an older install's exact-size prompts folder serves that size only");
cfg_set("TOTK_HUD_WIDTH", "16:9");
CHECK(romfs_shaped_ready(5120, 2160) && romfs_shape_missing(5120, 2160, NULL),
CHECK(romfs_shaped_ready(5120, 2160) && romfs_folders_missing(5120, 2160, NULL) == ROMFS_NEED_LAYOUT,
"HUD: a full layout allows wide output but does not hide a missing selected cap");
for (size_t i = 0; i < sizeof capped / sizeof *capped; i++) {
snprintf(f, sizeof f, "%s/%s", dir, capped[i]);
@@ -391,19 +404,39 @@ int probe_cfg(void) {
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, capped[i]);
plat_file_write(f, "#\n", 2);
}
CHECK(!romfs_shape_missing(5120, 2160, "romfs-patches-xbox") &&
romfs_shape_missing(5120, 2160, "romfs-patches-pc"),
CHECK(romfs_folders_missing(5120, 2160, "romfs-patches-xbox") == ROMFS_NEED_PROMPTS &&
romfs_folders_missing(5120, 2160, "romfs-patches-pc") ==
(ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS),
"HUD: canonical capped layouts serve aliases, including Xbox; missing PC prompts still need preparation");
cfg_set("TOTK_HUD_WIDTH", "21:9");
CHECK(romfs_shape_missing(5120, 2160, NULL) && !romfs_shape_missing(5120, 1440, NULL),
CHECK(romfs_folders_missing(5120, 2160, NULL) && !romfs_folders_missing(5120, 1440, NULL),
"HUD: a different cap needs a different folder; 5120x1440 uses the 3840x1080 shape");
cfg_set("TOTK_HUD_WIDTH", "full");
CHECK(!romfs_shaped_ready(5120, 1440), "HUD: switching to full does not reuse a capped-only layout");
cfg_set("TOTK_HUD_WIDTH", "21:9");
CHECK(!romfs_shape_missing(1920, 1080, NULL), "HUD: 16:9 output ignores a wider cap");
CHECK(!romfs_folders_missing(1920, 1080, NULL), "HUD: 16:9 output ignores a wider cap");
// The 16:9 prompts' folder is needed at every shape (an older setup or a failed step left it out); at 16:9
// nothing shaped is
CHECK(romfs_folders_missing(1920, 1080, "romfs-patches-playstation") == ROMFS_NEED_PROMPTS &&
romfs_folders_missing(2560, 1440, "romfs-patches-playstation") == ROMFS_NEED_PROMPTS,
"folders: missing 16:9 prompts are asked for at 16:9, without a shaped folder");
snprintf(f, sizeof f, "%s/romfs-patches-playstation", dir);
plat_file_mkdir_p(f);
snprintf(f, sizeof f, "%s/romfs-patches-playstation/manifest.tsv", dir);
plat_file_write(f, "#\n", 2);
CHECK(!romfs_folders_missing(1920, 1080, "romfs-patches-playstation") &&
(romfs_folders_missing(5120, 2160, "romfs-patches-playstation") &
(ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS)) == ROMFS_NEED_SHAPED_PROMPTS,
"folders: present 16:9 prompts leave only the shaped folder to make");
plat_file_delete(f);
plat_setenv("TOTK_ROMFS_PATCHES", "0");
CHECK(!romfs_shape_missing(5120, 2160, NULL), "HUD: explicit overlay overrides do not request generated layouts");
CHECK(!romfs_folders_missing(5120, 2160, NULL) && !romfs_folders_missing(1920, 1080, "romfs-patches-pc"),
"HUD: explicit overlay overrides do not request generated layouts or prompts");
plat_setenv("TOTK_ROMFS_PATCHES", NULL);
// Without build-cache/rebuild.txt (a source build) nothing starts: the menu's notes keep "run the setup
// again" and the start spawns nothing (romfs.c overlay_init)
CHECK(!romfs_folders_can_prepare() && !romfs_folders_prepare(5120, 2160, "romfs-patches-pc"),
"folders: no setup's tools, no generator");
cfg_set("TOTK_HUD_WIDTH", "full");
for (size_t i = 0; i < sizeof capped / sizeof *capped; i++) {
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, capped[i]);
+12 -7
View File
@@ -47,14 +47,19 @@ enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROM
ROMFS_PROMPTS_PATCHES };
const char *romfs_prompts(void);
int romfs_prompts_ready(const char *folder);
// 1 when w x h is of another shape whose selected HUD layout or prompts_folder's selected variant is missing.
// NULL prompts_folder means the game's own prompts; a full-layout fallback does not satisfy a requested HUD cap.
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder);
// The folders a start at game resolution w x h with prompts_folder (input_prompts_folder; NULL for the game's own
// prompts) and the selected HUD width needs and that have no manifest: ROMFS_NEED_PROMPTS, prompts_folder itself (16:9);
// at another shape (res_wants_wide_overlay) ROMFS_NEED_LAYOUT, its romfs-patches-<w>x<h>[-hud..], and
// ROMFS_NEED_SHAPED_PROMPTS, <prompts_folder>-<w>x<h>[-hud..]. A full-layout fallback does not satisfy a requested HUD
// cap. 0 with TOTK_ROMFS_PATCHES set.
enum { ROMFS_NEED_LAYOUT = 1, ROMFS_NEED_PROMPTS = 2, ROMFS_NEED_SHAPED_PROMPTS = 4 };
int romfs_folders_missing(unsigned w, unsigned h, const char *prompts_folder);
// 1 when build-cache/rebuild.txt names the setup's Python and tools/make_romfs_patches.py and both exist, with romfs/.
int romfs_shape_can_prepare(void);
// Starts the generator for w x h's shape and selected HUD width (including prompts_folder's variant when needed) as
// child processes the game does not wait for; the next start loads the result. 1 when every one started.
int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder);
int romfs_folders_can_prepare(void);
// Starts the generator for each folder romfs_folders_missing names, once per folder in this process, as child
// processes the game does not wait for; the next start loads the result. 1 when every one runs, 0 when none was
// missing, the tools are not there or one could not start.
int romfs_folders_prepare(unsigned w, unsigned h, const char *prompts_folder);
int romfs_prompts_off(const char *folder);
const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added); // RomFS path of overlay k
void fs_trace(const char *what, const char *path); // TOTK_TRACE=fs: one line per open
+1
View File
@@ -323,6 +323,7 @@ int romfs_shaped_ready(unsigned w, unsigned h); // romfs-patches-<w>x
int romfs_shaped_prompts_ready(const char *folder, unsigned w, unsigned h); // the same for <folder>-<w>x<h>, a
// prompts' folder (romfs-patches-xbox, -xbox-label, -pc)
void res_wanted(unsigned out[2]); // the output size TOTK_OUTPUT_RES asks for
void res_asked(unsigned out[2]); // the same before a missing shaped layout made it 16:9
void res_fov_live(void); // TOTK_FOV to the camera (set fov); on a settings change
void res_dynres_live(void); // TOTK_DYNAMIC_RES to the game (set fixres); on a settings change
// ---- code patches (patches.c) and the frame step (frame_rate.c)
+6 -1
View File
@@ -307,12 +307,17 @@ 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 : !strcasecmp(prompts, "pc") ? PROMPTS_PC : PROMPTS_NINTENDO;
return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX
: !strcasecmp(prompts, "playstation") || !strcasecmp(prompts, "ps") ? PROMPTS_PLAYSTATION
: !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_PLAYSTATION)
return input_pad_layout_pick(pad_layout, 0) == PAD_LAYOUT_NINTENDO ? "romfs-patches-playstation"
: "romfs-patches-playstation-xbox";
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.
+10 -7
View File
@@ -91,18 +91,21 @@ 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). PC: the key or
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). PlayStation: the
// face buttons as ○ × △ □, L1 R1 L2 R2, Options and Share, likewise on the button the pad layout presses. 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.
enum { PROMPTS_NINTENDO, PROMPTS_XBOX, PROMPTS_PLAYSTATION, PROMPTS_PC };
// The prompts for a TOTK_PROMPTS value ("nintendo", "xbox", "playstation" 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. 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).
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. The
// PlayStation prompts have the same two folders: romfs-patches-playstation (Nintendo layout, A on the right button is
// circle) and romfs-patches-playstation-xbox (xbox and auto, A on the bottom button is cross). 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);
+10 -4
View File
@@ -58,6 +58,7 @@
static struct {
int decided;
unsigned ow, oh, sw, sh; // output and scene
unsigned aw, ah; // the output TOTK_OUTPUT_RES asks for, before shape_fallback
int scene_set; // the scene differs from the game's 5/6 of the output
int heapdef_ok; // romfs.c serves the grown HeapDef
int on; // res_init switched the patch sets on
@@ -161,14 +162,14 @@ static void shape_fallback(void) {
static void decide(void) {
if (R.decided) return;
R.decided = 1;
R.ow = BASE_W;
R.oh = BASE_H;
R.ow = R.aw = BASE_W;
R.oh = R.ah = BASE_H;
const char *o = cfg_value("TOTK_OUTPUT_RES");
unsigned w = 0, h = 0;
char tail;
if (sscanf(o, "%ux%u%c", &w, &h, &tail) == 2 && w >= 1280 && h >= 720 && w <= 7680 && h <= 4320) {
R.ow = w & ~1u;
R.oh = h & ~1u;
R.ow = R.aw = w & ~1u;
R.oh = R.ah = h & ~1u;
shape_fallback();
} else {
rt_log("resolution: TOTK_OUTPUT_RES=%s is not <width>x<height> in 1280x720..7680x4320; 1920x1080", o);
@@ -677,6 +678,11 @@ void res_wanted(unsigned out[2]) {
out[0] = R.ow, out[1] = R.oh;
}
void res_asked(unsigned out[2]) {
decide();
out[0] = R.aw, out[1] = R.ah;
}
// A TOTK_DLSS change while the game runs (vk_dlaa.c, at a present): the new scene size goes to the patch page, where
// the game reads it when it sets its render size (main+0x585e48). 1.4.3 does that once, at start: its renderer setup
// (main+0x7000e67028) calls main+0x585bd0(renderer, force), which picks the console mode's sizes and flags the render
+122 -82
View File
@@ -934,14 +934,15 @@ static void camera_overlay(void) {
// did not load (ROMFS_PROMPTS_*). The menu compares them with the settings in effect (ui/menu.cpp prompts_note).
// Each folder keeps its name, but at a game resolution of another shape than 16:9 its files come from dir,
// <name>-<w>x<h> (overlay_init), and ready is that one's.
static struct { const char *name; int ready; char dir[64]; } prompts_folders[3];
#define PROMPTS_FOLDERS 5 // the two Xbox folders, the two PlayStation ones, the PC one (overlay_init)
static struct { const char *name; int ready; char dir[64]; } prompts_folders[PROMPTS_FOLDERS];
static const char *prompts_wanted, *prompts_loaded;
static int prompts_off;
const char *romfs_prompts(void) { return prompts_loaded; }
int romfs_prompts_ready(const char *folder) {
for (int i = 0; i < 3; i++)
for (int i = 0; i < PROMPTS_FOLDERS; i++)
if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready;
return 0;
}
@@ -1014,16 +1015,16 @@ static void overlay_init(void) {
// size, else the folder of its shape): the same overlay with the UI laid out for that shape
// (make_romfs_patches.py --aspect), when the game version has the camera aspect patch the layout goes with
// (res_wants_wide_overlay).
// With prompts = xbox, the Xbox prompts' folder for the pad layout in its place (input_prompts_folder): the same
// patches with Xbox button icons (make_romfs_patches.py --prompts); prompts = pc takes romfs-patches-pc whatever
// the pad layout. The game reads the archives once at boot, so the prompts stay until restart even though the
// layout itself changes live. Each folder replaces romfs-patches as a whole. At a game resolution of another shape
// the prompts come from <folder>-<w>x<h> (make_romfs_patches.py --prompts <style> --aspect): it carries that
// shape's UI layout too, so it replaces romfs-patches-<w>x<h> as the folder replaces romfs-patches. Without it the
// Switch prompts stay with the shape's layout. So they do when a RomFS mod (the TOTK_ROMFS_MODS manifest or a
// player mod) 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.
// With prompts = xbox or playstation, that controller's prompts' folder for the pad layout in its place
// (input_prompts_folder): the same patches with Xbox or PlayStation button icons (make_romfs_patches.py
// --prompts); prompts = pc takes romfs-patches-pc whatever the pad layout. The game reads the archives once at
// boot, so the prompts stay until restart even though the layout itself changes live. Each folder replaces
// romfs-patches as a whole. At a game resolution of another shape the prompts come from <folder>-<w>x<h>
// (make_romfs_patches.py --prompts <style> --aspect): it carries that shape's UI layout too, so it replaces
// romfs-patches-<w>x<h> as the folder replaces romfs-patches. Without it the Switch prompts stay with the shape's
// layout. So they do when a RomFS mod (the TOTK_ROMFS_MODS manifest or a player mod) 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.
char def[2100], path[2100];
const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS");
int wide = 0;
@@ -1039,17 +1040,20 @@ static void overlay_init(void) {
rt_log("RomFS overlay: the UI layout for %ux%u from %s", out[0], out[1], name);
const char *suffix = hud_suffix(out[0], out[1]);
if (*suffix && !ends_with(name, suffix))
rt_log("RomFS overlay: the selected HUD layout is missing; using the full HUD. Prepare it in the "
"Screen tab, rerun setup, or run tools/make_romfs_patches.py --aspect %ux%u --hud %s",
rt_log("RomFS overlay: the selected HUD layout is missing; using the full HUD (an install makes it "
"in the background below; a source build: tools/make_romfs_patches.py --aspect %ux%u --hud %s)",
shape[0], shape[1], cfg_value("TOTK_HUD_WIDTH"));
} else {
rt_log("RomFS overlay: no %s for this game resolution, the UI keeps its 16:9 layout (run the setup again, "
"or tools/make_romfs_patches.py --aspect %ux%u)", name, shape[0], shape[1]);
}
}
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);
// one of each Xbox and PlayStation folder, then the PC one
static const char *const layouts[2] = {"nintendo", "xbox"};
for (int i = 0; i < PROMPTS_FOLDERS; i++) {
const char *name = i < 2 ? input_prompts_folder(PROMPTS_XBOX, layouts[i])
: i < 4 ? input_prompts_folder(PROMPTS_PLAYSTATION, layouts[i - 2])
: input_prompts_folder(PROMPTS_PC, 0);
char *dir = prompts_folders[i].dir;
prompts_folders[i].name = name;
if (wide) {
@@ -1063,15 +1067,17 @@ static void overlay_init(void) {
}
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
int pick = input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout);
const char *style = pick == PROMPTS_PC ? "keyboard and mouse" : "Xbox";
const char *style = pick == PROMPTS_PC ? "keyboard and mouse"
: pick == PROMPTS_PLAYSTATION ? "PlayStation"
: "Xbox";
prompts_wanted = input_prompts_folder(pick, layout);
const char *wanted_dir = prompts_wanted; // the folder its files come from
for (int i = 0; i < 3; i++)
for (int i = 0; i < PROMPTS_FOLDERS; i++)
if (prompts_wanted && !strcmp(prompts_folders[i].name, prompts_wanted)) wanted_dir = prompts_folders[i].dir;
const char *suffix = hud_suffix(out[0], out[1]);
if (wide && prompts_wanted && romfs_prompts_ready(prompts_wanted) && *suffix && !ends_with(wanted_dir, suffix))
rt_log("RomFS overlay: the %s prompts have no selected HUD layout; their full HUD loads instead. Prepare "
"the layout in the Screen tab or rerun setup", style);
rt_log("RomFS overlay: the %s prompts have no selected HUD layout; their full HUD loads instead (an "
"install makes it in the background below)", style);
prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK
: patches && !wide ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? (wide ? ROMFS_PROMPTS_SHAPE : ROMFS_PROMPTS_MISSING)
@@ -1098,8 +1104,18 @@ static void overlay_init(void) {
snprintf(why, sizeof why, "%s", prompts_off == ROMFS_PROMPTS_PATCHES
? "TOTK_ROMFS_PATCHES is set"
: "their folder has no manifest.tsv (run the setup again)");
rt_log("RomFS overlay: prompts = %s, but %s; Switch prompts stay", pick == PROMPTS_PC ? "pc" : "xbox", why);
rt_log("RomFS overlay: prompts = %s, but %s; Switch prompts stay",
pick == PROMPTS_PC ? "pc" : pick == PROMPTS_PLAYSTATION ? "playstation" : "xbox", why);
}
// A folder the settings in effect ask for and the install lacks (an older setup, a failed setup step, a display
// of another shape): its generator starts in the background for the next start when the setup's tools are next to
// the game (romfs_folders_prepare). The size is the one output_res asks for: without its shape's layout the game
// draws 16:9 this time (resolution.c shape_fallback). Without an output_res it is the display's shape, which the
// default keeps only while that shape has the prompts' folder (cfg.c cfg_screen_size). Nothing with
// TOTK_ROMFS_PATCHES set; a source build has no build-cache/rebuild.txt and keeps the lines above.
unsigned asked[2];
if (!cfg_screen_size(asked)) res_asked(asked);
romfs_folders_prepare(asked[0], asked[1], prompts_wanted);
size_t prompts_end = noverlay;
char plain[2100]; // romfs-patches, when it has a manifest
int plain_ok = snprintf(plain, sizeof plain, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof plain &&
@@ -1173,14 +1189,19 @@ int romfs_shaped_ready(unsigned w, unsigned h) { return shaped_folder_ready("rom
// loads in its place with those prompts.
int romfs_shaped_prompts_ready(const char *folder, unsigned w, unsigned h) { return shaped_folder_ready(folder, w, h, 1); }
// ---- the layout for a new screen, from the settings menu (ui/menu.cpp row_output_res)
// The setup writes the shaped folders for the displays connected when it ran (installer/steps.py Shapes). After a
// monitor change the menu can start the same generator for the shape of the game resolution: the setup's Python and
// tools/make_romfs_patches.py, which build-cache/rebuild.txt names (installer/steps.py write_rebuild_command: line 1 the
// Python, pythonw on Windows, so no console opens; line 4 the setup's folder; both relative to the install folder for
// the build kit, installer/layout.py), on the install folder's romfs/. Child
// processes the game does not wait for: the generator writes manifest.tsv last, so a folder it has not finished is not
// taken, and the next start loads the finished one.
// ---- missing folders, made in the background (the settings menu, ui/menu.cpp folders_tick, and the start,
// overlay_init)
// The setup writes the 16:9 prompts' folders on every install (installer/steps.py Prepare, PcPrompts) and the shaped
// folders for the displays connected when it ran (Shapes). An install by an older setup, a failed setup step, a
// monitor change or a change of resolution, HUD width, prompts or pad layout can ask for a folder it did not write.
// The game then starts the same generator: the setup's Python and tools/make_romfs_patches.py, which
// build-cache/rebuild.txt names (installer/steps.py write_rebuild_command: line 1 the Python, pythonw on Windows, so
// no console opens; line 4 the setup's folder; both relative to the install folder for the build kit,
// installer/layout.py), on the install folder's romfs/. Child processes the game does not wait for. With --background
// the generator writes into a folder of its own beside the output and renames it into place at the end, unless a
// folder with a manifest is there by then: a folder this game or another start loaded is never written into, and two
// generators for one folder (the menu and the start, or a restart while the last one runs) do not mix their files.
// The next start loads the finished folder.
static int prepare_tools(char *python, size_t pcap, char *script, size_t scap, char *dir, size_t dcap) {
char path[2400];
index_folder(dir, dcap);
@@ -1209,14 +1230,24 @@ static int prepare_tools(char *python, size_t pcap, char *script, size_t scap, c
return ok && plat_file_exists(python) && plat_file_exists(script) && plat_file_exists(path);
}
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder) {
unsigned out[2] = {w, h};
if (cfg_get("TOTK_ROMFS_PATCHES") || !res_wants_wide_overlay(out)) return 0;
return !shaped_folder_ready("romfs-patches", w, h, 0) ||
(prompts_folder && !shaped_folder_ready(prompts_folder, w, h, 0));
// 1 when folder (a name next to romfs-index.bin) has a manifest.
static int plain_folder_ready(const char *folder) {
char dir[2100], path[2400];
index_folder(dir, sizeof dir);
return snprintf(path, sizeof path, "%s/%s/manifest.tsv", dir, folder) < (int)sizeof path && plat_file_exists(path);
}
int romfs_shape_can_prepare(void) {
int romfs_folders_missing(unsigned w, unsigned h, const char *prompts_folder) {
unsigned out[2] = {w, h};
if (cfg_get("TOTK_ROMFS_PATCHES")) return 0;
int need = prompts_folder && !plain_folder_ready(prompts_folder) ? ROMFS_NEED_PROMPTS : 0;
if (!res_wants_wide_overlay(out)) return need;
if (!shaped_folder_ready("romfs-patches", w, h, 0)) need |= ROMFS_NEED_LAYOUT;
if (prompts_folder && !shaped_folder_ready(prompts_folder, w, h, 0)) need |= ROMFS_NEED_SHAPED_PROMPTS;
return need;
}
int romfs_folders_can_prepare(void) {
static int known = -1;
if (known < 0) {
char python[1024], script[1100], dir[2100];
@@ -1225,9 +1256,10 @@ int romfs_shape_can_prepare(void) {
return known;
}
// The folders a generator was started for in this process. The menu thread alone calls romfs_shape_prepare, so no
// lock. The game picks its overlay at start, so a folder is not started twice before the next start, even when its
// generator has ended: a second click, or the same size chosen again, starts no second generator writing into it.
// The folders a generator was started for in this process, under shape_lock: the start (overlay_init) and the menu
// thread both start them. The game picks its overlay at start, so a folder is not started twice before the next start,
// even when its generator has ended: the same setting chosen again starts no second generator for it.
static PlatMutex shape_lock = PLAT_MUTEX_INIT;
static char (*shape_started)[160];
static int shape_started_n, shape_started_cap;
@@ -1238,63 +1270,71 @@ static int shape_was_started(const char *folder) {
}
// Starts the generator for folder (a name in dir) unless one was started for it before. 1 when one runs for it, 0 when
// it could not start. plat_spawn starts it detached and closes its handles without waiting, so a click costs the menu
// thread one CreateProcess.
// it could not start. plat_spawn starts it detached and closes its handles without waiting, so a start costs the
// calling thread one CreateProcess.
static int shape_spawn(const char *const *argv, const char *dir, const char *folder) {
if (shape_was_started(folder)) return 1;
if (shape_started_n == shape_started_cap) {
int cap = shape_started_cap ? shape_started_cap * 2 : 8;
void *grown = realloc(shape_started, (size_t)cap * sizeof *shape_started);
if (!grown) return 0; // never start a writer whose folder cannot be remembered for deduplication
shape_started = grown;
shape_started_cap = cap;
plat_mutex_lock(&shape_lock);
int ok = 1;
if (!shape_was_started(folder)) {
if (shape_started_n == shape_started_cap) {
int cap = shape_started_cap ? shape_started_cap * 2 : 8;
void *grown = realloc(shape_started, (size_t)cap * sizeof *shape_started);
if (grown) shape_started = grown, shape_started_cap = cap;
}
// never start a writer whose folder cannot be remembered for deduplication
ok = shape_started_n < shape_started_cap && plat_spawn(argv, dir);
if (ok) snprintf(shape_started[shape_started_n++], sizeof *shape_started, "%s", folder);
}
if (!plat_spawn(argv, dir)) return 0;
snprintf(shape_started[shape_started_n++], sizeof *shape_started, "%s", folder);
return 1;
plat_mutex_unlock(&shape_lock);
return ok;
}
int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder) {
int romfs_folders_prepare(unsigned w, unsigned h, const char *prompts_folder) {
char python[1024], script[1100], dir[2100], romfs[2200], out[2300], reuse[2300], binds[2300], size[32], version[8],
name[128], folder[160];
unsigned s[2];
if (!cfg_shape_size(w, h, s) || !prepare_tools(python, sizeof python, script, sizeof script, dir, sizeof dir))
return 0;
folder[160];
int need = romfs_folders_missing(w, h, prompts_folder);
if (!need || !prepare_tools(python, sizeof python, script, sizeof script, dir, sizeof dir)) return 0;
unsigned s[2] = {w, h};
int shaped = cfg_shape_size(w, h, s);
snprintf(size, sizeof size, "%ux%u", s[0], s[1]);
snprintf(version, sizeof version, "v%d", rt_game_version);
snprintf(romfs, sizeof romfs, "%s/romfs", dir);
const char *suffix = hud_suffix(w, h), *hud = *suffix ? cfg_value("TOTK_HUD_WIDTH") : "full";
const char *suffix = shaped ? hud_suffix(w, h) : "", *hud = *suffix ? cfg_value("TOTK_HUD_WIDTH") : "full";
const char *style = prompts_folder ? prompts_folder + strlen("romfs-patches-") : NULL;
// The keyboard and mouse prompts are drawn from totk.ini's bind_ lines, as the setup's PcPrompts and Shapes steps
// draw them (installer/steps.py pc_binds); a file without such lines gives the keyboard defaults.
snprintf(binds, sizeof binds, "%s/totk.ini", dir);
int pc = style && !strcmp(style, "pc") && plat_file_exists(binds);
static const int order[3] = {ROMFS_NEED_PROMPTS, ROMFS_NEED_LAYOUT, ROMFS_NEED_SHAPED_PROMPTS};
int started = 0, failed = 0;
if (!selected_shape(dir, "romfs-patches", w, h, name, sizeof name, 0)) {
snprintf(folder, sizeof folder, "romfs-patches-%s%s", size, suffix);
for (int k = 0; k < 3; k++) {
int what = order[k];
if (!(need & what) || (what != ROMFS_NEED_PROMPTS && !shaped)) continue;
if (what == ROMFS_NEED_PROMPTS) snprintf(folder, sizeof folder, "%s", prompts_folder);
else if (what == ROMFS_NEED_LAYOUT) snprintf(folder, sizeof folder, "romfs-patches-%s%s", size, suffix);
else snprintf(folder, sizeof folder, "%s-%s%s", prompts_folder, size, suffix);
snprintf(out, sizeof out, "%s/%s", dir, folder);
const char *argv[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--aspect", size,
"--hud", hud, NULL};
if (shape_spawn(argv, dir, folder)) started++;
else failed++;
}
if (prompts_folder && !selected_shape(dir, prompts_folder, w, h, name, sizeof name, 0)) {
const char *style = prompts_folder + strlen("romfs-patches-");
snprintf(reuse, sizeof reuse, "%s/%s/manifest.tsv", dir, prompts_folder);
int can_reuse = plat_file_exists(reuse);
snprintf(reuse, sizeof reuse, "%s/%s", dir, prompts_folder);
snprintf(folder, sizeof folder, "%s-%s%s", prompts_folder, size, suffix);
snprintf(out, sizeof out, "%s/%s", dir, folder);
// The keyboard and mouse prompts are drawn from totk.ini's bind_ lines, as the setup's PcPrompts and Shapes
// steps draw them (installer/steps.py pc_binds); a file without such lines gives the keyboard defaults.
snprintf(binds, sizeof binds, "%s/totk.ini", dir);
int pc = !strcmp(style, "pc") && plat_file_exists(binds);
const char *argv[24] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--prompts", style,
"--aspect", size, "--hud", hud};
int argc = 14;
if (can_reuse) argv[argc++] = "--reuse", argv[argc++] = reuse;
if (pc) argv[argc++] = "--binds", argv[argc++] = binds;
const char *argv[24] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--background"};
int argc = 9;
if (what != ROMFS_NEED_LAYOUT) argv[argc++] = "--prompts", argv[argc++] = style;
if (what != ROMFS_NEED_PROMPTS) {
argv[argc++] = "--aspect", argv[argc++] = size;
argv[argc++] = "--hud", argv[argc++] = hud;
}
// The shaped prompts differ from their 16:9 folder in the UI archive alone, so its fonts are linked, not
// compressed again; a 16:9 folder still being made has nothing to link yet.
if (what == ROMFS_NEED_SHAPED_PROMPTS && !(need & ROMFS_NEED_PROMPTS)) {
snprintf(reuse, sizeof reuse, "%s/%s", dir, prompts_folder);
argv[argc++] = "--reuse", argv[argc++] = reuse;
}
if (pc && what != ROMFS_NEED_LAYOUT) argv[argc++] = "--binds", argv[argc++] = binds;
argv[argc] = NULL;
if (shape_spawn(argv, dir, folder)) started++;
else failed++;
}
rt_log("RomFS overlay: making the layout for %s in the background (%d generators running, %d failed; %s)", size,
started, failed, script);
rt_log("RomFS overlay: making %d missing folder%s for %ux%u%s%s in the background (%d failed to start; %s)",
started + failed, started + failed == 1 ? "" : "s", w, h, style ? ", prompts " : "", style ? style : "",
failed, script);
return started && !failed;
}
+15 -1
View File
@@ -92,9 +92,23 @@ static const char *key_label(int k, char *buf, size_t n) {
return buf;
}
// A gamepad button: the label the open pad has on a face button, else its place on the pad.
// A gamepad button: the label the open pad has on a face button, else its place on the pad. A PlayStation pad (its
// bottom button labelled Cross, DualSense and DualShock 4 alike) has its shoulder, stick and menu buttons named as
// printed on it, the names the PlayStation prompts draw (tools/button_icons.py playstation_icons: Share for Minus).
static const char *pad_label(int p) {
if (p == PAD_NONE) return "";
if (input_pad_label(PAD_SOUTH) == PAD_LABEL_CROSS) {
switch (p) {
case PAD_L: return "L1";
case PAD_R: return "R1";
case PAD_ZL: return "L2";
case PAD_ZR: return "R2";
case PAD_LSTICK: return "L3";
case PAD_RSTICK: return "R3";
case PAD_START: return "Options";
case PAD_BACK: return "Share";
}
}
switch (input_pad_label(p)) {
case PAD_LABEL_A: return "A";
case PAD_LABEL_B: return "B";
+101 -42
View File
@@ -499,6 +499,73 @@ static void row_window_size(void) {
opt_choice_list("TOTK_WINDOW_SIZE", UI_MENU_WINDOW_SIZE, pv, pn, n, UI_MENU_WINDOW_SIZE_DESC);
}
// ---- the folders the next start needs (romfs.c romfs_folders_missing): a game resolution of another shape needs its
// layout's folder, and Xbox, PlayStation or PC prompts their folder, at that shape too. The setup writes them for the
// displays it saw and the prompts totk.ini had then (installer/steps.py Prepare, PcPrompts, Shapes). When the
// resolution, the HUD width, the prompts or the pad layout ask for one it lacks, the generator starts for the next
// start (romfs_folders_prepare: child processes, the menu does not wait), once per request: a request stays the same
// for SETTLE_NS first, so stepping through the sizes starts none for the ones passed. The notes under the resolution
// and the prompts say so (row_output_res, prompts_note); when it could not start they say that and offer a retry. The
// file checks run only when the request changes, after a settings change (cfg_version).
enum { SETTLE_NS = 1500000000 };
static struct {
unsigned seen; // cfg_version of the last look at the settings
char request[160]; // output_res|hud_width|prompts folder in the settings
unsigned w, h;
const char *want; // input_prompts_folder of the settings (a string literal), NULL for the game's own
int missing; // ROMFS_NEED_* for request
uint64_t at; // plat_now_ns from which request starts; 0 none waiting
char asked[160]; // the request started last
int started; // for asked: 1 running, -1 failed to start
} g_folders = {~0u, "", 0, 0, nullptr, 0, 0, "", 0};
static void folders_start(void) {
g_folders.at = 0;
snprintf(g_folders.asked, sizeof g_folders.asked, "%s", g_folders.request);
g_folders.started = romfs_folders_prepare(g_folders.w, g_folders.h, g_folders.want) ? 1 : -1;
}
// On every frame the menu lays out (now: start a waiting request at once, as the menu closes). 1 while a request
// waits.
static int folders_tick(bool now) {
unsigned v = cfg_version();
if (v != g_folders.seen) {
g_folders.seen = v;
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
// Without an output_res the display's shape: the default falls back to 1920x1080 while that shape lacks the
// prompts' folder, and the folders made for it bring the shape back at the next start (cfg_screen_size).
unsigned s[2] = {0, 0};
if (!cfg_screen_size(s) && sscanf(cfg_value("TOTK_OUTPUT_RES"), "%ux%u", &s[0], &s[1]) != 2) s[0] = s[1] = 0;
char request[sizeof g_folders.request];
snprintf(request, sizeof request, "%ux%u|%s|%s", s[0], s[1], cfg_value("TOTK_HUD_WIDTH"), want ? want : "");
if (strcmp(request, g_folders.request)) {
snprintf(g_folders.request, sizeof g_folders.request, "%s", request);
unsigned w = s[0], h = s[1];
g_folders.w = w, g_folders.h = h, g_folders.want = want;
g_folders.missing = w && h ? romfs_folders_missing(w, h, want) : 0;
g_folders.at = g_folders.missing && strcmp(request, g_folders.asked) && romfs_folders_can_prepare()
? plat_now_ns() + SETTLE_NS : 0;
}
}
if (!g_folders.at || (!now && plat_now_ns() < g_folders.at)) return g_folders.at != 0;
folders_start();
return 0;
}
// What happens to the folders of the request in the settings that need (a mask of ROMFS_NEED_*): 0 none missing or
// no tools to make them, 1 being made (or about to start), -1 the generator did not start.
static int folders_state(int need) {
if (!(g_folders.missing & need)) return 0;
if (g_folders.at) return 1;
return g_folders.started && !strcmp(g_folders.asked, g_folders.request) ? g_folders.started : 0;
}
// The retry under a row whose folders did not start.
static void folders_retry(const char *id, int need) {
if (folders_state(need) < 0 && opt_button(id, UI_MENU_PREPARE_RETRY, UI_MENU_PREPARE_RETRY_DESC)) folders_start();
}
// The game resolution (resolution.c): 16:9 sizes from its smallest, 1280x720 (for weak GPUs), up, the common 21:9 and
// 32:9 monitor sizes, the 16:10 screens of the Steam Deck, handhelds and laptops and the 3:2 screens of laptops and
// tablets (Surface, Framework; the camera and the HUD follow
@@ -518,35 +585,18 @@ static void row_output_res(void) {
snprintf(shown[i], sizeof shown[i], "%d × %d", w, h); // U+00D7, the multiplication sign
names[i] = shown[i];
}
// A size of another shape needs that shape's folders (romfs.c overlay_init): the layout, and with Xbox or PC
// prompts the prompts' one too. The setup writes them for the displays it saw (installer/steps.py Shapes); at a
// shape without them the game draws 16:9 with bars or keeps the Switch prompts, so the row says so and offers to
// start the generator for the next start (romfs_shape_prepare; a child process, the menu does not wait). The file
// checks run again only when a setting or the started generation changes.
static unsigned seen = ~0u;
static int missing, started; // started: 0 not asked, 1 running, -1 failed to start
static char asked[128];
char request[128];
const char *now = cfg_value("TOTK_OUTPUT_RES");
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
snprintf(request, sizeof request, "%s|%s|%s", now, cfg_value("TOTK_HUD_WIDTH"), want ? want : "");
if (seen != cfg_version()) {
seen = cfg_version();
unsigned w = 0, h = 0;
missing = sscanf(now, "%ux%u", &w, &h) == 2 && romfs_shape_missing(w, h, want);
}
int here = started && !strcmp(asked, request); // resolution, selected HUD width and button prompts
const char *note = !missing ? nullptr
: here ? menu_text(started > 0 ? UI_MENU_OUTPUT_RES_PREPARING : UI_MENU_SHAPE_PREPARE_FAILED)
: menu_text(UI_MENU_OUTPUT_RES_NO_LAYOUT);
// A size of another shape needs that shape's folders (romfs.c overlay_init): the layout, and with Xbox,
// PlayStation or PC prompts the prompts' one too. Without them the game draws 16:9 with bars or keeps the Switch
// prompts; folders_tick starts their generator, and the row says they are being made, or that the setup's tools
// are missing or did not start.
const int need = ROMFS_NEED_LAYOUT | ROMFS_NEED_SHAPED_PROMPTS;
int state = folders_state(need);
const char *note = !(g_folders.missing & need) ? nullptr
: state > 0 ? menu_text(UI_MENU_OUTPUT_RES_PREPARING)
: state < 0 ? menu_text(UI_MENU_SHAPE_PREPARE_FAILED)
: menu_text(UI_MENU_OUTPUT_RES_NO_LAYOUT);
opt_choice_list("TOTK_OUTPUT_RES", UI_MENU_OUTPUT_RES, vals, names, N, UI_MENU_OUTPUT_RES_DESC, -1, note);
if (!missing || here || !romfs_shape_can_prepare()) return;
if (!opt_button("##shape_prepare", UI_MENU_SHAPE_PREPARE, UI_MENU_SHAPE_PREPARE_DESC)) return;
unsigned w = 0, h = 0;
sscanf(now, "%ux%u", &w, &h);
snprintf(asked, sizeof asked, "%s", request);
started = romfs_shape_prepare(w, h, want) ? 1 : -1;
folders_retry("##shape_prepare", need);
}
// Offer only caps narrower than the canonical layout, using the same tolerance as romfs.c hud_suffix and Shapes.
@@ -896,10 +946,11 @@ static void row_quicksave_keys(void) {
// The note under the prompts. The settings name a folder of prompts (input_prompts_folder: the prompts and the pad
// layout, as a layout that puts A on the right button needs the face buttons named the other way round), but the game
// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: "files
// missing" when the setup did not write the one asked for, why it was left out at start (damaged, a game resolution
// that is not 16:9, a RomFS mod with the same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then
// *restart is set: a restart would bring the prompts asked for. NULL when they match.
// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: when the
// install lacks the one asked for (folders_tick looked), that it is being made in the background, or that it is
// missing (no setup's tools) or could not be made; else why it was left out at start (damaged, a RomFS mod with the
// same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then *restart is set: a restart would
// bring the prompts asked for. NULL when they match.
static const char *prompts_note(bool *restart) {
*restart = false;
const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts();
@@ -907,12 +958,15 @@ static const char *prompts_note(bool *restart) {
if (want == used || (want && used && !strcmp(want, used))) return nullptr;
// A game resolution of another shape needs a folder of its own for the prompts (<folder>-<w>x<h>, one per shape).
// The setup writes it for the shapes of the displays it saw and the prompts totk.ini had then; at another shape
// the shape is the reason (row_output_res offers to make it), not a damaged install.
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) {
// the shape is the reason, not a damaged install.
int need = g_folders.missing & (ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS), state = folders_state(need);
if (state > 0) return menu_text(UI_MENU_PROMPTS_PREPARING);
if (state < 0) return menu_text(UI_MENU_SHAPE_PREPARE_FAILED);
if (need & ROMFS_NEED_PROMPTS) return menu_text(UI_MENU_PROMPTS_MISSING);
if (need) return menu_text(UI_MENU_PROMPTS_OFF_SHAPE);
// ROMFS_PROMPTS_MISSING and _SHAPE: the folder the start lacked is there now, or the resolution needs another one
switch (romfs_prompts_off(want)) {
case ROMFS_PROMPTS_FAILED: return menu_text(UI_MENU_PROMPTS_FAILED);
case ROMFS_PROMPTS_SHAPE: return menu_text(UI_MENU_PROMPTS_OFF_SHAPE);
case ROMFS_PROMPTS_MODS: return menu_text(UI_MENU_PROMPTS_OFF_MODS);
case ROMFS_PROMPTS_PATCHES: return menu_text(UI_MENU_PROMPTS_OFF_PATCHES);
default: *restart = true; return menu_text(UI_MENU_PROMPTS_RESTART);
@@ -989,10 +1043,12 @@ 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, UI_MENU_PROMPTS_PC};
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PLAYSTATION,
UI_MENU_PROMPTS_PC};
bool restart;
const char *note = prompts_note(&restart);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 3, UI_MENU_PROMPTS_DESC, note);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 4, UI_MENU_PROMPTS_DESC, note);
folders_retry("##prompts_prepare", ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS);
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_toggle("TOTK_GYRO_CALIBRATION", UI_MENU_GYRO_CALIBRATION, UI_MENU_GYRO_CALIBRATION_DESC);
@@ -1477,7 +1533,8 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
ImGui::End();
}
static int g_save_pending; // a changed setting still waits for its write to totk.ini (opt_save_tick)
// a changed setting still waits for its write to totk.ini (opt_save_tick) or for its folders to start (folders_tick)
static int g_save_pending;
// ---- the performance overlay (TOTK_PERF_OVERLAY), in the top right corner. "fps": the frame rate over the presents of
// the last half second. "full": a panel of perfmon.c's numbers, in the style of SavageWindRecomp's perf_overlay_draw
@@ -1785,7 +1842,8 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
amiibo_tick();
bool open = g_open.load(std::memory_order_relaxed);
if (!open) {
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now
// closed: the last change goes to totk.ini now, and the folders it needs start being made
if (g_save_pending) g_save_pending = opt_save_tick(1) | folders_tick(true);
if (g_test.at && !g_test.opened && frame >= g_test.at) {
g_test.opened = frame;
g_test.page = 0;
@@ -1842,11 +1900,12 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
}
ImGui_ImplVulkan_NewFrame();
ImGui::NewFrame();
int folders_wait = open ? folders_tick(false) : 0; // before the rows, whose notes it sets
if (open) layout_menu(t->width, t->height, scale);
perf_draw(t, scale);
toast_draw(t, scale);
ImGui::Render();
if (open) g_save_pending = opt_save_tick(0);
if (open) g_save_pending = opt_save_tick(0) | folders_wait;
g_cost_ns += plat_now_ns() - t0;
if (g_test.page >= 0 && frame >= g_test.opened + g_test.per_page * (uint64_t)(g_test.page + 1)) {
static char path[512]; // this frame's image goes to a file; then the next tab, or the menu closes
+42 -28
View File
@@ -70,7 +70,7 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_HUD_WIDTH] = "HUD width",
[UI_MENU_HUD_WIDTH_DESC] = "On a screen wider than 16:9, how far apart the HUD's left and right sides are. Full puts "
"them at the screen's edges; 21:9 or 16:9 keeps the HUD within the middle of the screen "
"of that shape. Prepare a missing layout in this tab or rerun setup, then restart.",
"of that shape. A missing layout is made in the background and used after a restart.",
[UI_MENU_HUD_WIDTH_FULL] = "Full screen",
[UI_MENU_RENDER_SCALE] = "3D render scale",
[UI_MENU_RENDER_SCALE_DESC] = "Size of the 3D scene relative to the game resolution; the game's FSR scales it to "
@@ -296,19 +296,23 @@ 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). 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",
"prompts for A show B). PlayStation: the shapes on a PlayStation pad (○ × △ □, L1, R1, "
"L2, R2, Options and Share), on the button the layout above presses. 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_PLAYSTATION] = "PlayStation", [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",
[UI_MENU_PROMPTS_OFF_SHAPE] = "off at this game resolution (no layout made for it)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "no layout made for this shape: run the setup again",
[UI_MENU_OUTPUT_RES_PREPARING] = "layout being made in the background; used at the next start",
[UI_MENU_SHAPE_PREPARE] = "Prepare the layout for this screen",
[UI_MENU_SHAPE_PREPARE_DESC] = "Makes the interface layout and the chosen button prompts for this game resolution's shape in the background, with the setup's tools, as the setup does for the displays it saw. The game keeps running; it uses them from its next start.",
[UI_MENU_PROMPTS_PREPARING] = "prompt files being made in the background; used at the next start",
[UI_MENU_PREPARE_RETRY] = "Try again",
[UI_MENU_PREPARE_RETRY_DESC] = "Starts the setup's tools again to make the missing interface layout or button prompt files in the background. The game keeps running; it uses them from its next start.",
[UI_MENU_SHAPE_PREPARE_FAILED] = "the setup's tools did not start: run the setup again",
[UI_MENU_PROMPTS_OFF_MODS] = "off: a RomFS mod replaces their files",
[UI_MENU_PROMPTS_OFF_PATCHES] = "off while TOTK_ROMFS_PATCHES is set",
@@ -678,7 +682,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_HUD_WIDTH] = "Ширина интерфейса",
[UI_MENU_HUD_WIDTH_DESC] = "На экране шире 16:9: как далеко друг от друга левая и правая части интерфейса. "
"«Весь экран» ставит их у краёв экрана; 21:9 или 16:9 держит интерфейс в середине "
"экрана такой формы. Подготовьте недостающую раскладку на этой вкладке или повторите установку, затем перезапустите игру.",
"экрана такой формы. Недостающая раскладка создаётся в фоне и будет после перезапуска.",
[UI_MENU_HUD_WIDTH_FULL] = "Весь экран",
[UI_MENU_RENDER_SCALE] = "Масштаб 3D-отрисовки",
[UI_MENU_RENDER_SCALE_DESC] = "Размер 3D-сцены относительно разрешения игры; FSR игры доводит её до этого размера. "
@@ -903,19 +907,23 @@ 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). PC: клавиши и кнопки мыши стандартной раскладки клавиатуры "
"(E, Shift, пробел, левый клик...) и мышь для камеры. Игра читает подсказки при запуске, "
"так что они меняются после перезапуска. Подсказки записаны в файлах игры, поэтому у "
"кнопки, переназначенной на вкладке управления, на экране остаётся прежняя подсказка.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", [UI_MENU_PROMPTS_PC] = "PC",
"подсказки A показывают B). PlayStation: символы геймпада PlayStation (○ × △ □, L1, R1, "
"L2, R2, Options и Share) на кнопке, которую нажимает раскладка выше. PC: клавиши и "
"кнопки мыши стандартной раскладки клавиатуры (E, Shift, пробел, левый клик...) и мышь "
"для камеры. Игра читает подсказки при запуске, так что они меняются после перезапуска. "
"Подсказки записаны в файлах игры, поэтому у кнопки, переназначенной на вкладке "
"управления, на экране остаётся прежняя подсказка.",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox",
[UI_MENU_PROMPTS_PLAYSTATION] = "PlayStation", [UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова",
[UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова",
[UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска",
[UI_MENU_PROMPTS_OFF_SHAPE] = "выкл. при этом разрешении игры (для него нет раскладки)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "для этой формы нет раскладки: запустите установщик снова",
[UI_MENU_OUTPUT_RES_PREPARING] = "раскладка создаётся в фоне; будет при следующем запуске",
[UI_MENU_SHAPE_PREPARE] = "Подготовить раскладку для этого экрана",
[UI_MENU_SHAPE_PREPARE_DESC] = "Создаёт в фоне раскладку интерфейса и выбранные подсказки кнопок для формы этого разрешения игры инструментами установщика, как установщик делает для мониторов, которые видел. Игра продолжает работать; раскладка будет со следующего запуска.",
[UI_MENU_PROMPTS_PREPARING] = "файлы подсказок создаются в фоне; будут при следующем запуске",
[UI_MENU_PREPARE_RETRY] = "Повторить",
[UI_MENU_PREPARE_RETRY_DESC] = "Снова запускает инструменты установщика, чтобы создать в фоне недостающую раскладку интерфейса или файлы подсказок кнопок. Игра продолжает работать; они будут со следующего запуска.",
[UI_MENU_SHAPE_PREPARE_FAILED] = "инструменты установщика не запустились: запустите установщик снова",
[UI_MENU_PROMPTS_OFF_MODS] = "выкл.: мод RomFS заменяет их файлы",
[UI_MENU_PROMPTS_OFF_PATCHES] = "выкл., пока задан TOTK_ROMFS_PATCHES",
@@ -1327,7 +1335,7 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_HUD_WIDTH] = "Largura do HUD",
[UI_MENU_HUD_WIDTH_DESC] = "Em uma tela mais larga que 16:9: a distância entre os lados esquerdo e direito do HUD. "
"Tela cheia os coloca nas bordas da tela; 21:9 ou 16:9 mantém o HUD no meio da tela "
"desse formato. Prepare o layout ausente nesta aba ou execute a instalação novamente e reinicie o jogo.",
"desse formato. Um layout ausente é feito em segundo plano e usado depois de reiniciar o jogo.",
[UI_MENU_HUD_WIDTH_FULL] = "Tela cheia",
[UI_MENU_RENDER_SCALE] = "Escala da renderização 3D",
[UI_MENU_RENDER_SCALE_DESC] = "Tamanho da cena 3D em relação à resolução do jogo; o FSR do jogo a amplia até esse "
@@ -1701,13 +1709,15 @@ 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). 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.",
"letra B, então os ícones de A mostram B). PlayStation: os símbolos de um controle "
"PlayStation (○ × △ □, L1, R1, L2, R2, Options e Share), no botão que o layout acima "
"aperta. 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_PLAYSTATION] = "PlayStation",
[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 (jogos 1.4.3 e 1.2.1; o 1.1.0 usa a emulação do analógico). Emulação do analógico: o mouse age como o analógico direito.",
@@ -1738,8 +1748,9 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_OFF_SHAPE] = "desligados nesta resolução de jogo (sem layout feito para ela)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "sem layout feito para este formato: rode o instalador de novo",
[UI_MENU_OUTPUT_RES_PREPARING] = "layout sendo feito em segundo plano; usado na próxima vez que o jogo abrir",
[UI_MENU_SHAPE_PREPARE] = "Preparar o layout para esta tela",
[UI_MENU_SHAPE_PREPARE_DESC] = "Faz em segundo plano o layout da interface e os botões escolhidos para o formato desta resolução de jogo, com as ferramentas do instalador, como o instalador faz para os monitores que viu. O jogo continua rodando; ele os usa a partir da próxima vez que abrir.",
[UI_MENU_PROMPTS_PREPARING] = "arquivos dos ícones sendo feitos em segundo plano; usados na próxima vez que o jogo abrir",
[UI_MENU_PREPARE_RETRY] = "Tentar de novo",
[UI_MENU_PREPARE_RETRY_DESC] = "Abre de novo as ferramentas do instalador para fazer em segundo plano o layout da interface ou os arquivos dos ícones que faltam. O jogo continua rodando; ele os usa a partir da próxima vez que abrir.",
[UI_MENU_SHAPE_PREPARE_FAILED] = "as ferramentas do instalador não abriram: rode o instalador de novo",
[UI_MENU_PROMPTS_OFF_MODS] = "desligados: um mod de RomFS substitui os arquivos deles",
[UI_MENU_PROMPTS_OFF_PATCHES] = "desligados enquanto TOTK_ROMFS_PATCHES está definido",
@@ -1987,7 +1998,7 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_HUD_WIDTH] = "界面宽度",
[UI_MENU_HUD_WIDTH_DESC] = "在比 16:9 更宽的屏幕上,界面左右两侧相距多远。"
"“整个屏幕”把它们放在屏幕边缘;21:9 或 16:9 则把界面保持在屏幕中间该比例的区域内。"
"请在此选项卡准备缺少的布局,或重新运行安装程序,然后重启游戏。",
"缺少的布局会在后台制作,重启游戏后生效。",
[UI_MENU_HUD_WIDTH_FULL] = "整个屏幕",
[UI_MENU_RENDER_SCALE] = "3D 渲染比例",
[UI_MENU_RENDER_SCALE_DESC] = "3D 场景相对于游戏分辨率的尺寸;"
@@ -2455,10 +2466,12 @@ 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)。PC:键盘默认布局的按键和鼠标按键(E、Shift、空格、左键……),镜头用鼠标。"
"B)。PlayStation:PlayStation 手柄上的符号(○ × △ □、L1、R1、L2、R2、Options 和 Share),"
"显示在上方布局所按下的按键上。PC:键盘默认布局的按键和鼠标按键(E、Shift、空格、左键……),镜头用鼠标。"
"游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。",
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
[UI_MENU_PROMPTS_XBOX] = "Xbox",
[UI_MENU_PROMPTS_PLAYSTATION] = "PlayStation",
[UI_MENU_PROMPTS_PC] = "PC",
[UI_MENU_MOUSE_MODE] = "鼠标视角",
[UI_MENU_MOUSE_MODE_DESC] = "直接:镜头按鼠标移动的距离转动,与电脑游戏相同,没有摇杆死区和响应曲线(游戏 1.4.3 和 1.2.1;1.1.0 使用摇杆模拟)。摇杆模拟:鼠标相当于右摇杆。",
@@ -2489,8 +2502,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_PROMPTS_OFF_SHAPE] = "此游戏分辨率下关闭(未为其制作布局)",
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "未为此比例制作布局:请重新运行安装程序",
[UI_MENU_OUTPUT_RES_PREPARING] = "布局正在后台制作;下次启动时使用",
[UI_MENU_SHAPE_PREPARE] = "为此屏幕准备布局",
[UI_MENU_SHAPE_PREPARE_DESC] = "使用安装程序的工具,在后台为此游戏分辨率的比例制作界面布局和所选按键提示,与安装程序为其检测到的显示器所做的相同。游戏继续运行;下次启动时生效。",
[UI_MENU_PROMPTS_PREPARING] = "按键提示文件正在后台制作;下次启动时使用",
[UI_MENU_PREPARE_RETRY] = "重试",
[UI_MENU_PREPARE_RETRY_DESC] = "再次启动安装程序的工具,在后台制作缺少的界面布局或按键提示文件。游戏继续运行;下次启动时生效。",
[UI_MENU_SHAPE_PREPARE_FAILED] = "安装程序的工具未能启动:请重新运行安装程序",
[UI_MENU_PROMPTS_OFF_MODS] = "已关闭:RomFS 模组替换了它们的文件",
[UI_MENU_PROMPTS_OFF_PATCHES] = "设置了 TOTK_ROMFS_PATCHES 时关闭",
+5 -3
View File
@@ -133,11 +133,13 @@ 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_PC,
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PLAYSTATION,
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_OUTPUT_RES_NO_LAYOUT, UI_MENU_OUTPUT_RES_PREPARING, UI_MENU_SHAPE_PREPARE, UI_MENU_SHAPE_PREPARE_DESC,
UI_MENU_SHAPE_PREPARE_FAILED,
// the missing layout and prompts' folders, which the game makes in the background (ui/menu.cpp folders_tick)
UI_MENU_OUTPUT_RES_NO_LAYOUT, UI_MENU_OUTPUT_RES_PREPARING, UI_MENU_PROMPTS_PREPARING, UI_MENU_SHAPE_PREPARE_FAILED,
UI_MENU_PREPARE_RETRY, UI_MENU_PREPARE_RETRY_DESC,
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
// "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO)
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
+33
View File
@@ -635,6 +635,21 @@ class CleanupTest(unittest.TestCase):
lines = (self.dest / 'build-cache' / 'rebuild.txt').read_text(encoding='utf-8').splitlines()
self.assertEqual(lines[1:3], ['-c', steps.REBUILD_BOOT])
def test_removes_only_stale_part_folders(self):
# make_romfs_patches.py's unfinished folders: an hour-old one is a stopped run's, a fresh one a running one's
old, fresh = self.dest / 'romfs-patches-2560x1080.part-41', self.dest / 'romfs-patches-pc.part-stale-42'
for folder in (old, fresh):
(folder / 'UI').mkdir(parents=True)
(folder / 'UI' / 'a.zs').write_bytes(b'x')
(self.dest / 'romfs-patches-2560x1080').mkdir()
hour = steps.time.time() - steps.PART_STALE_S - 60
for path in (old, old / 'UI', old / 'UI' / 'a.zs'):
steps.os.utime(path, (hour, hour))
self.assertEqual(self.run_cleanup(), 'ok')
self.assertFalse(old.exists())
self.assertTrue(fresh.is_dir() and (self.dest / 'romfs-patches-2560x1080').is_dir())
self.assertIsNone(steps.SHAPED_FOLDER.match(old.name)) # the Shapes step's own clean-up leaves them
def test_emptied_romfs_fails(self):
for p in (self.dest / 'romfs').iterdir():
p.unlink()
@@ -866,6 +881,24 @@ class ShapesTest(unittest.TestCase):
'pad_layout = nintendo\nprompts = xbox',
'pad_layout = xbox_prompts', 'prompts = nintendo')],
[None, 'pc', 'xbox-label', 'xbox', 'xbox', None])
self.assertEqual([screens.prompts_style(t) for t in ('prompts = playstation', 'prompts = PS',
'pad_layout = nintendo\nprompts = playstation',
'pad_layout = xbox\nprompts = playstation')],
['playstation-xbox', 'playstation-xbox', 'playstation', 'playstation-xbox'])
def test_playstation_shapes_replace_every_older_shaped_folder(self):
screens.displays = lambda: [(2560, 1080)]
(self.dest / 'totk.ini').write_text('pad_layout = auto\nprompts = playstation\n')
for old in ('romfs-patches-playstation-1280x800', 'romfs-patches-playstation-xbox-3440x1440-hud21x9',
'romfs-patches-xbox-label-2560x1080', 'romfs-patches-playstation-xbox'):
(self.dest / old).mkdir()
(self.dest / 'romfs-patches-playstation-xbox' / 'manifest.tsv').write_text('#\n')
record = steps.Shapes().run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-playstation-xbox-2560x1080'])
self.assertEqual(sorted(p.name for p in self.dest.iterdir() if p.is_dir()),
['romfs-patches-2560x1080', 'romfs-patches-playstation-xbox',
'romfs-patches-playstation-xbox-2560x1080'])
self.assertEqual(self.calls[-1][self.calls[-1].index('--prompts') + 1], 'playstation-xbox')
def test_wanted_from_displays_and_ini(self):
(self.dest / 'totk.ini').write_text('[display]\noutput_res = 3000x2000\n[input]\nprompts = pc\n')
+160 -6
View File
@@ -12,12 +12,14 @@ import hashlib
import importlib.util
import io
import json
import os
import random
import shutil
import struct
import subprocess
import sys
import tempfile
import time
import unittest
import zlib
from pathlib import Path
@@ -38,7 +40,9 @@ spec.loader.exec_module(icons)
POSITION = {'nintendo': {'A': 'east', 'B': 'south', 'X': 'north', 'Y': 'west'},
'xbox': {'A': 'south', 'B': 'east', 'X': 'west', 'Y': 'north'}}
XBOX_LABEL = {'south': 'A', 'east': 'B', 'west': 'X', 'north': 'Y'}
STYLE_LAYOUT = {'xbox': 'nintendo', 'xbox-label': 'xbox'}
PS_SHAPE = {'nintendo': {'A': '○', 'B': '×', 'X': '△', 'Y': '□'}, # A east, B south, X north, Y west
'xbox': {'A': '×', 'B': '○', 'X': '□', 'Y': '△'}} # A south, B east, X west, Y north
STYLE_LAYOUT = {'xbox': 'nintendo', 'xbox-label': 'xbox', 'playstation': 'nintendo', 'playstation-xbox': 'xbox'}
FACE = {'A': 0xE040, 'B': 0xE041, 'X': 0xE042, 'Y': 0xE043}
# The glyphs drawn as Xbox icons, with their advance: LB RB LT RT, Menu and View, the d-pad.
DRAWN = {0xE044: 820, 0xE045: 820, 0xE046: 760, 0xE047: 760, 0xE04B: 640, 0xE04C: 640, 0xE049: 640,
@@ -359,6 +363,9 @@ LETTERS_2 = {ord('T'): (560, polygon((230, 0), (330, 0), (330, 600), (520, 600),
# 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('ACDEFGHIMQSW1234')})
# The PlayStation shapes the diamond needs in the text font (make_romfs_patches.py --prompts playstation checks them).
LETTERS_2.update({cp: (560, lambda pen, i=i: rect(pen, 60, 0, 300 + 10 * i, 700))
for i, cp in enumerate((0x25CB, 0x00D7, 0x25B3, 0x25A1))})
PC_PANES = {'A': 'E', 'B': '↑', 'X': '▬', 'Y': 'L'} # the diamond's letters with the default keys
@@ -453,7 +460,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', 'pc'):
for style in ('plain', 'xbox', 'xbox-label', 'playstation', 'playstation-xbox', 'pc'):
out = cls.base / v / style
proc = romfs.run(out, *(() if style == 'plain' else ('--prompts', style)))
assert proc.returncode == 0, proc.stderr
@@ -504,7 +511,8 @@ class PromptsTest(unittest.TestCase):
self.assertEqual(sarc_files(romfs.read(out, path))['LayoutMsg/Other_00.msbt'], msbt({'T_A_00': 'A'}))
def test_xbox_label_diamond_moves_letters_bars_and_hold_flashes(self):
for romfs, _, out, _ in self.each(('xbox-label',)):
# playstation-xbox plays the face buttons where an Xbox pad has them, so its diamond moves the same way
for romfs, _, out, _ in self.each(('xbox-label', 'playstation-xbox')):
before = sarc_files(romfs.contents[romfs.common])['blyt/DoCommand_00.bflyt']
after = sarc_files(romfs.read(out, romfs.common))['blyt/DoCommand_00.bflyt']
old, new = pane_positions(before), pane_positions(after)
@@ -517,6 +525,12 @@ class PromptsTest(unittest.TestCase):
self.assertEqual(new['N_LoopA_03'], tuple(a + b - c for a, b, c in
zip(old['N_LoopA_03'], old['P_CaptureB_01'], old['P_CaptureA_01'])))
def test_nintendo_layout_diamonds_keep_the_switch_positions(self):
for romfs, _, out, _ in self.each(('xbox', 'playstation')):
before = sarc_files(romfs.contents[romfs.common])['blyt/DoCommand_00.bflyt']
after = sarc_files(romfs.read(out, romfs.common))['blyt/DoCommand_00.bflyt']
self.assertEqual(pane_positions(after), pane_positions(before))
def test_other_buttons_are_drawn_as_xbox_icons(self):
for romfs, style, out, _ in self.each():
with self.subTest(version=romfs.version, style=style):
@@ -563,8 +577,97 @@ class PromptsTest(unittest.TestCase):
if member not in ('timg/__Combined.bntx', 'blyt/DoCommand_00.bflyt') and not member.startswith('anim/'):
self.assertEqual(after[member], before[member], member)
def test_face_buttons_are_playstation_shapes(self):
for romfs, style, out, _ in self.each(('playstation', 'playstation-xbox')):
with self.subTest(version=romfs.version, style=style):
layout = STYLE_LAYOUT[style]
shape = PS_SHAPE[layout]
advances = icons.font_advances(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
ps = icons.playstation_icons(icons.text_glyphs(romfs.text_fonts), advances, layout)
before, after = sarc_files(romfs.contents[romfs.common]), sarc_files(romfs.read(out, romfs.common))
old, new = bntx_images(before['timg/__Combined.bntx']), bntx_images(after['timg/__Combined.bntx'])
panes = pane_texts(after['blyt/DoCommand_00.bflyt'])
messages = {path: message_texts(sarc_files(romfs.read(out, path))['LayoutMsg/DoCommand_00.msbt'])
for path in romfs.mals}
original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
for path in (DEFAULT_FONT, REGIONAL_FONT):
drawn = font(sarc_files(romfs.read(out, path))['scft/External.bfotf'])
for b, cp in FACE.items():
outline, advance = glyph(drawn, cp)
self.assertNotEqual(outline, glyph(original, cp)[0], f'{path}: glyph of {b}')
self.assertEqual(advance, advances[cp], f'{path}: advance of {b}')
size = VERSIONS[romfs.version]['size']
for b in FACE:
fmt, width, image = new[f'Nt_KeyTex{b}_00']
self.assertEqual((fmt, width, len(image)), (R8_UNORM, size, len(old[f'Nt_KeyTex{b}_00'][2])),
f'action prompt image of {b}')
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(ps[FACE[b]][1], size), f'action prompt image of {b}')
self.assertEqual(panes[f'T_{b}_00'], shape[b], f'diamond letter of {b}')
for path, texts in messages.items():
self.assertEqual(texts[f'T_{b}_00'], shape[b], f'{path}: diamond message of {b}')
# Text that only looks like a letter pane, and every other message, stays.
self.assertEqual((panes['T_Name_00'], pane_texts(after['blyt/Title_00.bflyt'])), ('A', {'N_Title_00': 'Z'}))
for path, texts in messages.items():
self.assertEqual((texts['T_Name_00'], texts['Greeting']), ('A', 'Hello'))
self.assertEqual(sarc_files(romfs.read(out, path))['LayoutMsg/Other_00.msbt'], msbt({'T_A_00': 'A'}))
def test_other_buttons_are_drawn_as_playstation_icons(self):
for romfs, style, out, _ in self.each(('playstation', 'playstation-xbox')):
with self.subTest(version=romfs.version, style=style):
layout = STYLE_LAYOUT[style]
advances = icons.font_advances(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
ps = icons.playstation_icons(icons.text_glyphs(romfs.text_fonts), advances, layout)
original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
default = sarc_files(romfs.read(out, DEFAULT_FONT))
drawn = font(default['scft/External.bfotf'])
for cp in range(0xE040, 0xE069):
outline, advance = glyph(drawn, cp)
if cp in ps:
rec = RecordingPen()
ps[cp][1](rec)
self.assertNotEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} drawn')
self.assertEqual(advance, advances[cp], f'U+{cp:04X} advance')
self.assertEqual(sum(op == 'moveTo' for op, _ in outline),
sum(op == 'moveTo' for op, _ in rec.value), f'U+{cp:04X} contours')
elif cp not in FACE.values():
self.assertEqual((outline, advance), glyph(original, cp), f'U+{cp:04X} kept')
# A circle, square and triangle are outlines with a counter; the cross is a filled X.
moves = sorted(sum(op == 'moveTo' for op, _ in glyph(drawn, cp)[0]) for cp in FACE.values())
self.assertEqual(moves, [1, 2, 2, 2])
# The text fonts and the archives' other members stay byte for byte; both archives hold the same font.
before = sarc_files(romfs.contents[DEFAULT_FONT])
self.assertEqual({k: v for k, v in default.items() if k != 'scft/External.bfotf'},
{k: v for k, v in before.items() if k != 'scft/External.bfotf'})
regional = sarc_files(romfs.read(out, REGIONAL_FONT))
self.assertEqual(regional['fnt/rest.bin'], sarc_files(romfs.contents[REGIONAL_FONT])['fnt/rest.bin'])
self.assertEqual(unbfotf(regional['scft/External.bfotf']), unbfotf(default['scft/External.bfotf']))
self.assertEqual(struct.unpack_from('<I', regional['scft/External.bfotf'])[0] ^ MAGIC, 0x77777777)
def test_playstation_button_guide_images_show_the_same_icons(self):
for romfs, style, out, _ in self.each(('playstation', 'playstation-xbox')):
with self.subTest(version=romfs.version, style=style):
size = VERSIONS[romfs.version]['size']
layout = STYLE_LAYOUT[style]
advances = icons.font_advances(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf'])
ps = icons.playstation_icons(icons.text_glyphs(romfs.text_fonts), advances, layout)
before = sarc_files(romfs.contents[romfs.common])
after = sarc_files(romfs.read(out, romfs.common))
self.assertEqual(len(after['timg/__Combined.bntx']), len(before['timg/__Combined.bntx']))
old, new = bntx_images(before['timg/__Combined.bntx']), bntx_images(after['timg/__Combined.bntx'])
for name, cp in icons.PS_HUD_TEXTURES.items():
fmt, width, image = new[name]
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(ps[cp][1], size), name)
self.assertEqual({pixels[0], pixels[-1], max(pixels)}, {0, 255}, name) # a margin around a white key
self.assertEqual(new['Nt_KeyTexLSt_00'], old['Nt_KeyTexLSt_00'])
for member in before: # the 60 fps patch and the prompts touch only these
if member not in ('timg/__Combined.bntx', 'blyt/DoCommand_00.bflyt') and not member.startswith('anim/'):
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(('xbox', 'xbox-label', 'pc')):
for romfs, style, out, summary in self.each(('xbox', 'xbox-label', 'playstation', 'playstation-xbox', 'pc')):
with self.subTest(version=romfs.version, style=style):
table = restbl_sizes(romfs.read(out, romfs.restbl))
original = restbl_sizes(romfs.contents[romfs.restbl])
@@ -580,12 +683,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', 'pc')):
for romfs, style, out, _ in self.each(('plain', 'xbox', 'xbox-label', 'playstation', 'playstation-xbox', 'pc')):
with self.subTest(version=romfs.version, style=style):
expect = {romfs.common}
if style != 'plain':
expect |= {DEFAULT_FONT, REGIONAL_FONT, romfs.restbl}
expect |= set(romfs.mals) if style in ('xbox', 'pc') else set()
expect |= set(romfs.mals) if style in ('xbox', 'playstation', 'playstation-xbox', 'pc') else set()
lines = manifest(out)
self.assertEqual(set(lines), expect)
for path, (size, sha, original) in lines.items():
@@ -688,6 +791,56 @@ class PromptsTest(unittest.TestCase):
self.assertNotEqual((source / 'manifest.tsv').read_bytes(), (pc / 'manifest.tsv').read_bytes())
self.assertEqual({p: (self.base / 'reuse' / 'pc' / p).read_bytes() for p in manifest(pc)}, before)
def test_output_appears_whole_and_a_second_writer_keeps_it(self):
# The game starts --background runs for a folder it lacks (runtime/romfs.c romfs_folders_prepare): the menu and
# the start, or a restart while the last run goes on, can start two for one folder. Each writes its own
# <out>.part-<pid>; the first to finish renames it into place, the other drops its own.
romfs = self.romfs['v121']
want = (self.outs['v121', 'xbox'][0] / 'manifest.tsv').read_bytes()
base = self.base / 'publish'
out = base / 'romfs-patches-xbox'
base.mkdir()
command = [sys.executable, '-I', str(TOOL), '--version', 'v121', '--romfs', str(romfs.folder), '--out', str(out),
'--prompts', 'xbox', '--background']
runs = [subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for _ in range(2)]
results = [(p.returncode, *out) for p in runs for out in [p.communicate()]]
for code, _, err in results:
self.assertEqual(code, 0, err)
summaries = [json.loads(o.strip().splitlines()[-1]) for _, o, _ in results]
self.assertEqual(sum('kept' not in s for s in summaries), 1, summaries)
self.assertEqual((out / 'manifest.tsv').read_bytes(), want)
self.assertEqual(sorted(p.name for p in base.iterdir()), ['romfs-patches-xbox'])
# Once it is there a --background run leaves it as it is (a running game checks its files on every open)
stamp = (out / 'manifest.tsv').stat().st_mtime_ns
proc = romfs.run(out, '--prompts', 'xbox', '--background')
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertEqual(json.loads(proc.stdout.strip().splitlines()[-1]), {'status': 'pass', 'kept': str(out)})
self.assertEqual((out / 'manifest.tsv').stat().st_mtime_ns, stamp)
# An unfinished folder without a manifest (an older generator's) is replaced; a stopped run's .part folder an
# hour old goes, a younger one (a run going on) stays
shutil.rmtree(out)
(out / 'UI').mkdir(parents=True)
(out / 'UI' / 'half.zs').write_bytes(b'half')
stale, young = base / 'romfs-patches-xbox.part-1', base / 'romfs-patches-xbox.part-2'
for folder in (stale, young):
folder.mkdir()
(folder / 'x').write_bytes(b'x')
hour = time.time() - 3700
for path in (stale / 'x', stale):
os.utime(path, (hour, hour))
proc = romfs.run(out, '--prompts', 'xbox', '--background')
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertNotIn('kept', json.loads(proc.stdout.strip().splitlines()[-1]))
self.assertEqual((out / 'manifest.tsv').read_bytes(), want)
self.assertFalse((out / 'UI' / 'half.zs').exists())
self.assertEqual(sorted(p.name for p in base.iterdir()), ['romfs-patches-xbox', young.name])
# Without --background (the setup, a source build) the folder is replaced whole: no file of the old one stays
(out / 'extra.zs').write_bytes(b'old')
proc = romfs.run(out, '--prompts', 'xbox')
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertEqual((out / 'manifest.tsv').read_bytes(), want)
self.assertFalse((out / 'extra.zs').exists())
def test_unrecognised_romfs_fails_before_writing(self):
cases = {'no text fonts': (dict(text_fonts=False), icons.TEXT_FONTS[0]),
'no size entry': (dict(restbl_skips=(REGIONAL_FONT,)), 'has no entry in the resource size table'),
@@ -700,6 +853,7 @@ class PromptsTest(unittest.TestCase):
self.assertNotEqual(proc.returncode, 0)
self.assertIn(message, proc.stderr)
self.assertFalse(out.exists(), 'a failed run writes nothing')
self.assertEqual([p.name for p in out.parent.iterdir()], ['romfs'], 'and leaves no .part folder')
if __name__ == '__main__':
+57 -20
View File
@@ -20,6 +20,7 @@ HARNESS = r'''
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "fs.h"
#include "host.h"
#include "platform/platform.h"
#include "shape_functions.h"
@@ -50,10 +51,16 @@ uint8_t *plat_file_read(const char *p,uint64_t *size) {
uint8_t *b=calloc(1,*size+1); assert(b); assert(fread(b,1,*size,f)==*size); fclose(f); return b;
}
int plat_exe_path(char *out,size_t cap) { (void)out;(void)cap;abort(); }
static int locked;
void plat_mutex_lock(PlatMutex *m) { (void)m; assert(!locked); locked=1; }
void plat_mutex_unlock(PlatMutex *m) { (void)m; assert(locked); locked=0; }
void rt_fatal(const char *fmt,...) { (void)fmt;abort(); }
void rt_log(const char *fmt,...) { (void)fmt; }
static int spawn_fails;
int plat_spawn(const char *const *args,const char *cwd) {
assert(cwd && *cwd); spawns++;
assert(cwd && *cwd && locked);
if (spawn_fails) return 0;
spawns++;
int i; for (i=0;args[i];i++) { assert(i<23); snprintf(args_test[i],sizeof args_test[i],"%s",args[i]); }
args_test[i][0]=0; return 1;
}
@@ -61,6 +68,10 @@ static const char *arg(const char *key) {
for (int i=0;args_test[i][0];i++) if (!strcmp(args_test[i],key)) return args_test[i+1];
return NULL;
}
static int has(const char *flag) {
for (int i=0;args_test[i][0];i++) if (!strcmp(args_test[i],flag)) return 1;
return 0;
}
static void output_ends(const char *suffix) {
const char *p=arg("--out"); assert(p && strlen(p)>=strlen(suffix));
assert(!strcmp(p+strlen(p)-strlen(suffix),suffix));
@@ -77,28 +88,51 @@ int main(int argc,char **argv) {
assert(selected_shape(base,"romfs-patches",5120,1440,name,sizeof name,1));
assert(!strcmp(name,"romfs-patches-3840x1080"));
assert(!selected_shape(base,"romfs-patches",5120,1440,name,sizeof name,0));
assert(romfs_shape_missing(5120,1440,NULL));
override_test="0"; assert(!romfs_shape_missing(5120,1440,NULL)); override_test=NULL;
assert(!romfs_shape_missing(1920,1080,NULL));
assert(romfs_folders_missing(5120,1440,NULL)==ROMFS_NEED_LAYOUT);
override_test="0"; assert(!romfs_folders_missing(5120,1440,NULL)); override_test=NULL;
assert(!romfs_folders_missing(1920,1080,NULL));
assert(romfs_folders_missing(1920,1080,"romfs-patches-pc")==ROMFS_NEED_PROMPTS);
snprintf(index_test,sizeof index_test,"%s/generation/romfs-index.bin",argv[1]);
hud_test="16:9";
assert(romfs_shape_prepare(5120,2160,"romfs-patches-pc")); assert(spawns==2);
// Nothing missing: no generator, no log line
assert(!romfs_folders_prepare(1920,1080,"romfs-patches-xbox")); assert(spawns==0);
assert(romfs_folders_prepare(5120,2160,"romfs-patches-pc")); assert(spawns==2);
assert(has("--background"));
assert(!strcmp(arg("--aspect"),"2560x1080")); assert(!strcmp(arg("--hud"),"16:9"));
assert(!strcmp(arg("--version"),"v143")); assert(!strcmp(arg("--prompts"),"pc"));
assert(arg("--reuse") && strstr(arg("--reuse"),"/romfs-patches-pc"));
assert(arg("--binds") && strstr(arg("--binds"),"/totk.ini")); assert(!args_test[18][0]); output_ends("romfs-patches-pc-2560x1080-hud16x9");
assert(romfs_shape_prepare(5120,2160,"romfs-patches-pc")); assert(spawns==2);
assert(arg("--binds") && strstr(arg("--binds"),"/totk.ini")); assert(!args_test[19][0]); output_ends("romfs-patches-pc-2560x1080-hud16x9");
assert(romfs_folders_prepare(5120,2160,"romfs-patches-pc")); assert(spawns==2);
hud_test="full";
assert(romfs_shape_prepare(5120,2160,"romfs-patches-xbox")); assert(spawns==4);
assert(romfs_folders_prepare(5120,2160,"romfs-patches-xbox")); assert(spawns==4);
assert(!strcmp(arg("--hud"),"full")); assert(!strcmp(arg("--prompts"),"xbox"));
assert(arg("--reuse") && !arg("--binds")); output_ends("romfs-patches-xbox-2560x1080");
hud_test="21:9";
assert(romfs_shape_prepare(5120,1440,"romfs-patches-xbox-label")); assert(spawns==6);
// The 16:9 xbox-label folder is missing too: it is made first (no --aspect), and the shaped one cannot link it
assert(romfs_folders_prepare(5120,1440,"romfs-patches-xbox-label")); assert(spawns==7);
assert(!strcmp(arg("--hud"),"21:9")); assert(!strcmp(arg("--prompts"),"xbox-label"));
assert(!arg("--reuse") && !arg("--binds")); output_ends("romfs-patches-xbox-label-3840x1080-hud21x9");
// A cap wider than a tall canvas becomes full, never an invalid generator request.
assert(romfs_shape_prepare(1280,800,NULL)); assert(spawns==7);
assert(romfs_folders_prepare(1280,800,NULL)); assert(spawns==8);
assert(!strcmp(arg("--hud"),"full")); output_ends("romfs-patches-1280x800");
// Missing 16:9 prompts at 16:9: only that folder, without --aspect or --hud; pc takes totk.ini's binds
hud_test="16:9";
snprintf(index_test,sizeof index_test,"%s/sixteen/romfs-index.bin",argv[1]);
assert(romfs_folders_prepare(1920,1080,"romfs-patches-pc")); assert(spawns==9);
assert(!strcmp(arg("--prompts"),"pc") && !arg("--aspect") && !arg("--hud") && !arg("--reuse"));
assert(arg("--binds") && has("--background")); output_ends("/romfs-patches-pc");
assert(romfs_folders_prepare(1920,1080,"romfs-patches-pc")); assert(spawns==9); // once per process
assert(romfs_folders_prepare(2560,1440,"romfs-patches-playstation")); assert(spawns==10);
assert(!strcmp(arg("--prompts"),"playstation") && !arg("--binds")); output_ends("/romfs-patches-playstation");
// A generator that does not start is not remembered: the menu's retry starts it
spawn_fails=1;
assert(!romfs_folders_prepare(1920,1080,"romfs-patches-xbox")); assert(spawns==10);
spawn_fails=0;
assert(romfs_folders_prepare(1920,1080,"romfs-patches-xbox")); assert(spawns==11);
// Without the setup's tools nothing starts
snprintf(index_test,sizeof index_test,"%s/selection/romfs-index.bin",argv[1]);
assert(!romfs_folders_can_prepare() && !romfs_folders_prepare(1920,1080,"romfs-patches-xbox-label"));
assert(spawns==11);
// Beyond the old eight-folder limit every new folder must still be remembered.
const char *dummy[]={"python","script",NULL};
for (int i=0;i<12;i++) {
@@ -120,9 +154,10 @@ def production_functions():
source = (ROOT / 'runtime/romfs.c').read_text()
names = ('need', 'hud_suffix', 'shaped_name', 'selected_shape', 'index_path', 'index_folder',
'shaped_folder_ready', 'romfs_shaped_ready', 'romfs_shaped_prompts_ready', 'prepare_tools',
'romfs_shape_missing', 'shape_was_started', 'shape_spawn', 'romfs_shape_prepare')
state = re.findall(r'(?m)^static [^;\n]*\bshape_started[^;\n]*;', source)
assert len(state) == 2, 'update harness extraction for changed generation cache declarations'
'plain_folder_ready', 'romfs_folders_missing', 'romfs_folders_can_prepare', 'shape_was_started',
'shape_spawn', 'romfs_folders_prepare')
state = re.findall(r'(?m)^static [^;\n]*\bshape_(?:started|lock)[^;\n]*;', source)
assert len(state) == 3, 'update harness extraction for changed generation cache declarations'
functions = []
for name in names:
match = re.search(r'(?m)^[^\n;{}]*\b' + name + r'\([^;{}]*?\)\s*\{', source)
@@ -153,13 +188,15 @@ def main():
manifest.parent.mkdir(parents=True, exist_ok=True)
manifest.write_text('# synthetic\n')
generation = folder / 'generation'
for name in ('build-cache', 'romfs', 'tools', 'romfs-patches-pc', 'romfs-patches-xbox'):
(generation / name).mkdir(parents=True, exist_ok=True)
for name in ('romfs/romfs.bin', 'tools/make_romfs_patches.py', 'fake-python', 'totk.ini',
'romfs-patches-pc/manifest.tsv', 'romfs-patches-xbox/manifest.tsv'):
(generation / name).write_text('# synthetic\n')
(generation / 'build-cache/rebuild.txt').write_text(
f'{(generation / "fake-python").as_posix()}\n-c\nunused\n{generation.as_posix()}\n')
for install, prompts in ((folder / 'generation', ('romfs-patches-pc', 'romfs-patches-xbox')),
(folder / 'sixteen', ())): # an older setup's install without the prompts' folders
for name in ('build-cache', 'romfs', 'tools', *prompts):
(install / name).mkdir(parents=True, exist_ok=True)
for name in ('romfs/romfs.bin', 'tools/make_romfs_patches.py', 'fake-python', 'totk.ini',
*(f'{p}/manifest.tsv' for p in prompts)):
(install / name).write_text('# synthetic\n')
(install / 'build-cache/rebuild.txt').write_text(
f'{(install / "fake-python").as_posix()}\n-c\nunused\n{install.as_posix()}\n')
(folder / 'shape_functions.h').write_text(production_functions())
source = folder / 'harness.c'
source.write_text(HARNESS)
+4 -2
View File
@@ -314,8 +314,10 @@ def copy_romfs_patches(version, out):
manifest, the same way when it differs: romfs-patches, 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) and
the ones of another shape, romfs-patches-<w>x<h> and romfs-patches-<style>-<w>x<h> (make_romfs_patches.py
--aspect), which runtime/romfs.c overlay_init needs for a game resolution that is not 16:9."""
names = sorted(p.name for p in (ROOT / 'build' / version).glob('romfs-patches*') if p.is_dir())
--aspect), which runtime/romfs.c overlay_init needs for a game resolution that is not 16:9. The <name>.part-<pid>
folders a make_romfs_patches.py run writes before it renames them into place are no overlay and stay behind."""
names = sorted(p.name for p in (ROOT / 'build' / version).glob('romfs-patches*')
if p.is_dir() and '.part-' not in p.name)
for name in names:
src = ROOT / 'build' / version / name
dst = out / name
+132 -52
View File
@@ -1,6 +1,6 @@
# Adapted from MacNativeGames games/totk/scripts/make_button_icons.py @ 933b6a0 (MIT, Copyright (c) 2026
# MacNativeGames contributors).
"""Xbox and keyboard-and-mouse button icons for the game's prompts, drawn on the player's machine for
"""Xbox, PlayStation 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.
@@ -10,17 +10,18 @@ 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), 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).
cross), the face buttons as the PlayStation shapes (○ × △ □) with L1 R1 L2 R2, Options and Share, 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 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) with the keys of pc_binds. The font's glyphs use pc_binds(text=True): a text prompt shows
Y as T, the button guide the left mouse button. Prompts drawn as fixed images (some tutorial animations) keep the
Switch icons.
the size unchanged. The Xbox prompts redraw L and ZL, the PlayStation prompts the face buttons and L and ZL, the
keyboard and mouse ones every image (PC_HUD_TEXTURES: A, B, X, Y, L, ZL and the stick's two) with the keys of
pc_binds. The font's glyphs use pc_binds(text=True): a text prompt shows Y as T, the button guide the left mouse button.
Prompts drawn as fixed images (some tutorial animations) keep the Switch icons.
Needs fontTools (tools/requirements-installer.txt, tools/requirements-py314.txt).
"""
@@ -134,57 +135,136 @@ def polygon(pen, points):
pen.closePath()
def bumper(g, label, advance=820):
"""A shoulder button: a rounded key with its label cut out."""
def draw(pen):
rounded(pen, 40, Y0 + 70, advance - 40, Y1 - 70, 70, 150); g.hole(pen, label, advance / 2, CY, 230, advance - 200)
return advance, draw
def trigger(g, label, advance=760):
"""A trigger: a taller key with its label cut out."""
def draw(pen):
rounded(pen, 60, Y0, advance - 60, Y1, 60, 230); g.hole(pen, label, advance / 2, CY - 20, 230, advance - 220)
return advance, draw
def menu_key(advance=640): # three bars, as on the Menu button
def draw(pen):
circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen)
for dy in (-115, 0, 115):
rounded(reverse, advance / 2 - 150, CY + dy - 38, advance / 2 + 150, CY + dy + 38, 38)
return advance, draw
def view_key(advance=640): # two overlapping windows, as on the View button
def draw(pen):
circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen); s = 150
rounded(reverse, advance / 2 - s - 15, CY + 15, advance / 2 - 15, CY + s + 15, 16)
rounded(reverse, advance / 2 + 15, CY - s - 15, advance / 2 + s + 15, CY - 15, 16)
return advance, draw
def dpad_key(*lit, advance=640): # a cross with an arrow cut into each direction the prompt means
def draw(pen):
cx, length, arm = advance / 2, R, R * 0.40
polygon(pen, [(cx + length, CY - arm), (cx + length, CY + arm), (cx + arm, CY + arm), (cx + arm, CY + length),
(cx - arm, CY + length), (cx - arm, CY + arm), (cx - length, CY + arm), (cx - length, CY - arm),
(cx - arm, CY - arm), (cx - arm, CY - length), (cx + arm, CY - length), (cx + arm, CY - arm)])
m, t, h = (length + arm) / 2, arm * 0.72, arm * 0.80 # arm centre, half base and height of the arrow
heads = {'up': [(cx - t, CY + m - h / 2), (cx, CY + m + h / 2), (cx + t, CY + m - h / 2)],
'down': [(cx + t, CY - m + h / 2), (cx, CY - m - h / 2), (cx - t, CY - m + h / 2)],
'left': [(cx - m + h / 2, CY - t), (cx - m - h / 2, CY), (cx - m + h / 2, CY + t)],
'right': [(cx + m - h / 2, CY + t), (cx + m + h / 2, CY), (cx + m - h / 2, CY - t)]}
for d in lit:
polygon(pen, heads[d]) # already clockwise: a hole
return advance, draw
def xbox_icons(g):
"""Code point -> (advance, draw(pen)) for the buttons an Xbox controller names differently from a Switch: L R = LB
RB, ZL ZR = LT RT, Plus and Minus = Menu and View, the d-pad as a cross. g: Glyphs for the letters. The face
buttons keep the game's own glyphs (redraw_font swaps them for the Nintendo layout)."""
def bumper(label, advance=820):
def draw(pen):
rounded(pen, 40, Y0 + 70, advance - 40, Y1 - 70, 70, 150); g.hole(pen, label, advance / 2, CY, 230, advance - 200)
return advance, draw
def trigger(label, advance=760):
def draw(pen):
rounded(pen, 60, Y0, advance - 60, Y1, 60, 230); g.hole(pen, label, advance / 2, CY - 20, 230, advance - 220)
return advance, draw
def menu(advance=640): # three bars, as on the Menu button
def draw(pen):
circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen)
for dy in (-115, 0, 115):
rounded(reverse, advance / 2 - 150, CY + dy - 38, advance / 2 + 150, CY + dy + 38, 38)
return advance, draw
def view(advance=640): # two overlapping windows, as on the View button
def draw(pen):
circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen); s = 150
rounded(reverse, advance / 2 - s - 15, CY + 15, advance / 2 - 15, CY + s + 15, 16)
rounded(reverse, advance / 2 + 15, CY - s - 15, advance / 2 + s + 15, CY - 15, 16)
return advance, draw
def dpad(*lit, advance=640): # a cross with an arrow cut into each direction the prompt means
def draw(pen):
cx, length, arm = advance / 2, R, R * 0.40
polygon(pen, [(cx + length, CY - arm), (cx + length, CY + arm), (cx + arm, CY + arm), (cx + arm, CY + length),
(cx - arm, CY + length), (cx - arm, CY + arm), (cx - length, CY + arm), (cx - length, CY - arm),
(cx - arm, CY - arm), (cx - arm, CY - length), (cx + arm, CY - length), (cx + arm, CY - arm)])
m, t, h = (length + arm) / 2, arm * 0.72, arm * 0.80 # arm centre, half base and height of the arrow
heads = {'up': [(cx - t, CY + m - h / 2), (cx, CY + m + h / 2), (cx + t, CY + m - h / 2)],
'down': [(cx + t, CY - m + h / 2), (cx, CY - m - h / 2), (cx - t, CY - m + h / 2)],
'left': [(cx - m + h / 2, CY - t), (cx - m - h / 2, CY), (cx - m + h / 2, CY + t)],
'right': [(cx + m - h / 2, CY + t), (cx + m + h / 2, CY), (cx + m - h / 2, CY - t)]}
for d in lit:
polygon(pen, heads[d]) # already clockwise: a hole
return advance, draw
return {
0xE044: bumper('LB'), 0xE045: bumper('RB'), 0xE046: trigger('LT'), 0xE047: trigger('RT'),
0xE04B: menu(), 0xE04C: view(),
0xE049: dpad('up', 'down', 'left', 'right'), 0xE060: dpad('up'), 0xE061: dpad('down'),
0xE062: dpad('left'), 0xE063: dpad('right'), 0xE064: dpad('up', 'down'), 0xE065: dpad('left', 'right'),
0xE044: bumper(g, 'LB'), 0xE045: bumper(g, 'RB'), 0xE046: trigger(g, 'LT'), 0xE047: trigger(g, 'RT'),
0xE04B: menu_key(), 0xE04C: view_key(),
0xE049: dpad_key('up', 'down', 'left', 'right'), 0xE060: dpad_key('up'), 0xE061: dpad_key('down'),
0xE062: dpad_key('left'), 0xE063: dpad_key('right'), 0xE064: dpad_key('up', 'down'),
0xE065: dpad_key('left', 'right'),
}
# ---- PlayStation prompts (--prompts playstation, playstation-xbox): the shapes on a PlayStation pad, in the same
# filled-shape style. The game's text fonts have ○ U+25CB, × U+00D7, △ U+25B3 and □ U+25A1, so the diamond's letters
# become those characters (make_romfs_patches.py pane_letters). The face buttons are the shapes; the shoulders and
# triggers carry L1/R1/L2/R2; Plus and Minus show Options (three bars) and Share (a box with an arrow).
PS_FACE = {
'nintendo': {'A': '○', 'B': '×', 'X': '△', 'Y': '□'}, # A east, B south, X north, Y west
'xbox': {'A': '×', 'B': '○', 'X': '□', 'Y': '△'}, # A south, B east, X west, Y north
}
PS_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}
def ps_shape(shape, advance):
"""The filled outline of a PlayStation face button (○ × △ □) in the font's 1000-unit em, centred on the glyph's
advance. The ring, square and triangle are outlines about a tenth of their size wide, as on the controller; the
cross is a thick X."""
cx, cy = advance / 2, CY
if shape == '○':
def draw(pen):
circle(pen, cx, cy, R)
circle(ReverseContourPen(pen), cx, cy, R * 0.81)
elif shape == '×':
def draw(pen):
l, w = 270.0, 55.0
polygon(pen, [(cx - l, cy - l + w), (cx - l + w, cy - l), (cx, cy - w), (cx + l - w, cy - l),
(cx + l, cy - l + w), (cx + w, cy), (cx + l, cy + l - w), (cx + l - w, cy + l),
(cx, cy + w), (cx - l + w, cy + l), (cx - l, cy + l - w), (cx - w, cy)])
elif shape == '△':
def draw(pen):
polygon(pen, [(cx - 280, cy - 270), (cx + 280, cy - 270), (cx, cy + 270)])
polygon(ReverseContourPen(pen), [(cx - 215, cy - 205), (cx + 215, cy - 205), (cx, cy + 205)])
elif shape == '□':
def draw(pen):
polygon(pen, [(cx - 270, cy - 270), (cx + 270, cy - 270), (cx + 270, cy + 270), (cx - 270, cy + 270)])
polygon(ReverseContourPen(pen), [(cx - 216, cy - 216), (cx + 216, cy - 216), (cx + 216, cy + 216),
(cx - 216, cy + 216)])
else:
raise ValueError(f'no PlayStation shape {shape!r}')
return draw
def share_key(advance=640): # a box with an arrow, as on the Share button
def draw(pen):
cx = advance / 2
circle(pen, cx, CY, R)
reverse = ReverseContourPen(pen)
rounded(reverse, cx - 150, CY - 150, cx + 60, CY + 40, 20)
polygon(reverse, [(cx - 15, CY + 10), (cx + 15, CY + 10), (cx + 15, CY + 140), (cx - 15, CY + 140)])
polygon(reverse, [(cx, CY + 205), (cx + 70, CY + 120), (cx - 70, CY + 120)])
return advance, draw
def playstation_icons(g, adv, layout='nintendo'):
"""Code point -> (advance, draw(pen)) for the PlayStation prompts: the face buttons as ○ × △ □ on the button the
pad layout presses, L1 R1 L2 R2, Plus and Minus as Options and Share, and the d-pad cross. g: Glyphs for the
labels; adv: the game's advance of each glyph (font_advances), which each drawing keeps."""
face = PS_FACE[layout]
icons = {cp: (adv[cp], ps_shape(face[b], adv[cp]))
for b, cp in (('A', 0xE040), ('B', 0xE041), ('X', 0xE042), ('Y', 0xE043))}
icons.update({
0xE044: bumper(g, 'L1', adv[0xE044]), 0xE045: bumper(g, 'R1', adv[0xE045]),
0xE046: trigger(g, 'L2', adv[0xE046]), 0xE047: trigger(g, 'R2', adv[0xE047]),
0xE04B: menu_key(adv[0xE04B]), 0xE04C: share_key(adv[0xE04C]),
0xE049: dpad_key('up', 'down', 'left', 'right', advance=adv[0xE049]),
})
for cp, lit in ((0xE060, ('up',)), (0xE061, ('down',)), (0xE062, ('left',)), (0xE063, ('right',)),
(0xE064, ('up', 'down')), (0xE065, ('left', 'right'))):
icons[cp] = dpad_key(*lit, advance=adv[cp])
return icons
# ---- 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).
+158 -36
View File
@@ -41,8 +41,16 @@ 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 is
laid out as an Xbox pad's (bflyt_xbox_diamond): A at the bottom, B on the right, X on the left, Y at the top, the
button the prompt names lit in its place with its bar.
--xbox-prompts is the older name of --prompts xbox. With --aspect, romfs-patches-xbox-<w>x<h> or
romfs-patches-xbox-label-<w>x<h>: the same prompts with that shape's UI layout.
--prompts playstation | playstation-xbox: the same overlay with PlayStation button icons in the game's prompts, for
prompts = playstation (romfs-patches-playstation for pad_layout = nintendo, romfs-patches-playstation-xbox for xbox and
auto). The face buttons become the circle, cross, triangle and square shapes (button_icons.PS_FACE: with nintendo A is
the circle and B the cross, as the buttons sit; with xbox and auto A is the cross and B the circle), the shoulders and
triggers L1 R1 L2 R2, Plus and Minus Options and Share, and the d-pad keeps its cross. The game's text fonts get the
four shapes, so the diamond's letters become those characters; playstation-xbox lays the diamond out as xbox-label
does, since the face buttons sit where an Xbox pad's do. Drawn from the game's own files like the Xbox prompts
(tools/button_icons.py).
--xbox-prompts is the older name of --prompts xbox. With --aspect, romfs-patches-<style>-<w>x<h>: the same prompts with
that shape's UI layout.
--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
@@ -58,15 +66,27 @@ lists them. The output is byte for byte the same as without it.
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, -<w>x<h> with --aspect,
and -hud<a>x<b> with --hud), and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
The files go into <out>.part-<pid> beside <out>, which is renamed to <out> once complete (publish), so a folder is
never seen half written and two runs for one folder do not mix their files. Without --background an older <out> is
removed first (the setup and a source build replace it). --background is the game's (runtime/romfs.c
romfs_folders_prepare, for a folder the settings need and the install lacks): it runs at a lower priority, does
nothing when <out> has a manifest at its start, and drops its own result when another run finished <out> first, so a
folder a running game loaded (whose files totk.exe checks again on every open) is never written into. A .part folder
left by a run that was stopped is removed by the next run for that folder once it is an hour old.
"""
import argparse
import compression.zstd as zstd
import ctypes
import glob
import hashlib
import importlib.util
import json
import os
import re
import shutil
import struct
import time
from pathlib import Path
root = Path(__file__).resolve().parents[1]
@@ -79,14 +99,17 @@ ap.add_argument('--aspect', help='<w>x<h> of a game resolution of another shape
ap.add_argument('--hud', choices=('full', '21:9', '16:9'), default='full',
help='with --aspect on a wider screen: the HUD stays within the middle 21:9 or 16:9 (default full: the '
'screen\'s corners); the default --out gets a -hud21x9 or -hud16x9 suffix')
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), '
'pc for the keyboard and mouse')
ap.add_argument('--prompts', choices=('xbox', 'xbox-label', 'playstation', 'playstation-xbox', 'pc'),
help='Xbox or PlayStation 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), '
'playstation for the PlayStation shapes on the Nintendo layout and playstation-xbox for xbox and '
'auto, 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')
ap.add_argument('--reuse', type=Path,
help='an overlay folder made before: its files with the same contents are linked, not compressed again')
ap.add_argument('--background', action='store_true',
help='started by the game: lower priority, and an <out> that has a manifest is kept, not replaced')
args = ap.parse_args()
args.romfs = args.romfs or root / 'build/extracted' / args.version / 'romfs'
width = height = None
@@ -107,6 +130,54 @@ if not args.out:
if args.aspect: name += '-' + args.aspect
if args.hud != 'full': name += '-hud' + args.hud.replace(':', 'x')
args.out = root / 'build' / args.version / name
PART_STALE_S = 3600 # a .part folder untouched this long belongs to a run that was stopped
def finished(folder):
return (folder / 'manifest.tsv').is_file()
def newest_mtime(folder):
times = [folder.stat().st_mtime]
for path in folder.rglob('*'):
try:
times.append(path.stat().st_mtime)
except OSError:
pass
return max(times)
def remove_stale_parts(out):
"""Remove the <out>.part-* folders of runs that were stopped (none of their files changed for PART_STALE_S)."""
for part in out.parent.glob(glob.escape(out.name) + '.part-*'):
try:
if part.is_dir() and time.time() - newest_mtime(part) > PART_STALE_S:
shutil.rmtree(part, ignore_errors=True)
except OSError:
pass
def lower_priority():
"""Below-normal priority, so the game that started this run keeps its cores."""
try:
if os.name == 'nt':
kernel32 = ctypes.windll.kernel32
kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x4000) # BELOW_NORMAL_PRIORITY_CLASS
else:
os.nice(10)
except (OSError, AttributeError):
pass
if args.background:
if finished(args.out): # another run made it since the game looked
print(json.dumps(dict(status='pass', kept=str(args.out))))
raise SystemExit(0)
lower_priority()
args.out.parent.mkdir(parents=True, exist_ok=True)
remove_stale_parts(args.out)
part = args.out.with_name(f'{args.out.name}.part-{os.getpid()}') # the files go here first (publish)
shutil.rmtree(part, ignore_errors=True)
index = json.loads((args.romfs / 'index.json').read_text())
assert index['status'] == 'pass'
files = {f['path']: f for f in index['files']}
@@ -186,7 +257,8 @@ def bntx_swap(data, base, pairs):
def bflyt_letters(data, base, end, swap):
"""Swap the text of the one-letter text panes T_<letter>_<n> (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)."""
swap (text -> text, one UTF-16 code unit: a letter or a PlayStation shape); the names of the panes changed. Same
length (one character and its terminator)."""
assert data[base:base + 4] == b'FLYT'
pos, changed = base + struct.unpack_from('<H', data, base + 6)[0], []
while pos + 8 <= end:
@@ -293,8 +365,9 @@ def bflyt_xbox_diamond(data, base, end):
def msbt_letters(data, swap):
"""Swap the one-letter messages labelled T_<letter>_<n> (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/<language>/LayoutMsg/<layout>.msbt, over the text stored in the layout."""
swap (text -> text, one UTF-16 code unit: a letter or a PlayStation shape); the labels changed. The game sets a
layout's text panes from the messages of the same name in Mals/<language>/LayoutMsg/<layout>.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, 0x0e)[0]):
@@ -360,7 +433,9 @@ RESTBL = max((p for p in files if p.startswith('System/Resource/ResourceSizeTabl
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
ps = args.prompts in ('playstation', 'playstation-xbox')
ps_layout = 'nintendo' if args.prompts == 'playstation' else 'xbox'
letter_panes = by_position or pc or ps # 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 letter_panes, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
@@ -427,14 +502,20 @@ if args.prompts:
missing = [name for name in icons.TEXT_FONTS if name not in text]
assert not missing, f'no {", ".join(missing)} in {icons.TEXT_ARCHIVE}'
glyphs = icons.text_glyphs(archives[icons.TEXT_ARCHIVE][slice(*text[name])] for name in icons.TEXT_FONTS)
advances = icons.font_advances(archives[icons.TEXT_ARCHIVE][slice(*text[icons.FONT])])
if pc:
ini = args.binds.read_text(encoding='utf-8', errors='replace') if args.binds else None
binds = icons.pc_binds(ini)
advances = icons.font_advances(archives[icons.TEXT_ARCHIVE][slice(*text[icons.FONT])])
drawn = icons.pc_icons(glyphs, advances, binds)
# The text prompts show Y as T (button_icons.PC_TEXT_KEYS); the button guide's images keep the left click
font_drawn = icons.pc_icons(glyphs, advances, icons.pc_binds(ini, text=True))
pane_letters = {letter: icons.pc_letter(binds[letter]) for letter in 'ABXY'}
elif ps:
drawn = icons.playstation_icons(glyphs, advances, ps_layout)
for shape in set(icons.PS_FACE[ps_layout].values()):
glyphs.outline(shape) # the diamond's text needs the shape in the game's text fonts
font_drawn = drawn
pane_letters = icons.PS_FACE[ps_layout]
else:
drawn = font_drawn = icons.xbox_icons(glyphs)
pane_letters = KEY_LETTERS
@@ -443,7 +524,7 @@ if args.prompts:
if by_position:
bntx_swap(blarc, bntx, KEY_TEXTURES)
diamond = []
if args.prompts == 'xbox-label':
if args.prompts in ('xbox-label', 'playstation-xbox'):
diamond = bflyt_xbox_diamond(blarc, *members['blyt/DoCommand_00.bflyt'])
if letter_panes:
for member, (lo, hi) in members.items():
@@ -452,7 +533,8 @@ if args.prompts:
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.PC_HUD_TEXTURES if pc else icons.HUD_TEXTURES, drawn)
hud = icons.bntx_redraw(blarc, bntx, icons.PC_HUD_TEXTURES if pc else icons.PS_HUD_TEXTURES if ps 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():
@@ -494,30 +576,70 @@ def reusable(path, contents, dictionary):
return data if same else None
lines, reused = [], []
for path, contents in outputs.items():
raw = originals[path]
dictionary = dictionaries.get(zstd.get_frame_info(raw).dictionary_id)
target = args.out / path
target.parent.mkdir(parents=True, exist_ok=True)
# Unlinked first: a file linked from another folder (--reuse) is not written through, which would break the other
# folder's manifest.
target.unlink(missing_ok=True)
data = reusable(path, contents, dictionary)
if data is not None:
try: # a hard link takes no room; a volume without them gets a copy
os.link(args.reuse / path, target)
except OSError:
def publish(part, out, sizes, keep_existing):
"""Rename the complete folder part to out. Each file the manifest lists must be there with its size first: a
setup's clean-up that removed part's files under a running generator must not leave a manifest without them.
keep_existing (--background): an out that has a manifest by now stays and part is dropped; an out without one is
an unfinished folder of an older generator, which nothing loads. Without it out is replaced. Returns whether part
became out."""
for path, size in sizes.items():
assert (part / path).is_file() and (part / path).stat().st_size == size, f'{part / path} is missing or changed'
for attempt in range(3):
if keep_existing and finished(out):
shutil.rmtree(part, ignore_errors=True)
return False
if out.exists() and not keep_existing:
shutil.rmtree(out)
elif out.exists():
# Moved aside, never removed in place: another run may publish between the check and this rename, and a
# folder moved aside with a manifest goes back (a removed one could be the one a game just loaded).
stale = out.with_name(f'{out.name}.part-stale-{os.getpid()}')
try:
os.rename(out, stale)
except OSError:
pass
else:
if finished(stale):
os.rename(stale, out)
continue
shutil.rmtree(stale, ignore_errors=True)
try:
os.rename(part, out)
return True
except OSError: # another run renamed its folder into place after the check: the next pass looks again
if attempt == 2:
raise
shutil.rmtree(part, ignore_errors=True)
return False
lines, reused, sizes = [], [], {}
try:
for path, contents in outputs.items():
raw = originals[path]
dictionary = dictionaries.get(zstd.get_frame_info(raw).dictionary_id)
target = part / path
target.parent.mkdir(parents=True, exist_ok=True)
data = reusable(path, contents, dictionary)
if data is not None:
try: # a hard link takes no room; a volume without them gets a copy
os.link(args.reuse / path, target)
except OSError:
target.write_bytes(data)
reused.append(path)
else:
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.write_bytes(data)
reused.append(path)
else:
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.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'
sizes[path] = len(data)
lines.append('\t'.join([path, str(len(data)), hashlib.sha256(data).hexdigest(), hashlib.sha256(raw).hexdigest()]))
(part / 'manifest.tsv').write_text('# path\tsize\tsha256\toriginal_sha256 (tools/make_romfs_patches.py)\n'
+ ''.join(line + '\n' for line in lines))
published = publish(part, args.out, sizes, args.background)
except BaseException:
shutil.rmtree(part, ignore_errors=True)
raise
print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, changed_bytes=len(diff),
ultrawide_layout=dict(aspect=args.aspect, hud=args.hud, members=len(layout)) if args.aspect else None,
prompts=prompts, reused=reused)))
prompts=prompts, reused=reused, **({} if published else {'kept': str(args.out)}))))
+2 -1
View File
@@ -93,7 +93,8 @@ def main():
else:
print(f'package_build: {f} not in {build}, skipped')
n = copy_tree(build / 'romfs-patches', out / 'romfs-patches')
for name in ('romfs-patches-xbox', 'romfs-patches-xbox-label'): # prompts = xbox (make_romfs_patches.py --prompts)
for name in ('romfs-patches-xbox', 'romfs-patches-xbox-label', 'romfs-patches-playstation',
'romfs-patches-playstation-xbox'): # prompts = xbox or playstation (make_romfs_patches.py --prompts)
if (build / name).is_dir():
n += copy_tree(build / name, out / name)
n += copy_tree(exefs, out / 'exefs')
+5 -4
View File
@@ -411,10 +411,11 @@
# 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), 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"). 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").
# and A B X Y as labelled on the button pad_layout presses: with nintendo, A shows as B and X as Y), playstation
# (○ × △ □, L1 R1 L2 R2, Options and Share, on the button pad_layout presses: with nintendo, A shows as ○), or 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). Read at start
# (docs/controls.md, "Xbox and PlayStation button prompts", "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.