Merge pull request #1262 into task/hud: hud_width keeps the HUD narrower than a wide screen on the Shapes step (Marjaperse, ProSep)

This commit is contained in:
Valiantsin Dzerakh committed 2026-11-17 20:06:17 +03:00
commit 006c186928
18 files changed
+829 -97

No files matched your search

+7 -5
View File
@@ -109,11 +109,13 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
RCAS) on the present. An `output_res` that is not 16:9 (more than 1% off, `res_is_16x9`) also switches on the
`aspect` patch set, which hands the output's ratio to the camera, and `romfs.c` `overlay_init` loads the
`romfs-patches-<w>x<h>` overlay for it when it exists (`tools/make_romfs_patches.py --aspect`, laid out by
`tools/ultrawide_layout.py`; the installer builds fifteen sizes: 21:9 2560x1080, 3440x1440, 3840x1600, 5120x2160,
32:9 3840x1080, 5120x1440, 16:10 1280x800, 1680x1050, 1920x1200, 2560x1600 and 3:2 1920x1280, 2160x1440, 2256x1504,
2880x1920, 3000x2000). A wider layout moves the HUD to the
screen's corners, a narrower one to its top and bottom edges. Other sizes get the camera of their shape and the 16:9
HUD stretched over it. The `aspect` setting (`fit`, the default; `stretch`) decides what the present does
`tools/ultrawide_layout.py`; installer/steps.py Shapes builds one canonical folder per needed display/output shape,
chosen by installer/screens.py). A wider layout moves the HUD to the
screen's corners (`hud_width = 21:9` or `16:9` keeps it in the middle of the screen instead, from the `-hud21x9` or
`-hud16x9` variant of the folder), a narrower one to its top and bottom edges. Shapes generates a capped variant
only when selected, alongside the full layout and selected button prompts. `romfs.c` `shaped_name` checks the exact
size then its canonical shape; a missing cap falls back to full, while the menu still offers preparation for the cap.
Without any matching layout the output falls back to 16:9. The `aspect` setting (`fit`, the default; `stretch`) decides what the present does
when the window's shape differs from the output's: `fit` letterboxes, where a 16:9 game in a wider window used to be
stretched.
- HDR (`hdr = 1`, `vk_hdr.c`). The game tonemaps its scene into an r11g11b10f target, upscales it and draws the HUD
+16 -2
View File
@@ -126,12 +126,20 @@ of them.
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").
`--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`
(`21:9`) in `totk.ini` ([totk.ini.example](../totk.ini.example)).
Setup's Shapes step builds only the currently selected cap for the canonical shapes needed by connected displays
and `output_res`, together with the selected prompts. `full` generates no capped folders. After changing the HUD
width, use the Screen tab's layout preparation action or rerun setup before restarting the game. Lookup prefers
the selected cap at the exact or canonical size before falling back to a full-width layout.
A build from source has no layouts for other shapes than 16:9. At an `output_res` such as 5120x1440 the game then
draws the largest 16:9 size inside it (2560x1440) and the present adds bars, instead of a wide camera over a
stretched HUD (`runtime/resolution.c`, `shape_fallback`). For the full shape make `romfs-patches-<w>x<h>` once per
size: `make_romfs_patches.py --version <ver> --aspect <w>x<h> --out build\<ver>\romfs-patches-<w>x<h>` (the sizes
the installer makes are `ASPECT_SIZES` in `installer/steps.py`); `build_game.py` copies every `romfs-patches*`
the installer maps to are in `installer/screens.py`); `build_game.py` copies every `romfs-patches*`
folder next to `totk.exe`.
6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`)
@@ -226,7 +234,13 @@ Before a commit:
A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes
`.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game
files); a change to the settings passes `totk.exe --probe-cfg` and `python tests\settings_doc_check.py`, which fails
when a setting is described neither in `totk.ini.example` nor in [settings.md](settings.md). A change to the mods' ExeFS patches
when a setting is described neither in `totk.ini.example` nor in [settings.md](settings.md).
HUD pane/animation and generator naming regressions run with Python 3.14+: `tests/hud_layout_test.py`.
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.
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
table (no game files), and `totk.exe --probe-mods`. A change to the cheat VM or the cheat opcode tables
+6
View File
@@ -14,6 +14,12 @@ Many rows below are developer tools that only act together with another setting
`tests/settings_doc_check.py` fails when a name in `known[]` (`runtime/cfg.c`) is described neither here nor in `totk.ini.example`, or when a default here differs from the code.
## HUD placement
| 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 |
## Diagnostics and logging
| Setting | What it does | Effect of changing it | Safety |
+49 -23
View File
@@ -1404,7 +1404,24 @@ class PcPrompts(Step):
# ---- 6b. screen shapes
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-xbox|-xbox-label|-pc)?-\d+x\d+$')
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-xbox|-xbox-label|-pc)?-\d+x\d+(?:-hud(?:16|21)x9)?$')
def hud_width(dest):
"""The selected HUD cap, with the same default as runtime/cfg.c."""
try:
text = (dest / 'totk.ini').read_text(encoding='utf-8-sig', errors='replace')
except OSError:
text = ''
value = (screens.ini_value(text, 'hud_width') or 'full').lower()
return value if value in ('16:9', '21:9') else 'full'
def shape_hud(size, hud):
"""The selected cap when at least 1% narrower than the shape, as make_romfs_patches.py requires."""
w, h = (int(v) for v in size.split('x'))
cap = {'16:9': 16 / 9, '21:9': 21 / 9}.get(hud)
return hud if cap and cap < w / h * 0.99 else None
class Shapes(Step):
@@ -1412,7 +1429,7 @@ class Shapes(Step):
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 and the style, so a run of the setup after a
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)."""
@@ -1427,10 +1444,12 @@ class Shapes(Step):
sizes, style = self.wanted(ctx)
# The pc prompts' shaped folders are drawn from the same bindings as romfs-patches-pc, so they follow its key
prompts = ctx.keys.get('pc_prompts', '') if style == 'pc' else ''
return fingerprint('shapes-2', ctx.keys.get('prepare', ''), prompts, style or 'nintendo', *sizes)
return fingerprint('shapes-3', ctx.keys.get('prepare', ''), prompts, style or 'nintendo',
hud_width(ctx.dest), *sizes)
def current(self, ctx, record):
return all((ctx.dest / name / 'manifest.tsv').is_file() for name in record.get('folders', []))
return not record.get('failed') and all((ctx.dest / name / 'manifest.tsv').is_file()
for name in record.get('folders', []))
def run(self, ctx):
layout, rep, dest = ctx.layout, ctx.reporter, ctx.dest
@@ -1442,31 +1461,38 @@ class Shapes(Step):
version = version_tag(game_version(ctx))
plain = dest / f'romfs-patches-{style}' if style else None
folders, failed = [], None
hud = hud_width(dest)
for i, size in enumerate(sizes):
rep.progress('shapes', 'layouts', i, len(sizes), 'shapes', force=True)
out = dest / f'romfs-patches-{size}'
code, log = run_tool(ctx, 'shapes', layout.tools / 'make_romfs_patches.py',
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--aspect', size])
if code:
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
folders.append(out.name)
# Only the Common archive differs from romfs-patches-<style>: --reuse links the fonts, messages and size
# table from there. Optional like that folder: the game keeps the Switch prompts with this layout.
if not plain or not (plain / 'manifest.tsv').is_file():
continue
out = dest / f'romfs-patches-{style}-{size}'
code, log = run_tool(ctx, f'shapes-{style}', layout.tools / 'make_romfs_patches.py',
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--prompts', style,
'--aspect', size, '--reuse', plain, *(pc_binds(dest) if style == 'pc' else ())])
if code:
remove(out)
failed = failed or (code, log)
else:
cap = shape_hud(size, hud)
# Keep the full layout as a fallback, plus only the cap this player selected for this shape.
for variant in (None, cap) if cap else (None,):
suffix = '-hud' + variant.replace(':', 'x') if variant else ''
hud_args = ['--hud', variant] if variant else []
out = dest / f'romfs-patches-{size}{suffix}'
code, log = run_tool(ctx, 'shapes', layout.tools / 'make_romfs_patches.py',
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--aspect', size,
*hud_args])
if code:
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
folders.append(out.name)
# Reuse the selected prompts' fonts/messages/table; PC layouts retain the player's bindings.
if not plain or not (plain / 'manifest.tsv').is_file():
continue
out = dest / f'romfs-patches-{style}-{size}{suffix}'
code, log = run_tool(ctx, f'shapes-{style}', layout.tools / 'make_romfs_patches.py',
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--prompts', style,
'--aspect', size, *hud_args, '--reuse', plain,
*(pc_binds(dest) if style == 'pc' else ())])
if code:
remove(out)
failed = failed or (code, log)
else:
folders.append(out.name)
rep.progress('shapes', 'layouts', len(sizes), len(sizes), 'shapes', force=True)
if failed:
rep.warning('warn.xbox_prompts_failed', code=failed[0], log=str(failed[1]))
return {'folders': folders, 'sizes': sizes, 'style': style}
return {'folders': folders, 'sizes': sizes, 'style': style, 'hud': hud, 'failed': bool(failed)}
# ---- 7. NVIDIA DLSS
+3 -1
View File
@@ -51,7 +51,7 @@ static const char *const known[] = {
"GAMEPLAY_WEAPON_WHEEL",
"GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE",
"GYRO_BIAS_PAD", "GYRO_BIAS_X", "GYRO_BIAS_Y", "GYRO_BIAS_Z", "GYRO_CALIBRATION", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG",
"MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
@@ -78,6 +78,7 @@ static const struct { const char *key, *section; } sections[] = {
{"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"},
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
{"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"},
{"HUD_WIDTH", "display"},
{"SHARPNESS", "display"}, {"DYNAMIC_RES", "display"}, {"ASPECT", "display"}, {"MOVIE_ASPECT", "display"}, {"FOV", "display"}, {"ANISO", "display"},
{"LOD_STEADY", "display"}, {"COLOR_PRESET", "display"},
{"COLOR_BRIGHTNESS", "display"}, {"COLOR_CONTRAST", "display"}, {"COLOR_SATURATION", "display"},
@@ -136,6 +137,7 @@ static const CfgMeta metas[] = {
{"VK_PRESENT", "mailbox", "mailbox|fifo|immediate", LIVE}, {"GPU_INDEX", "", NULL, RESTART},
{"PERF_OVERLAY", "off", "off|fps|full", LIVE},
{"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART},
{"HUD_WIDTH", "full", "full|21:9|16:9", RESTART},
{"DYNAMIC_RES", "1", "0|1", LIVE}, // resolution.c res_dynres_live
{"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE},
{"DLAA", "0", "0|1", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
+45 -1
View File
@@ -6,6 +6,7 @@
#include <string.h>
#include "cfg.h"
#include "fs.h"
#include "host.h"
#include "input.h"
#include "input_map.h"
@@ -135,6 +136,9 @@ int probe_cfg(void) {
CHECK(m && EQ(m->def, "1") && m->live, "meta: fps60 defaults to 1 and is live");
m = cfg_meta("ASYNC_PREEMPT");
CHECK(m && EQ(m->values, "0|1|2") && !m->live, "meta: async_preempt takes 0|1|2 and needs a restart");
m = cfg_meta("HUD_WIDTH");
CHECK(m && EQ(m->def, "full") && EQ(m->values, "full|21:9|16:9") && !m->live,
"meta: HUD width defaults to full and changes after restart");
m = cfg_meta("totk_vk_present");
CHECK(m && EQ(m->key, "VK_PRESENT") && EQ(m->values, "mailbox|fifo|immediate") && m->live,
"meta: prefix and case are accepted");
@@ -363,12 +367,48 @@ int probe_cfg(void) {
}
snprintf(f, sizeof f, "%s/romfs-index.bin", dir);
plat_setenv("TOTK_ROMFS_INDEX", f);
plat_setenv("TOTK_HUD_WIDTH", NULL);
static const char *const capped[] = {"romfs-patches-2560x1080-hud16x9",
"romfs-patches-xbox-2560x1080-hud16x9",
"romfs-patches-3840x1080-hud21x9"};
for (size_t i = 0; i < sizeof capped / sizeof *capped; i++) {
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, capped[i]);
plat_file_delete(f);
}
cfg_set("TOTK_HUD_WIDTH", "full");
CHECK(romfs_shaped_ready(2560, 1080) && romfs_shaped_ready(5120, 2160) && !romfs_shaped_ready(3440, 1440),
"shape: 5120x2160 finds 2560x1080's layout folder, 3440x1440 does not");
CHECK(romfs_shaped_prompts_ready("romfs-patches-xbox", 5120, 2160) &&
!romfs_shaped_prompts_ready("romfs-patches-xbox", 2560, 1080) &&
!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),
"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]);
plat_file_mkdir_p(f);
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"),
"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),
"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");
plat_setenv("TOTK_ROMFS_PATCHES", "0");
CHECK(!romfs_shape_missing(5120, 2160, NULL), "HUD: explicit overlay overrides do not request generated layouts");
plat_setenv("TOTK_ROMFS_PATCHES", NULL);
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]);
plat_file_delete(f);
}
plat_setenv("TOTK_ROMFS_INDEX", NULL);
}
uint8_t pd[PAD_COUNT] = {0};
@@ -496,7 +536,11 @@ int probe_cfg(void) {
char name[96];
snprintf(name, sizeof name, "TOTK_%s", m->key);
plat_setenv(name, "");
CHECK(EQ(cfg_value(name), m->def), "cfg_value returns the table default");
// cfg_get may supply a display or device-profile default (notably OUTPUT_RES on an ultrawide monitor).
// The metadata default is used only when those leave the setting unset.
const char *effective = cfg_get(name);
CHECK(EQ(cfg_value(name), effective && *effective ? effective : m->def),
"cfg_value uses the effective default, falling back to the metadata table");
int ok = 0;
if (!m->values) ok = 1;
else if (strstr(m->values, "..")) {
+3 -3
View File
@@ -47,12 +47,12 @@ 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 the game resolution w x h is of another shape whose folders are missing: the UI layout, or that of
// prompts_folder (a prompts' folder that is there at 16:9; NULL for the game's own prompts). romfs.c shaped_name.
// 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);
// 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 (its layout, and prompts_folder's when that is there at 16:9 and lacks it) as
// 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_prompts_off(const char *folder);
+67 -24
View File
@@ -970,23 +970,44 @@ static void overlay_drop(size_t a, size_t b) {
noverlay -= b - a;
}
// The folder <prefix>-<w>x<h> the game resolution w x h takes in base: that exact size when it has a manifest (an
// The HUD cap for the canonical shape. An inapplicable cap is full, as in installer/steps.py shape_hud. The generator
// takes that same shape, so a resolution alias near the one-percent boundary cannot ask for an invalid variant.
static const char *hud_suffix(unsigned w, unsigned h) {
unsigned shape[2] = {w, h};
cfg_shape_size(w, h, shape);
const char *value = cfg_value("TOTK_HUD_WIDTH");
double cap = !strcmp(value, "21:9") ? 21.0 / 9 : !strcmp(value, "16:9") ? 16.0 / 9 : 0;
return cap && shape[1] && cap < (double)shape[0] / shape[1] * 0.99
? (cap > 2 ? "-hud21x9" : "-hud16x9") : "";
}
// The folder <prefix>-<w>x<h><suffix> the game resolution w x h takes in base: that exact size when it has a manifest (an
// install by a setup that wrote every size, or make_romfs_patches.py --aspect <w>x<h> in a source build), else the
// size of its shape (cfg.c cfg_shape_size), the one folder per shape installer/steps.py Shapes writes. name gets the
// folder found, or the shape's one when neither has a manifest (for the log). 1 when found.
static int shaped_name(const char *base, const char *prefix, unsigned w, unsigned h, char *name, size_t cap) {
static int shaped_name(const char *base, const char *prefix, unsigned w, unsigned h, const char *suffix,
char *name, size_t cap) {
char path[2400];
unsigned s[2] = {w, h};
for (int pass = 0; pass < 2; pass++) {
if (pass && !cfg_shape_size(w, h, s)) break;
if (pass && s[0] == w && s[1] == h) break;
snprintf(name, cap, "%s-%ux%u", prefix, s[0], s[1]);
if (snprintf(name, cap, "%s-%ux%u%s", prefix, s[0], s[1], suffix) >= (int)cap) return 0;
if (snprintf(path, sizeof path, "%s/%s/manifest.tsv", base, name) < (int)sizeof path && plat_file_exists(path))
return 1;
}
return 0;
}
// Prefer the selected HUD at both exact and canonical sizes. Boot may fall back to the full HUD, but preparation
// and the menu's missing-layout note use strict lookup so a full layout cannot hide a missing capped variant.
static int selected_shape(const char *base, const char *prefix, unsigned w, unsigned h, char *name, size_t cap,
int fallback) {
const char *suffix = hud_suffix(w, h);
if (shaped_name(base, prefix, w, h, suffix, name, cap)) return 1;
return fallback && *suffix && shaped_name(base, prefix, w, h, "", name, cap);
}
static void overlay_init(void) {
// TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py).
// A game resolution that is not 16:9 takes romfs-patches-<w>x<h> instead when it is there (shaped_name: the exact
@@ -1012,10 +1033,15 @@ static void overlay_init(void) {
cfg_shape_size(out[0], out[1], shape);
if (!patches && res_wants_wide_overlay(out)) {
char name[128];
if (shaped_name(index_dir, "romfs-patches", out[0], out[1], name, sizeof name) &&
if (selected_shape(index_dir, "romfs-patches", out[0], out[1], name, sizeof name, 1) &&
snprintf(def, sizeof def, "%s/%s", index_dir, name) < (int)sizeof def) {
patches = def, wide = 1;
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",
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]);
@@ -1027,7 +1053,8 @@ static void overlay_init(void) {
char *dir = prompts_folders[i].dir;
prompts_folders[i].name = name;
if (wide) {
prompts_folders[i].ready = shaped_name(index_dir, name, out[0], out[1], dir, sizeof prompts_folders[i].dir);
prompts_folders[i].ready = selected_shape(index_dir, name, out[0], out[1], dir,
sizeof prompts_folders[i].dir, 1);
continue;
}
snprintf(dir, sizeof prompts_folders[i].dir, "%s", name);
@@ -1041,6 +1068,10 @@ static void overlay_init(void) {
const char *wanted_dir = prompts_wanted; // the folder its files come from
for (int i = 0; i < 3; 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);
prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK
: patches && !wide ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? (wide ? ROMFS_PROMPTS_SHAPE : ROMFS_PROMPTS_MISSING)
@@ -1128,19 +1159,19 @@ static void index_folder(char *dir, size_t cap) {
}
// 1 when the folder overlay_init takes for <prefix> at w x h (shaped_name) has a manifest next to romfs-index.bin.
static int shaped_folder_ready(const char *prefix, unsigned w, unsigned h) {
static int shaped_folder_ready(const char *prefix, unsigned w, unsigned h, int fallback) {
char dir[2100], name[128];
index_folder(dir, sizeof dir);
return shaped_name(dir, prefix, w, h, name, sizeof name);
return selected_shape(dir, prefix, w, h, name, sizeof name, fallback);
}
// 1 when the game resolution w x h has the UI layout of its shape: romfs-patches-<w>x<h> of that size or of its shape,
// the folder overlay_init looks for.
int romfs_shaped_ready(unsigned w, unsigned h) { return shaped_folder_ready("romfs-patches", w, h); }
int romfs_shaped_ready(unsigned w, unsigned h) { return shaped_folder_ready("romfs-patches", w, h, 1); }
// 1 when it has a prompts' folder (input_prompts_folder) with that layout too: <folder>-<w>x<h>, which overlay_init
// 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); }
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
@@ -1180,9 +1211,9 @@ static int prepare_tools(char *python, size_t pcap, char *script, size_t scap, c
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder) {
unsigned out[2] = {w, h};
if (!res_wants_wide_overlay(out)) return 0;
return !shaped_folder_ready("romfs-patches", w, h) ||
(prompts_folder && romfs_prompts_ready(prompts_folder) && !shaped_folder_ready(prompts_folder, 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));
}
int romfs_shape_can_prepare(void) {
@@ -1197,8 +1228,8 @@ int romfs_shape_can_prepare(void) {
// 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.
static char shape_started[8][160];
static int shape_started_n;
static char (*shape_started)[160];
static int shape_started_n, shape_started_cap;
static int shape_was_started(const char *folder) {
for (int i = 0; i < shape_started_n; i++)
@@ -1211,9 +1242,15 @@ static int shape_was_started(const char *folder) {
// 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;
}
if (!plat_spawn(argv, dir)) return 0;
if (shape_started_n < (int)(sizeof shape_started / sizeof *shape_started))
snprintf(shape_started[shape_started_n++], sizeof *shape_started, "%s", folder);
snprintf(shape_started[shape_started_n++], sizeof *shape_started, "%s", folder);
return 1;
}
@@ -1226,27 +1263,33 @@ int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder) {
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";
int started = 0, failed = 0;
if (!shaped_name(dir, "romfs-patches", w, h, name, sizeof name)) {
snprintf(folder, sizeof folder, "romfs-patches-%s", size);
if (!selected_shape(dir, "romfs-patches", w, h, name, sizeof name, 0)) {
snprintf(folder, sizeof folder, "romfs-patches-%s%s", size, suffix);
snprintf(out, sizeof out, "%s/%s", dir, folder);
const char *argv[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--aspect", size,
NULL};
"--hud", hud, NULL};
if (shape_spawn(argv, dir, folder)) started++;
else failed++;
}
snprintf(reuse, sizeof reuse, "%s/%s/manifest.tsv", dir, prompts_folder ? prompts_folder : "");
if (prompts_folder && plat_file_exists(reuse) && !shaped_name(dir, prompts_folder, w, h, name, sizeof name)) {
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", prompts_folder, size);
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[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--prompts", style,
"--aspect", size, "--reuse", reuse, pc ? "--binds" : NULL, binds, NULL};
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;
argv[argc] = NULL;
if (shape_spawn(argv, dir, folder)) started++;
else failed++;
}
+24 -8
View File
@@ -525,16 +525,18 @@ static void row_output_res(void) {
// 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[16];
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;
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
missing = sscanf(now, "%ux%u", &w, &h) == 2 && romfs_shape_missing(w, h, want);
}
int here = started && !strcmp(asked, now); // the generation started for the value shown
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);
@@ -542,11 +544,24 @@ static void row_output_res(void) {
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;
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
sscanf(now, "%ux%u", &w, &h);
snprintf(asked, sizeof asked, "%s", now);
started = romfs_shape_prepare(w, h, input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout))
? 1 : -1;
snprintf(asked, sizeof asked, "%s", request);
started = romfs_shape_prepare(w, h, want) ? 1 : -1;
}
// Offer only caps narrower than the canonical layout, using the same tolerance as romfs.c hud_suffix and Shapes.
// This also keeps a selected 21:9 cap visible after changing to a slightly wider-than-21:9 game resolution.
static void row_hud_width(void) {
unsigned w = 0, h = 0, shape[2];
if (sscanf(cfg_value("TOTK_OUTPUT_RES"), "%ux%u", &w, &h) != 2 || !h) return;
shape[0] = w, shape[1] = h;
cfg_shape_size(w, h, shape);
double aspect = (double)shape[0] / shape[1];
if (16.0 / 9 >= aspect * 0.99) return;
const char *vals[3] = {"full", "21:9", "16:9"}, *names[3] = {menu_text(UI_MENU_HUD_WIDTH_FULL), "21:9", "16:9"};
int n = 21.0 / 9 < aspect * 0.99 ? 3 : 2;
if (n == 2) vals[1] = vals[2], names[1] = names[2];
opt_choice_list("TOTK_HUD_WIDTH", UI_MENU_HUD_WIDTH, vals, names, n, UI_MENU_HUD_WIDTH_DESC);
}
static void row_render_scale(void) {
@@ -705,6 +720,7 @@ static void tab_screen(float scale) {
opt_choice("TOTK_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC);
opt_group(UI_MENU_GRAPHICS);
row_output_res();
row_hud_width();
row_render_scale();
opt_toggle("TOTK_DYNAMIC_RES", UI_MENU_DYNAMIC_RES, UI_MENU_DYNAMIC_RES_DESC);
row_shadow_res();
+20
View File
@@ -67,6 +67,11 @@ static const char *const text_en[UI_TEXT_COUNT] = {
"more video memory and GPU time. A wider size (21:9) widens the camera's view and moves "
"the HUD to the screen's corners; a taller one (16:10, 3:2) moves it to the top "
"and bottom edges.",
[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.",
[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 "
"that size. Above 100 % smooths jagged edges (supersampling) at a high GPU cost.",
@@ -644,6 +649,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
"видеопамяти и времени GPU. Более широкий размер (21:9) расширяет обзор камеры и "
"переносит интерфейс в углы экрана, более высокий (16:10, 3:2) переносит его к "
"верхнему и нижнему краям.",
[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 игры доводит её до этого размера. "
"Выше 100 % сглаживает лесенки на краях (суперсэмплинг) ценой большой нагрузки на GPU.",
@@ -1262,6 +1272,11 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
"precisa de mais memória de vídeo e tempo de GPU. Um tamanho mais largo (21:9) amplia a "
"visão da câmera e leva o HUD para os cantos da tela; um mais alto (16:10, 3:2) "
"leva-o para as bordas de cima e de baixo.",
[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.",
[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 "
"tamanho. Acima de 100 % suaviza bordas serrilhadas (supersampling) com alto custo de "
@@ -1890,6 +1905,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
"高于 1920 x 1080 会占用更多显存和 GPU 时间。"
"更宽的尺寸(21:9)会扩大视野,并把界面移到屏幕四角;"
"更高的尺寸(16:10、3:2)则移到上下边缘。",
[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 会将其缩放到该尺寸。"
+1
View File
@@ -34,6 +34,7 @@ typedef enum {
UI_PERF_LINE_FPS,
UI_MENU_GRAPHICS, // group heading over the resolution rows
UI_MENU_OUTPUT_RES, UI_MENU_OUTPUT_RES_DESC,
UI_MENU_HUD_WIDTH, UI_MENU_HUD_WIDTH_DESC, UI_MENU_HUD_WIDTH_FULL,
UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME,
UI_MENU_DYNAMIC_RES, UI_MENU_DYNAMIC_RES_DESC,
UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR,
+171
View File
@@ -0,0 +1,171 @@
"""Synthetic HUD layout and generator CLI regressions, without game assets.
Run with .venv-py314/Scripts/python tests/hud_layout_test.py.
"""
import ast
import compression.zstd as zstd
import json
import os
import importlib.util
import math
import struct
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TOOL = ROOT / 'tools/make_romfs_patches.py'
spec = importlib.util.spec_from_file_location('ultrawide_layout', ROOT / 'tools/ultrawide_layout.py')
ui = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ui)
def archive():
"""Build shipped pane fields and animation keys; no copyrighted archive data."""
layouts = {name: {'RootPane': {}} for name in ui.KEEP_ROOT | ui.MARKER_ROOT.keys()}
for name, panes in ui.MARKER_ROOT.items():
for pane in panes: layouts[name][pane] = {}
for name, pane, field, value in ui.edits(1, None):
layouts.setdefault(name, {'RootPane': {}}).setdefault(pane, {})[field] = value
data, members = bytearray(), {}
for name, panes in sorted(layouts.items()):
blob = bytearray(20)
blob[:4] = b'FLYT'
struct.pack_into('<H', blob, 6, 20)
struct.pack_into('<H', blob, 16, len(panes))
for pane, fields in panes.items():
section = bytearray(80)
section[:4] = b'pan1'
struct.pack_into('<I', section, 4, 80)
section[12:12 + len(pane)] = pane.encode()
struct.pack_into('<2f', section, 68, 1, 1)
for field, value in fields.items(): struct.pack_into('<f', section, ui.FIELD[field], value)
blob += section
members[f'blyt/{name}.bflyt'] = (len(data), len(data) + len(blob))
data += blob
for anim in {row[0] for row in ui.anim_edits(1, None)}:
blob = bytearray(3600)
for name, offset, shipped, _ in ui.anim_edits(1, None):
if name == anim: struct.pack_into('<f', blob, offset, shipped)
members[f'anim/{anim}.bflan'] = (len(data), len(data) + len(blob))
data += blob
return data, members
def value(data, members, name, pane, field):
lo, hi = members[f'blyt/{name}.bflyt']
return struct.unpack_from('<f', data, ui.panes(data, lo, hi)[pane] + ui.FIELD[field])[0]
class HudLayoutTest(unittest.TestCase):
def test_caps_move_panes_and_animation_together(self):
for cap, extension in ((None, 960), (21 / 9, 300), (16 / 9, 0)):
with self.subTest(cap=cap):
data, members = archive()
ui.apply(data, members, 3840, 1080, cap)
self.assertAlmostEqual(value(data, members, 'PlayerStatus_00', 'N_HeartPos_00', 'x'), -extension)
self.assertAlmostEqual(value(data, members, 'EnvironmentInfo_00', 'RootPane', 'x'), extension / 2)
lo, _ = members['anim/AppMap_00_MiniMap.bflan']
for offset in (872, 880, 1628, 1636, 3264, 3272, 3468, 3476):
self.assertAlmostEqual(struct.unpack_from('<f', data, lo + offset)[0], 765 + extension)
self.assertAlmostEqual(value(data, members, 'SaveLoadIcon_00', 'RootPane', 'x'), -extension / 2)
self.assertEqual(value(data, members, 'GameOver_00', 'P_BG_00', 'scale_x'), 2)
self.assertEqual(value(data, members, 'AttentionLockOn_00', 'RootPane', 'scale_x'), 1)
self.assertEqual(value(data, members, 'AttentionLockOn_00', 'N_Offset_00', 'scale_x'), .5)
def test_unnecessary_caps_equal_full(self):
full, members = archive()
ui.apply(full, members, 3440, 1440)
for cap in (3440 / 1440, 4, 3440 / 1440 * .995):
data, members = archive()
ui.apply(data, members, 3440, 1440, cap)
self.assertEqual(data, full)
def test_invalid_parameters_do_not_mutate(self):
for width, height, cap in ((0, 1080, None), (3840, 0, None), (3840, 1080, 1), (3840, 1080, math.nan)):
data, members = archive()
before = bytes(data)
with self.assertRaises(ValueError): ui.apply(data, members, width, height, cap)
self.assertEqual(data, before)
def test_cli_rejects_invalid_before_output(self):
with tempfile.TemporaryDirectory() as folder:
out = Path(folder) / 'output'
for arguments in (['--aspect', 'bad'], ['--aspect', '0x1440'], ['--aspect', '1920x1080'],
['--hud', '16:9'], ['--aspect', '1280x800', '--hud', '16:9']):
result = subprocess.run([sys.executable, str(TOOL), '--out', str(out), *arguments], capture_output=True, text=True)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertIn('error:', result.stderr)
self.assertNotIn('Traceback', result.stderr)
self.assertFalse(out.exists())
def test_default_names_and_explicit_output(self):
# Execute only argument handling; input loading and archive generation remain untouched.
source = TOOL.read_text().split("index = json.loads", 1)[0]
old = sys.argv
try:
for style in (None, 'xbox', 'xbox-label', 'pc'):
for hud in ('full', '21:9', '16:9'):
argv = ['tool', '--aspect', '3840X1080', '--hud', hud]
if style: argv += ['--prompts', style]
sys.argv = argv
env = {'__file__': str(TOOL)}
exec(compile(source, str(TOOL), 'exec'), env)
expected = 'romfs-patches' + (f'-{style}' if style else '') + '-3840x1080'
if hud != 'full': expected += '-hud' + hud.replace(':', 'x')
self.assertEqual(env['args'].out.name, expected)
sys.argv = argv + ['--out', 'chosen']
exec(compile(source, str(TOOL), 'exec'), env)
self.assertEqual(env['args'].out, Path('chosen'))
finally: sys.argv = old
@unittest.skipUnless(os.environ.get('HUD_TEST_ROMFS'), 'set HUD_TEST_ROMFS for local archive comparisons')
class RealArchiveTest(unittest.TestCase):
def test_full_unchanged_and_caps_valid(self):
folder = Path(os.environ['HUD_TEST_ROMFS'])
index = json.loads((folder / 'index.json').read_text())
files = {entry['path']: entry for entry in index['files']}
tree = ast.parse(TOOL.read_text())
functions = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in ('sarc_nodes', 'sarc_members')]
namespace = {'struct': struct}
exec(compile(ast.Module(body=functions, type_ignores=[]), str(TOOL), 'exec'), namespace)
sarc = namespace['sarc_members']
with (folder / 'romfs.bin').open('rb') as image:
def read(path):
entry = files[path]
image.seek(entry['offset'])
return image.read(entry['size'])
pack = zstd.decompress(read('Pack/ZsDic.pack.zs'))
dictionaries = {}
for lo, hi in sarc(pack).values():
dictionary = zstd.ZstdDict(pack[lo:hi])
dictionaries[dictionary.dict_id] = dictionary
path = max(path for path in files if path.startswith('UI/LayoutArchive/Common.Product.') and path.endswith('.blarc.zs'))
raw = read(path)
original = zstd.decompress(raw, zstd_dict=dictionaries[zstd.get_frame_info(raw).dictionary_id])
members = sarc(original)
# The dev implementation before the HUD port is the full-width compatibility reference.
baseline_source = subprocess.check_output(['git', 'show', 'f85058070e955eae0e45c9adbbe903d340b05b32:tools/ultrawide_layout.py'], cwd=ROOT, text=True)
baseline = {}
exec(compile(baseline_source, '<dev layout>', 'exec'), baseline)
for width, height in ((3840, 1080), (3440, 1440), (1280, 800)):
full = bytearray(original)
ui.apply(full, members, width, height)
expected = bytearray(original)
baseline['apply'](expected, members, width, height)
self.assertEqual(full, expected)
for cap, extension in ((16 / 9, 0), (21 / 9, 300)):
data = bytearray(original)
ui.apply(data, members, 3840, 1080, cap)
self.assertAlmostEqual(value(data, members, 'PlayerStatus_00', 'N_HeartPos_00', 'x'), -extension)
self.assertAlmostEqual(value(data, members, 'SaveLoadIcon_00', 'RootPane', 'x'), -extension / 2)
for name in ui.KEEP_ROOT:
if name == 'AppMenuOverlay_00': continue
lo, hi = members[f'blyt/{name}.bflyt']
self.assertEqual(data[lo:hi], original[lo:hi])
if __name__ == '__main__': unittest.main()
+86
View File
@@ -892,6 +892,92 @@ class ShapesTest(unittest.TestCase):
str(self.dest / 'totk.ini')])
self.assertNotIn('--binds', self.calls[0])
def test_selected_hud_only_for_needed_canonical_shapes(self):
screens.displays = lambda: [(5120, 1440), (3840, 1080), (2560, 1600)]
(self.dest / 'totk.ini').write_text('output_res = 5120x2160\nhud_width = 21:9\n')
step = steps.Shapes()
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-2560x1080-hud21x9',
'romfs-patches-3840x1080', 'romfs-patches-3840x1080-hud21x9',
'romfs-patches-1280x800'])
caps = [c for c in self.calls if '--hud' in c]
self.assertEqual(len(caps), 2)
self.assertEqual(caps[0][-4:], ['--aspect', '2560x1080', '--hud', '21:9'])
self.assertEqual(caps[1][-4:], ['--aspect', '3840x1080', '--hud', '21:9'])
self.assertTrue(step.current(self.ctx, record))
(self.dest / record['folders'][3] / 'manifest.tsv').unlink()
self.assertFalse(step.current(self.ctx, record))
def test_hud_key_and_cleanup_follow_selection(self):
screens.displays = lambda: [(2560, 1080)]
ini = self.dest / 'totk.ini'
ini.write_text('hud_width = full\n')
step = steps.Shapes()
full_key = step.key(self.ctx)
for name in ('romfs-patches-3840x1080-hud21x9', 'romfs-patches-pc-2560x1080-hud16x9',
'romfs-patches-player-custom'):
(self.dest / name).mkdir()
ini.write_text('TOTK_HUD_WIDTH = 16:9\n')
self.assertNotEqual(step.key(self.ctx), full_key)
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-2560x1080-hud16x9'])
self.assertFalse((self.dest / 'romfs-patches-3840x1080-hud21x9').exists())
self.assertFalse((self.dest / 'romfs-patches-pc-2560x1080-hud16x9').exists())
self.assertTrue((self.dest / 'romfs-patches-player-custom').is_dir())
self.calls.clear()
ini.write_text('hud_width = full\n')
record = step.run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-2560x1080'])
self.assertTrue(all('--hud' not in c for c in self.calls))
self.assertFalse((self.dest / 'romfs-patches-2560x1080-hud16x9').exists())
def test_capped_pc_prompts_reuse_bindings(self):
screens.displays = lambda: [(3840, 1080)]
(self.dest / 'totk.ini').write_text('prompts = pc\nhud_width = 16:9\nbind_attack = key:f\n')
(self.dest / 'romfs-patches-pc').mkdir()
(self.dest / 'romfs-patches-pc' / 'manifest.tsv').write_text('#\n')
record = steps.Shapes().run(self.ctx)
self.assertEqual(record['folders'], ['romfs-patches-3840x1080', 'romfs-patches-pc-3840x1080',
'romfs-patches-3840x1080-hud16x9',
'romfs-patches-pc-3840x1080-hud16x9'])
self.assertEqual(self.calls[-1][-6:], ['--hud', '16:9', '--reuse', str(self.dest / 'romfs-patches-pc'),
'--binds', str(self.dest / 'totk.ini')])
self.assertNotIn('--binds', self.calls[-2])
def test_hud_caps_ignore_equal_narrow_and_invalid_choices(self):
# Common '21:9' modes are wider than exact 21/9: a manually selected cap is meaningful.
self.assertEqual(steps.shape_hud('2560x1080', '21:9'), '21:9')
self.assertEqual(steps.shape_hud('3440x1440', '21:9'), '21:9')
self.assertIsNone(steps.shape_hud('2520x1080', '21:9'))
self.assertIsNone(steps.shape_hud('1280x800', '16:9'))
self.assertIsNone(steps.shape_hud('3840x1080', 'full'))
self.assertEqual(steps.shape_hud('3440x1440', '16:9'), '16:9')
(self.dest / 'totk.ini').write_text('hud_width = invalid\n')
self.assertEqual(steps.hud_width(self.dest), 'full')
def test_failed_capped_prompts_are_retried(self):
screens.displays = lambda: [(3840, 1080)]
(self.dest / 'totk.ini').write_text('prompts = pc\nhud_width = 16:9\n')
(self.dest / 'romfs-patches-pc').mkdir()
(self.dest / 'romfs-patches-pc/manifest.tsv').write_text('#\n')
successful = steps.run_tool
def fail_cap(ctx, step, script, args, **kwargs):
if '--prompts' in args and '--hud' in args:
return 7, self.dest / 'failed.log'
return successful(ctx, step, script, args, **kwargs)
steps.run_tool = fail_cap
step = steps.Shapes()
record = step.run(self.ctx)
self.assertTrue(record['failed'])
self.assertFalse(step.current(self.ctx, record))
steps.run_tool = successful
record = step.run(self.ctx)
self.assertFalse(record['failed'])
self.assertTrue(step.current(self.ctx, record))
self.assertIn('romfs-patches-pc-3840x1080-hud16x9', record['folders'])
def test_pc_prompts_writes_only_the_16_9_folder(self):
(self.dest / 'totk.ini').write_text('[input]\nbind_attack = key:f\n')
self.assertEqual(steps.PcPrompts().run(self.ctx), {})
+73 -1
View File
@@ -169,6 +169,64 @@ def bflyt(panes):
return b'FLYT' + struct.pack('<HHIIHH', 0xFEFF, 0x14, 0x08000000, 0x14 + len(sections), len(panes) + 1, 0) + sections
def diamond_bflyt():
"""The action prompt's bars, flashes and textured bases, in addition to its letter panes."""
original = bflyt(PANES)
sections = [original[20:]]
names = ['N_BtnA_00', 'N_BtnA_01', 'N_CompanionBtnA_00', 'N_BtnB_00', 'N_BtnX_00', 'N_BtnY_00',
'N_LoopA_03', 'P_CaptureX_00', 'P_CaptureY_00', 'W_BaseX_00', 'W_BaseY_00',
'T_GuideX_00', 'T_GuideY_00', 'T_GuideX_TW', 'T_GuideY_TW']
names += [f'P_Capture{k}_{n:02}' for k in 'ABXY' for n in (1, 2, 3)]
bases = ['P_BaseA_00', 'P_BaseA_01', 'P_BaseB_00', 'P_BaseX_00', 'P_BaseY_00']
for i, name in enumerate(names + bases):
section = bytearray(0x80)
section[:4] = b'pic1' if name in bases else b'txt1' if name.startswith('T_') else b'pan1'
struct.pack_into('<I', section, 4, len(section))
section[12:12 + len(name)] = name.encode()
section[9] = i % 9
struct.pack_into('<8f', section, 0x2c, i * 3, i * -2, 0, 0, 0, i * 10, 1, -1 if i % 2 else 1)
if name in bases: struct.pack_into('<H', section, 0x64, bases.index(name))
elif name.startswith('T_'):
struct.pack_into('<H', section, 0x56, 4)
struct.pack_into('<I', section, 0x64, 0x70)
section[0x70:0x74] = b'G\0\0\0'
sections.append(section)
material = bytearray(12 + 4 * len(bases))
material[:4] = b'mat1'
struct.pack_into('<H', material, 8, len(bases))
for i in range(len(bases)):
struct.pack_into('<I', material, 12 + 4 * i, len(material))
entry = bytearray(0x30)
entry[:8] = f'Base{i:03}'.encode() + b'\0'
struct.pack_into('<H', entry, 0x2c, i)
material += entry
struct.pack_into('<I', material, 4, len(material))
sections.append(material)
textures = bytearray(12 + 4 * len(bases))
textures[:4] = b'txl1'
struct.pack_into('<H', textures, 8, len(bases))
for i in range(len(bases)):
struct.pack_into('<I', textures, 12 + 4 * i, len(textures) - 12)
textures += f'Nt_KeyBtnSubBase{i}'.encode() + b'\0'
struct.pack_into('<I', textures, 4, len(textures))
sections.append(textures)
body = b''.join(sections)
count = len(PANES) + 1 + len(names) + len(bases) + 2
return b'FLYT' + struct.pack('<HHIIHH', 0xFEFF, 20, 0x08000000, 20 + len(body), count, 0) + body
def pane_positions(data):
"""Synthetic layout pane x/y, read independently of the generator."""
pos, out = 20, {}
while pos < len(data):
magic, size = data[pos:pos + 4], struct.unpack_from('<I', data, pos + 4)[0]
if magic in (b'pan1', b'pic1', b'txt1'):
name = data[pos + 12:pos + 36].split(b'\0')[0].decode()
out[name] = struct.unpack_from('<2f', data, pos + 0x2c)
pos += size
return out
def pane_texts(data):
pos, out = struct.unpack_from('<H', data, 6)[0], {}
while pos + 8 <= len(data):
@@ -333,7 +391,7 @@ class Romfs:
self.common: sarc({'anim/ShortCutBG_00_In.bflan': bflan(('C_CaptureBG_00', 'C_CaptureClearBG_00',
'P_CaptureClearBG_00', 'N_Other_00')),
'anim/AutoBuilder_00_In.bflan': bflan(('C_CaptureBG_00',)),
'blyt/DoCommand_00.bflyt': bflyt(PANES),
'blyt/DoCommand_00.bflyt': diamond_bflyt(),
'blyt/Title_00.bflyt': bflyt({'N_Title_00': 'Z'}),
'timg/__Combined.bntx': bntx(images)}),
DEFAULT_FONT: sarc(default),
@@ -445,6 +503,20 @@ class PromptsTest(unittest.TestCase):
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_xbox_label_diamond_moves_letters_bars_and_hold_flashes(self):
for romfs, _, out, _ in self.each(('xbox-label',)):
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)
self.assertEqual(new['T_A_00'], (2, -39))
self.assertEqual(new['T_B_00'], (39, 1))
self.assertEqual(new['T_X_00'], (-38, 0))
self.assertEqual(new['T_Y_00'], (1, 39))
self.assertEqual(new['N_BtnA_00'], old['N_BtnB_00'])
self.assertEqual(new['N_BtnB_00'], old['N_BtnA_00'])
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_other_buttons_are_drawn_as_xbox_icons(self):
for romfs, style, out, _ in self.each():
with self.subTest(version=romfs.version, style=style):
+175
View File
@@ -0,0 +1,175 @@
"""Exercise runtime/romfs.c shape lookup and generator commands without game data.
Usage: python tests/romfs_shapes_check.py [--cc C:/msys64/ucrt64/bin/clang.exe]
The C harness compiles function bodies read from the production implementation;
only configuration, filesystem and process boundaries are supplied here. The spawn boundary records arguments.
"""
import argparse
import os
import re
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "platform/platform.h"
#include "shape_functions.h"
const int rt_game_version = 143;
static char index_test[2400];
static const char *hud_test="16:9", *override_test;
static int spawns;
static char args_test[24][2400];
const char *cfg_get(const char *key) {
if (!strcmp(key,"TOTK_ROMFS_INDEX")) return index_test;
if (!strcmp(key,"TOTK_ROMFS_PATCHES")) return override_test;
return NULL;
}
const char *cfg_value(const char *key) { return !strcmp(key,"TOTK_HUD_WIDTH") ? hud_test : ""; }
// Fixed aliases; cfg_probe independently checks the real canonicalization algorithm.
int cfg_shape_size(unsigned w,unsigned h,unsigned out[2]) {
if (w*9ull==h*16ull) return 0;
if (w==5120 && h==2160) out[0]=2560,out[1]=1080;
else if (w==5120 && h==1440) out[0]=3840,out[1]=1080;
else out[0]=w,out[1]=h;
return 1;
}
int res_wants_wide_overlay(const unsigned out[2]) { return out[0]*9ull!=out[1]*16ull; }
int plat_file_exists(const char *p) { struct stat s; return !stat(p,&s) && S_ISREG(s.st_mode); }
uint8_t *plat_file_read(const char *p,uint64_t *size) {
FILE *f=fopen(p,"rb"); if (!f) return NULL;
fseek(f,0,SEEK_END); *size=ftell(f); rewind(f);
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(); }
void rt_fatal(const char *fmt,...) { (void)fmt;abort(); }
void rt_log(const char *fmt,...) { (void)fmt; }
int plat_spawn(const char *const *args,const char *cwd) {
assert(cwd && *cwd); 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;
}
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 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));
}
int main(int argc,char **argv) {
assert(argc==2); char base[2400],name[128];
snprintf(base,sizeof base,"%s/selection",argv[1]);
snprintf(index_test,sizeof index_test,"%s/romfs-index.bin",base);
assert(selected_shape(base,"romfs-patches",5120,2160,name,sizeof name,1));
assert(!strcmp(name,"romfs-patches-2560x1080-hud16x9")); // selected canonical beats exact full
assert(selected_shape(base,"romfs-patches-xbox",5120,2160,name,sizeof name,0));
assert(!strcmp(name,"romfs-patches-xbox-5120x2160-hud16x9")); // exact cap beats canonical cap
hud_test="21:9";
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));
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);
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);
hud_test="full";
assert(romfs_shape_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);
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(!strcmp(arg("--hud"),"full")); output_ends("romfs-patches-1280x800");
// 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++) {
char folder[80]; snprintf(folder,sizeof folder,"additional-request-%d",i);
int before=spawns; assert(shape_spawn(dummy,argv[1],folder)); assert(spawns==before+1);
assert(shape_spawn(dummy,argv[1],folder)); assert(spawns==before+1);
}
puts("PASS production shape selection, command arguments and generation deduplication");
}
'''
def production_functions():
"""Compile the current function bodies, without duplicating their implementation.
MinGW resolves unrelated public RomFS entry points before section GC, so including
the complete unit would require fake audio, mod, decompression and filesystem APIs.
"""
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'
functions = []
for name in names:
match = re.search(r'(?m)^[^\n;{}]*\b' + name + r'\([^;{}]*?\)\s*\{', source)
assert match, f'production function not found: {name}'
end = match.end()
depth = 1
while depth:
assert end < len(source), f'unclosed production function: {name}'
if source[end] == '{': depth += 1
elif source[end] == '}': depth -= 1
end += 1
functions.append(source[match.start():end])
return '\n'.join(state + functions)
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--cc', default='C:/msys64/ucrt64/bin/clang.exe' if os.name == 'nt' else 'clang')
args = ap.parse_args()
work = ROOT / 'build' / 'romfs-shapes-check'
work.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=work) as temporary:
folder = Path(temporary)
for name in ('romfs-patches-5120x2160', 'romfs-patches-2560x1080-hud16x9',
'romfs-patches-xbox-5120x2160-hud16x9', 'romfs-patches-xbox-2560x1080-hud16x9',
'romfs-patches-3840x1080'):
manifest = folder / 'selection' / name / 'manifest.tsv'
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')
(folder / 'shape_functions.h').write_text(production_functions())
source = folder / 'harness.c'
source.write_text(HARNESS)
exe = folder / ('harness.exe' if os.name == 'nt' else 'harness')
command = [args.cc, '-O2', '-flto', '-ffunction-sections', '-fdata-sections', '-Wl,--gc-sections',
'-I', str(folder), '-I', str(ROOT / 'runtime'), str(source), '-o', str(exe)]
subprocess.run(command, check=True, cwd=ROOT)
env = os.environ.copy()
if os.name == 'nt': env['PATH'] = str(Path(args.cc).resolve().parent) + os.pathsep + env.get('PATH', '')
subprocess.run([str(exe), folder.as_posix()], check=True, cwd=ROOT, env=env)
if __name__ == '__main__': main()
+29 -6
View File
@@ -16,6 +16,9 @@ for that shape (tools/ultrawide_layout.py): menus keep their 16:9 proportions in
cover the screen and the HUD moves to the screen's corners (wider) or its top and bottom edges (narrower). totk.exe
loads that overlay from romfs-patches-<w>x<h> when the game resolution is that size (runtime/romfs.c overlay_init);
the camera's side of it is the patch set aspect (recomp/patches-v121.txt, patches-v143.txt).
--hud 21:9 | 16:9 (with --aspect, a screen wider than that; default full) keeps the HUD within the middle 21:9 or 16:9 of
the screen instead of its corners (totk.ini hud_width). The folder is romfs-patches-<w>x<h>-hud21x9 or -hud16x9, which
runtime/romfs.c overlay_init loads in place of romfs-patches-<w>x<h> when hud_width asks for it.
--prompts xbox | xbox-label: the same overlay with Xbox button icons in the game's prompts, for prompts = xbox
(runtime/romfs.c overlay_init loads romfs-patches-xbox or romfs-patches-xbox-label in place of romfs-patches). Drawn
@@ -53,7 +56,8 @@ contents match the new one is hard-linked (copied where links fail) instead of c
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), and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
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.
"""
import argparse
import compression.zstd as zstd
@@ -70,8 +74,11 @@ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--version', choices=('v110', 'v121', 'v143'), default='v121')
ap.add_argument('--romfs', type=Path, help='default build/extracted/<version>/romfs')
ap.add_argument('--out', type=Path,
help='default build/<version>/romfs-patches (romfs-patches-<style> with --prompts)')
help='default build/<version>/romfs-patches[-<style>][-<w>x<h>][-hud<a>x<b>]')
ap.add_argument('--aspect', help='<w>x<h> of a game resolution of another shape than 16:9: also lay the UI out for it')
ap.add_argument('--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), '
@@ -82,7 +89,24 @@ ap.add_argument('--reuse', type=Path,
help='an overlay folder made before: its files with the same contents are linked, not compressed again')
args = ap.parse_args()
args.romfs = args.romfs or root / 'build/extracted' / args.version / 'romfs'
args.out = args.out or root / 'build' / args.version / (f'romfs-patches-{args.prompts}' if args.prompts else 'romfs-patches')
width = height = None
if args.aspect:
match = re.fullmatch(r'([1-9][0-9]*)x([1-9][0-9]*)', args.aspect.lower())
if not match: ap.error('--aspect must be positive integer dimensions <w>x<h>')
width, height = map(int, match.groups())
if width * 9 == height * 16: ap.error('--aspect must have another shape than 16:9')
args.aspect = f'{width}x{height}'
HUD_CAP = {'full': None, '21:9': 21 / 9, '16:9': 16 / 9}[args.hud]
if HUD_CAP is not None:
if not args.aspect: ap.error('--hud needs --aspect')
if HUD_CAP >= width / height * 0.99:
ap.error(f'--hud {args.hud} is not narrower than a {width}x{height} screen (that is --hud full)')
if not args.out:
# Match runtime/romfs.c overlay_init, preserving the default 16:9 overlay.
name = f'romfs-patches-{args.prompts}' if args.prompts else 'romfs-patches'
if args.aspect: name += '-' + args.aspect
if args.hud != 'full': name += '-hud' + args.hud.replace(':', 'x')
args.out = root / 'build' / args.version / name
index = json.loads((args.romfs / 'index.json').read_text())
assert index['status'] == 'pass'
files = {f['path']: f for f in index['files']}
@@ -381,11 +405,10 @@ for member, panes in MEMBERS.items():
patched[member] = changed
layout = []
if args.aspect:
width, height = (int(v) for v in args.aspect.lower().split('x'))
spec = importlib.util.spec_from_file_location('ultrawide_layout', Path(__file__).with_name('ultrawide_layout.py'))
ultrawide = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ultrawide)
layout = ultrawide.apply(blarc, members, width, height)
layout = ultrawide.apply(blarc, members, width, height, HUD_CAP)
diff = [i for i in range(len(original)) if original[i] != blarc[i]]
touched = [members[m] for m in (*MEMBERS, *layout)]
assert diff and all(any(lo <= i < hi for lo, hi in touched) for i in diff), diff
@@ -496,5 +519,5 @@ for path, contents in outputs.items():
(args.out / 'manifest.tsv').write_text('# path\tsize\tsha256\toriginal_sha256 (tools/make_romfs_patches.py)\n'
+ ''.join(line + '\n' for line in lines))
print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, changed_bytes=len(diff),
ultrawide_layout=dict(aspect=args.aspect, members=len(layout)) if args.aspect else None,
ultrawide_layout=dict(aspect=args.aspect, hud=args.hud, members=len(layout)) if args.aspect else None,
prompts=prompts, reused=reused)))
+47 -23
View File
@@ -12,6 +12,7 @@ found for 1.0.0 .. 1.2.1 (GPL; only those values are taken, no code; THIRD_PARTY
implementation, checked against 1.2.1's Common.Product.110 and 1.4.3's Common.Product.140: every pane is found by name
and every pane field and animation key holds the value the edit expects before it is written.
"""
import math
import struct
# BFLYT pane sections (pan1, pic1, txt1, ...): name at +12 (24 bytes), translate x / y at +44 / +48, scale x / y at +68 / +72.
@@ -48,10 +49,24 @@ MARKER_ROOT = {
# animations only key alpha, visibility and N_Loop_00's y. (pane, x, y) as shipped.
BALLOON_PART = (('C_CaptureBase_00', 226.0, 20.0), ('N_InOut_00', 30.0, -10.0))
def edits(k, hud_corner):
def hud_extent(k, hud_aspect):
"""(w_hud, right_hud) for the HUD: how far its edge moves out in a 1920-wide layout's own units (960 * (1 / kc - 1))
and in the grid units of a root pane already scaled by k (960 * k * (1 / kc - 1)), where kc = (16/9) / C and C is
the HUD's aspect: hud_aspect, never wider than the screen's 16/9 / k. None (or a cap that is not narrower than the
screen) puts the HUD at the screen's edges: the same w and 960 * (1 - k) the screen itself uses. C = 16/9 gives
(0, 0), the HUD in the middle 16:9 as shipped."""
screen = (16 / 9) / k
if hud_aspect is None or hud_aspect >= screen * 0.99: return 960 * (1 / k - 1), 960 * (1 - k)
inner = 1 / ((16 / 9) / hud_aspect) - 1 # 1 / kc - 1
return 960 * inner, 960 * k * inner
def edits(k, hud_aspect):
"""(layout, pane, field, value) for the aspect: k = 16/9 over the aspect (the root's scale), w = how far a 1920-wide
layout's edge moves out in its own units (960 * (1 / k - 1)). OFF moves a pane out of sight."""
layout's edge moves out in its own units (960 * (1 / k - 1)). OFF moves a pane out of sight. hud_aspect: the
widest aspect the HUD spreads over (None = the screen's, see hud_extent); w_hud and right_hud replace w and the
root's x for the HUD panes below, everything else belongs to the screen and keeps w and k."""
w, OFF = 960 * (1 / k - 1), 10000.0
w_hud, right_hud = hud_extent(k, hud_aspect)
wide = 1 / k
out = [
('AppAlbum_00', 'N_FadeInOut_00', 'scale_x', k), ('AppAlbum_00', 'N_Open_01', 'scale_x', wide),
@@ -78,7 +93,8 @@ def edits(k, hud_corner):
('PaCommonBtnTitle_00', 'B_Hit_00', 'x', OFF), ('PaCommonBtnTitle_00', 'N_Cursor_00', 'x', OFF),
('PaLargeDungeonMap_00', 'P_BG_00', 'scale_x', wide), ('PaMessageBtn_00', 'B_Hit_00', 'x', OFF),
('PaRecipeCardList_00', 'P_BG_00', 'scale_x', wide),
('SaveLoadIcon_00', 'RootPane', 'x', -960 * (1 - k)),
# The saving indicator follows the same selected HUD area as the other corner indicators.
('SaveLoadIcon_00', 'RootPane', 'x', -right_hud),
('ShopMenu_00', 'N_BG_00', 'scale_x', wide), ('StaffRoll_00', 'N_BG_00', 'scale_x', wide),
*[e for pane, x, _ in BALLOON_PART for e in (('PaBalloonMessage_00', pane, 'scale_x', k),
('PaBalloonMessage_00', pane, 'x', x * k))],
@@ -97,18 +113,17 @@ def edits(k, hud_corner):
('SystemActionGuide_00', 'N_SystemBG_00', 'scale_x', wide),
('SystemActionGuide_00', 'P_DecoL_01', 'scale_x', k), ('SystemActionGuide_00', 'P_DecoL_01', 'x', -(675 + w) * k),
('SystemActionGuide_00', 'P_DecoL_02', 'scale_x', k), ('SystemActionGuide_00', 'P_DecoL_02', 'x', (675 + w) * k)]
if hud_corner: # the HUD in the screen's corners instead of the middle 16:9
right = 960 * (1 - k)
out += [(name, 'RootPane', 'x', right) for name in ('EnvironmentInfo_00', 'EventSkip_00', 'InstantTipsAppMenu_00',
if hud_aspect is None or hud_aspect > 16 / 9: # the HUD out to its area's edges; at 16:9 it stays as shipped
out += [(name, 'RootPane', 'x', right_hud) for name in ('EnvironmentInfo_00', 'EventSkip_00', 'InstantTipsAppMenu_00',
'InstantTipsWithPict_00', 'InstantTips_00', 'NumDisplaySecond_00',
'NumDisplay_00', 'PickUpWin_00')]
out += [('Location_00', 'N_Small_00', 'x', -(388 + w)),
('PlayerStatus3D_00', 'N_ExtraStaminaTarget_01', 'x', -(745 + w)),
('PlayerStatus_00', 'N_DevilDemoTargetC_00', 'x', -(284 + w)),
('PlayerStatus_00', 'N_DevilDemoTargetLT_00', 'x', -(576 + w)),
('PlayerStatus_00', 'N_HeartGaugeTargetLT_00', 'x', -(576 + w)),
('PlayerStatus_00', 'N_HeartPos_00', 'x', -w),
('PlayerStatus_00', 'Pa_CompanionLife_00', 'x', -(840 + w))]
out += [('Location_00', 'N_Small_00', 'x', -(388 + w_hud)),
('PlayerStatus3D_00', 'N_ExtraStaminaTarget_01', 'x', -(745 + w_hud)),
('PlayerStatus_00', 'N_DevilDemoTargetC_00', 'x', -(284 + w_hud)),
('PlayerStatus_00', 'N_DevilDemoTargetLT_00', 'x', -(576 + w_hud)),
('PlayerStatus_00', 'N_HeartGaugeTargetLT_00', 'x', -(576 + w_hud)),
('PlayerStatus_00', 'N_HeartPos_00', 'x', -w_hud),
('PlayerStatus_00', 'Pa_CompanionLife_00', 'x', -(840 + w_hud))]
return out
SYSTEM_MENUS = ('SystemLoadList_00', 'SystemOption_00', 'SystemSaveLoad_00')
@@ -217,12 +232,13 @@ def tall_anim(blarc, members, k, changed):
if len(curves) != 1 or values != [1.08, 1.28]: raise SystemExit(f'PaMapIconDragonTears_00_Zoom P_Geoglyph_00: keys {values}')
for key in curves[0]: put(key + 4, get(key + 4) / k)
def anim_edits(k, hud_corner):
"""(animation, byte offset, value the game ships, new value): floats inside BFLAN key tables."""
w = 960 * (1 / k - 1)
def anim_edits(k, hud_aspect):
"""(animation, byte offset, value the game ships, new value): floats inside BFLAN key tables. hud_aspect as in
edits."""
w_hud, _ = hud_extent(k, hud_aspect)
out = [('PaMapIconDragonTears_00_Zoom', 288, 1.08, 1.08 / k), ('PaMapIconDragonTears_00_Zoom', 300, 1.28, 1.28 / k)]
if hud_corner: # the minimap's slide-in keys end at x 765, the right edge of a 16:9 layout
out += [('AppMap_00_MiniMap', o, 765.0, 765 + w) for o in (872, 880, 1628, 1636, 3264, 3272, 3468, 3476)]
if hud_aspect is None or hud_aspect > 16 / 9: # the minimap's slide-in keys end at x 765, the right edge of a 16:9 layout
out += [('AppMap_00_MiniMap', o, 765.0, 765 + w_hud) for o in (872, 880, 1628, 1636, 3264, 3272, 3468, 3476)]
return out
def panes(blarc, lo, hi):
@@ -243,10 +259,18 @@ def find_pane(found, layout, name):
if name not in found: raise SystemExit(f'{layout}: no pane {name}')
return found[name]
def apply(blarc, members, width, height, hud_corner=True):
def apply(blarc, members, width, height, hud_aspect=None):
"""Edits blarc (bytearray) in place for a width x height canvas of another shape than 16:9. Returns the members it
changed. hud_corner (wider canvases): the HUD goes to the screen's corners; a narrower one always has it at the
top and bottom edges."""
changed. hud_aspect (wider canvases): the widest aspect the HUD spreads over, centred on the screen (21:9 =
21 / 9, 16:9 = 16 / 9); None, or one not narrower than the screen, puts it in the screen's corners. A taller canvas
always has the HUD at the top and bottom edges."""
if not all(isinstance(v, (int, float)) and math.isfinite(v) and v > 0 for v in (width, height)):
raise ValueError('canvas dimensions must be positive and finite')
if hud_aspect is not None:
if not math.isfinite(hud_aspect) or hud_aspect < 16 / 9:
raise ValueError('HUD aspect must be finite and at least 16:9')
# Runtime treats caps within one percent of the canvas as full width.
if hud_aspect >= width / height * 0.99: hud_aspect = None
wide = width / height > 16 / 9
k = (16 / 9) / (width / height) if wide else (width / height) / (16 / 9)
assert k < 1, 'only for canvases of another shape than 16:9'
@@ -276,7 +300,7 @@ def apply(blarc, members, width, height, hud_corner=True):
struct.pack_into('<f', blarc, at, k)
# Every edit's value at k = 1 is the value the game ships (a scale of 1, the 16:9 position): checked before writing,
# so a version with other numbers stops here instead of getting wrong positions. OFF moves a pane away: not checked.
table = zip(edits(k, hud_corner), edits(1.0, hud_corner)) if wide else zip(tall_edits(k), tall_edits(1.0))
table = zip(edits(k, hud_aspect), edits(1.0, hud_aspect)) if wide else zip(tall_edits(k), tall_edits(1.0))
for (layout, pane, field, value), (_, _, _, shipped) in table:
at = pane_offset(layout, pane) + FIELD[field]
have = struct.unpack_from('<f', blarc, at)[0]
@@ -285,7 +309,7 @@ def apply(blarc, members, width, height, hud_corner=True):
if not wide:
tall_anim(blarc, members, k, changed)
return sorted(changed)
for anim, offset, shipped, value in anim_edits(k, hud_corner):
for anim, offset, shipped, value in anim_edits(k, hud_aspect):
member = f'anim/{anim}.bflan'
if member not in members: raise SystemExit(f'{anim}: no animation {member} in the archive')
lo, hi = members[member]
+7
View File
@@ -203,6 +203,13 @@
# laptop, 2560x1080 on a 21:9 monitor), so the picture fills the screen without black bars, with prompts = xbox or pc
# too (on an install by an older setup, which built the Xbox prompts for 16:9 only, prompts = xbox keeps 1920x1080).
# output_res = 1920x1080
# HUD width on a game resolution wider than 16:9: full, the default, puts the HUD at the screen's left and right edges;
# 21:9 keeps it within the middle 21:9 of the screen and 16:9 within the middle 16:9 (the game's own HUD), so the
# corners of a 32:9 screen stay clear. A cap not narrower than the screen is the same as full, and a 16:9 or taller
# screen ignores it. The installer's Shapes step prepares only the selected cap for the shapes of connected displays
# and output_res, with the selected button prompts. full creates no capped layouts. After changing this setting,
# prepare a missing layout in the Screen tab or rerun setup, then restart. A missing capped folder keeps the full HUD.
# hud_width = full
# 3D render scale: the scene's size relative to the game resolution, game (5/6, the game's own 1600x900 at 1080p) or
# a percentage (25 to 400); above 100 supersamples the scene (anti-aliasing). The scene stays within 8192 pixels a side
# and within a texture heap under 2 GiB (8192x2304 at most on a 5120x1440 output); the log says when it is smaller.