diff --git a/docs/architecture.md b/docs/architecture.md index b4a18d98..c050d1a0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -109,12 +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-x` 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 + `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. 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 + `-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 diff --git a/docs/building.md b/docs/building.md index dac50564..fc6c5410 100644 --- a/docs/building.md +++ b/docs/building.md @@ -121,12 +121,16 @@ of them. (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\\romfs-patches-x-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-x` once per size: `make_romfs_patches.py --version --aspect x --out build\\romfs-patches-x` (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`) @@ -221,7 +225,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 ` 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 diff --git a/docs/settings.md b/docs/settings.md index b887a1af..4906c0b8 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -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 | diff --git a/installer/steps.py b/installer/steps.py index 3794be0e..bb709a9b 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -1243,7 +1243,8 @@ class Shapes(Step): 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 @@ -1286,7 +1287,7 @@ class Shapes(Step): 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, 'hud': hud} + return {'folders': folders, 'sizes': sizes, 'style': style, 'hud': hud, 'failed': bool(failed)} # ---- 7. NVIDIA DLSS diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index d0c79ae5..931b6621 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -6,6 +6,7 @@ #include #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, "..")) { diff --git a/runtime/fs.h b/runtime/fs.h index 4ca879bf..d113a1f2 100644 --- a/runtime/fs.h +++ b/runtime/fs.h @@ -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); diff --git a/runtime/romfs.c b/runtime/romfs.c index f8ce2d4f..18315450 100644 --- a/runtime/romfs.c +++ b/runtime/romfs.c @@ -1223,8 +1223,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++) @@ -1237,9 +1237,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; } diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 6d2950fc..9158fbde 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -549,17 +549,17 @@ static void row_output_res(void) { started = romfs_shape_prepare(w, h, want) ? 1 : -1; } -// The HUD's width on a screen wider than 16:9 (hud_width, romfs.c hud_suffix): the choices that narrow the HUD at the -// game resolution in the settings. 21:9 is offered on the 32:9 sizes (wider than 2.5), 16:9 on any size more than 1% -// wider than 16:9. The row is hidden on a screen that is not wider -// than that, where the setting does nothing (a value left in totk.ini stays as it is). +// 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) { - int w = 0, h = 0; - if (sscanf(cfg_value("TOTK_OUTPUT_RES"), "%dx%d", &w, &h) != 2 || h <= 0) return; - double aspect = (double)w / h; - if (aspect <= 16.0 / 9 * 1.01) return; + 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 = aspect > 2.5 ? 3 : 2; + 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); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 22aaea68..7dbfb366 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -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. Needs the setup's HUD layouts for the game resolution.", + "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 " @@ -646,7 +646,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 игры доводит её до этого размера. " @@ -1263,7 +1263,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. Precisa dos layouts de HUD da instalação para a resolução do jogo.", + "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 " @@ -1890,7 +1890,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 场景相对于游戏分辨率的尺寸;" diff --git a/tests/hud_layout_test.py b/tests/hud_layout_test.py new file mode 100644 index 00000000..7e45efd8 --- /dev/null +++ b/tests/hud_layout_test.py @@ -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('', '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() diff --git a/tests/installer_test.py b/tests/installer_test.py index d1615661..bf7c93a0 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -681,6 +681,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), {}) diff --git a/tests/romfs_prompts_test.py b/tests/romfs_prompts_test.py index 70ca24a0..f454b563 100644 --- a/tests/romfs_prompts_test.py +++ b/tests/romfs_prompts_test.py @@ -169,6 +169,64 @@ def bflyt(panes): return b'FLYT' + struct.pack(' +#include +#include +#include +#include +#include +#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() diff --git a/totk.ini.example b/totk.ini.example index d182f7da..0a8a1ac8 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -203,8 +203,9 @@ # 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 prepares 16:9 for every size above wider than 16:9 and 21:9 for the 32:9 ones -# (romfs-patches-x-hud16x9 and -hud21x9); without the folder the HUD stays at the edges. Read at start. +# 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