From 32fc1b35e16762e91d90b77ce7150c5f6cd36ef7 Mon Sep 17 00:00:00 2001 From: Seth <29849850+shin2344234@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:57:39 -0500 Subject: [PATCH 01/22] Add a right-stick camera speed setting that scales the game's own turn rates The game's five camera sensitivities (Options, Very Low to Very High) turn the camera at the rates in the StickSensitivity array of PlayerCamera.game__component__PlayerCameraParam.bgyml, 0.8 to 2.4. stick_sens (0.1 to 3, read at start) multiplies that array: camera_speed.c decompresses Pack/Actor/PlayerCamera.pack.zs with the RomFS's pack.zsdic, scales the floats in place and compresses it again with the same dictionary, and romfs.c serves the result from /camera/. Scaling the stick's deflection instead could not raise the top speed, since a full tilt cannot go further. The mouse camera reaches the game as a right-stick deflection, so input_win.c mouse_camera divides it by the same factor and mouse_sens alone keeps setting the mouse's speed. romfs.c heapdef_overlay is split into read_served and serve_generated so both generated files share the reading, writing and overlay bookkeeping. --- runtime/camera_speed.c | 160 +++++++++++++++++++++++++++++++++++++++++ runtime/cfg.c | 6 +- runtime/host.h | 7 ++ runtime/input_win.c | 12 +++- runtime/romfs.c | 104 ++++++++++++++++++--------- runtime/ui/menu.cpp | 1 + runtime/ui_text.c | 6 ++ runtime/ui_text.h | 2 +- totk.ini.example | 4 ++ 9 files changed, 263 insertions(+), 39 deletions(-) create mode 100644 runtime/camera_speed.c diff --git a/runtime/camera_speed.c b/runtime/camera_speed.c new file mode 100644 index 00000000..520e6095 --- /dev/null +++ b/runtime/camera_speed.c @@ -0,0 +1,160 @@ +// Camera speed: TOTK_STICK_SENS (0.1 to 3, default 1, read at start) multiplies the game's own right-stick camera speeds. +// The game's Options menu offers five camera sensitivities, Very Low to Very High; their turn rates are the array +// StickSensitivity {0.8, 1.2, 1.6, 2.0, 2.4} in Component/PlayerCameraParam/PlayerCamera.game__component__ +// PlayerCameraParam.bgyml inside Pack/Actor/PlayerCamera.pack.zs. romfs.c serves a copy of that pack with every entry +// multiplied (cam_pack_build), so the setting raises the camera's top speed as well as its speed at a partial tilt, at +// any of the five sensitivities. The mouse camera reaches the game as a right-stick deflection (input_win.c, +// mouse_camera); input_win.c divides it by the same factor (cam_speed_applied), so TOTK_MOUSE_SENS alone sets the +// mouse's speed. +// +// The pack is a SARC archive compressed with the dictionary pack.zsdic of Pack/ZsDic.pack.zs. A float in a BYML array +// is stored in the array itself, so the multiplied values take the bytes of the old ones and no offset moves. +#include +#include +#include +#include + +#include "cfg.h" +#include "host.h" + +#define MEMBER "Component/PlayerCameraParam/PlayerCamera.game__component__PlayerCameraParam.bgyml" +#define MAX_RAW (64u << 20) + +static float applied = 1.0f; + +float cam_speed_wanted(void) { + double v = cfg_double("TOTK_STICK_SENS"); + return (float)(v < 0.1 ? 0.1 : v > 3 ? 3 : v); +} + +float cam_speed_applied(void) { return applied; } + +static int u32_at(const uint8_t *p, size_t n, size_t off, uint32_t *v) { + if (off > n || n - off < 4) return 0; + memcpy(v, p + off, 4); + return 1; +} + +// SARC member `name` of the archive p[0..n): its start and size; 0 when it is not there. +static int sarc_member(const uint8_t *p, size_t n, const char *name, size_t *at, size_t *size) { + uint32_t data; + uint16_t head, count, bom; + if (n < 0x14 || memcmp(p, "SARC", 4)) return 0; + memcpy(&head, p + 4, 2); + memcpy(&bom, p + 6, 2); + if (bom != 0xfeff || !u32_at(p, n, 12, &data) || head + 12u > n || memcmp(p + head, "SFAT", 4)) return 0; + memcpy(&count, p + head + 6, 2); + size_t names = head + 12 + (size_t)count * 16; + if (names + 8 > n || memcmp(p + names, "SFNT", 4)) return 0; + names += 8; + for (unsigned i = 0; i < count; i++) { + uint32_t attr, lo, hi; + size_t e = head + 12 + (size_t)i * 16; + if (!u32_at(p, n, e + 4, &attr) || !u32_at(p, n, e + 8, &lo) || !u32_at(p, n, e + 12, &hi)) return 0; + size_t s = names + (size_t)(attr & 0xffffff) * 4, len = strlen(name); + if (!(attr >> 24) || s + len + 1 > n || memcmp(p + s, name, len + 1)) continue; + if (lo > hi || data + (size_t)hi > n) return 0; + *at = data + lo; + *size = hi - lo; + return 1; + } + return 0; +} + +// The StickSensitivity floats of the BYML p[0..n), multiplied by k; their count, 0 when the file has no such array. +static int scale_sensitivity(uint8_t *p, size_t n, float k, float was[8]) { + uint32_t keys, root, head; + if (n < 16 || memcmp(p, "YB", 2) || !u32_at(p, n, 4, &keys) || !u32_at(p, n, 12, &root) || + !u32_at(p, n, root, &head) || (head & 0xff) != 0xc1 || !u32_at(p, n, keys, &head) || (head & 0xff) != 0xc2) + return 0; + uint32_t nkeys = head >> 8; + if (!u32_at(p, n, root, &head)) return 0; + for (uint32_t i = 0; i < head >> 8; i++) { + uint32_t e, at, arr, ah; + if (!u32_at(p, n, root + 4 + 8 * (size_t)i, &e) || (e & 0xffffff) >= nkeys || + !u32_at(p, n, keys + 4 + 4 * (size_t)(e & 0xffffff), &at)) + return 0; + const char *name = (const char *)p + keys + at; + if (keys + at + sizeof "StickSensitivity" > n || strcmp(name, "StickSensitivity")) continue; + if (e >> 24 != 0xc0 || !u32_at(p, n, root + 8 + 8 * (size_t)i, &arr) || !u32_at(p, n, arr, &ah) || + (ah & 0xff) != 0xc0) + return 0; + uint32_t count = ah >> 8; + size_t vals = arr + 4 + ((count + 3) & ~3u); + if (!count || count > 8 || vals + 4 * (size_t)count > n) return 0; + for (uint32_t j = 0; j < count; j++) + if (p[arr + 4 + j] != 0xd2) return 0; + for (uint32_t j = 0; j < count; j++) { + float v; + memcpy(&v, p + vals + 4 * j, 4); + was[j] = v; + v *= k; + memcpy(p + vals + 4 * j, &v, 4); + } + return (int)count; + } + return 0; +} + +int cam_pack_build(const void *in, size_t n, const void *zsdic, size_t zsdic_n, void **out, size_t *out_n) { + float k = cam_speed_wanted(); + *out = NULL; + if (k == 1.0f) return 0; + int ok = 0; + uint8_t *dics = NULL, *raw = NULL; + ZSTD_DDict *dd = NULL; + ZSTD_CDict *cd = NULL; + void *z = NULL; + // The dictionaries: Pack/ZsDic.pack.zs is a SARC compressed without one. + unsigned long long dn = ZSTD_getFrameContentSize(zsdic, zsdic_n); + size_t dic_at, dic_n; + if (dn == ZSTD_CONTENTSIZE_UNKNOWN || dn == ZSTD_CONTENTSIZE_ERROR || dn > MAX_RAW || !(dics = malloc((size_t)dn)) || + ZSTD_decompress(dics, (size_t)dn, zsdic, zsdic_n) != dn || + !sarc_member(dics, (size_t)dn, "pack.zsdic", &dic_at, &dic_n)) { + rt_log("camera speed: no pack.zsdic in Pack/ZsDic.pack.zs; the camera keeps its own speed"); + goto done; + } + unsigned long long rn = ZSTD_getFrameContentSize(in, n); + unsigned id = ZSTD_getDictID_fromFrame(in, n); + dd = ZSTD_createDDict(dics + dic_at, dic_n); + if (!dd || id != ZSTD_getDictID_fromDDict(dd) || rn == ZSTD_CONTENTSIZE_UNKNOWN || + rn == ZSTD_CONTENTSIZE_ERROR || rn > MAX_RAW || !(raw = malloc((size_t)rn))) { + rt_log("camera speed: Pack/Actor/PlayerCamera.pack.zs is not a pack.zsdic frame with a size; the camera keeps its " + "own speed"); + goto done; + } + ZSTD_DCtx *dctx = ZSTD_createDCtx(); + size_t got = dctx ? ZSTD_decompress_usingDDict(dctx, raw, (size_t)rn, in, n, dd) : 0; + ZSTD_freeDCtx(dctx); + size_t at, size; + float was[8]; + int count = !ZSTD_isError(got) && got == rn && sarc_member(raw, (size_t)rn, MEMBER, &at, &size) + ? scale_sensitivity(raw + at, size, k, was) : 0; + if (!count) { + rt_log("camera speed: no StickSensitivity array in %s; the camera keeps its own speed", MEMBER); + goto done; + } + cd = ZSTD_createCDict(dics + dic_at, dic_n, 9); + size_t cap = ZSTD_compressBound((size_t)rn), zn = 0; + ZSTD_CCtx *cctx = cd ? ZSTD_createCCtx() : NULL; + if (cctx && (z = malloc(cap))) zn = ZSTD_compress_usingCDict(cctx, z, cap, raw, (size_t)rn, cd); + ZSTD_freeCCtx(cctx); + if (!z || !zn || ZSTD_isError(zn)) goto done; + *out = z; + *out_n = zn; + z = NULL; + ok = 1; + rt_log("camera speed: x%.2f, StickSensitivity %.2f %.2f %.2f %.2f %.2f -> %.2f %.2f %.2f %.2f %.2f", k, was[0], + count > 1 ? was[1] : 0, count > 2 ? was[2] : 0, count > 3 ? was[3] : 0, count > 4 ? was[4] : 0, was[0] * k, + count > 1 ? was[1] * k : 0, count > 2 ? was[2] * k : 0, count > 3 ? was[3] * k : 0, + count > 4 ? was[4] * k : 0); +done: + free(z); + free(raw); + free(dics); + ZSTD_freeDDict(dd); + ZSTD_freeCDict(cd); + return ok; +} + +void cam_pack_served(void) { applied = cam_speed_wanted(); } diff --git a/runtime/cfg.c b/runtime/cfg.c index 31eb9213..a6a8fad5 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -47,7 +47,7 @@ static const char *const known[] = { "RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", - "SHADER_MEMO", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", + "SHADER_MEMO", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_SENS", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_VERTEX", "VK_NO_FLOAT64", "VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS", "WB_FENCE_LIMIT", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE", @@ -63,7 +63,7 @@ static const struct { const char *key, *section; } sections[] = { {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, - {"PAD_LAYOUT", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"}, + {"PAD_LAYOUT", "input"}, {"STICK_SENS", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"}, {"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"}, {"BIND_RCLICK", "input"}, {"BIND_L", "input"}, {"BIND_R", "input"}, {"BIND_ZL", "input"}, {"BIND_ZR", "input"}, {"BIND_PLUS", "input"}, {"BIND_MINUS", "input"}, {"BIND_LEFT", "input"}, {"BIND_UP", "input"}, @@ -104,7 +104,7 @@ static const CfgMeta metas[] = { {"VOLUME", "100", "0..100", LIVE}, {"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE}, {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox", LIVE}, - {"MOUSE_SENS", "1", "0..10", LIVE}, + {"STICK_SENS", "1", "0.1..3", RESTART}, {"MOUSE_SENS", "1", "0..10", LIVE}, {"MENU_LANG", "", "en|ru", LIVE}, // Advanced: scheduling {"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART}, diff --git a/runtime/host.h b/runtime/host.h index 262b7b98..4ede550f 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -233,6 +233,13 @@ void account_uid(uint64_t out[2]); // the local user's n // ---- movies (ov_movie.c) void movie_tick(Cpu *c); // at every present, on the presenting guest thread: hands // decoded movie frames over when due, signals their events +// ---- camera speed (camera_speed.c): TOTK_STICK_SENS +float cam_speed_wanted(void); // the factor TOTK_STICK_SENS asks for, 0.1 to 3 +float cam_speed_applied(void); // the factor in effect: 1 until romfs.c serves the pack +int cam_pack_build(const void *in, size_t n, const void *zsdic, size_t zsdic_n, void **out, size_t *out_n); + // Pack/Actor/PlayerCamera.pack.zs with the camera speeds + // multiplied, malloc'd; 0 = factor 1 or cannot (logged) +void cam_pack_served(void); // romfs.c serves the multiplied pack // ---- game resolution (resolution.c): TOTK_OUTPUT_RES, TOTK_RENDER_SCALE uint64_t res_heap_extra_bytes(void); // added to the application pool (mem_init), 2 MiB steps uint64_t res_heap_extra_kib(void); // added to the HeapDef texture heap and its parent; 0 = none diff --git a/runtime/input_win.c b/runtime/input_win.c index 61bb7dea..618b9294 100644 --- a/runtime/input_win.c +++ b/runtime/input_win.c @@ -5,6 +5,7 @@ // The gamepad also rumbles (input_rumble) and, when it has a gyro and an accelerometer, feeds the six-axis sensor from a // thread of its own (input_motion_start). Every SDL call on the gamepad is made under `lock`. #include +#include #include #include #include @@ -399,7 +400,10 @@ int input_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) { static int key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; } -// The mouse camera as a right-stick sample, held for the whole presented frame. Under `lock`. +// The mouse camera as a right-stick sample, held for the whole presented frame. Under `lock`. The sample is divided by +// the camera speed factor the game runs with (camera_speed.c, cam_speed_applied), which multiplies every right-stick +// turn rate, so TOTK_MOUSE_SENS alone sets the mouse's speed; below 1 the sample stays within the stick's range, so the +// mouse's top speed drops with the factor. static void mouse_camera(int32_t out[2]) { static uint64_t frame = ~0ull; static LARGE_INTEGER t0; @@ -424,8 +428,10 @@ static void mouse_camera(int32_t out[2]) { held[0] = held[1] = 0; // frames stopped: do not hold a deflection } } - out[0] = held[0]; - out[1] = held[1]; + double k = cam_speed_applied(), x = held[0] / k, y = held[1] / k, len = sqrt(x * x + y * y); + if (len > STICK_MAX) x *= STICK_MAX / len, y *= STICK_MAX / len; + out[0] = (int32_t)lround(x); + out[1] = (int32_t)lround(y); } static int32_t axis(int16_t v) { diff --git a/runtime/romfs.c b/runtime/romfs.c index 0d7aee5b..05ac6b62 100644 --- a/runtime/romfs.c +++ b/runtime/romfs.c @@ -343,46 +343,52 @@ static void added_init(void) { rt_log("RomFS overlay: %zu files added to the RomFS", nadded); } -// The HeapDef table a bigger game resolution needs (resolution.c): its texture heap and that heap's parent grow. The -// base is an overlay that replaces the table (a mod's heap sizes stay), else the RomFS original; the grown table is -// written to /resolution/ and served in the base's place. -#define HEAPDEF "System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs" -static void heapdef_overlay(void) { - if (!res_heap_extra_kib()) return; - uint64_t i = lower(HEAPDEF); - if (i >= file_count || strcmp(entry_name(entry(i)), HEAPDEF)) { - rt_log("RomFS: %s missing; the game keeps its own resolution", HEAPDEF); - return; +// RomFS file `rel` as the game would read it: from an overlay that replaces it (*base), else from the image. malloc'd; +// NULL when it is missing, unreadable or 16 MiB or more (logged with `keeps`, what the game does without it). +static void *read_served(const char *rel, Overlay **base, size_t *n, const char *keeps) { + uint64_t i = lower(rel); + *base = NULL; + if (i >= file_count || strcmp(entry_name(entry(i)), rel)) { + rt_log("RomFS: %s missing; %s", rel, keeps); + return NULL; } - Overlay *base = NULL; for (size_t k = 0; k < noverlay; k++) - if (overlays[k].index == i) base = &overlays[k]; - HANDLE f = base ? open_read(base->path, 1) : image; - uint64_t off = base ? 0 : entry(i).offset, n = base ? base->size : entry(i).size; - void *in = n && n < (16u << 20) && f != INVALID_HANDLE_VALUE ? malloc((size_t)n) : NULL; - int ok = in && read_at(f, in, (uint32_t)n, off) == (int64_t)n; - if (base && f != INVALID_HANDLE_VALUE) CloseHandle(f); - void *out = NULL; - size_t out_n = 0; - ok = ok && res_heapdef_build(in, (size_t)n, &out, &out_n); - free(in); - if (!ok) return; + if (overlays[k].index == i) *base = &overlays[k]; + HANDLE f = *base ? open_read((*base)->path, 1) : image; + uint64_t off = *base ? 0 : entry(i).offset, size = *base ? (*base)->size : entry(i).size; + void *in = size && size < (16u << 20) && f != INVALID_HANDLE_VALUE ? malloc((size_t)size) : NULL; + int ok = in && read_at(f, in, (uint32_t)size, off) == (int64_t)size; + if (*base && f != INVALID_HANDLE_VALUE) CloseHandle(f); + if (!ok) { + free(in); + rt_log("RomFS: cannot read %s; %s", rel, keeps); + return NULL; + } + *n = (size_t)size; + return in; +} + +// Serves out[0..out_n) (malloc'd, freed here) in place of RomFS file `rel` and of an overlay that replaces it (base): +// written to //. `what` names the change in the log. 0 when it cannot be written. +static int serve_generated(const char *rel, Overlay *base, void *out, size_t out_n, const char *sub, const char *what, + const char *keeps) { char dir[2100], file[2200]; - need(snprintf(dir, sizeof dir, "%s/resolution", rt_config()->profile) < (int)sizeof dir, "resolution path"); - need(snprintf(file, sizeof file, "%s/Product.Nin_NX_NVN.HeapDef.byml.zs", dir) < (int)sizeof file, "resolution path"); + const char *leaf = strrchr(rel, '/') ? strrchr(rel, '/') + 1 : rel; + need(snprintf(dir, sizeof dir, "%s/%s", rt_config()->profile, sub) < (int)sizeof dir, "generated overlay path"); + need(snprintf(file, sizeof file, "%s/%s", dir, leaf) < (int)sizeof file, "generated overlay path"); wchar_t *wd = fs_wide(dir), *wf = fs_wide(file); CreateDirectoryW(wd, NULL); HANDLE w = CreateFileW(wf, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); DWORD put = 0; - ok = w != INVALID_HANDLE_VALUE && WriteFile(w, out, (DWORD)out_n, &put, NULL) && put == out_n; + int ok = w != INVALID_HANDLE_VALUE && WriteFile(w, out, (DWORD)out_n, &put, NULL) && put == out_n; if (w != INVALID_HANDLE_VALUE) CloseHandle(w); free(wd); free(wf); free(out); HANDLE r = ok ? open_read(file, 1) : INVALID_HANDLE_VALUE; if (r == INVALID_HANDLE_VALUE) { - rt_log("RomFS: cannot write %s (error %lu); the game keeps its own resolution", file, GetLastError()); - return; + rt_log("RomFS: cannot write %s (error %lu); %s", file, GetLastError(), keeps); + return 0; } Identity id = identity_of(r); CloseHandle(r); @@ -399,12 +405,45 @@ static void heapdef_overlay(void) { overlays = realloc(overlays, overlay_cap * sizeof *overlays); need(overlays != NULL, "overlay table"); } - char *rel = _strdup(HEAPDEF); - need(rel != NULL, "overlay path copy"); - overlays[noverlay++] = (Overlay){i, out_n, copy, rel, id}; + char *name = _strdup(rel); + need(name != NULL, "overlay path copy"); + overlays[noverlay++] = (Overlay){lower(rel), out_n, copy, name, id}; } - rt_log("RomFS overlay: %s (%zu bytes, grown heaps) replaces %s", file, out_n, base ? "the mod's table" : "the original"); - res_heapdef_served(); + rt_log("RomFS overlay: %s (%zu bytes, %s) replaces %s", file, out_n, what, base ? "the mod's file" : "the original"); + return 1; +} + +// The HeapDef table a bigger game resolution needs (resolution.c): its texture heap and that heap's parent grow. The +// base is an overlay that replaces the table (a mod's heap sizes stay), else the RomFS original; the grown table is +// written to /resolution/ and served in the base's place. +#define HEAPDEF "System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs" +static void heapdef_overlay(void) { + if (!res_heap_extra_kib()) return; + static const char keeps[] = "the game keeps its own resolution"; + Overlay *base; + size_t n; + void *in = read_served(HEAPDEF, &base, &n, keeps), *out = NULL; + size_t out_n = 0; + int ok = in && res_heapdef_build(in, n, &out, &out_n); + free(in); + if (ok && serve_generated(HEAPDEF, base, out, out_n, "resolution", "grown heaps", keeps)) res_heapdef_served(); +} + +// The player camera's pack with its stick speeds multiplied by TOTK_STICK_SENS (camera_speed.c). The base is an +// overlay that replaces the pack (a mod's camera stays), else the RomFS original; the dictionary is the RomFS's own. +#define CAMPACK "Pack/Actor/PlayerCamera.pack.zs" +static void camera_overlay(void) { + if (cam_speed_wanted() == 1.0f) return; + static const char keeps[] = "the camera keeps its own speed"; + Overlay *base, *dic_base; + size_t n, dn; + void *in = read_served(CAMPACK, &base, &n, keeps), *out = NULL; + void *dic = in ? read_served("Pack/ZsDic.pack.zs", &dic_base, &dn, keeps) : NULL; + size_t out_n = 0; + int ok = in && dic && cam_pack_build(in, n, dic, dn, &out, &out_n); + free(in); + free(dic); + if (ok && serve_generated(CAMPACK, base, out, out_n, "camera", "camera speed", keeps)) cam_pack_served(); } static void overlay_init(void) { @@ -420,6 +459,7 @@ static void overlay_init(void) { for (int i = 0; i < 2; i++) if (dirs[i] && *dirs[i] && strcmp(dirs[i], "0")) overlay_load(dirs[i]); heapdef_overlay(); + camera_overlay(); added_init(); if (noverlay) qsort(overlays, noverlay, sizeof *overlays, overlay_order); for (size_t k = 1; k < noverlay; k++) diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 7d52baa9..05829688 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -573,6 +573,7 @@ static void tab_controls(float scale) { opt_slider("TOTK_RUMBLE_STRENGTH", UI_MENU_RUMBLE_STRENGTH, 0, 300, UI_MENU_RUMBLE_STRENGTH_DESC, 10, "%.0f %%"); opt_slider("TOTK_RUMBLE_CURVE", UI_MENU_RUMBLE_CURVE, 0.2f, 1.5f, UI_MENU_RUMBLE_CURVE_DESC, 0.05f, "%.2f"); opt_toggle("TOTK_RUMBLE_TRIGGERS", UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC); + opt_slider("TOTK_STICK_SENS", UI_MENU_STICK_SENS, 0.1f, 3, UI_MENU_STICK_SENS_DESC, 0.05f, "%.2f"); opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f"); binds_rows(scale); opt_end(); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 0de0818f..2ae8b839 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -99,6 +99,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s", [UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity", [UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.", + [UI_MENU_STICK_SENS] = "Stick camera speed", + [UI_MENU_STICK_SENS_DESC] = "Multiplies the game's own right-stick camera speed, top speed included, at each of the " + "game's five camera sensitivities. The mouse keeps its own setting.", [UI_BINDS_HELP] = "Select a cell and press A or Enter, then the key, mouse button or controller button. Delete or " "X clears a cell. A key in use moves here; a controller button swaps with the one it replaces.", @@ -317,6 +320,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", [UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.", + [UI_MENU_STICK_SENS] = "Скорость камеры (стик)", + [UI_MENU_STICK_SENS_DESC] = "Умножает скорость поворота камеры правым стиком, включая наибольшую, при каждой из пяти " + "чувствительностей камеры в игре. На мышь не влияет.", [UI_BINDS_HELP] = "Выберите ячейку и нажмите A или Enter, затем клавишу, кнопку мыши или кнопку контроллера. " "Delete или X очищает ячейку. Занятая клавиша переходит сюда; кнопка контроллера меняется " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 96e10618..6fdb955b 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -57,7 +57,7 @@ typedef enum { UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC, UI_MENU_PAD_LAYOUT, UI_MENU_PAD_LAYOUT_DESC, UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_IN_USE, - UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, + UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC, // Controls tab: the remapping rows (ui/binds_page.cpp) UI_BINDS_HELP, UI_BINDS_COL_KEY1, UI_BINDS_COL_KEY2, UI_BINDS_COL_PAD, diff --git a/totk.ini.example b/totk.ini.example index 30c3a2af..8752f35f 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -150,6 +150,10 @@ # west X, north Y, as an Xbox pad labels them; cross A on a PlayStation pad) or auto (nintendo for a pad with Nintendo # labels, xbox for the others). The bind_ lines below apply on top. Changes while the game runs take effect at once. # pad_layout = auto +# Right-stick camera speed (0.1 to 3): multiplies the game's own camera turn rates, top speed included, at each of the +# five camera sensitivities in the game's Options. Keys bound to the right stick follow it; the mouse keeps mouse_sens. +# Read at start. +# stick_sens = 1 # Mouse camera sensitivity (0 to 10; 0 = no mouse camera and no cursor capture). # mouse_sens = 1 # Write the input of this run to a file that replays as a script (docs/controls.md, "Scripted input"). Default: off. From 3aa604a9dbd376b08f800c188f3fceacc22195e4 Mon Sep 17 00:00:00 2001 From: Lucas-blip-png <177052392+Lucas-blip-png@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:21:36 -0400 Subject: [PATCH 02/22] Add a Brazilian Portuguese catalog for the settings menu and the overlay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The menu had English and Russian. pt-BR gets its own row with every menu id, a Português (Brasil) entry in the menu language list (TOTK_MENU_LANG = pt-BR), and is picked automatically when the Windows display language is pt-BR. The game language pt-BR now maps to this row instead of Portugal's pt, so the software keyboard shows Brazilian text too; pt keeps its row and the English menu. probe_menu_text checks the row is complete, keeps its overlay formats and follows the setting. --- docs/architecture.md | 2 +- runtime/cfg.c | 2 +- runtime/ov_probe.c | 26 +++-- runtime/ui/menu.cpp | 5 +- runtime/ui_text.c | 262 ++++++++++++++++++++++++++++++++++++++++++- runtime/ui_text.h | 12 +- totk.ini.example | 4 +- 7 files changed, 288 insertions(+), 25 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 29967538..dea663ac 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,7 +54,7 @@ MacNativeGames cannot run on x86-64 as is: its CPU path executes ARM64 code nati libzstd on the host (`ov_zstd.c`, `TOTK_ZSTD_NATIVE`); the lifted decoder took almost three times as long. - Settings and menu: every key with its default is in one table (`cfg.c`), read from `totk.ini` and `TOTK_*` variables and written back when the in-game menu changes it. The menu and the performance overlay are Dear ImGui, - drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian). + drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian, Brazilian Portuguese). - OS calls the host makes go through `runtime/platform/` (`platform.h`, `win32.c`), so a Linux or macOS host adds one file instead of touching the rest. The split is not finished: `tools/check_platform.py` lists the Win32 uses left in the other files. #### Threads and cores diff --git a/runtime/cfg.c b/runtime/cfg.c index 25a30f18..84a72ab0 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -106,7 +106,7 @@ static const CfgMeta metas[] = { {"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE}, {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox|xbox_prompts", LIVE}, {"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, - {"MENU_LANG", "", "en|ru", LIVE}, + {"MENU_LANG", "", "en|ru|pt-BR", LIVE}, // Advanced: scheduling {"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART}, {"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART}, diff --git a/runtime/ov_probe.c b/runtime/ov_probe.c index c0ffa181..05f0df2b 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -814,13 +814,16 @@ static void probe_fonts(void) { (unsigned long long)size, path); } -// The host catalog (ui_text.c): every menu id has its own English and Russian text, the software keyboard keeps its -// game-language rows, and menu_text follows TOTK_MENU_LANG. +// The host catalog (ui_text.c): every menu id has its own English, Russian and Brazilian Portuguese text, the software +// keyboard keeps its game-language rows, and menu_text follows TOTK_MENU_LANG. static void probe_menu_text(void) { - static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko"}; + static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko", + "pt-BR"}; for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) { - CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id), "menu text id %d lacks en or ru", id); - CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id), "menu text id %d is empty", id); + CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id) && + ui_text_defined("pt-BR", (UiTextId)id), "menu text id %d lacks en, ru or pt-BR", id); + CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id) && *ui_text_in("pt-BR", (UiTextId)id), + "menu text id %d is empty", id); } CHECK(!ui_text_defined("en", UI_TEXT_COUNT) && !*ui_text_in("ru", UI_TEXT_COUNT), "an id past the catalog gives text"); // other languages fall back to English for the menu, and keep their own keyboard texts @@ -828,22 +831,29 @@ static void probe_menu_text(void) { CHECK(!strcmp(ui_text_in("ru", UI_SWKBD_OK), "ОК") && !strcmp(ui_text_in("de", UI_SWKBD_CANCEL), "Abbrechen") && !strcmp(ui_text_in("en", UI_SWKBD_OK), "OK"), "keyboard texts changed"); // language names: the same string in every row - for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_KO; id++) + for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_PT_BR; id++) for (size_t i = 1; i < sizeof langs / sizeof *langs; i++) CHECK(!strcmp(ui_text_in(langs[i], (UiTextId)id), ui_text_in("en", (UiTextId)id)), "language name %d differs in %s", id, langs[i]); CHECK(!strcmp(ui_text_in("en", UI_MENU_LANGNAME_RU), "Русский"), "Russian is not shown as Russian"); // the overlay formats keep their conversions CHECK(strstr(ui_text_in("ru", UI_MENU_OV_GAME_PCT), "%.0f%%") && strstr(ui_text_in("ru", UI_MENU_OV_MAX_MS), "%.1f"), "overlay format lost its conversion"); + CHECK(strstr(ui_text_in("pt-BR", UI_MENU_OV_GAME_PCT), "%.0f%%") && + strstr(ui_text_in("pt-BR", UI_MENU_OV_MAX_MS), "%.1f"), "pt-BR overlay format lost its conversion"); + // a Brazilian game language gets the Brazilian keyboard row, Portugal's Portuguese keeps its own + CHECK(!strcmp(ui_text_lang("pt-BR"), "pt-BR") && !strcmp(ui_text_lang("pt"), "pt") && + strcmp(ui_text_in("pt-BR", UI_SWKBD_PROMPT), ui_text_in("pt", UI_SWKBD_PROMPT)), "pt-BR keyboard row not used"); // menu_text follows the setting live cfg_set("TOTK_MENU_LANG", "ru"); CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("ru", UI_MENU_CONTINUE), "menu_text ignores MENU_LANG=ru"); + cfg_set("TOTK_MENU_LANG", "pt-BR"); + CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("pt-BR", UI_MENU_CONTINUE), "menu_text ignores MENU_LANG=pt-BR"); cfg_set("TOTK_MENU_LANG", "en"); CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en"); cfg_set("TOTK_MENU_LANG", ""); const char *sys = plat_ui_language(); - int ru = !strncmp(sys, "ru", 2); - CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(ru ? "ru" : "en", UI_MENU_CONTINUE), "menu_text auto ignores the system language"); + const char *want = !strcmp(sys, "pt-BR") ? "pt-BR" : !strncmp(sys, "ru", 2) ? "ru" : "en"; + CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(want, UI_MENU_CONTINUE), "menu_text auto ignores the system language"); } static void probe_main(Cpu *c) { diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 865f6b17..ee118dff 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -596,8 +596,9 @@ static void tab_controls(float scale) { static void tab_menu(float scale) { opt_begin("##menu", scale); - static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU}; - opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, 3, UI_MENU_MENU_LANG_DESC); + static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU, + UI_MENU_LANGNAME_PT_BR}; + opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, 4, UI_MENU_MENU_LANG_DESC); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 65a1926e..948902e9 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -1,6 +1,6 @@ // Catalog of the text the host shows the player (ui_text.h). One array per catalog language, indexed by UiTextId: a new // string gets an id in ui_text.h and an entry in every language that has one (a missing entry falls back to English). -// The software keyboard has every language; the menu has English and Russian. +// The software keyboard has every language; the menu has English, Russian and Brazilian Portuguese. #include #include @@ -16,7 +16,8 @@ typedef struct { const char *lang; const char *const *text; } Row; [UI_MENU_LANGNAME_EN] = "English", [UI_MENU_LANGNAME_JA] = "日本語", [UI_MENU_LANGNAME_FR] = "Français", \ [UI_MENU_LANGNAME_DE] = "Deutsch", [UI_MENU_LANGNAME_IT] = "Italiano", [UI_MENU_LANGNAME_ES] = "Español", \ [UI_MENU_LANGNAME_NL] = "Nederlands", [UI_MENU_LANGNAME_RU] = "Русский", \ - [UI_MENU_LANGNAME_ZH_HANS] = "简体中文", [UI_MENU_LANGNAME_ZH_HANT] = "繁體中文", [UI_MENU_LANGNAME_KO] = "한국어" + [UI_MENU_LANGNAME_ZH_HANS] = "简体中文", [UI_MENU_LANGNAME_ZH_HANT] = "繁體中文", [UI_MENU_LANGNAME_KO] = "한국어", \ + [UI_MENU_LANGNAME_PT_BR] = "Português (Brasil)" // SWKBD: TITLE, PROMPT, DEFAULT_NAME (at most 9 UTF-16 units, no '@' '%' '\'), OK, CANCEL, PAD_HINT. #define SWKBD(title, prompt, name, ok, cancel, hint) \ @@ -496,6 +497,252 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_OV_SCALE_BILINEAR] = "билинейное", }; +static const char *const text_pt_br[UI_TEXT_COUNT] = { + SWKBD("Inserir texto", "Insira um nome", "Cavalo", "OK", "Cancelar", "Controle: A = OK, B = Cancelar"), + + [UI_MENU_TITLE] = "Configurações", + [UI_MENU_TAB_SCREEN] = "Tela", [UI_MENU_TAB_GAME] = "Jogo", [UI_MENU_TAB_SOUND] = "Som", + [UI_MENU_TAB_CONTROLS] = "Controles", [UI_MENU_TAB_MENU] = "Menu", [UI_MENU_TAB_ADVANCED] = "Avançado", + [UI_MENU_CONTINUE] = "Continuar", [UI_MENU_QUIT] = "Sair do jogo", + [UI_MENU_ON] = "Ligado", [UI_MENU_OFF] = "Desligado", [UI_MENU_AUTO] = "Automático", + [UI_MENU_DEFAULT_MARK] = "padrão", + [UI_MENU_AFTER_RESTART] = "após reiniciar", [UI_MENU_SET_BY_ENV] = "definido por variável de ambiente", + [UI_MENU_SAVE_FAILED] = "não foi possível salvar as configurações", + [UI_MENU_VERSION] = "TotK Recomp %s, jogo %s", + + [UI_MENU_FULLSCREEN] = "Tela cheia", [UI_MENU_FULLSCREEN_DESC] = "O jogo ocupa a tela inteira; F11 alterna.", + [UI_MENU_WINDOW_SIZE] = "Tamanho da janela", + [UI_MENU_WINDOW_SIZE_DESC] = "Tamanho da janela do jogo fora da tela cheia.", + [UI_MENU_WINDOW_SIZE_CUSTOM] = "Personalizado", + [UI_MENU_PRESENT] = "Apresentação", [UI_MENU_PRESENT_DESC] = "Como os quadros prontos chegam à tela.", + [UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "VSync", [UI_MENU_PRESENT_IMMEDIATE] = "Imediato", + [UI_MENU_PRESENT_IN_USE] = "em uso: %s", + [UI_MENU_GPU] = "Placa de vídeo", [UI_MENU_GPU_DESC] = "O dispositivo Vulkan que desenha o jogo.", + [UI_MENU_GPU_AUTO] = "Automática", + [UI_MENU_PERF_OVERLAY] = "Indicador de desempenho", + [UI_MENU_PERF_OVERLAY_DESC] = "Taxa de quadros no canto superior direito. Completo adiciona os tempos de quadro com " + "gráfico, o uso de CPU, GPU e memória, as temperaturas e as esperas da thread de " + "renderização. F10 alterna os modos.", + [UI_MENU_PERF_OFF] = "Desligado", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Completo", + [UI_PERF_LINE_FPS] = "%.0f fps", + [UI_MENU_GRAPHICS] = "Imagem", + [UI_MENU_OUTPUT_RES] = "Resolução do jogo", + [UI_MENU_OUTPUT_RES_DESC] = "O tamanho em que o jogo desenha a imagem e a interface. Acima de 1920 x 1080 o jogo " + "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.", + [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 " + "GPU.", + [UI_MENU_RENDER_SCALE_GAME] = "Jogo (83 %)", + [UI_MENU_UPSCALER] = "Escala para a janela", + [UI_MENU_UPSCALER_DESC] = "Como a imagem é ampliada quando a janela é maior que a resolução do jogo. O FSR mantém " + "bordas e detalhes mais nítidos que o bilinear.", + [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear", + [UI_MENU_ASPECT] = "Formato da imagem", + [UI_MENU_ASPECT_DESC] = "Quando o formato da janela difere do da resolução do jogo (uma imagem 16:9 numa tela " + "21:9): manter o formato da imagem com barras pretas ou esticá-la sobre a janela.", + [UI_MENU_ASPECT_FIT] = "Barras pretas", [UI_MENU_ASPECT_STRETCH] = "Esticar", + [UI_MENU_SHARPNESS] = "Nitidez do FSR", + [UI_MENU_SHARPNESS_DESC] = "Aumento de nitidez após a ampliação do FSR; 0 desliga.", + + [UI_MENU_FPS_LIMIT] = "Limite de quadros", + [UI_MENU_FPS_LIMIT_DESC] = "O máximo de quadros por segundo que o jogo desenha. Acima de 60 é experimental e " + "precisa de Velocidade do jogo pelo relógio.", + [UI_MENU_FPS_30] = "30 FPS", [UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS", + [UI_MENU_FPS_DISPLAY] = "Taxa do monitor", [UI_MENU_FPS_DISPLAY_HZ] = "Taxa do monitor (%.0f Hz)", + [UI_MENU_REALTIME] = "Velocidade do jogo pelo relógio", + [UI_MENU_REALTIME_DESC] = "Avança o jogo pelo tempo real, para que um quadro lento não deixe o jogo mais lento.", + [UI_MENU_CLOTH_REALTIME] = "Tecidos pelo relógio", + [UI_MENU_CLOTH_REALTIME_DESC] = "Avança tecidos e cabelos pelo tempo real também.", + [UI_MENU_HIGHFPS_FIX] = "Correções para alta taxa de quadros", + [UI_MENU_HIGHFPS_FIX_DESC] = "Corrige a física que se comporta mal acima de 30 quadros por segundo e objetos que ficam transparentes ou invisíveis acima de 60.", + [UI_MENU_GAME_LANG] = "Idioma do jogo", [UI_MENU_GAME_LANG_DESC] = "Idioma dos textos e das vozes do jogo.", + [UI_MENU_GAME_LANG_AUTO] = "Automático", + [UI_MENU_OPERATION_MODE] = "Modo do console", + [UI_MENU_OPERATION_MODE_DESC] = "Se o jogo acha que está no modo TV ou no modo portátil.", + [UI_MENU_MODE_DOCKED] = "Modo TV", [UI_MENU_MODE_HANDHELD] = "Modo portátil", + + [UI_MENU_VOLUME] = "Volume", [UI_MENU_VOLUME_DESC] = "Volume geral do jogo.", + + [UI_MENU_MOTION] = "Controles de movimento", [UI_MENU_MOTION_DESC] = "Mirar com o giroscópio do controle.", + [UI_MENU_RUMBLE_STRENGTH] = "Intensidade da vibração", + [UI_MENU_RUMBLE_STRENGTH_DESC] = "Quão forte o controle vibra.", + [UI_MENU_RUMBLE_CURVE] = "Curva da vibração", + [UI_MENU_RUMBLE_CURVE_DESC] = "Valores menores deixam a vibração fraca mais forte.", + [UI_MENU_RUMBLE_TRIGGERS] = "Vibração dos gatilhos (Xbox)", + [UI_MENU_RUMBLE_TRIGGERS_DESC] = "Também vibra os gatilhos de um controle de Xbox.", + [UI_MENU_PAD_LAYOUT] = "Layout dos botões", + [UI_MENU_PAD_LAYOUT_DESC] = "Qual botão é o A. Nintendo: o da direita, como no Switch. Xbox: o de baixo, como " + "indicado no controle de Xbox (cruz no controle de PlayStation). Automático escolhe " + "Nintendo para controles com os rótulos da Nintendo e Xbox para os demais. Ícones de " + "Xbox: o A é o da direita, como no Nintendo, e o jogo mostra os rótulos do Xbox (B no " + "lugar de A, A no lugar de B, Y no lugar de X, X no lugar de Y); os ícones mudam após " + "reiniciar. As letras fazem parte dos arquivos do jogo, então um botão remapeado em " + "Controles continua com a letra antiga na tela.", + [UI_MENU_PAD_LAYOUT_AUTO] = "Automático", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A à direita)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A embaixo)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Ícones de Xbox (A à direita)", + [UI_MENU_PAD_LAYOUT_IN_USE] = "em uso: %s", + [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "faltam os arquivos dos ícones: execute a instalação de novo", + [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "os ícones mudam após reiniciar", + [UI_MENU_STICK_DEADZONE] = "Zona morta dos analógicos", + [UI_MENU_STICK_DEADZONE_DESC] = "Quanto um analógico do controle precisa se mover antes que o jogo perceba. Aumente se o personagem ou a câmera se moverem sozinhos.", + [UI_MENU_MOUSE_SENS] = "Sensibilidade da câmera no mouse", + [UI_MENU_MOUSE_SENS_DESC] = "Quão rápido o mouse gira a câmera.", + + [UI_BINDS_HELP] = "Selecione uma célula e aperte A ou Enter, depois a tecla, o botão do mouse ou o botão do " + "controle. Delete ou X limpa a célula. Uma tecla já em uso vem para cá; um botão do controle " + "troca de lugar com o que ele substitui.", + [UI_BINDS_COL_KEY1] = "Tecla 1", [UI_BINDS_COL_KEY2] = "Tecla 2", [UI_BINDS_COL_PAD] = "Controle", + [UI_BINDS_GROUP_BUTTONS] = "Botões", [UI_BINDS_GROUP_MOVE] = "Movimento", [UI_BINDS_GROUP_CAMERA] = "Câmera", + [UI_BINDS_PRESS_KEY] = "Aperte uma tecla ou um botão do mouse para %s", + [UI_BINDS_PRESS_PAD] = "Aperte um botão do controle para %s", + [UI_BINDS_CANCEL_HINT] = "Esc cancela, ou aguarde %d s", + [UI_BINDS_TAKEN] = "%s saiu de %s", [UI_BINDS_SWAPPED] = "%s trocou de lugar com %s", + [UI_BINDS_RESET] = "Restaurar todos os botões", + [UI_BINDS_RESET_DESC] = "Volta às teclas e aos botões do controle padrão. O layout dos botões acima volta a valer: " + "os botões do controle remapeados ficam onde você os colocou até esta restauração.", + [UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y", + [UI_BIND_LCLICK] = "Clique do analógico esquerdo", [UI_BIND_RCLICK] = "Clique do analógico direito", + [UI_BIND_L] = "L", [UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", [UI_BIND_PLUS] = "Mais", + [UI_BIND_MINUS] = "Menos", + [UI_BIND_LEFT] = "Direcional para a esquerda", [UI_BIND_UP] = "Direcional para cima", + [UI_BIND_RIGHT] = "Direcional para a direita", [UI_BIND_DOWN] = "Direcional para baixo", + [UI_BIND_LSTICK_LEFT] = "Mover para a esquerda", [UI_BIND_LSTICK_UP] = "Mover para a frente", + [UI_BIND_LSTICK_RIGHT] = "Mover para a direita", [UI_BIND_LSTICK_DOWN] = "Mover para trás", + [UI_BIND_RSTICK_LEFT] = "Câmera para a esquerda", [UI_BIND_RSTICK_UP] = "Câmera para cima", + [UI_BIND_RSTICK_RIGHT] = "Câmera para a direita", [UI_BIND_RSTICK_DOWN] = "Câmera para baixo", + [UI_BIND_DESC_A] = "Interagir, pegar, conversar.", [UI_BIND_DESC_B] = "Correr, cancelar, voltar.", + [UI_BIND_DESC_X] = "Pular.", [UI_BIND_DESC_Y] = "Atacar.", [UI_BIND_DESC_LCLICK] = "Agachar.", + [UI_BIND_DESC_RCLICK] = "Visão em primeira pessoa.", [UI_BIND_DESC_L] = "Habilidades.", + [UI_BIND_DESC_R] = "Arremessar a arma.", [UI_BIND_DESC_ZL] = "Escudo, travar a mira.", [UI_BIND_DESC_ZR] = "Arco.", + [UI_BIND_DESC_PLUS] = "Menu, inventário.", [UI_BIND_DESC_MINUS] = "Mapa.", + [UI_BIND_DESC_DPAD] = "Seleção rápida.", + [UI_BIND_DESC_MOVE] = "Move o Link como o analógico esquerdo. O analógico esquerdo do controle também sempre " + "funciona.", + [UI_BIND_DESC_CAMERA] = "Gira a câmera como o analógico direito. O mouse e o analógico direito do controle também " + "sempre funcionam.", + [UI_KEY_SPACE] = "Espaço", [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "Shift esquerdo", + [UI_KEY_LCTRL] = "Ctrl esquerdo", + [UI_KEY_UP] = "Seta para cima", [UI_KEY_DOWN] = "Seta para baixo", [UI_KEY_LEFT] = "Seta para a esquerda", + [UI_KEY_RIGHT] = "Seta para a direita", + [UI_KEY_MOUSE_L] = "Mouse esquerdo", [UI_KEY_MOUSE_R] = "Mouse direito", [UI_KEY_MOUSE_M] = "Mouse do meio", + [UI_KEY_MOUSE_X1] = "Mouse 4", [UI_KEY_MOUSE_X2] = "Mouse 5", + [UI_KEY_ENTER] = "Enter", [UI_KEY_BACKSPACE] = "Backspace", [UI_KEY_RSHIFT] = "Shift direito", + [UI_KEY_RCTRL] = "Ctrl direito", [UI_KEY_LALT] = "Alt", [UI_KEY_CAPSLOCK] = "Caps Lock", [UI_KEY_INSERT] = "Insert", + [UI_KEY_DELETE] = "Delete", [UI_KEY_HOME] = "Home", [UI_KEY_END] = "End", [UI_KEY_PAGEUP] = "Page Up", + [UI_KEY_PAGEDOWN] = "Page Down", [UI_KEY_NUM_FMT] = "Num %s", + [UI_PAD_SOUTH] = "Botão de baixo", [UI_PAD_EAST] = "Botão da direita", [UI_PAD_WEST] = "Botão da esquerda", + [UI_PAD_NORTH] = "Botão de cima", [UI_PAD_LSTICK] = "Analógico esquerdo", [UI_PAD_RSTICK] = "Analógico direito", + [UI_PAD_L] = "Bumper esquerdo", [UI_PAD_R] = "Bumper direito", [UI_PAD_START] = "Start", [UI_PAD_BACK] = "Back", + [UI_PAD_DPAD_LEFT] = "Direcional para a esquerda", [UI_PAD_DPAD_UP] = "Direcional para cima", + [UI_PAD_DPAD_RIGHT] = "Direcional para a direita", [UI_PAD_DPAD_DOWN] = "Direcional para baixo", + [UI_PAD_ZL] = "Gatilho esquerdo", [UI_PAD_ZR] = "Gatilho direito", + [UI_PAD_LPADDLE1] = "Botão traseiro esquerdo", [UI_PAD_RPADDLE1] = "Botão traseiro direito", + [UI_PAD_LPADDLE2] = "Botão traseiro esquerdo 2", [UI_PAD_RPADDLE2] = "Botão traseiro direito 2", + [UI_PAD_CROSS] = "Cruz", [UI_PAD_CIRCLE] = "Círculo", [UI_PAD_SQUARE] = "Quadrado", [UI_PAD_TRIANGLE] = "Triângulo", + + [UI_MENU_MENU_LANG] = "Idioma do menu", [UI_MENU_MENU_LANG_DESC] = "Idioma deste menu e do indicador.", + [UI_MENU_MENU_LANG_AUTO] = "Automático (do Windows)", + + [UI_MENU_ADV_WARNING] = "Estas configurações são para testes e solução de problemas. Altere-as só quando souber " + "por quê.", + [UI_MENU_GROUP_SCHED] = "Agendamento", [UI_MENU_GROUP_SHADERS] = "Shaders e pipelines", + [UI_MENU_GROUP_TEXMEM] = "Texturas e memória", [UI_MENU_GROUP_FIXES] = "Correções de renderização", + [UI_MENU_GROUP_VULKAN] = "Vulkan", [UI_MENU_GROUP_DIAG] = "Diagnóstico", + [UI_MENU_ASYNC_PREEMPT] = "Preempção de núcleo virtual", + [UI_MENU_ASYNC_PREEMPT_DESC] = "Deixa uma thread do jogo interromper outra no mesmo núcleo virtual.", + [UI_MENU_PREEMPT_OFF] = "Desligado", [UI_MENU_PREEMPT_ON] = "Ligado", [UI_MENU_PREEMPT_INHERIT] = "Só herança", + [UI_MENU_REPLAY_ASYNC] = "Preparo de quadro da GPU em thread própria", + [UI_MENU_REPLAY_ASYNC_DESC] = "Prepara os quadros para a GPU numa thread separada em vez da thread do jogo. Adiciona até um quadro de latência.", + [UI_MENU_FREE_CORES] = "Trava de núcleo virtual", + [UI_MENU_FREE_CORES_DESC] = "Deixa só uma thread rodar por núcleo virtual, como no console.", + [UI_MENU_TIMER_1MS] = "Timer do Windows de 1 ms", + [UI_MENU_TIMER_1MS_DESC] = "Aumenta a resolução do timer do sistema para 1 ms, para um ritmo de quadros mais estável.", + [UI_MENU_PIPE_WAIT] = "Tratamento de desenhos em espera", + [UI_MENU_PIPE_WAIT_DESC] = "Padrão mantém o agendamento atual, com um worker reservado para desenhos em espera; Antigo (draw) usa o agendamento anterior.", + [UI_MENU_PIPE_WAIT_DEFAULT] = "Padrão", [UI_MENU_PIPE_WAIT_DRAW] = "Antigo (draw)", + [UI_MENU_PIPE_SKIP] = "Desenhos pulados enquanto um pipeline é montado", + [UI_MENU_PIPE_SKIP_DESC] = "Quais desenhos são descartados em vez de esperar pelo seu pipeline.", + [UI_MENU_PIPE_SKIP_STRICT] = "Estrito", [UI_MENU_PIPE_SKIP_ANY] = "Qualquer", + [UI_MENU_PIPE_SKIP_FULLSCREEN] = "Passes de tela cheia", + [UI_MENU_LIB_PREBUILD] = "Pré-montagem das bibliotecas de estágio", + [UI_MENU_LIB_PREBUILD_DESC] = "Monta antes, em segundo plano, as bibliotecas de estágio dos shaders.", + [UI_MENU_LIB_PREBUILD_THREADS] = "Threads da pré-montagem das bibliotecas", + [UI_MENU_LIB_PREBUILD_THREADS_DESC] = "Threads usadas na pré-montagem; Automático escolhe um número pela sua CPU.", + [UI_MENU_PIPE_PREBUILD] = "Pré-montagem de pipelines", + [UI_MENU_PIPE_PREBUILD_DESC] = "Monta antes os pipelines conhecidos.", + [UI_MENU_PREWARM_XLATE] = "Pré-aquecimento do tradutor", + [UI_MENU_PREWARM_XLATE_DESC] = "Threads que traduzem os shaders conhecidos ao iniciar; Automático usa metade das threads da CPU, no máximo 16.", + [UI_MENU_GPL] = "Biblioteca de pipelines gráficos", + [UI_MENU_GPL_DESC] = "Usa a extensão de biblioteca de pipelines do Vulkan; desligue se o seu driver tiver problemas com ela.", + [UI_MENU_ASTC] = "Decodificação de texturas ASTC", + [UI_MENU_ASTC_DESC] = "Onde as texturas comprimidas em ASTC são decodificadas.", + [UI_MENU_ASTC_AUTO] = "Automático", [UI_MENU_ASTC_GPU] = "Shader da GPU", [UI_MENU_ASTC_NATIVE] = "Nativo", + [UI_MENU_ASTC_CPU] = "CPU", + [UI_MENU_MEMORY] = "Modo de memória da GPU", + [UI_MENU_MEMORY_DESC] = "Como a memória do jogo é compartilhada com a GPU.", + [UI_MENU_MEMORY_AUTO] = "Automático", [UI_MENU_MEMORY_IMPORT] = "Importar", [UI_MENU_MEMORY_MIRROR] = "Espelhar", + [UI_MENU_MEMORY_VERIFY] = "Verificar", + [UI_MENU_TEX_ALIAS] = "Aliasing de texturas", [UI_MENU_TEX_ALIAS_DESC] = "Uma textura nova criada sobre a memória de uma textura viva começa com esse conteúdo em vez de vazia.", + [UI_MENU_TEX_VRAM_PRESSURE] = "Limite de memória de texturas", [UI_MENU_TEX_VRAM_PRESSURE_DESC] = "Porcentagem da memória de vídeo acima da qual as texturas liberadas pelo jogo são descartadas (voltam do armazenamento quando usadas de novo). 0 mantém todas.", + [UI_MENU_ASTC_BC] = "Comprimir ASTC em BC3", [UI_MENU_ASTC_BC_DESC] = "Com o decodificador da GPU: recodifica as texturas ASTC decodificadas em BC3, que ocupa um quarto da memória de vídeo. Para GPUs com 4 GB ou menos; as texturas ficam um pouco mais quadriculadas.", + [UI_MENU_LOD_GUARD] = "Proteção de LOD", [UI_MENU_LOD_GUARD_DESC] = "Evita que objetos pisquem no lugar errado ou que o plano distante fique achatado por um quadro, esperando o jogo terminar de reescrever os dados de nível de detalhe antes que a GPU os leia.", + [UI_MENU_FIX_C0] = "Correção do buffer de constantes", + [UI_MENU_FIX_C0_DESC] = "Preenche o banco de constantes c0 reservado ao driver (tamanhos de armazenamento, tamanho do dispatch, tamanho do ponto, instância base) em vez de ler zeros.", + [UI_MENU_FIX_ZERO] = "Zerar memória nova da GPU", + [UI_MENU_FIX_ZERO_DESC] = "Novos pools de memória da GPU começam zerados, como a memória do Switch.", + [UI_MENU_BIND_SKIP] = "Pular bindings repetidos", + [UI_MENU_BIND_SKIP_DESC] = "Otimização: pula bindings que não mudaram.", + [UI_MENU_SHADER_MEMO] = "Memória de shaders", [UI_MENU_SHADER_MEMO_DESC] = "Otimização: lembra as buscas de shaders.", + [UI_MENU_PIPE_MEMO] = "Memória de pipeline", [UI_MENU_PIPE_MEMO_DESC] = "Otimização: reaproveita o pipeline do desenho anterior quando o estado se repete.", + [UI_MENU_TEX_MEMO] = "Memória de bindings de textura", [UI_MENU_TEX_MEMO_DESC] = "Otimização: lembra os descritores de textura entre desenhos.", + [UI_MENU_DESC_TEMPLATE] = "Templates de descritores", + [UI_MENU_DESC_TEMPLATE_DESC] = "Otimização: atualiza os descritores em lote.", + [UI_MENU_PUSH_SKIP] = "Pular push constants repetidas", + [UI_MENU_PUSH_SKIP_DESC] = "Otimização: pula push constants que não mudaram.", + [UI_MENU_SPLIT_DRAWS] = "Envio antecipado à GPU", + [UI_MENU_SPLIT_DRAWS_DESC] = "Envia o trabalho da GPU em partes a cada N desenhos entre passes, para a GPU começar mais cedo; 0 desliga.", + [UI_MENU_VK_VALIDATION] = "Camada de validação", + [UI_MENU_VK_VALIDATION_DESC] = "Verifica cada chamada Vulkan e deixa o jogo muito mais lento.", + [UI_MENU_VK_VALIDATION_MISSING] = "A camada de validação não está instalada.", + [UI_MENU_VK_DYN_VERTEX] = "Estado dinâmico de vértices", + [UI_MENU_VK_DYN_VERTEX_DESC] = "Força a entrada dinâmica de vértices ligada ou desligada; o padrão depende da GPU.", + [UI_MENU_VK_SUBGROUP_PIN] = "Fixar tamanho do subgrupo", + [UI_MENU_VK_SUBGROUP_PIN_DESC] = "Fixa o tamanho do subgrupo dos shaders.", + [UI_MENU_TRACE] = "Registro de desempenho", [UI_MENU_TRACE_DESC] = "Grava os tempos de quadro num arquivo.", + [UI_MENU_FLIGHT] = "Caixa-preta", + [UI_MENU_FLIGHT_DESC] = "Guarda um histórico curto e o salva quando um quadro trava.", + [UI_MENU_FLIGHT_SPIKE_MS] = "Limite de travamento (ms)", + [UI_MENU_FLIGHT_SPIKE_MS_DESC] = "Tempo de quadro que conta como travamento.", + [UI_MENU_INPUT_RECORD] = "Gravação de comandos", + [UI_MENU_INPUT_RECORD_DESC] = "Grava os seus comandos num arquivo para relatórios de bug.", + [UI_MENU_OPEN_LOG] = "Abrir pasta de logs", [UI_MENU_OPEN_LOG_DESC] = "Mostra a pasta com os arquivos de log.", + [UI_MENU_COPY_INFO] = "Copiar informações do sistema", + [UI_MENU_COPY_INFO_DESC] = "Copia GPU, driver, CPU, RAM e as configurações alteradas para a área de transferência.", + [UI_MENU_COPY_INFO_DONE] = "Copiado", [UI_MENU_ACTION_FAILED] = "não funcionou", + [UI_MENU_RESET] = "Restaurar todas as configurações", [UI_MENU_RESET_DESC] = "Vale para todas as abas.", + [UI_MENU_RESET_CONFIRM] = "Restaurar todas as configurações para o padrão?", [UI_MENU_RESET_YES] = "Restaurar", + [UI_MENU_RESET_NO] = "Cancelar", + + [UI_MENU_OV_FPS] = "%.0f FPS", [UI_MENU_OV_FRAME_MS] = "%.1f ms", [UI_MENU_OV_GAME_PCT] = "jogo %.0f%%", + [UI_MENU_OV_MAX_MS] = "máx. %.1f ms", + [UI_MENU_OV_GPU] = "GPU", [UI_MENU_OV_CPU] = "CPU", [UI_MENU_OV_RAM] = "RAM", [UI_MENU_OV_VRAM] = "VRAM", + [UI_MENU_OV_TEMP] = "Temperatura", [UI_MENU_OV_POWER] = "Consumo", [UI_MENU_OV_CLOCK] = "Frequência", + [UI_MENU_OV_NONE] = "-", + [UI_MENU_OV_REPLAY] = "Preparo de quadro da GPU", [UI_MENU_OV_GPU_TIME] = "GPU ocupada por quadro", + [UI_MENU_OV_PIPE_WAIT] = "Esperas de pipeline", + [UI_MENU_OV_SHADER_WAIT] = "Esperas de shader", [UI_MENU_OV_TEX_UPLOADS] = "Envios de textura", + [UI_MENU_OV_FMT_PCT] = "%.0f%%", [UI_MENU_OV_FMT_TEMP] = "%.0f °C", [UI_MENU_OV_FMT_POWER] = "%.0f W", + [UI_MENU_OV_FMT_MHZ] = "%.0f MHz", [UI_MENU_OV_FMT_GB] = "%.1f GB", [UI_MENU_OV_FMT_GB_OF] = "/ %.1f GB", + [UI_MENU_OV_GAME_GB] = "jogo %.1f GB", [UI_MENU_OV_FMT_MS] = "%.2f ms", [UI_MENU_OV_PER_FRAME] = "%.1f por quadro", + [UI_MENU_OV_WINDOW] = "Janela", [UI_MENU_OV_OUTPUT] = "Imagem do jogo", [UI_MENU_OV_SCENE] = "Cena 3D", + [UI_MENU_OV_SCALING] = "Escala", [UI_MENU_OV_LIMIT] = "Limite de quadros", [UI_MENU_OV_PRESENT] = "Apresentação", + [UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u, %.0f%%", + [UI_MENU_OV_FMT_FSR] = "AMD FSR 1, nitidez %d%%", [UI_MENU_OV_SCALE_NONE] = "nenhuma (1:1)", + [UI_MENU_OV_SCALE_BILINEAR] = "bilinear", +}; + #define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)} SWKBD_ONLY(text_ja, "文字入力", "名前を入力してください", "ウマ", "OK", "キャンセル", "コントローラー: A = OK、B = キャンセル"); SWKBD_ONLY(text_fr, "Saisie de texte", "Entrez un nom", "Cheval", "OK", "Annuler", "Manette : A = OK, B = Annuler"); @@ -512,12 +759,12 @@ SWKBD_ONLY(text_ko, "문자 입력", "이름을 입력하세요", "말", "확인 static const Row rows[] = { {"en", text_en}, {"ja", text_ja}, {"fr", text_fr}, {"de", text_de}, {"it", text_it}, {"es", text_es}, {"nl", text_nl}, {"pt", text_pt}, {"ru", text_ru}, {"zh-Hans", text_zh_hans}, {"zh-Hant", text_zh_hant}, - {"ko", text_ko}, + {"ko", text_ko}, {"pt-BR", text_pt_br}, }; const char *ui_text_lang(const char *code) { static const struct { const char *code, *lang; } map[] = { - {"en-US", "en"}, {"en-GB", "en"}, {"fr-CA", "fr"}, {"es-419", "es"}, {"pt-BR", "pt"}, + {"en-US", "en"}, {"en-GB", "en"}, {"fr-CA", "fr"}, {"es-419", "es"}, {"zh-CN", "zh-Hans"}, {"zh-TW", "zh-Hant"}, }; for (size_t i = 0; i < sizeof map / sizeof *map; i++) @@ -543,13 +790,16 @@ const char *ui_text_in(const char *lang, UiTextId id) { const char *ui_text(UiTextId id) { return ui_text_in(ui_text_lang(ov_language()), id); } -// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG "ru" or "en"; anything else (unset included) -// follows the system UI language: Russian for "ru", "ru-RU", ..., else English. +// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG "ru", "pt-BR" or "en"; anything else (unset +// included) follows the system UI language: Russian for "ru", "ru-RU", ..., Brazilian Portuguese for "pt-BR", else +// English. static const char *resolve_menu_lang(void) { const char *v = cfg_value("TOTK_MENU_LANG"); if (v && !strcmp(v, "ru")) return "ru"; + if (v && !strcmp(v, "pt-BR")) return "pt-BR"; if (v && !strcmp(v, "en")) return "en"; const char *sys = plat_ui_language(); + if (sys && !strcmp(sys, "pt-BR")) return "pt-BR"; return sys && (!strcmp(sys, "ru") || !strncmp(sys, "ru-", 3)) ? "ru" : "en"; } diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 13a328b6..89e3544d 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -11,7 +11,8 @@ typedef enum { UI_SWKBD_CANCEL, UI_SWKBD_PAD_HINT, // how a controller answers - // Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English and Russian texts. + // Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian and Brazilian Portuguese + // texts. UI_MENU_FIRST, UI_MENU_TITLE = UI_MENU_FIRST, UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, @@ -98,7 +99,7 @@ typedef enum { // Language names, each in its own language and the same in every row (game language and menu language lists) UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_DE, UI_MENU_LANGNAME_IT, UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS, - UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO, + UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO, UI_MENU_LANGNAME_PT_BR, // Advanced UI_MENU_ADV_WARNING, @@ -166,13 +167,14 @@ typedef enum { // UTF-8 text for id in the language of ov_language(); English when the catalog has no row for that language. const char *ui_text(UiTextId id); // The same for an explicit catalog language ("en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", -// "zh-Hant", "ko"); an empty entry gives the English text. +// "zh-Hant", "ko", "pt-BR"); an empty entry gives the English text. const char *ui_text_in(const char *lang, UiTextId id); // 1 when the row of lang has its own text for id (no fallback to English), for the probe. int ui_text_defined(const char *lang, UiTextId id); // The catalog language for a Switch language code ("en-GB" -> "en", "zh-CN" -> "zh-Hans", ...). const char *ui_text_lang(const char *switch_code); -// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en" / "ru"); unset, Russian when the -// system UI language is Russian, else English. Follows a live change of the setting. +// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en" / "ru" / "pt-BR"); unset, Russian +// or Brazilian Portuguese when the system UI language is one of them, else English. Follows a live change of the +// setting. const char *menu_text(UiTextId id); diff --git a/totk.ini.example b/totk.ini.example index aba2432d..b882b808 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -134,8 +134,8 @@ # lang = en-US # System mode reported to the game: docked or handheld. # operation_mode = docked -# Language of the settings menu and the overlay: en or ru. Default: the Windows display language, English if it is -# neither. +# Language of the settings menu and the overlay: en, ru or pt-BR. Default: the Windows display language, English if +# it is none of them. # menu_lang = en [audio] From 655253444a2b0b3618f28914a4afc9268167988c Mon Sep 17 00:00:00 2001 From: Lucas-blip-png <177052392+Lucas-blip-png@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:52:15 -0400 Subject: [PATCH 03/22] Shorten the pt-BR label of the pipeline skip row so its value fits beside it --- runtime/ui_text.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 948902e9..293eb18d 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -662,7 +662,7 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_PIPE_WAIT] = "Tratamento de desenhos em espera", [UI_MENU_PIPE_WAIT_DESC] = "Padrão mantém o agendamento atual, com um worker reservado para desenhos em espera; Antigo (draw) usa o agendamento anterior.", [UI_MENU_PIPE_WAIT_DEFAULT] = "Padrão", [UI_MENU_PIPE_WAIT_DRAW] = "Antigo (draw)", - [UI_MENU_PIPE_SKIP] = "Desenhos pulados enquanto um pipeline é montado", + [UI_MENU_PIPE_SKIP] = "Desenhos pulados ao montar pipeline", [UI_MENU_PIPE_SKIP_DESC] = "Quais desenhos são descartados em vez de esperar pelo seu pipeline.", [UI_MENU_PIPE_SKIP_STRICT] = "Estrito", [UI_MENU_PIPE_SKIP_ANY] = "Qualquer", [UI_MENU_PIPE_SKIP_FULLSCREEN] = "Passes de tela cheia", From f7d563db05eefcfc12afeb12d7490ac60dd89051 Mon Sep 17 00:00:00 2001 From: Deon Fouche Date: Sat, 31 Oct 2026 18:55:39 +1000 Subject: [PATCH 04/22] Draw Xbox button icons into the prompts overlay with make_romfs_patches.py --prompts tools/button_icons.py, adapted from MacNativeGames' make_button_icons.py, draws LB, RB, LT, RT, Menu, View and a d-pad cross into the button font of every font archive and into the button guide's L and ZL images, with the letters cut out in the game's own text fonts, and raises the resource size table for the archives that grow. --prompts xbox swaps the face buttons as --xbox-prompts did (now its older name); --prompts xbox-label keeps their letters for the xbox and auto pad layouts. The plain overlay is unchanged. tests/romfs_prompts_test.py runs both on a RomFS it builds itself. Co-Authored-By: Claude Opus 5.5 --- THIRD_PARTY_NOTICES.md | 3 +- tests/romfs_prompts_test.py | 537 +++++++++++++++++++++++++++++++ tools/button_icons.py | 319 ++++++++++++++++++ tools/make_romfs_patches.py | 233 +++++--------- tools/requirements-installer.txt | 2 + tools/requirements-py314.txt | 1 + 6 files changed, 944 insertions(+), 151 deletions(-) create mode 100644 tests/romfs_prompts_test.py create mode 100644 tools/button_icons.py diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 2d52b952..0a074358 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -11,6 +11,7 @@ Code copied or adapted from another project is listed here with its source, the | MacNativeGames TotK frame-rate patches: 60 fps present-interval controller, real-time frame step and its present sampling, hair and cloth clock, trampoline slow-motion check (instruction words and 1.2.1 sites), player position chain; quick-menu capture background RomFS overlay | https://github.com/ly05010419/MacNativeGames @ `ebe621de99bfc48f3c42f2d2aa73e04fbcc6eae2` (`games/totk/runtime/game_patches.c`, `game_version.h`, `world_survey.c`, `games/totk/scripts/make_romfs_patches.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/frame_rate.c`, `recomp/patches-v121.txt`, `tools/make_romfs_patches.py` | | MacNativeGames TotK 1.4.3 fade fix: the four distance / LOD and pre-actor fade sites, their instruction words and the floor of the fade step at 1 | https://github.com/ly05010419/MacNativeGames @ `3e9e7f67fdfdd3404134dcfa0f24969a9425a33f` (`games/totk/runtime/game_patches_v143.c` patch_fade_increment), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v143.txt` (set fade; the floor without flags, clz >> 5, as in pull request #78) | | MacNativeGames TotK aspect ratio: the camera and viewport sites that hand the perspective projection its aspect ratio, and the UI layout edits for a canvas wider than 16:9 | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/runtime/aspect_patch.h`, `aspect_math.h`, `game_patches_v143.c`, `games/totk/scripts/ultrawide_layout.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v143.txt` (set aspect), `tools/ultrawide_layout.py`, `tools/make_romfs_patches.py` (--aspect) | +| MacNativeGames TotK button icons: the Xbox controller's shoulder buttons, triggers, Menu, View and d-pad drawn with letters from the game's own text fonts, the .bfotf key, the button guide's images and their block-linear layout, the resource size table raised for the archives that grew | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/scripts/make_button_icons.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/button_icons.py`, `tools/make_romfs_patches.py` (--prompts) | | TOTK-Ultrawide, the community mod for emulators: the list of UI panes the ultrawide layout edits and the distances they move (data only, no code copied; the edit code is our own, and MacNativeGames' `ultrawide_layout.py` in the row above already carries the same values). The mod's repository URL and licence version are not recorded in this repository | TOTK-Ultrawide (community mod; URL not recorded here) | GPL (version not recorded here) | `tools/ultrawide_layout.py` (`KEEP_ROOT`, `edits`, `anim_edits`) | | MacNativeGames TotK virtual-core preemption: asynchronous preemption of an owner in top-level game code, priority inheritance through guest mutexes, the SDK's preemption-disable protocol (TLR+0x100/+0x102, SVC 0x36), the core-wait diagnostics | https://github.com/ly05010419/MacNativeGames @ `33e8fa83052ea1ae09a3583137008e9797e12950` (`games/totk/runtime/threads.c`, commits 8bf0893 and 19730cd), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/kernel.c` (SuspendThread and a register-saving stub replace SIGUSR2), `runtime/hostfn.c`, `runtime/svc.c` (host depth) | | MacNativeGames RomFS index builder (`TOTKRFS1` layout) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/scripts/prepare_romfs_backend.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/romfs_index.py` | @@ -65,7 +66,7 @@ These tools run on the developer's or player's machine during the build. They ar | Component | Source | License | Where in the release | |---|---|---|---| | CPython 3.14.9 embeddable package, with `tkinter` and Tcl/Tk 9.0.4 taken from the python.org 3.14.9 installer's component MSI (unpacked, never run); includes `vcruntime140*.dll` (Microsoft, redistributable with Python), OpenSSL, libffi, SQLite, zlib, libtommath | https://www.python.org/downloads/release/python-3149/ | PSF-2.0 (Tcl/Tk: Tcl/Tk licence, BSD-style) | `python/` | -| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, cryptography 50.0.2 (with its bundled OpenSSL), cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | BSD-3-Clause; lz4 BSD-3-Clause; cryptography Apache-2.0 OR BSD-3-Clause; cffi MIT; pycparser BSD-3-Clause | `python/Lib/site-packages/` | +| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, cryptography 50.0.2 (with its bundled OpenSSL), fontTools 4.68.0, cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | BSD-3-Clause; lz4 BSD-3-Clause; cryptography Apache-2.0 OR BSD-3-Clause; fontTools MIT; cffi MIT; pycparser BSD-3-Clause | `python/Lib/site-packages/` | | llvm-mingw 20261020 (LLVM/Clang/LLD 23, mingw-w64, libc++, libunwind, compiler-rt), x86_64 subset | https://github.com/mstorsjo/llvm-mingw/releases/tag/20261020 | Apache-2.0 with LLVM exception; mingw-w64 ZPL-2.1/BSD/public domain; libc++ and libunwind Apache-2.0 with LLVM exception and MIT/UIUC; winpthreads MIT | `llvm/` | | SDL 3.4.18 upstream Windows release (`SDL3.dll`) and mingw development package (headers, `libSDL3.dll.a`) | https://github.com/libsdl-org/SDL/releases/tag/release-3.4.18 | zlib | `bin/SDL3.dll`, `runtime/deps/` | | libopus 1.6.1 (MSYS2 `mingw-w64-ucrt-x86_64-opus` 1.6.1-2; `libopus-0.dll` imports only KERNEL32 and the UCRT api-ms-win-crt DLLs), headers and import library | https://repo.msys2.org/mingw/ucrt64/ | BSD-3-Clause | `bin/libopus-0.dll`, `runtime/deps/` | diff --git a/tests/romfs_prompts_test.py b/tests/romfs_prompts_test.py new file mode 100644 index 00000000..e68b89bc --- /dev/null +++ b/tests/romfs_prompts_test.py @@ -0,0 +1,537 @@ +"""tools/make_romfs_patches.py --prompts and tools/button_icons.py on a RomFS made here, with no game files: each prompt +names the label of the Xbox button that the pad layout presses, the shoulder buttons, triggers, Plus, Minus and the +d-pad are drawn as on an Xbox controller, the resource size table grows with the fonts, every other file and member +stays byte for byte, the same input gives the same output, and a RomFS the tool does not recognise fails before it +writes anything. Both game versions: 1.2.1 (Common.Product.110, 72x72 button guide images) and 1.4.3 +(Common.Product.140, 108x108). + +Run: .venv-py314\\Scripts\\python tests\\romfs_prompts_test.py +""" +import compression.zstd as zstd +import hashlib +import importlib.util +import io +import json +import random +import struct +import subprocess +import sys +import tempfile +import unittest +import zlib +from pathlib import Path + +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.recordingPen import RecordingPen +from fontTools.pens.t2CharStringPen import T2CharStringPen +from fontTools.ttLib import TTFont + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / 'tools' / 'make_romfs_patches.py' +spec = importlib.util.spec_from_file_location('button_icons', ROOT / 'tools' / 'button_icons.py') +icons = importlib.util.module_from_spec(spec) +spec.loader.exec_module(icons) + +# The face button each Switch button is in a pad layout (docs/controls.md, runtime/input_map.c), the label an Xbox pad +# prints on it, and the layout each overlay is made for (runtime/input_map.c input_prompts_folder). +POSITION = {'nintendo': {'A': 'east', 'B': 'south', 'X': 'north', 'Y': 'west'}, + 'xbox': {'A': 'south', 'B': 'east', 'X': 'west', 'Y': 'north'}} +XBOX_LABEL = {'south': 'A', 'east': 'B', 'west': 'X', 'north': 'Y'} +STYLE_LAYOUT = {'xbox': 'nintendo', 'xbox-label': 'xbox'} +FACE = {'A': 0xE040, 'B': 0xE041, 'X': 0xE042, 'Y': 0xE043} +# The glyphs drawn as Xbox icons, with their advance: LB RB LT RT, Menu and View, the d-pad. +DRAWN = {0xE044: 820, 0xE045: 820, 0xE046: 760, 0xE047: 760, 0xE04B: 640, 0xE04C: 640, 0xE049: 640, + **{cp: 640 for cp in range(0xE060, 0xE066)}} + +VERSIONS = {'v121': dict(common='110', size=72, newest=121), 'v143': dict(common='140', size=108, newest=143)} +DEFAULT_FONT, REGIONAL_FONT = 'Font/Font.Nin_NX_NVN.bfarc.zs', 'Font/Font_KRko.Nin_NX_NVN.bfarc.zs' +PANES = {'T_A_00': 'A', 'T_B_00': 'B', 'T_X_00': 'X', 'T_Y_00': 'Y', 'T_Name_00': 'A'} +MESSAGES = {**PANES, 'Greeting': 'Hello'} +R8_UNORM, BC1 = 0x201, 0x1a01 +IMAGE = 16384 # an R8 square up to 128 rows, two GOBs wide, block height 16: the size of the game's key images + + +# ---- the formats, written here from their layout so the tools' readers are checked against an independent writer +def sarc(members, align=0x80): + names, sfnt, name_at = list(members), b'', {} + for name in names: + name_at[name] = len(sfnt) // 4 + sfnt += name.encode() + b'\0' + sfnt += bytes(-len(sfnt) % 4) + head = 0x14 + 12 + 16 * len(names) + 8 + len(sfnt) + start = head + -head % align + data, nodes = b'', b'' + for name in names: + data += bytes(-len(data) % align) + nodes += struct.pack('<4I', zlib.crc32(name.encode()), 0x01000000 | name_at[name], len(data), len(data) + len(members[name])) + data += members[name] + out = (b'SARC' + struct.pack(' [(frame, value)] of a FLAN made by bflan().""" + pos, out = 0x14, {} + count, table = struct.unpack_from(' (format, size, image).""" + out = bytearray(0x30) + out[0:4], out[0x20:0x24] = b'BNTX', b'NX ' + table = len(out) + out += bytes(8 * len(textures)) + struct.pack_into(' (format, size, image) of a BNTX made by bntx().""" + count, table = struct.unpack_from(' text) after a pan1 section.""" + sections = b'pan1' + struct.pack(' text).""" + labels = b''.join(bytes([len(name)]) + name.encode() + struct.pack(' size).""" + crcs = sorted((zlib.crc32(path.removesuffix('.zs').encode()), size) for path, size in entries.items()) + return b'RESTBL' + struct.pack(' (advance, draw(pen)).""" + names = {cp: f'uni{cp:04X}' for cp in glyphs} + fb = FontBuilder(1000, isTTF=False) + fb.setupGlyphOrder(['.notdef'] + list(names.values())) + fb.setupCharacterMap(names) + charstrings, metrics = {}, {} + for gname, (advance, draw) in [('.notdef', (500, lambda pen: rect(pen, 50, 0, 450, 700)))] + \ + [(names[cp], glyphs[cp]) for cp in glyphs]: + pen = T2CharStringPen(advance, None) + draw(pen) + charstrings[gname], metrics[gname] = pen.getCharString(), (advance, 0) + fb.setupCFF(name, {'FullName': name}, charstrings, {}) + fb.setupHorizontalMetrics(metrics) + fb.setupHorizontalHeader(ascent=800, descent=-200) + fb.setupNameTable({'familyName': name, 'styleName': 'Regular'}) + fb.setupOS2(sTypoAscender=800, usWinAscent=800, usWinDescent=200) + fb.setupPost() + out = io.BytesIO() + fb.save(out) + return out.getvalue() + + +# A distinct rectangle and advance for every button glyph, so a glyph that moved is found by its outline. +BUTTONS = {cp: (600 + 4 * (cp - 0xE040), lambda pen, i=cp - 0xE040: rect(pen, 20 + 5 * i, 20, 300 + 5 * i, 400 + 3 * i)) + for cp in range(0xE040, 0xE069)} +LETTERS_1 = {ord('L'): (560, polygon((60, 0), (480, 0), (480, 100), (160, 100), (160, 700), (60, 700))), + ord('B'): (560, lambda pen: [rect(pen, 60, 0, 460, 700), rect(pen, 160, 100, 360, 300, True), + rect(pen, 160, 400, 360, 600, True)]), + ord('R'): (560, lambda pen: [rect(pen, 60, 0, 460, 700), rect(pen, 160, 400, 360, 600, True)])} +LETTERS_2 = {ord('T'): (560, polygon((230, 0), (330, 0), (330, 600), (520, 600), (520, 700), (40, 700), (40, 600), (230, 600)))} + + +class Romfs: + """A RomFS (romfs.bin, index.json) holding the files make_romfs_patches.py reads, the originals kept to compare.""" + + def __init__(self, folder, version, text_fonts=True, restbl_skips=(), l_format=R8_UNORM): + v, rnd = VERSIONS[version], random.Random(version) + words = [b'Layout', b'Pane', b'Font', b'Msg', b'Texture', b'Anim', b'Group', b'Text', b'Base', b'Key'] + samples = [b' '.join(rnd.choice(words) + str(rnd.randrange(999)).encode() for _ in range(rnd.randrange(20, 80))) + for _ in range(400)] + self.dictionary = zstd.train_dict(samples, 4096) + self.common = f'UI/LayoutArchive/Common.Product.{v["common"]}.Nin_NX_NVN.blarc.zs' + self.mals = [f'Mals/EUen.Product.{v["newest"]}.sarc.zs', f'Mals/USen.Product.{v["newest"]}.sarc.zs'] + self.old_mals = 'Mals/USen.Product.110.sarc.zs' + self.restbl = f'System/Resource/ResourceSizeTable.Product.{v["newest"]}.Nin_NX_NVN.rsizetable.zs' + self.old_restbl = 'System/Resource/ResourceSizeTable.Product.100.Nin_NX_NVN.rsizetable.zs' + size = v['size'] + images = {f'Nt_KeyTex{b}_00': (R8_UNORM, size, rnd.randbytes(IMAGE)) for b in 'ABXY'} + images.update({'Nt_KeyTexL_00^z': (l_format, size, rnd.randbytes(IMAGE)), + 'Nt_KeyTexZL_00': (R8_UNORM, size, rnd.randbytes(IMAGE)), + 'Nt_KeyTexLSt_00': (R8_UNORM, size, rnd.randbytes(IMAGE))}) + self.text_fonts = [bfotf(cff_font('Text1', LETTERS_1), 0x01020304), bfotf(cff_font('Text2', LETTERS_2), 0x0a0b0c0d)] + default = {'scft/External.bfotf': bfotf(cff_font('External', BUTTONS), 0x5a17c3e9), 'fnt/rest.bin': rnd.randbytes(700)} + if text_fonts: + default.update(zip(icons.TEXT_FONTS, self.text_fonts)) + mals = sarc({'LayoutMsg/DoCommand_00.msbt': msbt(MESSAGES), 'LayoutMsg/Other_00.msbt': msbt({'T_A_00': 'A'})}) + self.contents = { # RomFS path -> contents before compression + 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/Title_00.bflyt': bflyt({'N_Title_00': 'Z'}), + 'timg/__Combined.bntx': bntx(images)}), + DEFAULT_FONT: sarc(default), + # The same font under another key: drawn once, stored under each archive's own key. + REGIONAL_FONT: sarc({'scft/External.bfotf': bfotf(cff_font('External', BUTTONS), 0x77777777), + 'fnt/rest.bin': rnd.randbytes(500)}), + **{path: mals for path in self.mals + [self.old_mals]}, + } + sizes = {path: len(data) + 256 for path, data in self.contents.items() if path not in restbl_skips} + self.contents[self.restbl] = restbl({**sizes, **{f'Other/{i}.bin': 1000 + i for i in range(20)}}) + self.contents[self.old_restbl] = restbl({DEFAULT_FONT: 1}) + plain = (REGIONAL_FONT, self.restbl, self.old_restbl) # stored without a dictionary + self.files = {'Pack/ZsDic.pack.zs': zstd.compress(sarc({'zs.zsdic': self.dictionary.dict_content}))} + self.files.update({path: zstd.compress(data, zstd_dict=None if path in plain else self.dictionary) + for path, data in self.contents.items()}) + self.files['Other/file.bin'] = rnd.randbytes(100) + image, entries = bytearray(), [] + for path, data in self.files.items(): + image += bytes(-len(image) % 16) + entries.append(dict(path=path, offset=len(image), size=len(data))) + image += data + folder.mkdir(parents=True) + (folder / 'romfs.bin').write_bytes(image) + (folder / 'index.json').write_text(json.dumps(dict(status='pass', files=entries))) + self.folder, self.version = folder, version + + def run(self, out, *flags): + return subprocess.run([sys.executable, '-I', str(TOOL), '--version', self.version, '--romfs', str(self.folder), + '--out', str(out), *flags], capture_output=True, text=True, encoding='utf-8') + + def read(self, out, path): + """The overlay's file, decompressed.""" + raw = (out / path).read_bytes() + return zstd.decompress(raw, zstd_dict=self.dictionary if zstd.get_frame_info(raw).dictionary_id else None) + + +def font(blob): + return TTFont(io.BytesIO(unbfotf(blob))) + + +def glyph(f, cp): + """(outline, advance) of the glyph of code point cp.""" + name = f.getBestCmap()[cp] + pen = RecordingPen() + f.getGlyphSet()[name].draw(pen) + return pen.value, f['hmtx'][name][0] + + +def manifest(out): + return {line.split('\t')[0]: line.split('\t')[1:] for line in (out / 'manifest.tsv').read_text().splitlines() + if not line.startswith('#')} + + +class PromptsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory(prefix='totk-prompts-') + cls.base = Path(cls.tmp.name) + cls.romfs = {v: Romfs(cls.base / v / 'romfs', v) for v in VERSIONS} + cls.outs = {} + for v, romfs in cls.romfs.items(): + for style in ('plain', 'xbox', 'xbox-label'): + out = cls.base / v / style + proc = romfs.run(out, *(() if style == 'plain' else ('--prompts', style))) + assert proc.returncode == 0, proc.stderr + cls.outs[v, style] = (out, json.loads(proc.stdout.strip().splitlines()[-1])) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def each(self, styles=('xbox', 'xbox-label')): + """(RomFS, style, overlay folder, summary) of every run of these styles.""" + return [(self.romfs[v], style, out, summary) for (v, style), (out, summary) in self.outs.items() + if style in styles] + + def test_plain_overlay_has_only_the_frame_rate_patch(self): + for romfs, _, out, summary in self.each(('plain',)): + with self.subTest(version=romfs.version, style="plain"): + self.assertEqual(set(manifest(out)), {romfs.common}) + self.assertIsNone(summary['prompts']) + keys = visibility(sarc_files(romfs.read(out, romfs.common))['anim/ShortCutBG_00_In.bflan']) + self.assertEqual(keys['C_CaptureBG_00'], [(0.0, 0), (0.0, 1)]) + self.assertEqual(keys['N_Other_00'], [(0.0, 0), (1.0, 1)]) + + def test_face_buttons_name_the_xbox_label_of_the_button_pressed(self): + for romfs, style, out, _ in self.each(): + with self.subTest(version=romfs.version, style=style): + layout = STYLE_LAYOUT[style] + label = {b: XBOX_LABEL[POSITION[layout][b]] for b in FACE} # Switch button -> the label of its button + before, after = sarc_files(romfs.contents[romfs.common]), sarc_files(romfs.read(out, romfs.common)) + old, new = bntx_images(before['timg/__Combined.bntx']), bntx_images(after['timg/__Combined.bntx']) + panes, messages = pane_texts(after['blyt/DoCommand_00.bflyt']), {} + for path in romfs.mals if layout == 'nintendo' else []: + messages[path] = message_texts(sarc_files(romfs.read(out, path))['LayoutMsg/DoCommand_00.msbt']) + original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf']) + for path in (DEFAULT_FONT, REGIONAL_FONT): + drawn = font(sarc_files(romfs.read(out, path))['scft/External.bfotf']) + for b, cp in FACE.items(): + self.assertEqual(glyph(drawn, cp), glyph(original, FACE[label[b]]), f'{path}: glyph of {b}') + for b in FACE: + self.assertEqual(new[f'Nt_KeyTex{b}_00'], old[f'Nt_KeyTex{label[b]}_00'], f'action prompt image of {b}') + self.assertEqual(panes[f'T_{b}_00'], label[b], f'diamond letter of {b}') + for path, texts in messages.items(): + self.assertEqual(texts[f'T_{b}_00'], label[b], f'{path}: diamond message of {b}') + # Text that only looks like a letter pane, and every other message, stays. + self.assertEqual((panes['T_Name_00'], pane_texts(after['blyt/Title_00.bflyt'])), ('A', {'N_Title_00': 'Z'})) + for path, texts in messages.items(): + self.assertEqual((texts['T_Name_00'], texts['Greeting']), ('A', 'Hello')) + self.assertEqual(sarc_files(romfs.read(out, path))['LayoutMsg/Other_00.msbt'], msbt({'T_A_00': 'A'})) + + def test_other_buttons_are_drawn_as_xbox_icons(self): + for romfs, style, out, _ in self.each(): + with self.subTest(version=romfs.version, style=style): + original = font(sarc_files(romfs.contents[DEFAULT_FONT])['scft/External.bfotf']) + default = sarc_files(romfs.read(out, DEFAULT_FONT)) + drawn = font(default['scft/External.bfotf']) + for cp in range(0xE040, 0xE069): + outline, advance = glyph(drawn, cp) + if cp in DRAWN: + self.assertNotEqual(outline, glyph(original, cp)[0], f'U+{cp:04X} drawn') + self.assertEqual(advance, DRAWN[cp], f'U+{cp:04X} advance') + elif cp not in FACE.values(): + self.assertEqual((outline, advance), glyph(original, cp), f'U+{cp:04X} kept') + # The letters are holes in the key: LB is the key, L, and B with its two counters. + moves = sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE044)[0]) + self.assertEqual(moves, 5) + self.assertEqual(sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE047)[0]), 1 + 1 + 1 + 1) # RT: key, R + counter, T + self.assertEqual(sum(op == 'moveTo' for op, _ in glyph(drawn, 0xE060)[0]), 2) # d-pad up: cross, arrow + # The text fonts and the archives' other members stay byte for byte; both archives hold the same font. + before = sarc_files(romfs.contents[DEFAULT_FONT]) + self.assertEqual({k: v for k, v in default.items() if k != 'scft/External.bfotf'}, + {k: v for k, v in before.items() if k != 'scft/External.bfotf'}) + regional = sarc_files(romfs.read(out, REGIONAL_FONT)) + self.assertEqual(regional['fnt/rest.bin'], sarc_files(romfs.contents[REGIONAL_FONT])['fnt/rest.bin']) + self.assertEqual(unbfotf(regional['scft/External.bfotf']), unbfotf(default['scft/External.bfotf'])) + self.assertEqual(struct.unpack_from(' 0 and grown[REGIONAL_FONT] > 0, grown) + self.assertEqual(summary['prompts']['grown'], {p: g for p, g in grown.items() if g > 0}) + for crc, entry in original.items(): + paths = [p for p in grown if zlib.crc32(p.removesuffix('.zs').encode()) == crc and grown[p] > 0] + self.assertEqual(table[crc], entry + (grown[paths[0]] if paths else 0)) + self.assertEqual(set(table), set(original)) + + def test_manifest_lists_what_changed_with_both_hashes(self): + for romfs, style, out, _ in self.each(('plain', 'xbox', 'xbox-label')): + with self.subTest(version=romfs.version, style=style): + expect = {romfs.common} + if style != 'plain': + expect |= {DEFAULT_FONT, REGIONAL_FONT, romfs.restbl} | (set(romfs.mals) if style == 'xbox' else set()) + lines = manifest(out) + self.assertEqual(set(lines), expect) + for path, (size, sha, original) in lines.items(): + data = (out / path).read_bytes() + self.assertEqual((int(size), sha), (len(data), hashlib.sha256(data).hexdigest()), path) + self.assertEqual(original, hashlib.sha256(romfs.files[path]).hexdigest(), path) + + def test_same_input_same_output_and_the_older_flag(self): + romfs = self.romfs['v121'] + for flags in (('--prompts', 'xbox'), ('--xbox-prompts',)): + out = self.base / 'again' / '-'.join(flags) + proc = romfs.run(out, *flags) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual((out / 'manifest.tsv').read_bytes(), (self.outs['v121', 'xbox'][0] / 'manifest.tsv').read_bytes()) + + def test_unrecognised_romfs_fails_before_writing(self): + cases = {'no text fonts': (dict(text_fonts=False), icons.TEXT_FONTS[0]), + 'no size entry': (dict(restbl_skips=(REGIONAL_FONT,)), 'has no entry in the resource size table'), + 'compressed L image': (dict(l_format=BC1), 'Nt_KeyTexL_00: format')} + for i, (case, (options, message)) in enumerate(cases.items()): + with self.subTest(case): + romfs = Romfs(self.base / 'bad' / str(i) / 'romfs', 'v121', **options) + out = self.base / 'bad' / str(i) / 'out' + proc = romfs.run(out, '--prompts', 'xbox-label') + self.assertNotEqual(proc.returncode, 0) + self.assertIn(message, proc.stderr) + self.assertFalse(out.exists(), 'a failed run writes nothing') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/button_icons.py b/tools/button_icons.py new file mode 100644 index 00000000..c062080e --- /dev/null +++ b/tools/button_icons.py @@ -0,0 +1,319 @@ +# Adapted from MacNativeGames games/totk/scripts/make_button_icons.py @ 933b6a0 (MIT, Copyright (c) 2026 +# MacNativeGames contributors). +"""Xbox button icons for the game's prompts, drawn on the player's machine for tools/make_romfs_patches.py --prompts. +The outlines are our own shapes with letters cut out of them in the game's own text fonts: nothing of the game is in +the repository. + +Every prompt except the button guide in play is text in the button font, scft/External.bfotf of each +Font/Font*.Nin_NX_NVN.bfarc.zs: private-use code points from U+E040 (A, B, X, Y, then L, R, ZL, ZR, the d-pad, Plus and +Minus, the sticks). A .bfotf is an OpenType (CFF) font after an 8-byte header; from offset 4 on, every byte is XORed +with a 4-byte key, which the size in the header's second word gives away (bfotf_decode). redraw_font draws the shoulder +buttons, the triggers, Plus, Minus and the d-pad as an Xbox controller names them (LB RB, LT RT, Menu and View, a +cross), can swap the glyphs of the face buttons (A with B, X with Y), and has fontTools write the font again. The +archive then grows by a kilobyte or two, more than the game's resource size table allows it: grow_restbl raises those +entries (without it the game stops at start, MacNativeGames found). + +The button guide in play (bottom right) draws L and ZL from images of the common layout archive instead +(timg/__Combined.bntx, Nt_KeyTexL_00 and Nt_KeyTexZL_00): bntx_redraw paints the same icons into them, the size +unchanged. The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations). + +Needs fontTools (tools/requirements-installer.txt, tools/requirements-py314.txt). +""" +import io +import struct +import zlib + +from fontTools.pens.basePen import BasePen +from fontTools.pens.boundsPen import BoundsPen +from fontTools.pens.recordingPen import RecordingPen +from fontTools.pens.reverseContourPen import ReverseContourPen +from fontTools.pens.t2CharStringPen import T2CharStringPen +from fontTools.pens.transformPen import TransformPen +from fontTools.ttLib import TTFont + +FONT = 'scft/External.bfotf' +# The letters on the keys come from the text fonts of the default archive; the regional archives lack them. +TEXT_ARCHIVE = 'Font/Font.Nin_NX_NVN.bfarc.zs' +TEXT_FONTS = ('scft/ninP_RodinNTLG-B_DH_003_subset.bfotf', 'scft/nintendo_NTLG-DB_DH_002.bfotf') +# The button guide's images and the glyph each one shows. +HUD_TEXTURES = {'Nt_KeyTexL_00': 0xE044, 'Nt_KeyTexZL_00': 0xE046} + + +def xor(data, key): + """data with byte i XORed with key[i % 4].""" + pad = (key * (len(data) // 4 + 1))[:len(data)] + return (int.from_bytes(data, 'little') ^ int.from_bytes(pad, 'little')).to_bytes(len(data), 'little') + + +def bfotf_decode(blob): + """(OpenType font, key) of a .bfotf (the module docstring). The font fills the rest of the file.""" + key = xor(blob[4:8], struct.pack('>I', len(blob) - 8)) + otf = xor(blob[8:], key) + assert otf[:4] == b'OTTO', 'not a CFF OpenType font' + return otf, key + + +def bfotf_encode(otf, key, head): + """The .bfotf of otf: head (the original's first word) and the size, the rest XORed with key as bfotf_decode reads + it. The size field holds the whole font, so its length has to be a multiple of 4 (fontTools pads its tables).""" + assert len(otf) % 4 == 0, len(otf) + return head[:4] + xor(struct.pack('>I', len(otf)) + otf, key) + + +# ---- drawing, in units of the font's 1000-unit em; the round A/B/X/Y icons fill y 20..585 +Y0, Y1 = 20, 585 +CY, R = (Y0 + Y1) / 2, (Y1 - Y0) / 2 +K = 0.5523 # control point distance of a quarter circle drawn with one cubic curve, per unit of radius + + +class Glyphs: + """Outlines of letters from the game's own text fonts, drawn as holes in a shape.""" + def __init__(self, fonts): + self.fonts = fonts + + def outline(self, ch): + for font in self.fonts: + cmap = font.getBestCmap() + if ord(ch) in cmap: + glyphs = font.getGlyphSet(); g = glyphs[cmap[ord(ch)]] + rec = RecordingPen(); g.draw(rec); box = BoundsPen(glyphs); g.draw(box) + return rec, box.bounds, font['head'].unitsPerEm, g.width + raise KeyError(f'no text font has {ch!r}') + + def hole(self, pen, text, cx, cy, cap, max_width): + """text centred on (cx, cy), at most cap high and max_width wide, its contours reversed so they cut holes.""" + parts, x, ink = [], 0.0, [1e9, 1e9, -1e9, -1e9] + for ch in text: + rec, b, upm, advance = self.outline(ch); k = 1000 / upm + parts.append((rec, k, x)) + ink = [min(ink[0], x + b[0] * k), min(ink[1], b[1] * k), max(ink[2], x + b[2] * k), max(ink[3], b[3] * k)] + x += advance * k * 0.96 + width, height = ink[2] - ink[0], ink[3] - ink[1] + scale = min(cap / height, max_width / width) + ox, oy = cx - (ink[0] + width / 2) * scale, cy - (ink[1] + height / 2) * scale + reverse = ReverseContourPen(pen) + for rec, k, x in parts: + rec.replay(TransformPen(reverse, (scale * k, 0, 0, scale * k, ox + x * scale, oy))) + + +def text_glyphs(blobs): + """Glyphs over the text fonts in blobs (.bfotf files), the first that has a letter giving it.""" + return Glyphs([TTFont(io.BytesIO(bfotf_decode(blob)[0])) for blob in blobs]) + + +def circle(pen, cx, cy, r): + k = K * r + pen.moveTo((cx + r, cy)) + pen.curveTo((cx + r, cy + k), (cx + k, cy + r), (cx, cy + r)) + pen.curveTo((cx - k, cy + r), (cx - r, cy + k), (cx - r, cy)) + pen.curveTo((cx - r, cy - k), (cx - k, cy - r), (cx, cy - r)) + pen.curveTo((cx + k, cy - r), (cx + r, cy - k), (cx + r, cy)) + pen.closePath() + + +def rounded(pen, x0, y0, x1, y1, bottom, top=None): + """Counter-clockwise rounded rectangle (bottom and top corner radii).""" + top = bottom if top is None else top + kb, kt = K * bottom, K * top + pen.moveTo((x0 + bottom, y0)); pen.lineTo((x1 - bottom, y0)) + pen.curveTo((x1 - bottom + kb, y0), (x1, y0 + bottom - kb), (x1, y0 + bottom)); pen.lineTo((x1, y1 - top)) + pen.curveTo((x1, y1 - top + kt), (x1 - top + kt, y1), (x1 - top, y1)); pen.lineTo((x0 + top, y1)) + pen.curveTo((x0 + top - kt, y1), (x0, y1 - top + kt), (x0, y1 - top)); pen.lineTo((x0, y0 + bottom)) + pen.curveTo((x0, y0 + bottom - kb), (x0 + bottom - kb, y0), (x0 + bottom, y0)); pen.closePath() + + +def polygon(pen, points): + pen.moveTo(points[0]) + for p in points[1:]: + pen.lineTo(p) + pen.closePath() + + +def xbox_icons(g): + """Code point -> (advance, draw(pen)) for the buttons an Xbox controller names differently from a Switch: L R = LB + RB, ZL ZR = LT RT, Plus and Minus = Menu and View, the d-pad as a cross. g: Glyphs for the letters. The face + buttons keep the game's own glyphs (redraw_font swaps them for the Nintendo layout).""" + def bumper(label, advance=820): + def draw(pen): + rounded(pen, 40, Y0 + 70, advance - 40, Y1 - 70, 70, 150); g.hole(pen, label, advance / 2, CY, 230, advance - 200) + return advance, draw + + def trigger(label, advance=760): + def draw(pen): + rounded(pen, 60, Y0, advance - 60, Y1, 60, 230); g.hole(pen, label, advance / 2, CY - 20, 230, advance - 220) + return advance, draw + + def menu(advance=640): # three bars, as on the Menu button + def draw(pen): + circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen) + for dy in (-115, 0, 115): + rounded(reverse, advance / 2 - 150, CY + dy - 38, advance / 2 + 150, CY + dy + 38, 38) + return advance, draw + + def view(advance=640): # two overlapping windows, as on the View button + def draw(pen): + circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen); s = 150 + rounded(reverse, advance / 2 - s - 15, CY + 15, advance / 2 - 15, CY + s + 15, 16) + rounded(reverse, advance / 2 + 15, CY - s - 15, advance / 2 + s + 15, CY - 15, 16) + return advance, draw + + def dpad(*lit, advance=640): # a cross with an arrow cut into each direction the prompt means + def draw(pen): + cx, length, arm = advance / 2, R, R * 0.40 + polygon(pen, [(cx + length, CY - arm), (cx + length, CY + arm), (cx + arm, CY + arm), (cx + arm, CY + length), + (cx - arm, CY + length), (cx - arm, CY + arm), (cx - length, CY + arm), (cx - length, CY - arm), + (cx - arm, CY - arm), (cx - arm, CY - length), (cx + arm, CY - length), (cx + arm, CY - arm)]) + m, t, h = (length + arm) / 2, arm * 0.72, arm * 0.80 # arm centre, half base and height of the arrow + heads = {'up': [(cx - t, CY + m - h / 2), (cx, CY + m + h / 2), (cx + t, CY + m - h / 2)], + 'down': [(cx + t, CY - m + h / 2), (cx, CY - m - h / 2), (cx - t, CY - m + h / 2)], + 'left': [(cx - m + h / 2, CY - t), (cx - m - h / 2, CY), (cx - m + h / 2, CY + t)], + 'right': [(cx + m - h / 2, CY + t), (cx + m + h / 2, CY), (cx + m - h / 2, CY - t)]} + for d in lit: + polygon(pen, heads[d]) # already clockwise: a hole + return advance, draw + + return { + 0xE044: bumper('LB'), 0xE045: bumper('RB'), 0xE046: trigger('LT'), 0xE047: trigger('RT'), + 0xE04B: menu(), 0xE04C: view(), + 0xE049: dpad('up', 'down', 'left', 'right'), 0xE060: dpad('up'), 0xE061: dpad('down'), + 0xE062: dpad('left'), 0xE063: dpad('right'), 0xE064: dpad('up', 'down'), 0xE065: dpad('left', 'right'), + } + + +def redraw_font(otf, icons, swaps=()): + """The OpenType font otf with the glyphs of each (code point, code point) pair of swaps trading places (outlines and + horizontal metrics), then every code point of icons (code point -> (advance, draw)) drawn anew, written again by + fontTools. The timestamps stay, so the same input gives the same bytes.""" + font = TTFont(io.BytesIO(otf), recalcTimestamp=False) + assert font['head'].unitsPerEm == 1000, f'em of {font["head"].unitsPerEm} units, the drawings assume 1000' + cff = font['CFF '].cff + top = cff.topDictIndex[0] + assert not hasattr(top, 'ROS'), 'CID-keyed CFF' # its glyphs can use different private dictionaries + charstrings, private, hmtx, cmap = top.CharStrings, top.Private, font['hmtx'], font.getBestCmap() + nominal = getattr(private, 'nominalWidthX', 0) + for a, b in swaps: + ga, gb = cmap[a], cmap[b] + outline_a, outline_b = charstrings[ga], charstrings[gb] + charstrings[ga], charstrings[gb] = outline_b, outline_a + hmtx[ga], hmtx[gb] = hmtx[gb], hmtx[ga] + for cp, (advance, draw) in icons.items(): + pen = T2CharStringPen(advance - nominal, None); draw(pen) # the width operand is relative to nominalWidthX + charstrings[cmap[cp]] = pen.getCharString(private=private, globalSubrs=cff.GlobalSubrs) + glyphs = font.getGlyphSet() + for cp, (advance, _) in icons.items(): + box = BoundsPen(glyphs); glyphs[cmap[cp]].draw(box) + hmtx[cmap[cp]] = (advance, int(round(box.bounds[0]))) + out = io.BytesIO(); font.save(out) + return out.getvalue() + + +# ---- the button guide's images: square R8_UNORM masks (white key, black letter), one mip, block-linear, 72x72 up to +# 1.2.1 and 108x108 in 1.4.3. Each is drawn from the icon of the same Switch button, fitted into the square. +R8_UNORM, HUD_MARGIN, SUPERSAMPLE = 0x201, 4, 4 + + +def gob_offset(x, y, width_gobs, block_height): + """Byte offset of (x, y) in a Tegra block-linear surface of 1 byte per pixel (GOBs of 64 bytes x 8 rows).""" + return ((y // (8 * block_height)) * 512 * block_height * width_gobs + (x // 64) * 512 * block_height + + ((y % (8 * block_height)) // 8) * 512 + ((x % 64) // 32) * 256 + ((y % 8) // 2) * 64 + + ((x % 32) // 16) * 32 + (y % 2) * 16 + (x % 16)) + + +class PolygonPen(BasePen): + """Outlines flattened to closed polygons.""" + def __init__(self): + super().__init__(None); self.polygons = [] + + def _moveTo(self, pt): + self.polygons.append([pt]) + + def _lineTo(self, pt): + self.polygons[-1].append(pt) + + def _curveToOne(self, pt1, pt2, pt3): + p0 = self.polygons[-1][-1] + for i in range(1, 17): + t = i / 16; u = 1 - t + self.polygons[-1].append(tuple(u ** 3 * p0[k] + 3 * u * u * t * pt1[k] + 3 * u * t * t * pt2[k] + t ** 3 * pt3[k] + for k in (0, 1))) + + def _qCurveToOne(self, pt1, pt2): + p0 = self.polygons[-1][-1] + for i in range(1, 17): + t = i / 16; u = 1 - t + self.polygons[-1].append(tuple(u * u * p0[k] + 2 * u * t * pt1[k] + t * t * pt2[k] for k in (0, 1))) + + +def rasterize(draw, size): + """A size x size coverage mask (0..255, rows top down) of draw's outline, fitted into the square, nonzero winding.""" + rec = RecordingPen(); draw(rec) + box = BoundsPen(None); rec.replay(box); x0, y0, x1, y1 = box.bounds + inner = size - 2 * HUD_MARGIN; scale = inner / max(x1 - x0, y1 - y0) + ox = HUD_MARGIN + (inner - (x1 - x0) * scale) / 2 - x0 * scale + oy = HUD_MARGIN + (inner - (y1 - y0) * scale) / 2 - y0 * scale + flat = PolygonPen(); rec.replay(TransformPen(flat, (scale, 0, 0, -scale, ox, size - oy))) # font y up -> rows down + edges = [(a, b) for poly in flat.polygons for a, b in zip(poly, poly[1:] + poly[:1]) if a[1] != b[1]] + n = size * SUPERSAMPLE; cover = [0] * (size * size) + for row in range(n): + y = (row + 0.5) / SUPERSAMPLE + crossings = sorted((a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]), 1 if b[1] > a[1] else -1) + for a, b in edges if min(a[1], b[1]) <= y < max(a[1], b[1])) + winding, start = 0, None + for x, d in crossings: + if winding == 0: + start = x + winding += d + if winding == 0: + for col in range(max(0, round(start * SUPERSAMPLE)), min(n, round(x * SUPERSAMPLE))): + cover[(row // SUPERSAMPLE) * size + col // SUPERSAMPLE] += 1 + return bytes(min(255, c * 255 // (SUPERSAMPLE * SUPERSAMPLE)) for c in cover) + + +def bntx_redraw(data, base, textures, icons): + """Paint the icon of each texture of textures (name without the ^ suffix -> code point; icons: code point -> + (advance, draw)) over its image in the BNTX at data[base:] (a bytearray), in place. Returns the names painted.""" + assert data[base:base + 4] == b'BNTX' and data[base + 0x20:base + 0x24] == b'NX ' + count, table = struct.unpack_from('.Nin_NX_NVN.rsizetable.zs, a RESTBL whose +# entries are keyed by the CRC32 of the RomFS path without .zs. The game sizes the buffer it loads a file into from its +# entry, so an archive that grew needs its entry raised by as much. +def restbl_offsets(table): + """CRC32 of a path -> offset of its size in the RESTBL table.""" + assert table[:6] == b'RESTBL', 'not a RESTBL' + count = struct.unpack_from(' bytes it grew) raised by that much.""" + at, out = restbl_offsets(table), bytearray(table) + for path, extra in growth.items(): + h = zlib.crc32(path.removesuffix('.zs').encode()) + assert h in at, f'{path} has no entry in the resource size table' + struct.pack_into('x 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-v143.txt). ---xbox-prompts: the same overlay with the A and B, and the X and Y button prompts swapped, for pad_layout = xbox_prompts -(runtime/romfs.c overlay_init loads romfs-patches-xbox in place of romfs-patches). That layout plays an Xbox pad by -position, as nintendo does: the button that does Switch A is labelled B, and the prompts then name the label. Built from -the game's own images and glyphs, nothing added: -- the action prompt (blyt/DoCommand_00.bflyt) draws the letter images Nt_KeyTexA/B/X/Y_00 of timg/__Combined.bntx in - the Common archive: their image data is swapped (same format, size and tiling). Around it, a diamond names the - other face buttons with one-letter text panes (T_B_00, T_X_00, ...). The game fills them from the messages of the - same name in LayoutMsg/DoCommand_00.msbt of each Mals/ archive, over the layout's own text: both have - their letters swapped the same way. The diamond's shape (Nt_KeyBtnSubBase*) shows the button's position, which - stays right. -- every other prompt is text: the button glyphs U+E040 A, U+E041 B, U+E042 X, U+E043 Y of scft/External.bfotf, the - same font in each Font/Font*.Nin_NX_NVN.bfarc.zs. Their CFF outlines and horizontal metrics are swapped. +--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 +from the game's own files on the player's machine, nothing added (tools/button_icons.py, which needs fontTools): +- both: L, R, ZL, ZR, Plus, Minus and the d-pad become LB, RB, LT, RT, Menu, View and a cross in the button font + (scft/External.bfotf, the same font in each Font/Font*.Nin_NX_NVN.bfarc.zs), and L and ZL in the button guide's images + (Nt_KeyTexL_00 and Nt_KeyTexZL_00 of timg/__Combined.bntx in the Common archive). The fonts grow, so the overlay also + carries the resource size table (System/Resource/ResourceSizeTable.Product....rsizetable.zs) with their entries + raised by as much. +- xbox, for pad_layout = nintendo. That layout plays an Xbox pad by position: the button that does Switch A is + labelled B, so the face buttons' prompts are swapped to name the labels, A with B and X with Y: + - the action prompt (blyt/DoCommand_00.bflyt) draws the letter images Nt_KeyTexA/B/X/Y_00 of timg/__Combined.bntx in + the Common archive: their image data is swapped (same format, size and tiling). Around it, a diamond names the + other face buttons with one-letter text panes (T_B_00, T_X_00, ...). The game fills them from the messages of the + same name in LayoutMsg/DoCommand_00.msbt of each Mals/ archive, over the layout's own text: both have + their letters swapped the same way. The diamond's shape (Nt_KeyBtnSubBase*) shows the button's position, which + stays right. + - every other prompt: the glyphs U+E040 A, U+E041 B, U+E042 X, U+E043 Y of the button font trade places. +- xbox-label, for pad_layout = xbox and auto. Those layouts put Switch A on the button labelled A (auto picks xbox for + every pad not labelled the Nintendo way), so the face buttons keep their letters; the action prompt's diamond keeps + the Switch positions (A on the right). +--xbox-prompts is the older name of --prompts xbox. Input: build/extracted//romfs (romfs.bin and index.json, verified by tools/extract.py). Output: -build//romfs-patches/ by default (romfs-patches-xbox with --xbox-prompts), and /manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314. +build//romfs-patches/ by default (romfs-patches-