From 3df82b8842271737eee55a7a830751831c1ab935 Mon Sep 17 00:00:00 2001 From: conongnang <173552257+conongnang@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:28:30 +0700 Subject: [PATCH 001/177] Load Atmosphere cheat files and switch their cheats from a Cheats tab in the menu Players bring their own cheats\.txt next to totk.exe; none ship with the port. The setup turns cheats that write main's code into patch sets (tools/cheats.py), cheats that write data run in a cheat VM after dmnt's every presented frame (runtime/cheats.c), and the menu's Cheats tab switches each one, saved under [cheats] in totk.ini. The patch table now takes several sets per site, first set in file order winning, and replacements that end in a branch or ret, so cheats that patch the same instruction or end in a jump can be built. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/cheats.md | 62 +++++ installer/steps.py | 27 +- recomp/gen.py | 115 ++++++--- recomp/patches.py | 32 ++- runtime/boot.c | 2 + runtime/cfg.c | 3 +- runtime/cheats.c | 516 +++++++++++++++++++++++++++++++++++++ runtime/cheats.h | 43 ++++ runtime/ui/menu.cpp | 65 ++++- runtime/ui/option_rows.cpp | 47 +++- runtime/ui/option_rows.h | 7 + runtime/ui_text.c | 32 +++ runtime/ui_text.h | 9 +- tools/cheats.py | 349 +++++++++++++++++++++++++ totk.ini.example | 5 + 16 files changed, 1241 insertions(+), 74 deletions(-) create mode 100644 docs/cheats.md create mode 100644 runtime/cheats.c create mode 100644 runtime/cheats.h create mode 100644 tools/cheats.py diff --git a/README.md b/README.md index 13e75988..381995f6 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - In-game settings menu (F1) and performance overlay (F10) - Keyboard, mouse and gamepad with remapping, rumble and gyro - Shaders prepared at install instead of during play +- Atmosphère cheat files: bring your own, switch cheats in the menu ([docs/cheats.md](docs/cheats.md)) ## Planned diff --git a/docs/cheats.md b/docs/cheats.md new file mode 100644 index 00000000..f402fadf --- /dev/null +++ b/docs/cheats.md @@ -0,0 +1,62 @@ +# Cheats + +The port reads Atmosphère cheat files, the format Switch homebrew and the emulators use. No cheats ship with the port: bring your own file for your game update. + +## Adding a cheat file + +1. Find the cheat file for your update. It is named after the first 8 bytes of the game's build id: + + | Update | File | + |---|---| + | 1.2.1 | `9B4E43650501A4D4.txt` | + | 1.4.3 | `277178B7DBA1B6D4.txt` | + + The Cheats tab of the menu names the file the installed game reads, and `logs\totk.log` says `cheats: no cheats\.txt` when it is missing. +2. Put it in a `cheats` folder next to `totk.exe`: `cheats\277178B7DBA1B6D4.txt`. +3. Run `TotK-Setup.exe` again on the same folder. It builds the cheats that change the game's code into the game (about three minutes); saves and settings are kept. A file with only data cheats works without this step. +4. In game, open the menu (F1) and switch cheats on and off on the Cheats tab. The switches are saved under `[cheats]` in `totk.ini`. + +## The file format + +Standard Atmosphère: a `[name]` line starts a cheat, `{name}` a master cheat that is always on, and the cheat's opcodes follow as 8-digit hex words. A name with no opcodes is shown as a heading. The file's title line (the one with `TID=`) is not shown. + +``` +[The Legend of Zelda: Tears of the Kingdom v1.4.3 TID=0100F2C0115B6000 BID=277178B7DBA1B6D4] + +[Player] +[A code cheat] +040A0000 XXXXXXXX YYYYYYYY + +[A data cheat (Hold ZL+X)] +80000104 +580F0000 XXXXXXXX +640F0000 00000000 YYYYYYYY +20000000 +``` + +The words above are placeholders: `XXXXXXXX` an offset, `YYYYYYYY` a value. + +Each cheat's switch is `cheat_ = 1`, where the hash is FNV-1a 32 of the cheat's name. Two files that use the same names, for example one per update, share their switches. + +## How cheats run + +The game's code is compiled ahead of time, so a cheat cannot write new instructions into it while the game runs. The port sorts each cheat by what it writes (`tools/cheats.py` at setup, `runtime/cheats.c` in game): + +| Kind | What the cheat does | How the port runs it | +|---|---|---| +| code | Opcode 0 writes into main's code | Built into the game at setup as a patch set (`recomp/patches.py`); switches at once. | +| key | Code writes inside a button condition (`8` mask, writes, `21` else, the original words, `20`) | A patch set that is on while the cheat is on and the buttons are held. | +| data | Writes data only: heap, main's data, pointer chains, button conditions | Runs in a cheat VM after dmnt's, opcodes 0 to A, every presented frame while on. | +| master | `{name}` with code writes | A patch set that is always on. | +| restore | Writes back only the game's original instructions | Not needed: switching a cheat off restores them. Greyed out. | + +A cheat whose code writes call or jump into a code cave the cheat writes itself (into main's zero padding) gets the cave inlined at the call site. A code cheat added to the file or edited after the setup ran is greyed out until the setup runs again; a data cheat runs at once. + +Not supported, and shown greyed out with the reason: + +- the 0xC and 0xF opcode extensions; +- opcode 5 with a register offset; +- code writes mixed with other opcodes, except the button pattern above; +- code writes that change the CPU flags differently from the game's instruction, or code caves with branches or pc-relative instructions. + +`cheats\.status`, written by the setup, records which cheats were built and how; the log line `cheats: ...` sums it up at start. diff --git a/installer/steps.py b/installer/steps.py index c7d9c40a..ea01b99a 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -490,12 +490,24 @@ EMITTED = re.compile(r'^emitted (\d+)/(\d+) chunks') DISCOVERED = re.compile(r'^(\w+): \d+ functions \(.*discovery') +def cheats_file(ctx): + """/cheats/.txt, the Atmosphere cheat file of the installed main (tools/cheats.py), whether or not + it exists.""" + try: + with open(ctx.dest / 'exefs' / 'main', 'rb') as f: + bid = f.read(0x48)[0x40:0x48].hex().upper() + except OSError: + bid = 'unknown' + return ctx.dest / 'cheats' / f'{bid}.txt' + + class Lift(Step): id = 'lift' transient = True def key(self, ctx): - return fingerprint('lift-1', ctx.keys['extract'], ctx.layout.recomp, ctx.layout.patches(game_version(ctx))) + return fingerprint('lift-2', ctx.keys['extract'], ctx.layout.recomp, ctx.layout.patches(game_version(ctx)), + ctx.layout.tools / 'cheats.py', cheats_file(ctx)) def current(self, ctx, record): gen = ctx.temp / 'gen' @@ -512,8 +524,19 @@ class Lift(Step): if m: rep.progress('lift', 'emit', int(m.group(1)), int(m.group(2)), 'chunks') + # The code cheats of the cheat file become patch sets (tools/cheats.py); its status file tells the runtime + # which cheats the build has. + patches, cheats = layout.patches(game_version(ctx)), cheats_file(ctx) + if cheats.is_file(): + combined = ctx.temp / 'patches-cheats.txt' + code, log = run_tool(ctx, 'lift', layout.tools / 'cheats.py', + ['--exefs', ctx.dest / 'exefs', '--cheats', cheats, '--patches', patches, + '--out', combined, '--status', cheats.with_suffix('.status')]) + if code: + raise InstallError('lift.failed', code=code, log=str(log)) + patches = combined code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', - ['--exefs', ctx.dest / 'exefs', '--out', gen, '--patches', layout.patches(game_version(ctx))], parse) + ['--exefs', ctx.dest / 'exefs', '--out', gen, '--patches', patches], parse) if code: raise InstallError('lift.failed', code=code, log=str(log)) (gen / STAMP).write_text(ctx.keys['lift'] + '\n') diff --git a/recomp/gen.py b/recomp/gen.py index e07396fa..27926e45 100644 --- a/recomp/gen.py +++ b/recomp/gen.py @@ -210,7 +210,7 @@ class Emitter: def __init__(self, mod, starts, patched=None, reg_locals=regs.LOCALS, callee_saved=True, spins=None): self.mod = mod self.starts = starts - self.patched = patched or {} # {address: (set index, [replacement words])} (recomp/patches.py) + self.patched = patched or {} # {address: [(set index, [replacement words])]} (recomp/patches.py) self.spins = spins or {} # {spin wait back-edge: its head} (recomp/patches.py `spin`) self.reg_locals = reg_locals # recomp/regs.py: registers per function in C locals self.kept = regs.CALLEE_SAVED if callee_saved else frozenset() # not reloaded after a call @@ -249,33 +249,54 @@ class Emitter: self.unsupported[re.sub(r'\b[0-9a-f]{8}\b', '', msg).strip()] += 1 elif k == 'asm': raise ValueError(f'{entry + 4 * i:#x}: asm instruction from the portable lifter') + for a in self.patched: # a replacement's branch into the function needs its label + if entry <= a < end: + for words in self.replacements(a): + r = words[-1] + if r.kind in ('b', 'bcond') and entry <= r.target < end: + labels.add(r.target) return labels, tables def replacements(self, a): - """Lifted replacement words of the patched site a.""" - return [self.mod.lifter.lift(w, a) for w in self.patched[a][1]] + """The lifted words of each alternative of the patched site a, in set order. Only the last word of an + alternative may branch (bl, b, b.cond / cbz / tbz, ret).""" + out = [] + for _, words in self.patched[a]: + lifted = [self.mod.lifter.lift(w, a) for w in words] + for j, r in enumerate(lifted): + last = j == len(lifted) - 1 + if r.kind != 'op' and not (last and r.kind in ('bl', 'b', 'bcond', 'ret')): + raise patches.PatchError(f'{a:#x}: replacement word {words[j]:08x} is a {r.kind}') + out.append(lifted) + return out - @staticmethod - def flow(insns, entry, end, tables): + def flow(self, insns, entry, end, tables): """Successors of each instruction inside the function [entry, end). Index len(insns) stands for falling - through into the next function and has none.""" + through into the next function and has none. A patched site has the successors of all its alternatives.""" def idx(t): return [(t - entry) // 4] if entry <= t < end else [] - succ = [] - for i, ins in enumerate(insns): + def of(ins, i): k = ins.kind if k in ('op', 'bl', 'blr'): - succ.append([i + 1]) - elif k == 'b': - succ.append(idx(ins.target)) - elif k == 'bcond': - succ.append(idx(ins.target) + [i + 1]) - elif k == 'br': + return [i + 1] + if k == 'b': + return idx(ins.target) + if k == 'bcond': + return idx(ins.target) + [i + 1] + if k == 'br': jt = tables.get(entry + 4 * i) - succ.append([t for x in jt for t in idx(x)] if jt and jt != 'all' else []) - else: # ret, trap - succ.append([]) + return [t for x in jt for t in idx(x)] if jt and jt != 'all' else [] + return [] # ret, trap + + succ = [] + for i, ins in enumerate(insns): + s = of(ins, i) + a = entry + 4 * i + if a in self.patched: + for words in self.replacements(a): + s += [t for t in of(words[-1], i) if t not in s] + succ.append(s) succ.append([]) return succ @@ -293,27 +314,34 @@ class Emitter: exits.add(i) # through rt_dispatch, also a table's default if a in self.patched: effects.append(self.patched_effect(ins, a)) - if any(r.kind == 'bl' for r in self.replacements(a)): - calls.add(i) + for words in self.replacements(a): + r = words[-1] + if r.kind == 'bl': + calls.add(i) + elif r.kind in ('b', 'bcond') and not entry <= r.target < end: + exits.add(i) else: effects.append(flags.effect(ins.cond if k == 'bcond' else ins.code or '')) effects.append((False, None)) return flags.plan(effects, succ, calls, exits) def patched_effect(self, ins, a): - """Flag effect of a patched site: both alternatives must have the same one, in at most one word each.""" + """Flag effect of a patched site: every alternative (the original and each replacement) must write the same + flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them).""" alts = [] - for words in ([ins], self.replacements(a)): - fx = [flags.effect(w.code or '') for w in words if w.kind == 'op'] + for words in [[ins]] + self.replacements(a): + fx = [flags.effect(w.code or '') if w.kind == 'op' else flags.effect(w.cond) for w in words + if w.kind in ('op', 'bcond')] fx = [e for e in fx if e[0] or e[1]] if len(fx) > 1: raise patches.PatchError(f'{a:#x}: several flag-using words in one alternative') alts.append(fx[0] if fx else (False, None)) - if alts[0][1] != alts[1][1]: - raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({alts[0][1]}, {alts[1][1]})') - if (alts[0][1] or alts[0][0] or alts[1][0]) and ins.kind == 'bl': + if any(e[1] != alts[0][1] for e in alts): + raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({[e[1] for e in alts]})') + reads = any(e[0] for e in alts) + if (alts[0][1] or reads) and (ins.kind == 'bl' or any(w[-1].kind == 'bl' for w in self.replacements(a))): raise patches.PatchError(f'{a:#x}: a patched call that uses flags') - return alts[0][0] or alts[1][0], alts[0][1] + return reads, alts[0][1] def function(self, entry, end): """(lines of C, referenced function starts) for the guest function [entry, end).""" @@ -384,23 +412,30 @@ class Emitter: code = fx(i, code) return f'{spill}{code}{reload}' if regs.ESCAPE.search(code) else code + def one(i, r, a): + """C of one lifted word of a patched site.""" + if r.kind == 'op': + return op(i, r.code) + if r.kind == 'bl': + return call(r.target, a) + if r.kind == 'b': + return jump(r.target, i) + if r.kind == 'bcond': + return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}' + if r.kind == 'ret': + return f'{spill}return;' + raise patches.PatchError(f'{a:#x}: patched instruction is a {r.kind}') + def patch(i, ins, a): - """if (switch) { replacement } else { original } for a patched site (recomp/patches.py).""" - k, words = self.patched[a] - if ins.kind not in ('op', 'bl'): + """if (switch) { replacement } else if ... else { original } for a patched site (recomp/patches.py).""" + if ins.kind not in ('op', 'bl', 'b', 'bcond'): raise patches.PatchError(f'{a:#x}: patched instruction is a {ins.kind}') - repl = [] - for j, (w, r) in enumerate(zip(words, self.replacements(a))): - if r.kind == 'op': - repl.append(op(i, r.code)) - elif r.kind == 'bl' and j == len(words) - 1: - repl.append(call(r.target, a)) - else: - raise patches.PatchError(f'{a:#x}: replacement word {w:08x} is a {r.kind}') - orig = op(i, ins.code) if ins.kind == 'op' else call(ins.target, a) + line = ' ' + for (k, _), words in zip(self.patched[a], self.replacements(a)): + line += f' if (rt_patch_on[{k}]) {{ {" ".join(one(i, r, a) for r in words)} }} else' self.uses_patches = True self.stats['patched_sites'] += 1 - return f' if (rt_patch_on[{k}]) {{ {" ".join(repl)} }} else {{ {orig} }}' + return f'{line} {{ {one(i, ins, a)} }}' body = [] # (instruction index or None for a label, line); a line belongs to the instruction it lifts @@ -444,7 +479,7 @@ class Emitter: else: raise ValueError(f'{a:#x}: unknown instruction kind {k!r}') n = len(insns) - if k not in TERMINATORS: # falls through into the next function + if k not in TERMINATORS or end - 4 in self.patched: # falls through into the next function if end < mod.hi: emit(n, ' ' + jump(end, n)) else: diff --git a/recomp/patches.py b/recomp/patches.py index 99c3cc49..17cbca03 100644 --- a/recomp/patches.py +++ b/recomp/patches.py @@ -14,10 +14,12 @@ encoded for the site's address. The patch page is the first 4 KiB page after mai of the 2 MiB-aligned module slot free); the runtime commits it and owns its contents. The replacement words are lifted at the site's address in place of the original instruction, and the generated C reads -`if (rt_patch_on[]) { replacement } else { original }`: one byte load and a branch per executed site. Replacement -words must not branch except a final `bl` (lifted with the site's return address); the original must not be a branch -other than `bl`. So the function's control flow, labels and jump tables are the original's. The generator writes -patches.h (set names, switches, the page address) next to layout.h for the runtime. +`if (rt_patch_on[]) { replacement } else { original }`: one byte load and a branch per executed site. Several +sets may patch one address (cheats that write different values there): `if (a) {..} else if (b) {..} else {..}`, the +first set in file order wins. The original may be any instruction but br, blr and ret; a replacement's last word may be +a bl (lifted with the site's return address), a b or b.cond / cbz / tbz (its target joins the function's labels when +inside it) or a ret; earlier words must not branch. Every alternative of a site writes the same flags. The generator +writes patches.h (set names, switches, the page address) next to layout.h for the runtime. A `spin` line names a spin wait found by tools/spin_waits.py: a loop with head that only another thread can end, and the direct branches back to it (module offsets). Each back-edge (checked: a b, b.cond, cbz / cbnz or tbz / tbnz to @@ -42,7 +44,8 @@ def adrp(pc, target, rd): class Table: - """sets: [(name, env, default)]; sites: {module: {offset: (set index, [word | ('page', reg)], original)}}; page.""" + """sets: [(name, env, default)]; sites: {module: {offset: [(set index, [word | ('page', reg)], original)]}} (the + alternatives of a site in file order); page.""" def __init__(self, sets=(), sites=None, page=0, spins=None): self.sets = list(sets) @@ -55,11 +58,12 @@ class Table: return {base + b: base + h for b, h in self.spins.get(name, {}).items()} def for_module(self, name, base): - """{absolute address: (set index, [words])} with @page resolved.""" + """{absolute address: [(set index, [words])]} with @page resolved.""" out = {} - for off, (k, repl, _) in self.sites.get(name, {}).items(): + for off, alts in self.sites.get(name, {}).items(): a = base + off - out[a] = (k, [adrp(a, self.page, w[1]) if isinstance(w, tuple) else w for w in repl]) + out[a] = [(k, [adrp(a, self.page, w[1]) if isinstance(w, tuple) else w for w in repl]) + for k, repl, _ in alts] return out @@ -89,10 +93,12 @@ def load(path, mods): repl.append(('page', int(w[7:]))) else: repl.append(int(w, 16)) - mod = sites.setdefault(f[2], {}) - if off in mod: - raise PatchError(f'{where}: {f[2]}+{off:#x} patched twice') - mod[off] = (index[f[1]], repl, orig) + alts = sites.setdefault(f[2], {}).setdefault(off, []) + if any(k == index[f[1]] for k, _, _ in alts): + raise PatchError(f'{where}: {f[2]}+{off:#x} patched twice by set {f[1]}') + if alts and alts[0][2] != orig: + raise PatchError(f'{where}: {f[2]}+{off:#x} expects {orig:08x}, an earlier line {alts[0][2]:08x}') + alts.append((index[f[1]], repl, orig)) elif f[0] == 'spin' and len(f) >= 4: if f[1] not in bases: raise PatchError(f'{where}: module {f[1]} not in the layout') @@ -114,7 +120,7 @@ def load(path, mods): def check(table, mod, name): """Stops on a site whose original word differs from the module's.""" - for off, (_, _, want) in table.sites.get(name, {}).items(): + for off, [(_, _, want), *_] in table.sites.get(name, {}).items(): a = mod.base + off if not mod.in_text(a): raise PatchError(f'{name}+{off:#x}: patch site outside .text') diff --git a/runtime/boot.c b/runtime/boot.c index 382ac850..68b780cc 100644 --- a/runtime/boot.c +++ b/runtime/boot.c @@ -15,6 +15,7 @@ #include #include "cfg.h" +#include "cheats.h" #include "fs.h" #include "gfx.h" #include "nvn_api.h" @@ -341,6 +342,7 @@ void rt_boot(void) { rt_patches_init(); frame_step_init(); res_init(); + cheats_init(); // after the patch sets: a cheat's set follows its setting cb_addr[0] = hostfn_register("", cb_loader_ready); cb_addr[1] = hostfn_register("", cb_module_inits); cb_addr[2] = hostfn_register("", cb_module_finis); diff --git a/runtime/cfg.c b/runtime/cfg.c index 84abed08..30445a3f 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -132,7 +132,7 @@ static const CfgMeta metas[] = { static int is_known(const char *key) { for (size_t i = 0; i < sizeof known / sizeof *known; i++) if (!strcmp(known[i], key)) return 1; - return 0; + return !strncmp(key, "CHEAT_", 6); // cheats.c and the cheat patch sets (tools/cheats.py) } static void clear(void) { @@ -391,6 +391,7 @@ static void puts_(Out *o, const char *s) { put(o, s, strlen(s)); } static const char *section_of(const char *key) { for (size_t i = 0; i < sizeof sections / sizeof *sections; i++) if (!strcmp(sections[i].key, key)) return sections[i].section; + if (!strncmp(key, "CHEAT_", 6)) return "cheats"; // cheats.c: one key per cheat of the cheat file return NULL; } diff --git a/runtime/cheats.c b/runtime/cheats.c new file mode 100644 index 00000000..472e56df --- /dev/null +++ b/runtime/cheats.c @@ -0,0 +1,516 @@ +// Cheats of an Atmosphere cheat file (cheats.h). The file is cheats\.txt next to totk.exe, the build id the +// first 8 bytes of main's NSO build id, as Atmosphere and the emulators name it. Each cheat's switch is the setting +// TOTK_CHEAT_ (cheat_ under [cheats] in totk.ini). +// +// Code cheats (opcode 0 writes into main's code) cannot be applied here: the game's code is lifted C. tools/cheats.py +// turns them into patch sets cheat_ when the game is built and writes cheats\.status, one line per +// cheat: name hash, content hash, kind, buttons, note (tools/cheats.py has the format). A cheat whose status line is +// missing or has another content hash was added or edited after the build: a data cheat runs anyway, a code cheat waits +// for the setup to run again. +// +// Data cheats run in a VM after Atmosphere's dmnt cheat VM (opcodes 0-A; the 0xC.. and 0xF.. extensions are not +// supported), every presented frame while their switch is on, with registers cleared before each cheat. Memory is the +// guest's, mapped at its own addresses: main's image is written through VirtualProtect (its read-only data included, +// as dmnt writes through the debugger), everything else after mem_query says the guest may read or write it. Buttons +// are input_poll's HidNpadButton bits, the same as the cheat format's key masks; they read 0 while the menu is open. +#include +#include +#include +#include +#include + +#include "cfg.h" +#include "cheats.h" +#include "host.h" +#include "input.h" +#include "platform/platform.h" + +enum { STATUS_MAX = 160, OPS_PER_RUN = 1 << 20 }; + +typedef struct { + CheatInfo info; + uint32_t *words; + int n; + int set; // patch set, -1 none + volatile LONG on; + char note[STATUS_MAX]; +} Cheat; + +static Cheat *g_cheats; +static int g_n, g_vm; // g_vm: some cheat needs cheats_frame +static char g_file[64]; +static uint64_t g_main, g_main_size, g_code_end; // main's image; its code with the padding up to .rodata + +static uint32_t fnv(const char *s, size_t n) { + uint32_t h = 0x811C9DC5u; + for (size_t i = 0; i < n; i++) h = (h ^ (uint8_t)s[i]) * 0x01000193u; + return h; +} + +// The folder of totk.exe, UTF-8, with a trailing backslash. +static int exe_dir(char *out, int n) { + wchar_t w[MAX_PATH * 2]; + DWORD k = GetModuleFileNameW(NULL, w, MAX_PATH * 2); + if (!k || k >= MAX_PATH * 2) return 0; + wchar_t *cut = wcsrchr(w, L'\\'); + if (!cut) return 0; + cut[1] = 0; + return WideCharToMultiByte(CP_UTF8, 0, w, -1, out, n, NULL, NULL) > 0; +} + +static int build_id(char out[17]) { + char path[1024]; + snprintf(path, sizeof path, "%s/main", rt_config()->exefs); + wchar_t w[1024]; + if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, w, 1024)) return 0; + HANDLE f = CreateFileW(w, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + if (f == INVALID_HANDLE_VALUE) return 0; + uint8_t head[0x48]; + DWORD got = 0; + int ok = ReadFile(f, head, sizeof head, &got, NULL) && got == sizeof head && !memcmp(head, "NSO0", 4); + CloseHandle(f); + for (int i = 0; ok && i < 8; i++) snprintf(out + 2 * i, 3, "%02X", head[0x40 + i]); + return ok; +} + +// ---- opcodes + +// Words of the opcode at w (left words remain), 0 when it is cut short. +static int op_len(const uint32_t *w, int left) { + uint32_t f = w[0]; + int t = f >> 28, width = (f >> 24) & 0xF, n; + switch (t) { + case 0: case 1: n = width == 8 ? 4 : 3; break; + case 2: case 8: n = 1; break; + case 3: n = width == 0 ? 2 : 1; break; + case 4: case 6: n = 3; break; + case 5: case 7: n = 2; break; + case 9: n = 1 + (((f >> 8) & 0xF) ? (width == 8 ? 2 : 1) : 0); break; + case 0xA: n = ((f >> 8) & 0xF) == 2 || ((f >> 8) & 0xF) == 4 || ((f >> 8) & 0xF) == 5 ? 2 : 1; break; + default: n = 1; break; + } + return n <= left ? n : 0; +} + +// NULL when the VM runs the opcode, else why not (tools/cheats.py vm_ok). +static const char *vm_unsupported(const uint32_t *w, char *buf, int n) { + uint32_t f = w[0]; + int t = f >> 28, width = (f >> 24) & 0xF; + if (t > 0xA || (t == 5 && ((f >> 12) & 0xF) > 1) || (t == 0xA && ((f >> 8) & 0xF) > 5)) { + snprintf(buf, n, "opcode %08X is not supported", f); + return buf; + } + if ((t <= 1 || t == 5 || t == 6 || t == 7 || t == 9 || t == 0xA) && width != 1 && width != 2 && width != 4 && + width != 8) { + snprintf(buf, n, "opcode %08X has a bad width", f); + return buf; + } + return NULL; +} + +// The kind of a cheat the build did not see: heading, data, rebuild (it writes main's code) or unsupported. +static CheatKind classify(Cheat *c) { + int ops = 0, ends = 0; + for (int i = 0; i < c->n;) { + int len = op_len(c->words + i, c->n - i); + if (!len) { + snprintf(c->note, sizeof c->note, "opcode %08X is cut short", c->words[i]); + return CHEAT_UNSUPPORTED; + } + uint32_t f = c->words[i]; + ops++; + ends += f >> 28 == 2; + if (f >> 28 == 0 && ((f >> 20) & 0xF) == 0) { + uint64_t off = ((uint64_t)(f & 0xFF) << 32) | c->words[i + 1]; + if (off < g_code_end - g_main) return CHEAT_REBUILD; + } + if (vm_unsupported(c->words + i, c->note, sizeof c->note)) return CHEAT_UNSUPPORTED; + i += len; + } + return ops == ends && ops <= 1 ? CHEAT_HEADING : CHEAT_DATA; +} + +// ---- guest memory + +static uint64_t region(int m) { + const RtGuestLayout *l = mem_layout(); + switch (m) { + case 0: return g_main; + case 1: return l->heap.base; + case 2: return l->alias.base; + case 3: return l->aslr.base; + default: return 0; + } +} + +static int in_main(uint64_t a, unsigned n) { return a >= g_main && a + n <= g_main + g_main_size; } + +static int guest_ok(uint64_t a, unsigned n, uint32_t perm) { + if (in_main(a, n)) return 1; + RtMemoryInfo mi; + if (mem_query(a, &mi) || !mi.state || (mi.perm & perm) != perm) return 0; + return a + n <= mi.base + mi.size; +} + +static int rd(uint64_t a, int width, uint64_t *v) { + if (!a || !guest_ok(a, (unsigned)width, 1)) return 0; + uint64_t x = 0; + memcpy(&x, (const void *)(uintptr_t)a, (size_t)width); + *v = x; + return 1; +} + +static void wr(uint64_t a, int width, uint64_t v) { + uint64_t now; + if (!rd(a, width, &now) || !memcmp(&now, &v, (size_t)width)) return; // unchanged: no write, no protection change + void *p = (void *)(uintptr_t)a; + if (in_main(a, (unsigned)width)) { + DWORD old, back; + if (!VirtualProtect(p, (SIZE_T)width, PAGE_READWRITE, &old)) return; + memcpy(p, &v, (size_t)width); + VirtualProtect(p, (SIZE_T)width, old, &back); + } else if (guest_ok(a, (unsigned)width, 2)) { + memcpy(p, &v, (size_t)width); // a frozen region thaws on the write (memory.c) + } +} + +static uint64_t masked(int width, uint64_t v) { return width >= 8 ? v : v & ((1ull << (8 * width)) - 1); } + +static uint64_t arith(int op, uint64_t a, uint64_t b) { + switch (op) { + case 0: return a + b; + case 1: return a - b; + case 2: return a * b; + case 3: return b < 64 ? a << b : 0; + case 4: return b < 64 ? a >> b : 0; + case 5: return a & b; + case 6: return a | b; + case 7: return ~a; + case 8: return a ^ b; + default: return a; // 9: move + } +} + +static int compare(int cond, uint64_t a, uint64_t b) { + switch (cond) { + case 1: return a > b; + case 2: return a >= b; + case 3: return a < b; + case 4: return a <= b; + case 5: return a == b; + case 6: return a != b; + default: return 0; + } +} + +// From i (after a failed condition, or an else reached while running), the opcode to continue at: after the +// matching else (else_ok) or end. +static int skip(const uint32_t *w, int n, int i, int else_ok) { + int depth = 0; + while (i < n) { + int len = op_len(w + i, n - i); + if (!len) return n; + uint32_t f = w[i]; + int t = f >> 28; + i += len; + if (t == 1 || t == 8) depth++; + else if (t == 2 && ((f >> 24) & 0xF) == 0 && depth-- == 0) return i; + else if (t == 2 && depth == 0 && else_ok) return i; + } + return n; +} + +static uint64_t imm64(const uint32_t *w) { return (uint64_t)w[0] << 32 | w[1]; } + +static void run(const Cheat *c, uint64_t keys) { + uint64_t r[16] = {0}; + int loop[16] = {0}; + const uint32_t *w = c->words; + int n = c->n, budget = OPS_PER_RUN; + for (int i = 0; i < n && budget-- > 0;) { + int len = op_len(w + i, n - i); + if (!len) return; + uint32_t f = w[i]; + int t = f >> 28, width = (f >> 24) & 0xF, x = (f >> 20) & 0xF, y = (f >> 16) & 0xF, z = (f >> 12) & 0xF; + uint64_t rel = ((uint64_t)(f & 0xFF) << 32) | (len > 1 ? w[i + 1] : 0), v; + switch (t) { + case 0: // 0TMR00AA AAAAAAAA V..: store a value at region M + A + register R + wr(region(x) + rel + r[y], width, width == 8 ? imm64(w + i + 2) : w[i + 2]); + break; + case 1: // 1TMC00AA AAAAAAAA V..: if (region M + A) V + if (!rd(region(x) + rel, width, &v) || !compare(y, v, width == 8 ? imm64(w + i + 2) : w[i + 2])) { + i = skip(w, n, i + len, 1); + continue; + } + break; + case 2: // 20000000 end, 21000000 else: an else reached while running skips to the end + if (width == 1) { + i = skip(w, n, i + len, 0); + continue; + } + break; + case 3: // 300R0000 VVVVVVVV loop start, 310R0000 loop end + if (width == 0) { + r[y] = w[i + 1]; + loop[y] = i + len; + } else if (r[y] && --r[y]) { + i = loop[y]; + continue; + } + break; + case 4: // 400R0000 V V: register R = V + r[y] = imm64(w + i + 1); + break; + case 5: // 5TMRI0AA AAAAAAAA: R = (I ? R : region M) + A, read + if (!rd(z ? r[y] + rel : region(x) + rel, width, &v)) return; // a broken pointer chain: nothing more + r[y] = v; + break; + case 6: { // 6T0RIor0 V V: store V at R (+ register r); I: R += width + uint64_t a = r[y] + (((f >> 8) & 0xF) ? r[(f >> 4) & 0xF] : 0); + wr(a, width, imm64(w + i + 1)); + if (z) r[y] += (uint64_t)width; + break; + } + case 7: // 7T0RC000 VVVVVVVV: R = R V + r[y] = masked(width, arith(z, r[y], w[i + 1])); + break; + case 8: // 8kkkkkkk: if the buttons are held + if ((keys & (f & 0x0FFFFFFF)) != (f & 0x0FFFFFFF)) { + i = skip(w, n, i + len, 1); + continue; + } + break; + case 9: { // 9TCRS0s0 / 9TCRS100 V..: R = S (s or V) + uint64_t b = (f >> 8) & 0xF ? (width == 8 ? imm64(w + i + 1) : w[i + 1]) : r[(f >> 4) & 0xF]; + r[y] = masked(width, arith(x, r[z], b)); + break; + } + case 0xA: { // ATSRIOxa (aaaaaaaa): store register S at an address of type O + int o = (f >> 8) & 0xF, m = (f >> 4) & 0xF; + uint64_t imm = ((uint64_t)(f & 0xF) << 32) | (len > 1 ? w[i + 1] : 0), a; + switch (o) { + case 0: a = r[y]; break; + case 1: a = r[y] + r[m]; break; + case 2: a = r[y] + imm; break; + case 3: a = region(m) + r[y]; break; + case 4: a = region(m) + imm; break; + default: a = region(m) + r[y] + imm; break; + } + wr(a, width, r[x]); + if (z) r[y] += (uint64_t)width; + break; + } + default: + return; + } + i += len; + } +} + +// ---- the file + +static char *read_text(const char *path) { + uint64_t n = 0; + char *s = (char *)plat_file_read(path, &n); + if (s && n >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) memmove(s, s + 3, (size_t)n - 2); // a UTF-8 BOM + return s; +} + +static void add_word(Cheat *c, uint32_t v, int *cap) { + if (c->n == *cap) { + *cap = *cap ? *cap * 2 : 16; + c->words = (uint32_t *)realloc(c->words, sizeof *c->words * (size_t)*cap); + if (!c->words) rt_fatal("cheats: out of memory"); + } + c->words[c->n++] = v; +} + +static void parse(char *s) { + int cap = 0, wcap = 0; + for (char *line = s; line && *line;) { + char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL; + if (end) *end = 0; + while (*line == ' ' || *line == '\t') line++; + size_t len = strlen(line); + while (len && (line[len - 1] == '\r' || line[len - 1] == ' ' || line[len - 1] == '\t')) line[--len] = 0; + if (len >= 2 && (line[0] == '[' || line[0] == '{') && (line[len - 1] == ']' || line[len - 1] == '}')) { + if (g_n == cap) { + cap = cap ? cap * 2 : 32; + g_cheats = (Cheat *)realloc(g_cheats, sizeof *g_cheats * (size_t)cap); + if (!g_cheats) rt_fatal("cheats: out of memory"); + } + Cheat *c = &g_cheats[g_n++]; + memset(c, 0, sizeof *c); + line[len - 1] = 0; + char *name = line + 1; + while (*name == ' ' || *name == '\t') name++; + size_t k = strlen(name); + while (k && (name[k - 1] == ' ' || name[k - 1] == '\t')) name[--k] = 0; + c->info.name = _strdup(name); + c->info.kind = line[0] == '{' ? CHEAT_MASTER : CHEAT_HEADING; + c->set = -1; + wcap = 0; + } else if (g_n) { + for (char *tok = strtok(line, " \t"); tok; tok = strtok(NULL, " \t")) { + char *e; + unsigned long v = strtoul(tok, &e, 16); + if (e - tok == 8 && !*e) add_word(&g_cheats[g_n - 1], (uint32_t)v, &wcap); + } + } + line = next; + } +} + +// The status line of key, its fields split in place; 0 when none. +static int status_of(char *status, const char *key, char **fields) { + for (char *line = status; line && *line;) { + char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL; + if (!strncmp(line, key, 8) && line[8] == '\t') { + static char copy[512]; + size_t n = end ? (size_t)(end - line) : strlen(line); + if (n >= sizeof copy) n = sizeof copy - 1; + memcpy(copy, line, n); + copy[n] = 0; + if (n && copy[n - 1] == '\r') copy[n - 1] = 0; + int k = 0; + fields[k++] = copy; + for (char *p = copy; *p && k < 5; p++) + if (*p == '\t') *p = 0, fields[k++] = p + 1; + while (k < 5) fields[k++] = (char *)""; + return 1; + } + line = next; + } + return 0; +} + +void cheats_init(void) { + const RtLoaded *m = ldr_count() ? ldr_module(0) : NULL; + char dir[MAX_PATH * 3], bid[17], path[MAX_PATH * 3 + 64]; + if (!m || !exe_dir(dir, sizeof dir) || !build_id(bid)) return; + g_main = m->base; + g_main_size = m->size; + g_code_end = m->base + ((m->text_end + 0xFFF) & ~0xFFFull); + snprintf(g_file, sizeof g_file, "cheats\\%s.txt", bid); + snprintf(path, sizeof path, "%s%s", dir, g_file); + char *text = read_text(path); + if (!text) { + rt_log("cheats: no %s", g_file); + return; + } + parse(text); + free(text); + snprintf(path, sizeof path, "%scheats\\%s.status", dir, bid); + char *status = read_text(path); + int counts[CHEAT_UNSUPPORTED + 1] = {0}, seen_dups = 0; + for (int i = 0; i < g_n; i++) { + Cheat *c = &g_cheats[i]; + // the name hash: a repeated name gets "#2", "#3" ... (tools/cheats.py parse) + int dup = 1; + for (int j = 0; j < i; j++) dup += !strcmp(g_cheats[j].info.name, c->info.name); + char named[600]; + snprintf(named, sizeof named, dup > 1 ? "%s#%d" : "%s", c->info.name, dup); + seen_dups += dup > 1; + char key[9], content[9]; + snprintf(key, sizeof key, "%08X", fnv(named, strlen(named))); + size_t tn = (size_t)c->n * 9 + 1, tl = 0; + char *t = (char *)malloc(tn); + if (!t) rt_fatal("cheats: out of memory"); + t[0] = 0; + for (int k = 0; k < c->n; k++) tl += (size_t)snprintf(t + tl, tn - tl, k ? " %08X" : "%08X", c->words[k]); + snprintf(content, sizeof content, "%08X", fnv(t, tl)); + free(t); + snprintf(c->info.key, sizeof c->info.key, "TOTK_CHEAT_%s", key); + int master = c->info.kind == CHEAT_MASTER; + char *f[5]; + CheatKind kind; + if (status && status_of(status, key, f) && !strcmp(f[1], content)) { + const char *k = f[2]; + kind = !strcmp(k, "code") ? CHEAT_CODE : !strcmp(k, "key") ? CHEAT_KEY : !strcmp(k, "master") ? CHEAT_MASTER + : !strcmp(k, "restore") ? CHEAT_RESTORE : !strcmp(k, "heading") ? CHEAT_HEADING + : !strcmp(k, "data") ? CHEAT_DATA : CHEAT_UNSUPPORTED; + c->info.buttons = (uint32_t)strtoul(f[3], NULL, 16); + snprintf(c->note, sizeof c->note, "%s", f[4]); + if (kind == CHEAT_CODE || kind == CHEAT_KEY || kind == CHEAT_MASTER) { + char set[32]; + snprintf(set, sizeof set, "cheat_%08x", fnv(named, strlen(named))); + c->set = rt_patch_set(set); + if (c->set < 0 && kind != CHEAT_MASTER) kind = CHEAT_REBUILD; + } + } else { + kind = classify(c); + } + if (master && kind == CHEAT_DATA) kind = CHEAT_MASTER; // a data master code: the VM, always on + c->info.kind = kind; + c->info.note = c->note; + const char *v = cfg_get(c->info.key); + c->on = kind == CHEAT_MASTER || (v && *v && strcmp(v, "0") != 0); + if (kind == CHEAT_KEY && c->set >= 0) rt_patch_switch(c->set, 0); // on while the buttons are held + if (kind == CHEAT_KEY || kind == CHEAT_DATA || (kind == CHEAT_MASTER && c->set < 0)) g_vm = 1; + counts[kind]++; + } + free(status); + int on = 0; + for (int i = 0; i < g_n; i++) on += g_cheats[i].on && g_cheats[i].info.kind != CHEAT_HEADING; + rt_log("cheats: %s: %d cheats, %d on; %d code, %d while buttons are held, %d data, %d master, %d restore, " + "%d headings, %d need the setup again, %d not supported%s", + g_file, g_n, on, counts[CHEAT_CODE], counts[CHEAT_KEY], counts[CHEAT_DATA], counts[CHEAT_MASTER], + counts[CHEAT_RESTORE], counts[CHEAT_HEADING], counts[CHEAT_REBUILD], counts[CHEAT_UNSUPPORTED], + seen_dups ? " (repeated names numbered)" : ""); +} + +int cheats_count(void) { return g_n; } + +const CheatInfo *cheats_info(int i) { return i >= 0 && i < g_n ? &g_cheats[i].info : NULL; } + +int cheats_on(int i) { return i >= 0 && i < g_n && g_cheats[i].on; } + +const char *cheats_file(void) { return g_file; } + +void cheats_set(int i, int on) { + if (i < 0 || i >= g_n) return; + Cheat *c = &g_cheats[i]; + if (c->info.kind != CHEAT_CODE && c->info.kind != CHEAT_KEY && c->info.kind != CHEAT_DATA) return; + InterlockedExchange(&c->on, on != 0); + if (c->info.kind == CHEAT_CODE) rt_patch_switch(c->set, on); // CHEAT_KEY: cheats_frame follows the buttons + cfg_set(c->info.key, on ? "1" : "0"); + rt_log("cheats: %s %s", c->info.name, on ? "on" : "off"); +} + +void cheats_frame(uint64_t frame) { + if (!g_vm || frame < 60) return; // the game polls its input (and starts SDL) before this + uint64_t keys = 0; + int32_t lx, ly, rx, ry; + input_poll(&keys, &lx, &ly, &rx, &ry); // 0 while the menu is open + for (int i = 0; i < g_n; i++) { + Cheat *c = &g_cheats[i]; + switch (c->info.kind) { + case CHEAT_KEY: + if (c->set >= 0) { + int want = c->on && (keys & c->info.buttons) == c->info.buttons; + if (rt_patch_enabled(c->set) != want) rt_patch_switch(c->set, want); + } + break; + case CHEAT_DATA: + if (c->on) run(c, keys); + break; + case CHEAT_MASTER: + if (c->set < 0) run(c, keys); + break; + default: + break; + } + } +} + +const char *cheats_buttons(uint32_t mask, char *buf, int n) { + static const char *const names[] = {"A", "B", "X", "Y", "Left stick press", "Right stick press", "L", "R", "ZL", + "ZR", "+", "-", "D-pad left", "D-pad up", "D-pad right", "D-pad down", + "Left stick left", "Left stick up", "Left stick right", "Left stick down", + "Right stick left", "Right stick up", "Right stick right", "Right stick down"}; + int k = 0; + buf[0] = 0; + for (int b = 0; b < 24; b++) + if (mask & (1u << b)) k += snprintf(buf + k, (size_t)(n > k ? n - k : 0), "%s%s", k ? " + " : "", names[b]); + return buf; +} diff --git a/runtime/cheats.h b/runtime/cheats.h new file mode 100644 index 00000000..a6746890 --- /dev/null +++ b/runtime/cheats.h @@ -0,0 +1,43 @@ +// Cheats of an Atmosphere cheat file (cheats.c): cheats\.txt next to totk.exe, switched from the menu's +// Cheats tab. A cheat that writes the game's instructions is a code patch set that tools/cheats.py built into the game +// (switched with rt_patch_switch); one that writes data runs in the cheat VM every presented frame. +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + CHEAT_HEADING, // no opcodes: a title or a group label + CHEAT_CODE, // a patch set + CHEAT_KEY, // a patch set on while the buttons are held + CHEAT_DATA, // the cheat VM + CHEAT_MASTER, // {master}: always on + CHEAT_RESTORE, // writes the original instructions back: nothing to do + CHEAT_REBUILD, // writes instructions, but the game was built without this version of it + CHEAT_UNSUPPORTED, // note says why +} CheatKind; + +typedef struct { + const char *name; // UTF-8, as in the file + const char *note; // why it is unsupported ("" otherwise) + CheatKind kind; + uint32_t buttons; // CHEAT_KEY: HidNpadButton mask + char key[24]; // its setting, TOTK_CHEAT_ +} CheatInfo; + +void cheats_init(void); // after rt_patches_init: reads the file and its build status +int cheats_count(void); +const CheatInfo *cheats_info(int i); +int cheats_on(int i); // the player's switch (1 for a master cheat) +void cheats_set(int i, int on); // switches at once and sets the cheat's setting (the menu saves totk.ini) +const char *cheats_file(void); // "cheats\.txt" +// Every presented frame (the present path): the data cheats' VM and the button state of CHEAT_KEY cheats. +void cheats_frame(uint64_t frame); +// The button names of a mask ("ZL + Right stick left"), into buf. +const char *cheats_buttons(uint32_t mask, char *buf, int n); + +#ifdef __cplusplus +} +#endif diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 64c3c4c0..9a62fb31 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -24,6 +24,7 @@ extern "C" { #include "cfg.h" +#include "cheats.h" #include "input.h" #include "input_map.h" #include "perfmon.h" @@ -245,10 +246,11 @@ static int vk_up(const MenuTarget *t) { return 1; } -// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean -// and Chinese language names merged in from a system font when there is one (each language is named in its own script). -// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture). -static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0}; +// Roboto Medium (Latin, Cyrillic, dashes, quotes and the numero sign of cheat names) at 26 px per 1080 lines, with +// the glyphs of the Japanese, Korean and Chinese language names merged in from a system font when there is one (each +// language is named in its own script). Made again when the window height changes; the old texture goes after the +// queue is idle (CreateFontsTexture). +static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0x2116, 0x2116, 0}; static const struct { const char *lang; UiTextId name; } kCjk[] = { {"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS}, {"zh-Hant", UI_MENU_LANGNAME_ZH_HANT}, @@ -299,7 +301,7 @@ extern "C" void menu_vk_release(void) { // TOTK_MENU_TEST_SET=:=[,=...][;:...]: cfg_set of each key (TOTK_ prefix // optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by // the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note). -enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_ADVANCED, TAB_COUNT }; +enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_CHEATS, TAB_ADVANCED, TAB_COUNT }; enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 }; struct TestSet { uint64_t frame; char key[64], value[64]; }; static struct { @@ -580,6 +582,54 @@ static void tab_menu(float scale) { opt_end(); } +// ---- Cheats: the cheats of cheats\.txt (cheats.c), a row per cheat in file order and a heading per group +// label; a cheat that cannot be switched here is greyed out with the reason. +static void tab_cheats(float scale) { + opt_begin("##cheats", scale); + static char line[512], desc[768], buttons[192]; + int n = cheats_count(); + if (!n) { + snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_NONE), + cheats_file()[0] ? cheats_file() : "cheats\\.txt"); + opt_text_str(line); + opt_end(); + return; + } + int listed = 0; + for (int i = 0; i < n; i++) listed += cheats_info(i)->kind != CHEAT_HEADING; + snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_FILE), cheats_file(), listed); + opt_text_str(line); + for (int i = 0; i < n; i++) { + const CheatInfo *c = cheats_info(i); + UiTextId text = UI_MENU_CHEAT_CODE_DESC; + switch (c->kind) { + case CHEAT_HEADING: + if (!strstr(c->name, "TID=")) opt_group_text(c->name); // the file's title line only names the game + continue; + case CHEAT_CODE: break; + case CHEAT_KEY: text = UI_MENU_CHEAT_KEY_DESC; break; + case CHEAT_DATA: text = UI_MENU_CHEAT_DATA_DESC; break; + case CHEAT_MASTER: text = UI_MENU_CHEAT_MASTER_DESC, opt_disable_next(UI_MENU_CHEAT_MASTER); break; + case CHEAT_RESTORE: text = UI_MENU_CHEAT_RESTORE_DESC, opt_disable_next(UI_MENU_CHEAT_RESTORE); break; + case CHEAT_REBUILD: text = UI_MENU_CHEAT_REBUILD_DESC, opt_disable_next(UI_MENU_CHEAT_REBUILD); break; + case CHEAT_UNSUPPORTED: + text = UI_MENU_CHEAT_UNSUPPORTED_DESC, opt_disable_next(UI_MENU_CHEAT_UNSUPPORTED); + break; + } + if (c->kind == CHEAT_KEY) + snprintf(desc, sizeof desc, menu_text(text), cheats_buttons(c->buttons, buttons, sizeof buttons)); + else if (c->kind == CHEAT_UNSUPPORTED) + snprintf(desc, sizeof desc, "%s %s", menu_text(text), c->note); + else + snprintf(desc, sizeof desc, "%s", menu_text(text)); + if (opt_toggle_text(c->key, c->name, desc, cheats_on(i) != 0)) { + cheats_set(i, !cheats_on(i)); + opt_save_soon(); + } + } + opt_end(); +} + // ---- Advanced: the testing and troubleshooting keys, the bug report helpers and the reset of every setting static bool g_modal; // the reset confirmation is open: B and Esc close it, not the menu; L / R stay on the page @@ -737,7 +787,8 @@ static void tab_advanced(float scale) { } static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, - UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED}; + UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_CHEATS, + UI_MENU_TAB_ADVANCED}; static int g_tab; // the tab shown static int g_tab_request = -1; // select this tab at the next layout; -1 none static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none @@ -789,6 +840,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { case TAB_SOUND: tab_sound(scale); break; case TAB_CONTROLS: tab_controls(scale); break; case TAB_MENU: tab_menu(scale); break; + case TAB_CHEATS: tab_cheats(scale); break; case TAB_ADVANCED: tab_advanced(scale); break; } ImGui::EndTabItem(); @@ -1065,6 +1117,7 @@ static void perf_draw(const MenuTarget *t, float scale) { extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) { *shot = NULL; + cheats_frame(frame); // the data cheats and the buttons of the cheats that need them held if (!g_test.parsed) test_parse(); if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame); if (g_perf_save.exchange(0)) cfg_save(); diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp index f0f82b36..50c8d5a7 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -33,15 +33,15 @@ static char g_focus_key[64]; // opt_focus_key: the row that takes th static bool g_held; // the last row's left / right has been held a while (steppers go faster) static float g_bottom; // opt_reserve_bottom: kept free under the panes static bool g_disable_next; // opt_disable_next: the next row is greyed out with g_disable_note -static UiTextId g_disable_note; +static const char *g_disable_note; // The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown. struct Desc { char text[512]; }; static Desc g_hover, g_focus, g_first, g_shown; // disabled: the note of a row opt_disable_next greyed out, else NULL. -static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m, const char *disabled) { - int n = snprintf(d.text, sizeof d.text, "%s", menu_text(desc)); +static void desc_set(Desc &d, const char *desc, const char *key, const CfgMeta *m, const char *disabled) { + int n = snprintf(d.text, sizeof d.text, "%s", desc); if (n < 0 || n >= (int)sizeof d.text) return; if (disabled) snprintf(d.text + n, sizeof d.text - n, "\n\n%s", disabled); @@ -57,7 +57,9 @@ void opt_focus_key(const char *key) { snprintf(g_focus_key, sizeof g_focus_key, void opt_reserve_bottom(float h) { g_bottom = h; } -void opt_disable_next(UiTextId note) { +void opt_disable_next(UiTextId note) { opt_disable_next_text(menu_text(note)); } + +void opt_disable_next_text(const char *note) { g_disable_next = true; g_disable_note = note; } @@ -109,9 +111,9 @@ struct RowView { // One row: draws it, handles A / click and left / right while selected. Returns 2 (A / click), -1 / +1 (left / right) or // 0; always 0 for a row the environment fixes (greyed out, still selectable so its description shows). -static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) { +static int row_text(const char *key, const char *label, const char *desc, const RowView &v) { const CfgMeta *m = cfg_meta(key); - const char *disabled = g_disable_next ? menu_text(g_disable_note) : NULL; + const char *disabled = g_disable_next ? g_disable_note : NULL; g_disable_next = false; bool off = disabled || cfg_from_env(key) != 0; ImGui::PushID(key); @@ -187,8 +189,7 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) } // the label and its note, clipped before the value ImVec4 clip(p.x, p.y, value_left - fs * 0.6f, p.y + h); - dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), menu_text(label), NULL, 0, - &clip); + dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), label, NULL, 0, &clip); const char *note = disabled ? disabled : off ? menu_text(UI_MENU_SET_BY_ENV) : m && !m->live ? menu_text(UI_MENU_AFTER_RESTART) @@ -198,6 +199,10 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) return off ? 0 : step; } +static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) { + return row_text(key, menu_text(label), menu_text(desc), v); +} + // ---- writing a setting: at once in memory (live settings follow), to totk.ini a moment later (opt_save_tick) static uint64_t g_save_at; // plat_now_ns deadline of the pending write; 0 none static bool g_save_logged; @@ -241,6 +246,26 @@ bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value return row(id, label, desc, v) == 2; // A or a click; left and right do nothing } +bool opt_toggle_text(const char *id, const char *label, const char *desc, bool on, const char *value) { + // off is the plain state: its value drawn dim, without the "default" mark + RowView v = {value ? value : menu_text(on ? UI_MENU_ON : UI_MENU_OFF), !on, false, on ? NULL : ""}; + return row_text(id, label, desc, v) != 0; // any step flips it +} + +void opt_group_text(const char *title) { + ImGui::Dummy(ImVec2(0, 6 * g_scale)); + ImGui::PushTextWrapPos(0); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", title); + ImGui::PopTextWrapPos(); +} + +void opt_text_str(const char *text, bool warn) { + ImGui::PushTextWrapPos(0); + if (warn) ImGui::TextColored(ImVec4(0.95f, 0.66f, 0.40f, 1), "%s", text); + else ImGui::TextUnformatted(text); + ImGui::PopTextWrapPos(); +} + void opt_group(UiTextId title) { ImGui::Dummy(ImVec2(0, 6 * g_scale)); ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(title)); @@ -400,9 +425,9 @@ int opt_bind_row(const char *key, const char *label, UiTextId desc, const char * } char k[64]; snprintf(k, sizeof k, "TOTK_%s", key); - if (row_foc) desc_set(g_focus, desc, k, NULL, NULL); - if (row_hov) desc_set(g_hover, desc, k, NULL, NULL); - if (!g_first.text[0]) desc_set(g_first, desc, k, NULL, NULL); + if (row_foc) desc_set(g_focus, menu_text(desc), k, NULL, NULL); + if (row_hov) desc_set(g_hover, menu_text(desc), k, NULL, NULL); + if (!g_first.text[0]) desc_set(g_first, menu_text(desc), k, NULL, NULL); if (note && (row_foc || row_hov)) { // e.g. what moved here, after the description Desc &d = row_hov ? g_hover : g_focus; size_t n = strlen(d.text); diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 6e03faf8..1e7e57c6 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -25,6 +25,7 @@ void opt_focus_first(void); void opt_focus_key(const char *key); // The next row is greyed out like one the environment fixes, with note under its label and in its description. void opt_disable_next(UiTextId note); +void opt_disable_next_text(const char *note); // note must outlive the frame // Page text that is not a row: a group heading in the accent colour, a wrapped paragraph (warn: the warning colour). void opt_group(UiTextId title); @@ -45,6 +46,12 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values, // A row that runs an action: true on A or a click. id: unique on the page and not a setting ("##copy_info"); value: // shown on the right ("" none). bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value = ""); +// Rows and text that are not settings of the cfg table: a label and description of the caller's own (the cheats of +// the cheat file). opt_toggle_text shows on / off (value: shown instead, NULL for On / Off) and returns true on A, a +// click, left or right; the caller changes its state. id: unique on the page, the environment check uses it. +bool opt_toggle_text(const char *id, const char *label, const char *desc, bool on, const char *value = nullptr); +void opt_group_text(const char *title); +void opt_text_str(const char *text, bool warn = false); // lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%"). bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1, const char *fmt = "%g"); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index f93107ae..a2389b5d 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -237,6 +237,22 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u, %.0f%%", [UI_MENU_OV_FMT_FSR] = "AMD FSR 1, sharpness %d%%", [UI_MENU_OV_SCALE_NONE] = "none (1:1)", [UI_MENU_OV_SCALE_BILINEAR] = "bilinear", + [UI_MENU_TAB_CHEATS] = "Cheats", + [UI_MENU_CHEATS_NONE] = "No cheats for this game version. Put an Atmosphere cheat file in %s next to totk.exe and " + "run the setup again on this folder: it builds the cheats that change the game's code.", + [UI_MENU_CHEATS_FILE] = "%s, %d cheats", + [UI_MENU_CHEAT_CODE_DESC] = "Changes the game's code. Switches at once.", + [UI_MENU_CHEAT_KEY_DESC] = "Changes the game's code while you hold %s. Switches at once.", + [UI_MENU_CHEAT_DATA_DESC] = "Writes the game's memory every frame while it is on.", + [UI_MENU_CHEAT_MASTER] = "always on", + [UI_MENU_CHEAT_MASTER_DESC] = "The file's master code: it is always on.", + [UI_MENU_CHEAT_RESTORE] = "not needed", + [UI_MENU_CHEAT_RESTORE_DESC] = "It only writes the game's own code back. Switching a cheat off already does that.", + [UI_MENU_CHEAT_REBUILD] = "run the setup again", + [UI_MENU_CHEAT_REBUILD_DESC] = "This cheat changes the game's code and is new or edited since the game was built. " + "Run the setup again on this folder to build it (about three minutes).", + [UI_MENU_CHEAT_UNSUPPORTED] = "not supported", + [UI_MENU_CHEAT_UNSUPPORTED_DESC] = "This cheat cannot be used with this version of the game:", }; static const char *const text_ru[UI_TEXT_COUNT] = { @@ -459,6 +475,22 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u, %.0f%%", [UI_MENU_OV_FMT_FSR] = "AMD FSR 1, резкость %d%%", [UI_MENU_OV_SCALE_NONE] = "нет (1:1)", [UI_MENU_OV_SCALE_BILINEAR] = "билинейное", + [UI_MENU_TAB_CHEATS] = "Читы", + [UI_MENU_CHEATS_NONE] = "Для этой версии игры читов нет. Положите файл читов Atmosphere в %s рядом с totk.exe и " + "запустите установщик для этой папки ещё раз: он соберёт читы, меняющие код игры.", + [UI_MENU_CHEATS_FILE] = "%s, читов: %d", + [UI_MENU_CHEAT_CODE_DESC] = "Меняет код игры. Включается и выключается сразу.", + [UI_MENU_CHEAT_KEY_DESC] = "Меняет код игры, пока вы держите %s. Включается и выключается сразу.", + [UI_MENU_CHEAT_DATA_DESC] = "Пока включён, записывает память игры каждый кадр.", + [UI_MENU_CHEAT_MASTER] = "всегда вкл.", + [UI_MENU_CHEAT_MASTER_DESC] = "Главный код файла: включён всегда.", + [UI_MENU_CHEAT_RESTORE] = "не нужен", + [UI_MENU_CHEAT_RESTORE_DESC] = "Он только возвращает исходный код игры. Выключение чита уже делает это.", + [UI_MENU_CHEAT_REBUILD] = "запустите установщик", + [UI_MENU_CHEAT_REBUILD_DESC] = "Этот чит меняет код игры и появился или изменился после сборки игры. Запустите " + "установщик для этой папки ещё раз, чтобы собрать его (около трёх минут).", + [UI_MENU_CHEAT_UNSUPPORTED] = "не поддерживается", + [UI_MENU_CHEAT_UNSUPPORTED_DESC] = "Этот чит нельзя использовать с этой версией игры:", }; #define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)} diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 6eb805cf..209a8a15 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -153,7 +153,14 @@ typedef enum { UI_MENU_OV_FMT_SCENE, // "%ux%u, %.0f%%": the scene and its share of the game image's width UI_MENU_OV_FMT_FSR, // "AMD FSR 1, sharpness %d%%" UI_MENU_OV_SCALE_NONE, UI_MENU_OV_SCALE_BILINEAR, - UI_MENU_LAST_ID = UI_MENU_OV_SCALE_BILINEAR, + // the Cheats tab (cheats.c): the file, the kinds of cheat and why one cannot be switched + UI_MENU_TAB_CHEATS, + UI_MENU_CHEATS_NONE, // "%s": cheats\.txt + UI_MENU_CHEATS_FILE, // "%s": the file, "%d": its cheats + UI_MENU_CHEAT_CODE_DESC, UI_MENU_CHEAT_KEY_DESC /* "%s": the buttons */, UI_MENU_CHEAT_DATA_DESC, + UI_MENU_CHEAT_MASTER, UI_MENU_CHEAT_MASTER_DESC, UI_MENU_CHEAT_RESTORE, UI_MENU_CHEAT_RESTORE_DESC, + UI_MENU_CHEAT_REBUILD, UI_MENU_CHEAT_REBUILD_DESC, UI_MENU_CHEAT_UNSUPPORTED, UI_MENU_CHEAT_UNSUPPORTED_DESC, + UI_MENU_LAST_ID = UI_MENU_CHEAT_UNSUPPORTED_DESC, UI_TEXT_COUNT } UiTextId; diff --git a/tools/cheats.py b/tools/cheats.py new file mode 100644 index 00000000..eb718a3e --- /dev/null +++ b/tools/cheats.py @@ -0,0 +1,349 @@ +"""Cheat file to code patch sets: the code cheats of an Atmosphere cheat file become patch sets of the lifted game. + +Lifted code cannot be written to while the game runs, so a cheat that writes instructions into main's .text is turned +into `site` lines (recomp/patches.py) when the game is lifted; the runtime (runtime/cheats.c) switches each cheat's set +from the in-game menu. A cheat that only writes data (heap, main's data, pointer chains, button conditions) needs no +patch: runtime/cheats.c runs it in its cheat VM. + + python tools/cheats.py --exefs --cheats .txt --patches --out --status + +--out gets the --patches file followed by one set per convertible cheat (`cheat_`, switch TOTK_CHEAT_, +default off) and its sites. --status gets one line per cheat of the file, in file order, tab separated: + + + +name hash: FNV-1a 32 of the UTF-8 name (a repeated name: name + "#2", "#3" ...), 8 upper-case hex digits; content +hash: the same over the cheat's words, so the runtime sees an edited cheat that was not rebuilt. kind: + code instruction writes, a patch set + key instruction writes while buttons are held (8 mask / writes / 21 else / the original words / 20): a patch + set the runtime switches on while the cheat is on and (hex HidNpadButton mask) are held + master a {master} cheat with instruction writes: a set that is always on + restore writes only the original instructions (switching a cheat off restores them): nothing to do + heading no opcodes (a title or a group label) + data no instruction writes: the runtime's cheat VM + unsupported says why +A code cheat that calls or jumps into a code cave it writes (words where main has zeros) gets the cave's body inlined +at the call site; a conditional skip of one store in the body (cbz wN, +8; str wN, ...) is dropped. + +Standard library and recomp/ only. +""" +import argparse +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'recomp')) +import flags # noqa: E402 +from lifter import Lifter # noqa: E402 +from nso import Nso # noqa: E402 + +BASE = 0x7000000000 # main's base in the layout (recomp/layout.py); only pc-relative decoding sees it +NOP = 0xD503201F +RET = 0xD65F03C0 + + +def fnv(data): + h = 0x811C9DC5 + for b in data: + h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF + return f'{h:08X}' + + +def build_id(main): + """The first 8 bytes of the NSO build id, as cheat files name themselves.""" + return Path(main).read_bytes()[0x40:0x48].hex().upper() + + +# ---- parsing + +class Cheat: + def __init__(self, name, master, line): + self.name, self.master, self.line, self.words = name, master, line, [] + self.key = self.kind = self.note = '' + self.buttons = 0 + self.sites = {} # {offset: [words]} + + +def parse(text): + """Cheats in file order; words that are not 8 hex digits are skipped.""" + out = [] + for no, raw in enumerate(text.splitlines(), 1): + s = raw.strip() + if len(s) >= 2 and s[0] in '[{' and s[-1] in ']}': + out.append(Cheat(s[1:-1].strip(), s[0] == '{', no)) + elif out: + for w in s.split(): + if len(w) == 8: + try: + out[-1].words.append(int(w, 16)) + except ValueError: + pass + seen = {} + for c in out: + n = seen[c.name] = seen.get(c.name, 0) + 1 + c.key = fnv((c.name if n == 1 else f'{c.name}#{n}').encode()) + return out + + +def ops(words): + """[(type, [words])] of a cheat; type is the opcode nibble, 0xC0.. for the extended ones. ValueError when the last + opcode is cut short.""" + out, i = [], 0 + while i < len(words): + w = words[i] + t = w >> 28 + width = (w >> 24) & 0xF + if t in (0, 1): + n = 4 if width == 8 else 3 + elif t in (2, 8): + n = 1 + elif t == 3: + n = 2 if (w >> 24) & 0xF == 0 else 1 + elif t in (4, 6): + n = 3 + elif t in (5, 7): + n = 2 + elif t == 9: + n = 1 + ((2 if width == 8 else 1) if (w >> 8) & 0xF else 0) + elif t == 0xA: + n = 2 if (w >> 8) & 0xF in (2, 4, 5) else 1 + else: + t = (w >> 24) & 0xFF if t == 0xC else (w >> 20) & 0xFFF + n = 1 + if i + n > len(words): + raise ValueError(f'opcode {w:08X} is cut short') + out.append((t, words[i:i + n])) + i += n + return out + + +VM_TYPES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA} + + +def vm_ok(o): + """None when runtime/cheats.c runs the opcode, else why not.""" + t, w = o + if t not in VM_TYPES: + return f'opcode {w[0]:08X} is not supported' + if t == 5 and (w[0] >> 12) & 0xF > 1: + return f'opcode {w[0]:08X} (load from a register offset) is not supported' + if t == 0xA and (w[0] >> 8) & 0xF > 5: + return f'opcode {w[0]:08X} is not supported' + if t in (0, 1, 5, 6, 7, 9, 0xA) and (w[0] >> 24) & 0xF not in (1, 2, 4, 8): + return f'opcode {w[0]:08X} has a bad width' + return None + + +# ---- instruction writes + +class Main: + def __init__(self, path): + n = Nso(str(path)) + self.image = bytes(n.image) + self.text = n.text # (offset, size) + self.code_end = n.rodata[0] # .text and its padding up to .rodata, where code caves go + self.lifter = Lifter(BASE, 'c') + + def in_text(self, off): + return self.text[0] <= off < self.text[0] + self.text[1] and off % 4 == 0 + + def in_code(self, off): + return self.text[0] <= off < self.code_end and off % 4 == 0 + + def word(self, off): + return struct.unpack_from('> 20) & 0xF != 0: + return None + width = (w[0] >> 24) & 0xF + off = ((w[0] & 0xFF) << 32) | w[1] + if not main.in_code(off - off % 4): + return None + if width == 4 and off % 4 == 0: + return {off: w[2]} + if width == 8 and off % 4 == 0: + return {off: w[3], off + 4: w[2]} + raise ValueError(f'a {width}-byte write into the code at main+{off:X}') + + +def branch(w, off): + """(kind, target offset) of a b / bl word at off, else None.""" + if w & 0x7C000000 == 0x14000000: + return ('bl' if w >> 31 else 'b', off + ((((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000) << 2)) + return None + + +def pc_relative(w): + """adr / adrp, a literal load, or any branch: wrong once moved to another address.""" + return (w & 0x1F000000 == 0x10000000 or w & 0x3B000000 == 0x18000000 or w & 0x7C000000 == 0x14000000 + or w & 0xFE000000 in (0x54000000, 0x34000000, 0x36000000, 0xB4000000, 0xB6000000) + or w & 0xFE000000 == 0xD6000000) + + +def skip_store(body, i): + """body[i] is cbz / cbnz wN / xN, +8 and body[i + 1] a str of that register: the skip can go (the cheat stores + only when the value is non-zero).""" + w = body[i] + if w & 0x7E000000 != 0x34000000 or (w >> 5) & 0x7FFFF != 2 or i + 1 >= len(body): + return False + s = body[i + 1] + return s & 0x3B400000 == 0x39000000 and s & 0x1F == w & 0x1F # str (unsigned offset), same Rt + + +def cave_body(writes, caves, start, back, call): + """The cave's words from start up to its ret (call) or its b to back.""" + body, a = [], start + while True: + if a not in caves: + raise ValueError(f'the cheat branches to main+{a:X}, which it does not write') + w = writes[a] + if call and w == RET: + return body + b = branch(w, a) + if not call and b and b[0] == 'b' and b[1] == back: + return body + body.append(w) + a += 4 + if len(body) > 64: + raise ValueError('a code cave of more than 64 instructions') + + +def convert(main, writes): + """{offset: [replacement words]} of a set of instruction writes; ValueError when it cannot.""" + caves = {a for a in writes if main.word(a) == 0} + sites = {} + for a, w in sorted(writes.items()): + if a in caves or w == main.word(a): + continue + if not main.in_text(a): + raise ValueError(f'main+{a:X} is past the end of the code') + b = branch(w, a) + if b and b[1] in caves: + body = cave_body(writes, caves, b[1], a + 4, b[0] == 'bl') + out = [] + for i, x in enumerate(body): + if skip_store(body, i): + continue + if pc_relative(x): + raise ValueError(f'the code cave at main+{b[1]:X} has a branch or pc-relative instruction') + out.append(x) + repl = out or [NOP] + else: + repl = [w] + orig = main.word(a) + kind = main.lift(orig, a).kind + if kind not in ('op', 'bl', 'b', 'bcond'): + raise ValueError(f'main+{a:X} is a {kind}, which a patch cannot replace') + last = main.lift(repl[-1], a).kind + if last not in ('op', 'bl', 'b', 'bcond', 'ret'): + raise ValueError(f'main+{a:X} gets a {last}') + want = main.effect(orig, a)[1] + got = [e[1] for e in (main.effect(x, a) for x in repl) if e[1]] + if (got[0] if got else None) != want or len(got) > 1: + # a nop over adds / subs Rd, Rd, #imm: subtract 0 instead, the flags still written and Rd unchanged + if repl == [NOP] and orig & 0x1F000000 == 0x11000000 and orig & 0x20000000 and \ + orig & 0x1F == (orig >> 5) & 0x1F: + repl = [orig & ~0x003FFC00] + else: + raise ValueError(f'main+{a:X}: the cheat changes the CPU flags differently from the game') + sites[a] = repl + return sites + + +def classify(main, c): + try: + os_ = ops(c.words) + except ValueError as e: + c.kind, c.note = 'unsupported', str(e) + return + os_ = [o for o in os_ if not (o[0] == 2 and len(os_) == 1)] # [Link] 20000000: a label + if not os_: + c.kind = 'heading' + return + try: + cw = [code_writes(main, o) for o in os_] + except ValueError as e: + c.kind, c.note = 'unsupported', str(e) + return + if not any(x is not None for x in cw): + bad = next((r for r in map(vm_ok, os_) if r), None) + c.kind, c.note = ('unsupported', bad) if bad else ('data', '') + return + try: + if all(x is not None for x in cw): + writes = {k: v for x in cw for k, v in x.items()} + if all(main.word(a) == w for a, w in writes.items()): + c.kind = 'restore' + return + c.sites, c.kind = convert(main, writes), 'master' if c.master else 'code' + return + # 8 mask, writes, 21000000, the original words, 20000000 + t = [o[0] for o in os_] + els = next((i for i, o in enumerate(os_) if o[0] == 2 and (o[1][0] >> 24) & 0xF == 1), -1) + if (t[0] == 8 and t[-1] == 2 and (os_[-1][1][0] >> 24) & 0xF == 0 and els > 1 + and all(x is not None for x in cw[1:els] + cw[els + 1:-1])): + on = {k: v for x in cw[1:els] for k, v in x.items()} + off = {k: v for x in cw[els + 1:-1] for k, v in x.items()} + if set(off) == set(on) and all(main.word(a) == w for a, w in off.items()): + c.sites, c.kind, c.buttons = convert(main, on), 'key', os_[0][1][0] & 0x0FFFFFFF + return + raise ValueError('it mixes instruction writes with other cheat opcodes') + except ValueError as e: + c.kind, c.note, c.sites = 'unsupported', str(e), {} + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument('--exefs', type=Path, required=True) + ap.add_argument('--cheats', type=Path, required=True) + ap.add_argument('--patches', type=Path, required=True, help='the game version\'s patch file') + ap.add_argument('--out', type=Path, required=True, help='the patch file with the cheats added') + ap.add_argument('--status', type=Path, required=True) + args = ap.parse_args() + sys.stdout.reconfigure(errors='replace') # cheat names in a console without their characters + m = Main(args.exefs / 'main') + text = args.patches.read_text() + cheats = parse(args.cheats.read_text(encoding='utf-8-sig', errors='replace')) if args.cheats.is_file() else [] + sets, sites, status = [], [], [] + for c in cheats: + classify(m, c) + if c.sites: + name = f'cheat_{c.key.lower()}' + label = c.name.encode('ascii', 'replace').decode() # recomp/patches.py reads the file as ASCII + sets.append(f'set {name} TOTK_CHEAT_{c.key} {1 if c.kind == "master" else 0} # {label}') + for a, repl in sorted(c.sites.items()): + sites.append(f'site {name} main {a:x} {m.word(a):08x} {" ".join(f"{w:08x}" for w in repl)}') + content = fnv(' '.join(f'{w:08X}' for w in c.words).encode()) + note = c.note.replace('\t', ' ') + status.append(f'{c.key}\t{content}\t{c.kind}\t{c.buttons:X}\t{note}') + print(f'cheats: {c.kind:11} {c.name}' + (f' ({note})' if note else '')) + if sets: + text += (f'\n# Cheats of {args.cheats.name} (tools/cheats.py)\n' + '\n'.join(sets) + '\n' + + '\n'.join(sites) + '\n') + args.out.write_text(text) + args.status.write_text('\n'.join(status) + ('\n' if status else ''), encoding='utf-8') + kinds = {} + for c in cheats: + kinds[c.kind] = kinds.get(c.kind, 0) + 1 + print(f'cheats: {len(cheats)} in {args.cheats.name}: ' + + ', '.join(f'{n} {k}' for k, n in sorted(kinds.items())) + f'; {len(sites)} sites') + + +if __name__ == '__main__': + main() diff --git a/totk.ini.example b/totk.ini.example index f8213a99..1c73c84e 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -172,6 +172,11 @@ # Folder with RomFS mod files that replace or add game files. Default: none. # romfs_mods = +[cheats] +# One line per cheat of cheats\.txt next to totk.exe (docs/cheats.md); the Cheats tab of the menu writes +# them. cheat_ = 1 switches a cheat on, the hash being FNV-1a 32 of its name. Default: every cheat off. +# cheat_0123abcd = 1 + [diagnostics] # Extra lines in the log, comma separated: svc, host, ipc, fs, gfx, perf, sched, audio, present or all. The menu's # Performance log sets perf (frame timings). Default: none. From bfb49335312bc80452731ca70edf80191e703e52 Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:47:47 +0100 Subject: [PATCH 002/177] Add shadow map resolution and anisotropic filtering settings TotK draws its sun cascades into a 960x960 DEPTH16 array of 4 layers, and its static shadows into 1440x1440 and 720x720 arrays of 2, whatever the output resolution, and shrinks the cascades under load. shadow_scale (1 to 4, default 1) creates those images that many times larger on each side: passes into them scale the game's viewports, scissors and support-buffer viewport size, and copies scale their regions, so the game is unaware of it. Images the CPU writes or that alias pool memory keep their size. When the maps are enlarged, depth-compare samplers filter linearly, because the game's few nearest taps are spaced for its own texels and leave hard, stepped edges otherwise. aniso (game, 2, 4, 8, 16; default 16) raises anisotropic filtering of linear mipmapped colour samplers; depth-compare, nearest and unmipmapped samplers keep the game's setting. Both are in totk.ini.example and on the Screen tab of the settings menu (English and Russian). Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 7 +++--- runtime/ui/menu.cpp | 15 +++++++++++++ runtime/ui_text.c | 14 ++++++++++++ runtime/ui_text.h | 2 ++ runtime/vk.h | 3 +++ runtime/vk_exec.c | 11 +++++++--- runtime/vk_exec.h | 3 +++ runtime/vk_exec_draw.c | 10 ++++++--- runtime/vk_exec_xfer.c | 11 +++++++--- runtime/vk_texture.c | 50 +++++++++++++++++++++++++++++++++++++++--- totk.ini.example | 7 ++++++ 11 files changed, 118 insertions(+), 15 deletions(-) diff --git a/runtime/cfg.c b/runtime/cfg.c index 84abed08..11cebb4a 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -30,7 +30,7 @@ static int save_ok = 1; // the last cfg_save_to wrote (o // Every name the runtime reads (and the patch sets in generated/), without the prefix. A file key outside this list is // logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line. static const char *const known[] = { - "AB", "APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", + "AB", "ANISO", "APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT", "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", @@ -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", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "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", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -93,6 +93,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, + {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 64c3c4c0..a9ee648f 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -438,6 +438,19 @@ static void row_render_scale(void) { opt_choice_list("TOTK_RENDER_SCALE", UI_MENU_RENDER_SCALE, vals, names, N, UI_MENU_RENDER_SCALE_DESC); } +static void row_aniso(void) { + static const char *const vals[] = {"game", "2", "4", "8", "16"}; + static const char *names[] = {NULL, "2x", "4x", "8x", "16x"}; + names[0] = menu_text(UI_MENU_ANISO_GAME); + opt_choice_list("TOTK_ANISO", UI_MENU_ANISO, vals, names, 5, UI_MENU_ANISO_DESC); +} + +static void row_shadow_scale(void) { + static const char *const vals[] = {"1", "2", "3", "4"}; + static const char *const names[] = {"960 (1x)", "1920 (2x)", "2880 (3x)", "3840 (4x)"}; + opt_choice_list("TOTK_SHADOW_SCALE", UI_MENU_SHADOW_SCALE, vals, names, 4, UI_MENU_SHADOW_SCALE_DESC); +} + static void row_gpu(void) { const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1]; char idx[MAX_GPUS][4]; @@ -528,6 +541,8 @@ static void tab_screen(float scale) { static const UiTextId up[] = {UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR}; opt_choice("TOTK_UPSCALER", UI_MENU_UPSCALER, up, 2, UI_MENU_UPSCALER_DESC); opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%"); + row_aniso(); + row_shadow_scale(); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index f93107ae..aa31587e 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -63,6 +63,13 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", + [UI_MENU_ANISO] = "Anisotropic filtering", + [UI_MENU_ANISO_DESC] = "Keeps ground and walls seen at a steep angle sharp. The game's own level is the Switch's; " + "16x costs little on a desktop GPU.", + [UI_MENU_ANISO_GAME] = "The game's", + [UI_MENU_SHADOW_SCALE] = "Shadow resolution", + [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " + "sharper shadow edges and leaf shadows. Takes effect at the next start.", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -281,6 +288,13 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Билинейное", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", + [UI_MENU_ANISO] = "Анизотропная фильтрация", + [UI_MENU_ANISO_DESC] = "Сохраняет чёткость земли и стен под острым углом. Уровень самой игры — как на Switch; " + "16x почти ничего не стоит настольной видеокарте.", + [UI_MENU_ANISO_GAME] = "Как в игре", + [UI_MENU_SHADOW_SCALE] = "Разрешение теней", + [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " + "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 6eb805cf..680e9cfe 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -36,6 +36,8 @@ typedef enum { UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME, UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, + UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, + UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/runtime/vk.h b/runtime/vk.h index 961f2f35..fdfaf319 100644 --- a/runtime/vk.h +++ b/runtime/vk.h @@ -268,6 +268,9 @@ typedef struct { uint8_t fb_usage; // created with ATTACHMENT_FEEDBACK_LOOP usage (VK_FEEDBACK_LAYOUT, attachable images) uint8_t fb_learned; // a draw sampled it while it was a written attachment of the open pass: its passes // attach it in ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT (vk_exec.c vk_exec_pass_begin) + uint8_t scale; // 1, or TOTK_SHADOW_SCALE for a shadow map made larger than the game's (vk_texture.c + // shadow_scale_of): width and height above are the larger ones, the game's regions + // are multiplied by it } VkTexImage; const VkTexImage *vk_texture_get(const tex_t *t); // created and made current; NULL for BUFFER or unmapped formats // A texture slot; a slot whose texture was finalized follows the live texture at the same storage (hle_nvn.c). diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index d82c0574..0abd2b63 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -192,6 +192,7 @@ static void resolve_target(const tex_t *t, const view_t *v, int has_v, int depth } o->image = img->image; o->img = img; + o->scale = img->scale ? img->scale : 1; o->format = fmt; o->view_type = layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D; o->aspect = depth_slot ? img->aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) @@ -227,7 +228,7 @@ static void resolve_rt(VkExec *ex) { ex->rt_resolved = 1; const p_set_rt *r = &ex->rt; int n = r->n < 0 ? 0 : r->n > 8 ? 8 : r->n; - uint32_t w = UINT32_MAX, h = UINT32_MAX, layers = UINT32_MAX, samples = 0; + uint32_t w = UINT32_MAX, h = UINT32_MAX, layers = UINT32_MAX, samples = 0, scale = 1; for (int i = 0; i < 8; i++) { VkExecTarget *t = &ex->color[i]; resolve_target(i < n ? r->color[i] : NULL, &r->cview[i], i < n && r->has_cview[i], 0, t); @@ -238,6 +239,7 @@ static void resolve_rt(VkExec *ex) { if (t->height < h) h = t->height; if (t->layers < layers) layers = t->layers; if (!samples) samples = t->samples; + if (t->scale > scale) scale = t->scale; } VkExecTarget *d = &ex->depth; resolve_target(r->depth, &r->dview, r->has_dview, 1, d); @@ -249,6 +251,7 @@ static void resolve_rt(VkExec *ex) { if (d->height < h) h = d->height; if (d->layers < layers) layers = d->layers; if (!samples) samples = d->samples; + if (d->scale > scale) scale = d->scale; } ex->pass_noatt = w == UINT32_MAX; if (ex->pass_noatt) { @@ -260,6 +263,7 @@ static void resolve_rt(VkExec *ex) { ex->vp[0][1], ex->vp[0][2], ex->vp[0][3]); } ex->pass_w = w, ex->pass_h = h, ex->pass_layers = layers; + ex->pass_scale = ex->pass_noatt ? 1 : scale; ex->pass_ncolor = (uint32_t)n; ex->pass_samples = samples ? samples : 1; ex->pipe.samples = (uint8_t)ex->pass_samples; @@ -511,8 +515,9 @@ VkBuffer vk_exec_inline_buffer(VkDeviceSize size) { VkRect2D vk_exec_scissor(const VkExec *ex) { int64_t w = ex->pass_w, h = ex->pass_h; if (!ex->has_scissor) return (VkRect2D){{0, 0}, {(uint32_t)w, (uint32_t)h}}; - int64_t x0 = ex->scissor.x, y0 = ex->scissor.y; - int64_t x1 = x0 + ex->scissor.w, y1 = y0 + ex->scissor.h; + int64_t k = ex->pass_scale > 1 ? ex->pass_scale : 1; + int64_t x0 = ex->scissor.x * k, y0 = ex->scissor.y * k; + int64_t x1 = x0 + (int64_t)ex->scissor.w * k, y1 = y0 + (int64_t)ex->scissor.h * k; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x1 > w) x1 = w; diff --git a/runtime/vk_exec.h b/runtime/vk_exec.h index c81d5c61..b0095f63 100644 --- a/runtime/vk_exec.h +++ b/runtime/vk_exec.h @@ -35,6 +35,7 @@ typedef struct { uint32_t width, height, samples; // extent of that level; with blocks, in blocks int32_t nvn_format; // NVNformat of the view (VkPipeState.color_fmt / depth_fmt) const VkTexImage *img; // the image (fb_usage, fb_learned) + uint8_t scale; // VkTexImage.scale } VkExecTarget; // The replay state. One instance lives for the run: NVN state is queue state and carries over from one submission to @@ -52,6 +53,8 @@ typedef struct VkExec { int rt_resolved; // color[] and depth hold this command buffer's images for rt VkExecTarget color[8], depth; // resolved targets uint32_t pass_w, pass_h, pass_layers; // render area and layer count of the open (or next) pass + uint32_t pass_scale; // its targets' VkTexImage.scale: game viewports and scissors + // are multiplied by it int pass_noatt; // the pass has no attachment: its size follows the draws (vk_exec_noatt_dims) VkFormat pass_color[8], pass_depth, pass_stencil; // attachment formats of the pass (VkPipelineRenderingCreateInfo); // VK_FORMAT_UNDEFINED: none diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index e9326df5..e23741e9 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -1240,8 +1240,9 @@ static VkDescriptorSet alloc_set(VkExec *ex, VkDescriptorSetLayout layout) { } static void support_in(const VkExec *ex, float in[3]) { // what support_fill reads: viewport size, point size - in[0] = ex->in_pass && ex->has_vp ? ex->vp[0][2] : (float)ex->pass_w; - in[1] = ex->in_pass && ex->has_vp ? ex->vp[0][3] : (float)ex->pass_h; + float k = ex->pass_scale > 1 ? (float)ex->pass_scale : 1.0f; + in[0] = ex->in_pass && ex->has_vp ? ex->vp[0][2] * k : (float)ex->pass_w; + in[1] = ex->in_pass && ex->has_vp ? ex->vp[0][3] * k : (float)ex->pass_h; in[2] = ex->point_size > 0 ? ex->point_size : 1.0f; } @@ -1670,7 +1671,10 @@ static void record_fixed(VkExec *ex) { VkCommandBuffer cb = ex->cb; if (ex->dirty & VK_EXEC_DIRTY_VIEWPORT) { float x = 0, y = 0, w = (float)ex->pass_w, h = (float)ex->pass_h; - if (ex->has_vp) x = ex->vp[0][0], y = ex->vp[0][1], w = ex->vp[0][2], h = ex->vp[0][3]; + if (ex->has_vp) { + float k = ex->pass_scale > 1 ? (float)ex->pass_scale : 1.0f; + x = ex->vp[0][0] * k, y = ex->vp[0][1] * k, w = ex->vp[0][2] * k, h = ex->vp[0][3] * k; + } if (w < 1) w = 1; if (h < 1) h = 1; VkViewport v = {x, y + h, w, -h, ex->depth_range[0], ex->depth_range[1]}; // the y flip: negative height diff --git a/runtime/vk_exec_xfer.c b/runtime/vk_exec_xfer.c index 34548153..ffb3b420 100644 --- a/runtime/vk_exec_xfer.c +++ b/runtime/vk_exec_xfer.c @@ -352,10 +352,11 @@ static int sub_resolve(const tex_t *t, const view_t *v, int has_v, const NVNcopy s->level = has_v && v->set_levels ? v->base_level : 0; s->layer0 = has_v && v->set_layers ? v->min_layer : 0; uint32_t lw = max1(img->width >> s->level), lh = max1(img->height >> s->level); - s->x = r->xoffset, s->y = r->yoffset, s->z = r->zoffset; + int k = img->scale > 1 ? img->scale : 1; // a larger shadow map: the game's region in its texels + s->x = r->xoffset * k, s->y = r->yoffset * k, s->z = r->zoffset; s->nz = r->depth > 0 ? (uint32_t)r->depth : 1; - s->w = r->width > 0 ? (uint32_t)r->width : defaults_to_level ? (s->x < (int32_t)lw ? lw - (uint32_t)s->x : 0) : 0; - s->h = r->height > 0 ? (uint32_t)r->height : defaults_to_level ? (s->y < (int32_t)lh ? lh - (uint32_t)s->y : 0) : 0; + s->w = r->width > 0 ? (uint32_t)r->width * k : defaults_to_level ? (s->x < (int32_t)lw ? lw - (uint32_t)s->x : 0) : 0; + s->h = r->height > 0 ? (uint32_t)r->height * k : defaults_to_level ? (s->y < (int32_t)lh ? lh - (uint32_t)s->y : 0) : 0; int is3d = img->type == VK_IMAGE_TYPE_3D; uint32_t layers = is3d ? 1 : (uint32_t)s->z + s->nz, first = is3d ? 0 : s->layer0; if (s->level >= img->levels || s->x < 0 || s->y < 0 || s->z < 0 || !s->w || !s->h || @@ -411,6 +412,10 @@ static int buffer_side(const VkExec *ex, const Sub *s, uint64_t addr, uint64_t * static void copy_buffer_image(VkExec *ex, const p_copy_b2t *p, int to_image) { Sub s; if (!sub_resolve(p->tex, &p->view, p->has_view, &p->r, 1, &s)) return; + if (s.img->scale > 1) { // the buffer holds the game's texel count, the image more + warn_once(W_REGION, "buffer copy of a shadow map enlarged by TOTK_SHADOW_SCALE: skipped"); + return; + } uint64_t size; VkBufferImageCopy c; VkMemSpan m; diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index b65f21e7..e2fda908 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -273,6 +273,33 @@ static void init_image(Tex *e, VkCommandBuffer cb) { } } +// TOTK_SHADOW_SCALE (1 to 4): the game's shadow maps are made this many times larger on each side. TotK renders its +// sun cascades into a 960x960 DEPTH16 2D array of 4 layers and its static shadows into 1440x1440 and 720x720 arrays of 2, +// whatever the output resolution, and shrinks the cascades under load (872, 848, 800, 480 and so on). Those are made +// larger here: render passes into them scale the game's viewports and scissors (vk_exec.c resolve_rt, pass_scale), +// copies scale their regions (vk_exec_xfer.c sub_resolve), and shaders sample them with normalised coordinates, so the +// game sees nothing of it. A map whose storage the CPU writes (mirrored) or that aliases pool memory keeps its size, +// as its texels must match the guest layout. +static int shadow_scale(void) { + static int scale = -1; + if (scale < 0) { + int s = cfg_int("TOTK_SHADOW_SCALE"); + s = s < 1 ? 1 : s > 4 ? 4 : s; + rt_log("vk: shadow map scale %d", s); + scale = s; + } + return scale; +} + +static int shadow_scale_of(const nvn_texdesc *d, const TexVkFormat *f, uint32_t samples, int mirrored) { + int scale = shadow_scale(); + if (scale == 1 || mirrored || samples > 1 || d->format != NVN_FORMAT_DEPTH16 || !f->depth) return 1; + if (d->target != NVN_TEXTURE_TARGET_2D_ARRAY || d->width != d->height || d->width < 256 || d->depth < 2 || d->depth > 4) + return 1; + uint32_t most = vk_ctx()->props.limits.maxImageDimension2D; + return d->width * (uint32_t)scale <= most ? scale : 1; +} + // defer_init: the caller records the image's first transition (init_image or alias_copy). static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { static volatile long n_unmapped, n_unsupported, n_failed, n_unbound; @@ -300,6 +327,8 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { case NVN_TEXTURE_TARGET_CUBEMAP: case NVN_TEXTURE_TARGET_CUBEMAP_ARRAY: layers = L.layers; break; default: break; } + int scale = shadow_scale_of(d, &f, d->samples > 1 ? (uint32_t)d->samples : 1, tex_mirrored(t)); + w *= (uint32_t)scale, h *= (uint32_t)scale; uint32_t levels = umax(d->levels, 1), most = 1; for (uint32_t s = umax(umax(w, h), depth); s > 1; s >>= 1) most++; if (levels > most) levels = most; @@ -342,7 +371,7 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { e->f = f; e->pub.addr = k->addr; VkImage img = VK_NULL_HANDLE; - if (nvn_gpu_only(k->addr)) { // storage in a physical or virtual pool: alias the pool memory (section 3.2) + if (scale == 1 && nvn_gpu_only(k->addr)) { // storage in a physical or virtual pool: alias the pool memory (section 3.2) if (vkCreateImage(c->device, &ci, NULL, &img) == VK_SUCCESS && !bind_pool_memory(c, e, img)) { vkDestroyImage(c->device, img, NULL); img = VK_NULL_HANDLE; @@ -384,6 +413,7 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { p->bound = e->bound_to != NULL; p->block_views = (uint8_t)block_views; p->fb_usage = (uint8_t)fb_usage; + p->scale = (uint8_t)scale; if (!defer_init) { init_image(e, vk_upload_begin()); @@ -1421,6 +1451,7 @@ static VkCompareOp compare_op(uint32_t f) { } static struct { int init, mirror_clamp_edge, minmax, border_no_format; } sf; +static float aniso_force; // TOTK_ANISO: 0 = the game's level, else the least level of mipmapped colour samplers static void sampler_features(VkCtx *c) { if (sf.init) return; @@ -1432,6 +1463,9 @@ static void sampler_features(VkCtx *c) { sf.mirror_clamp_edge = f12.samplerMirrorClampToEdge; sf.minmax = f12.samplerFilterMinmax; sf.border_no_format = c->has_custom_border_color && cbf.customBorderColors && cbf.customBorderColorWithoutFormat; + const char *an = cfg_value("TOTK_ANISO"); + aniso_force = strcmp(an, "game") ? (float)atoi(an) : 0; + rt_log("vk: anisotropic filtering: %s", aniso_force > 1 ? an : "the game's"); sf.init = 1; } @@ -1466,13 +1500,23 @@ static VkSampler make_sampler(VkCtx *c, const samp_par *d) { if (si.maxLod < si.minLod) si.maxLod = si.minLod; float lim = c->props.limits.maxSamplerLodBias; si.mipLodBias = fmaxf(-lim, fminf(lim, d->lod_bias)); - if (d->aniso > 1) { + float aniso = d->aniso; + // TOTK_ANISO raises the level for filtered, mipmapped colour samplers only: depth-compare (shadow) samplers and + // nearest or unmipmapped ones (data maps, LUTs) keep what the game set. + if (aniso_force > 1 && !d->cmp_mode && si.magFilter == VK_FILTER_LINEAR && si.minFilter == VK_FILTER_LINEAR && + (mf == NVN_MIN_FILTER_LINEAR_MIPMAP_NEAREST || mf == NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR) && aniso < aniso_force) + aniso = aniso_force; + if (aniso > 1) { si.anisotropyEnable = VK_TRUE; - si.maxAnisotropy = fminf(d->aniso, c->props.limits.maxSamplerAnisotropy); + si.maxAnisotropy = fminf(aniso, c->props.limits.maxSamplerAnisotropy); } if (d->cmp_mode) { si.compareEnable = VK_TRUE; si.compareOp = compare_op(d->cmp_func); + // A depth-compare sampler set to nearest returns 0 or 1 per tap, and the game's shaders smooth shadow edges by + // a few taps spaced for its own shadow map texels. With TOTK_SHADOW_SCALE those taps cover a fraction of the + // area and the edges turn hard and stepped; linear filtering makes every tap a 2x2 PCF instead. + if (shadow_scale() > 1) si.magFilter = si.minFilter = VK_FILTER_LINEAR; } VkSamplerCustomBorderColorCreateInfoEXT cb = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT}; VkSamplerReductionModeCreateInfo rm = {.sType = VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; diff --git a/totk.ini.example b/totk.ini.example index f8213a99..68e9f306 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -115,6 +115,13 @@ # from 0 (off) to 100. Changes while the game runs take effect at once. # upscaler = fsr # sharpness = 80 +# Anisotropic filtering of mipmapped textures: game (the level the game asks for, as on the Switch) or 2, 4, 8, 16. +# Keeps ground and walls seen at a steep angle sharp. Depth-compare (shadow) and nearest-filtered samplers keep the +# game's setting. Read at start. +# aniso = 16 +# Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game +# resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. Read at start. +# shadow_scale = 1 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 386e70453b4f5be8eed1ff4704c05ff249bd894f Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:06:58 +0100 Subject: [PATCH 003/177] Add a shadow cascade range setting for 1.4.3 The sun's shadow cascades end at 20, 40, 80 and 160 m: the depth shadow parameter object (main+0x6fa3c0) registers depth_shadow_near_0_1..3 and depth_shadow_far_0 as immediates, and the field's .bgsdw files do not override them. The new cascade patch set reads the four distances from patch page +64..+76 instead, and shadow_range (percent, 50 to 400, default 100) writes them there at start, so the visible steps where shadows turn softer move away from the player. It spreads the shadow map over more ground, which shadow_scale pays back. Only patches-v143.txt has the set; on 1.2.1 the setting logs that and does nothing. The setting is in totk.ini.example and on the Screen tab of the menu (English and Russian). Co-Authored-By: Claude Opus 5.5 --- recomp/patches-v143.txt | 9 +++++++++ runtime/cfg.c | 5 +++-- runtime/resolution.c | 18 ++++++++++++++++++ runtime/ui/menu.cpp | 7 +++++++ runtime/ui_text.c | 8 ++++++++ runtime/ui_text.h | 1 + totk.ini.example | 3 +++ 7 files changed, 49 insertions(+), 2 deletions(-) diff --git a/recomp/patches-v143.txt b/recomp/patches-v143.txt index 16189169..dd47fea5 100644 --- a/recomp/patches-v143.txt +++ b/recomp/patches-v143.txt @@ -10,6 +10,7 @@ set cloth TOTK_CLOTH_REALTIME 1 set bounce TOTK_HIGHFPS_FIX 1 set output TOTK_PATCH_OUTPUT 0 set scene TOTK_PATCH_SCENE 0 +set cascade TOTK_PATCH_CASCADE 0 # 60 fps: the adaptive present-interval controller (main+0x2db174, 1.2.1 0x8f26c8) gets the minimum interval 1. site fps60 main 2db204 6b08015f 7100055f # clamp: cmp w10, #1 (was cmp w10, w8 = minimum) @@ -936,3 +937,11 @@ spin subsdk0 1c4e54 1c4e60 # 4 instructions; loads spin sdk 2d3654 2d3668 # 6 instructions; loads spin sdk 443864 443884 # 9 instructions; loads spin sdk 541e54 541f98 # 32 instructions; loads + +# Sun shadow cascade distances (runtime/resolution.c res_shadow_range switches the set on). The depth shadow parameter +# object (main+0x6fa3c0) registers depth_shadow_near_0_1..3 = 20, 40, 80 m and depth_shadow_far_0 = 160 m as +# immediates, and the field's .bgsdw files do not override them; with the set on they come from page +64..+76. +site cascade main 6fabb8 52a83408 @page:x8 b9404108 # mov w8, #20.0 -> ldr w8, [page+64] +site cascade main 6fac40 52a84408 @page:x8 b9404508 # mov w8, #40.0 -> ldr w8, [page+68] +site cascade main 6facc8 52a85408 @page:x8 b9404908 # mov w8, #80.0 -> ldr w8, [page+72] +site cascade main 6fad4c 52a86408 @page:x8 b9404d08 # mov w8, #160.0 -> ldr w8, [page+76] diff --git a/runtime/cfg.c b/runtime/cfg.c index 11cebb4a..bfd87294 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", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", + "SHADER_MEMO", "SHADOW_RANGE", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "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", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -94,6 +94,7 @@ static const CfgMeta metas[] = { {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, + {"SHADOW_RANGE", "100", "50..400", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/resolution.c b/runtime/resolution.c index 2e4b1d7c..fc8d5524 100644 --- a/runtime/resolution.c +++ b/runtime/resolution.c @@ -191,7 +191,25 @@ void res_heapdef_served(void) { R.heapdef_ok = 1; } // ---- start: the patch page and the sets static uint64_t pack(unsigned w, unsigned h) { return (uint64_t)h << 32 | w; } +// TOTK_SHADOW_RANGE (percent, 50 to 400; 100 = the game's): the sun's shadow cascades end at 20, 40, 80 and 160 m. +// Other values multiply those distances through the cascade patch set (recomp/patches-v143.txt), so the sharp first +// cascade reaches further and the visible steps between cascades move away from the player, at the cost of shadow +// texels per metre (TOTK_SHADOW_SCALE pays that back). +static void res_shadow_range(void) { + int pct = cfg_int("TOTK_SHADOW_RANGE"), set = rt_patch_set("cascade"); + if (pct == 100) return; + if (set < 0) { + rt_log("resolution: the generated C has no cascade patch set; shadow_range stays 100"); + return; + } + float k = (float)(pct < 50 ? 50 : pct > 400 ? 400 : pct) / 100.0f, d[4] = {20 * k, 40 * k, 80 * k, 160 * k}; + memcpy((uint8_t *)rt_patch_page() + 64, d, sizeof d); + rt_patch_switch(set, 1); + rt_log("resolution: shadow cascades end at %g, %g, %g and %g m", d[0], d[1], d[2], d[3]); +} + void res_init(void) { + res_shadow_range(); if (!bigger()) { rt_log("resolution: the game's own (output 1920x1080, scene 1600x900)"); return; diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index a9ee648f..d3eb04f9 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -451,6 +451,12 @@ static void row_shadow_scale(void) { opt_choice_list("TOTK_SHADOW_SCALE", UI_MENU_SHADOW_SCALE, vals, names, 4, UI_MENU_SHADOW_SCALE_DESC); } +static void row_shadow_range(void) { + static const char *const vals[] = {"100", "150", "200", "300"}; + static const char *const names[] = {"160 m (1x)", "240 m (1.5x)", "320 m (2x)", "480 m (3x)"}; + opt_choice_list("TOTK_SHADOW_RANGE", UI_MENU_SHADOW_RANGE, vals, names, 4, UI_MENU_SHADOW_RANGE_DESC); +} + static void row_gpu(void) { const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1]; char idx[MAX_GPUS][4]; @@ -543,6 +549,7 @@ static void tab_screen(float scale) { opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%"); row_aniso(); row_shadow_scale(); + row_shadow_range(); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index aa31587e..d279674a 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -70,6 +70,10 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Shadow resolution", [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " "sharper shadow edges and leaf shadows. Takes effect at the next start.", + [UI_MENU_SHADOW_RANGE] = "Shadow cascade range", + [UI_MENU_SHADOW_RANGE_DESC] = "Moves the steps where shadows turn softer (the game's 20, 40, 80 and 160 m) further " + "away. Spreads the shadow map over more ground: raise Shadow resolution with it. " + "Takes effect at the next start.", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -295,6 +299,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Разрешение теней", [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", + [UI_MENU_SHADOW_RANGE] = "Дальность каскадов теней", + [UI_MENU_SHADOW_RANGE_DESC] = "Отодвигает границы, за которыми тени становятся мягче (в игре 20, 40, 80 и 160 м). " + "Карта теней растягивается на большую площадь, поэтому вместе с этим поднимайте " + "разрешение теней. Действует после перезапуска.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 680e9cfe..7462a703 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -38,6 +38,7 @@ typedef enum { UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, + UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/totk.ini.example b/totk.ini.example index 68e9f306..d8744e73 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -122,6 +122,9 @@ # Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game # resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. Read at start. # shadow_scale = 1 +# Sun shadow cascade range in percent of the game's (its cascades end at 20, 40, 80 and 160 m), 50 to 400: higher moves +# the steps where shadows turn softer further away, and spreads the shadow map over more ground. Read at start. +# shadow_range = 100 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 4af60604de5d96da5bdafb4c6653df1f80a52bac Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:29:53 +0100 Subject: [PATCH 004/177] Add screen-space contact shadows TotK fills a full-resolution G-buffer with a B10G11R11 scene colour, an R32F linear depth and a D32F depth, lights it in half resolution, and composites the lighting into the scene colour in one pass whose only target is that colour, with a D16 class depth. vk_contact.c recognises both passes, and when the pass after the composite begins (or a dispatch or copy comes first) runtime/shaders/contact_shadow.comp marches each pixel 16 steps toward the sun through the linear depth and darkens the scene colour where nearby geometry blocks the ray: the small shadows at feet, under stones and in grass that the shadow maps miss. Transparent surfaces, the sky and post-processing come after. The projection, far plane and sun direction come from the fragment stage's 0x940-byte camera block (c4): c4[7].x, c4[8].y, c4[14].y, and the first cascade's depth row c4[44].xyz, whose negation points toward the sun. Scene colour images get STORAGE usage while the setting is on. contact_shadows (percent strength, default 0) is in totk.ini.example and on the Screen tab of the menu (English and Russian). TOTK_CONTACT_DEBUG=1 shows the shadow factor in grey instead of the frame. It costs about 0.45 ms per frame at a 3840x2160 scene on an RTX 4080 SUPER. Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 6 +- runtime/contact_shadow_spv.h | 156 +++++++++++++++++++++++ runtime/gfx_window.c | 1 + runtime/shaders/contact_shadow.comp | 67 ++++++++++ runtime/ui/menu.cpp | 1 + runtime/ui_text.c | 6 + runtime/ui_text.h | 1 + runtime/vk.h | 3 + runtime/vk_contact.c | 188 ++++++++++++++++++++++++++++ runtime/vk_exec.c | 1 + runtime/vk_exec.h | 3 + runtime/vk_exec_draw.c | 1 + runtime/vk_exec_xfer.c | 1 + runtime/vk_texture.c | 4 + totk.ini.example | 4 + 15 files changed, 440 insertions(+), 3 deletions(-) create mode 100644 runtime/contact_shadow_spv.h create mode 100644 runtime/shaders/contact_shadow.comp create mode 100644 runtime/vk_contact.c diff --git a/runtime/cfg.c b/runtime/cfg.c index bfd87294..2372ad1b 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -35,7 +35,7 @@ static const char *const known[] = { "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", - "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", + "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -94,7 +94,7 @@ static const CfgMeta metas[] = { {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, - {"SHADOW_RANGE", "100", "50..400", RESTART}, + {"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/contact_shadow_spv.h b/runtime/contact_shadow_spv.h new file mode 100644 index 00000000..7d506c8f --- /dev/null +++ b/runtime/contact_shadow_spv.h @@ -0,0 +1,156 @@ +// Generated by tools/build_shaders.py from runtime/shaders/contact_shadow.comp; do not edit. +// source sha256 b452a1920e59c4d83b2c994b0c6573cc1e479f7032a1310a7432d11c5c2e9908 +#pragma once +#include +static const uint32_t contact_shadow_spv[] = { + 0x07230203, 0x00010300, 0x000d000b, 0x000001b1, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00000069, + 0x00060010, 0x00000004, 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00030047, 0x00000027, + 0x00000002, 0x00050048, 0x00000027, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000027, + 0x00000001, 0x00000023, 0x00000010, 0x00050048, 0x00000027, 0x00000002, 0x00000023, 0x00000020, + 0x00050048, 0x00000027, 0x00000003, 0x00000023, 0x00000030, 0x00040047, 0x00000069, 0x0000000b, + 0x0000001c, 0x00040047, 0x00000088, 0x00000021, 0x00000000, 0x00040047, 0x00000088, 0x00000022, + 0x00000000, 0x00040047, 0x0000013f, 0x00000021, 0x00000001, 0x00040047, 0x0000013f, 0x00000022, + 0x00000000, 0x00040047, 0x0000015c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021, + 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, + 0x00000002, 0x00040017, 0x0000000a, 0x00000006, 0x00000003, 0x0004002b, 0x00000006, 0x0000001b, + 0x40000000, 0x0004002b, 0x00000006, 0x0000001d, 0x3f800000, 0x00040015, 0x00000020, 0x00000020, + 0x00000000, 0x0004002b, 0x00000020, 0x00000021, 0x00000000, 0x00040017, 0x00000026, 0x00000006, + 0x00000004, 0x0006001e, 0x00000027, 0x00000026, 0x00000026, 0x00000026, 0x00000026, 0x00040020, + 0x00000028, 0x00000009, 0x00000027, 0x0004003b, 0x00000028, 0x00000029, 0x00000009, 0x00040015, + 0x0000002a, 0x00000020, 0x00000001, 0x0004002b, 0x0000002a, 0x0000002b, 0x00000000, 0x00040020, + 0x0000002c, 0x00000009, 0x00000006, 0x0004002b, 0x00000020, 0x00000030, 0x00000001, 0x0004002b, + 0x00000020, 0x0000003f, 0x00000002, 0x0004002b, 0x00000006, 0x00000043, 0x3f000000, 0x0004002b, + 0x00000006, 0x00000059, 0x4253ee82, 0x0004002b, 0x00000006, 0x0000005b, 0x3d897143, 0x0004002b, + 0x00000006, 0x0000005c, 0x3bbf4590, 0x0005002c, 0x00000007, 0x0000005d, 0x0000005b, 0x0000005c, + 0x00040017, 0x00000064, 0x0000002a, 0x00000002, 0x00040017, 0x00000067, 0x00000020, 0x00000003, + 0x00040020, 0x00000068, 0x00000001, 0x00000067, 0x0004003b, 0x00000068, 0x00000069, 0x00000001, + 0x00040017, 0x0000006a, 0x00000020, 0x00000002, 0x00020014, 0x0000006e, 0x0004002b, 0x0000002a, + 0x00000072, 0x00000002, 0x00090019, 0x00000085, 0x00000006, 0x00000001, 0x00000000, 0x00000000, + 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000086, 0x00000085, 0x00040020, 0x00000087, + 0x00000000, 0x00000086, 0x0004003b, 0x00000087, 0x00000088, 0x00000000, 0x0004002b, 0x00000006, + 0x0000008f, 0x00000000, 0x0004002b, 0x00000006, 0x00000092, 0x3f7fbe77, 0x0004002b, 0x00000006, + 0x0000009e, 0x42a00000, 0x00040020, 0x000000a8, 0x00000009, 0x00000026, 0x0004002b, 0x0000002a, + 0x000000b4, 0x00000001, 0x0004002b, 0x00000020, 0x000000b5, 0x00000003, 0x0004002b, 0x00000006, + 0x000000bb, 0x3ecccccd, 0x0004002b, 0x00000006, 0x000000bc, 0x40400000, 0x0004002b, 0x00000006, + 0x000000c0, 0x3e19999a, 0x0004002b, 0x00000006, 0x000000c2, 0x3c23d70a, 0x0004002b, 0x00000006, + 0x000000cb, 0x3e800000, 0x0004002b, 0x0000002a, 0x000000da, 0x00000010, 0x0004002b, 0x00000006, + 0x000000e6, 0xbd4ccccd, 0x0005002c, 0x00000007, 0x000000f0, 0x0000008f, 0x0000008f, 0x00040017, + 0x000000f1, 0x0000006e, 0x00000002, 0x0005002c, 0x00000007, 0x000000f8, 0x0000001d, 0x0000001d, + 0x0004002b, 0x00000006, 0x00000114, 0x3ca3d70a, 0x0004002b, 0x00000006, 0x00000116, 0x3b03126f, + 0x0004002b, 0x00000006, 0x0000012b, 0x42200000, 0x0004002b, 0x0000002a, 0x00000137, 0x00000003, + 0x00090019, 0x0000013d, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000002, + 0x00000008, 0x00040020, 0x0000013e, 0x00000000, 0x0000013d, 0x0004003b, 0x0000013e, 0x0000013f, + 0x00000000, 0x0004002b, 0x00000020, 0x0000015b, 0x00000008, 0x0006002c, 0x00000067, 0x0000015c, + 0x0000015b, 0x0000015b, 0x00000030, 0x0005002c, 0x00000007, 0x000001ad, 0x00000043, 0x00000043, + 0x0004002b, 0x00000006, 0x000001af, 0x3dcccccd, 0x0004002b, 0x00000006, 0x000001b0, 0x3d800000, + 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7, + 0x0000015d, 0x00000000, 0x000300fb, 0x00000021, 0x0000015e, 0x000200f8, 0x0000015e, 0x0004003d, + 0x00000067, 0x0000006b, 0x00000069, 0x0007004f, 0x0000006a, 0x0000006c, 0x0000006b, 0x0000006b, + 0x00000000, 0x00000001, 0x0004007c, 0x00000064, 0x0000006d, 0x0000006c, 0x00050051, 0x0000002a, + 0x00000071, 0x0000006d, 0x00000000, 0x00060041, 0x0000002c, 0x00000073, 0x00000029, 0x00000072, + 0x00000021, 0x0004003d, 0x00000006, 0x00000074, 0x00000073, 0x0004006e, 0x0000002a, 0x00000075, + 0x00000074, 0x000500af, 0x0000006e, 0x00000076, 0x00000071, 0x00000075, 0x000400a8, 0x0000006e, + 0x00000077, 0x00000076, 0x000300f7, 0x00000079, 0x00000000, 0x000400fa, 0x00000077, 0x00000078, + 0x00000079, 0x000200f8, 0x00000078, 0x00050051, 0x0000002a, 0x0000007b, 0x0000006d, 0x00000001, + 0x00060041, 0x0000002c, 0x0000007c, 0x00000029, 0x00000072, 0x00000030, 0x0004003d, 0x00000006, + 0x0000007d, 0x0000007c, 0x0004006e, 0x0000002a, 0x0000007e, 0x0000007d, 0x000500af, 0x0000006e, + 0x0000007f, 0x0000007b, 0x0000007e, 0x000200f9, 0x00000079, 0x000200f8, 0x00000079, 0x000700f5, + 0x0000006e, 0x00000080, 0x00000076, 0x0000015e, 0x0000007f, 0x00000078, 0x000300f7, 0x00000082, + 0x00000000, 0x000400fa, 0x00000080, 0x00000081, 0x00000082, 0x000200f8, 0x00000081, 0x000200f9, + 0x0000015d, 0x000200f8, 0x00000082, 0x0004003d, 0x00000086, 0x00000089, 0x00000088, 0x00040064, + 0x00000085, 0x0000008b, 0x00000089, 0x0007005f, 0x00000026, 0x0000008c, 0x0000008b, 0x0000006d, + 0x00000002, 0x0000002b, 0x00050051, 0x00000006, 0x0000008d, 0x0000008c, 0x00000000, 0x000500bc, + 0x0000006e, 0x00000090, 0x0000008d, 0x0000008f, 0x000500be, 0x0000006e, 0x00000093, 0x0000008d, + 0x00000092, 0x000500a6, 0x0000006e, 0x00000094, 0x00000090, 0x00000093, 0x000300f7, 0x00000096, + 0x00000000, 0x000400fa, 0x00000094, 0x00000095, 0x00000096, 0x000200f8, 0x00000095, 0x000200f9, + 0x0000015d, 0x000200f8, 0x00000096, 0x00060041, 0x0000002c, 0x0000009a, 0x00000029, 0x0000002b, + 0x0000003f, 0x0004003d, 0x00000006, 0x0000009b, 0x0000009a, 0x00050085, 0x00000006, 0x0000009c, + 0x0000008d, 0x0000009b, 0x000500ba, 0x0000006e, 0x0000009f, 0x0000009c, 0x0000009e, 0x000300f7, + 0x000000a1, 0x00000000, 0x000400fa, 0x0000009f, 0x000000a0, 0x000000a1, 0x000200f8, 0x000000a0, + 0x000200f9, 0x0000015d, 0x000200f8, 0x000000a1, 0x0004006f, 0x00000007, 0x000000a5, 0x0000006d, + 0x00050081, 0x00000007, 0x000000a7, 0x000000a5, 0x000001ad, 0x00050041, 0x000000a8, 0x000000a9, + 0x00000029, 0x00000072, 0x0004003d, 0x00000026, 0x000000aa, 0x000000a9, 0x0007004f, 0x00000007, + 0x000000ab, 0x000000aa, 0x000000aa, 0x00000002, 0x00000003, 0x00050085, 0x00000007, 0x000000ac, + 0x000000a7, 0x000000ab, 0x0005008e, 0x00000007, 0x00000167, 0x000000ac, 0x0000001b, 0x00050083, + 0x00000007, 0x00000169, 0x00000167, 0x000000f8, 0x00050051, 0x00000006, 0x0000016b, 0x00000169, + 0x00000000, 0x00050085, 0x00000006, 0x0000016d, 0x0000016b, 0x0000009c, 0x00060041, 0x0000002c, + 0x0000016e, 0x00000029, 0x0000002b, 0x00000021, 0x0004003d, 0x00000006, 0x0000016f, 0x0000016e, + 0x00050088, 0x00000006, 0x00000170, 0x0000016d, 0x0000016f, 0x00050051, 0x00000006, 0x00000172, + 0x00000169, 0x00000001, 0x0004007f, 0x00000006, 0x00000173, 0x00000172, 0x00050085, 0x00000006, + 0x00000175, 0x00000173, 0x0000009c, 0x00060041, 0x0000002c, 0x00000176, 0x00000029, 0x0000002b, + 0x00000030, 0x0004003d, 0x00000006, 0x00000177, 0x00000176, 0x00050088, 0x00000006, 0x00000178, + 0x00000175, 0x00000177, 0x0004007f, 0x00000006, 0x0000017a, 0x0000009c, 0x00060050, 0x0000000a, + 0x0000017b, 0x00000170, 0x00000178, 0x0000017a, 0x00060041, 0x0000002c, 0x000000b6, 0x00000029, + 0x000000b4, 0x000000b5, 0x0004003d, 0x00000006, 0x000000b7, 0x000000b6, 0x00050085, 0x00000006, + 0x000000ba, 0x0000009c, 0x000001af, 0x0008000c, 0x00000006, 0x000000bd, 0x00000001, 0x0000002b, + 0x000000ba, 0x000000bb, 0x000000bc, 0x00050085, 0x00000006, 0x000000be, 0x000000b7, 0x000000bd, + 0x00050085, 0x00000006, 0x000000c3, 0x0000009c, 0x000000c2, 0x00050081, 0x00000006, 0x000000c4, + 0x000000c0, 0x000000c3, 0x00050085, 0x00000006, 0x000000c8, 0x000000be, 0x000001b0, 0x00050094, + 0x00000006, 0x0000017f, 0x000000a5, 0x0000005d, 0x0006000c, 0x00000006, 0x00000180, 0x00000001, + 0x0000000a, 0x0000017f, 0x00050085, 0x00000006, 0x00000181, 0x00000059, 0x00000180, 0x0006000c, + 0x00000006, 0x00000182, 0x00000001, 0x0000000a, 0x00000181, 0x00050081, 0x00000006, 0x000000d0, + 0x000000cb, 0x00000182, 0x00050085, 0x00000006, 0x000000d1, 0x000000c8, 0x000000d0, 0x000200f9, + 0x000000d4, 0x000200f8, 0x000000d4, 0x000700f5, 0x00000006, 0x000001a7, 0x000000d1, 0x000000a1, + 0x00000129, 0x000000d7, 0x000700f5, 0x0000002a, 0x000001a6, 0x0000002b, 0x000000a1, 0x00000126, + 0x000000d7, 0x000500b1, 0x0000006e, 0x000000db, 0x000001a6, 0x000000da, 0x000400f6, 0x000000d6, + 0x000000d7, 0x00000000, 0x000400fa, 0x000000db, 0x000000d5, 0x000000d6, 0x000200f8, 0x000000d5, + 0x00050041, 0x000000a8, 0x000000de, 0x00000029, 0x000000b4, 0x0004003d, 0x00000026, 0x000000df, + 0x000000de, 0x0008004f, 0x0000000a, 0x000000e0, 0x000000df, 0x000000df, 0x00000000, 0x00000001, + 0x00000002, 0x0005008e, 0x0000000a, 0x000000e2, 0x000000e0, 0x000001a7, 0x00050081, 0x0000000a, + 0x000000e3, 0x0000017b, 0x000000e2, 0x00050051, 0x00000006, 0x000000e5, 0x000000e3, 0x00000002, + 0x000500be, 0x0000006e, 0x000000e7, 0x000000e5, 0x000000e6, 0x000300f7, 0x000000e9, 0x00000000, + 0x000400fa, 0x000000e7, 0x000000e8, 0x000000e9, 0x000200f8, 0x000000e8, 0x000200f9, 0x000000d6, + 0x000200f8, 0x000000e9, 0x0004007f, 0x00000006, 0x00000188, 0x000000e5, 0x00050051, 0x00000006, + 0x0000018a, 0x000000e3, 0x00000000, 0x00050085, 0x00000006, 0x0000018b, 0x00000043, 0x0000018a, + 0x00050085, 0x00000006, 0x0000018e, 0x0000018b, 0x0000016f, 0x00050088, 0x00000006, 0x00000190, + 0x0000018e, 0x00000188, 0x00050081, 0x00000006, 0x00000191, 0x00000043, 0x00000190, 0x00050051, + 0x00000006, 0x00000193, 0x000000e3, 0x00000001, 0x00050085, 0x00000006, 0x00000194, 0x00000043, + 0x00000193, 0x00050085, 0x00000006, 0x00000197, 0x00000194, 0x00000177, 0x00050088, 0x00000006, + 0x00000199, 0x00000197, 0x00000188, 0x00050083, 0x00000006, 0x0000019a, 0x00000043, 0x00000199, + 0x00050050, 0x00000007, 0x0000019b, 0x00000191, 0x0000019a, 0x000500b8, 0x000000f1, 0x000000f2, + 0x0000019b, 0x000000f0, 0x0004009a, 0x0000006e, 0x000000f3, 0x000000f2, 0x000400a8, 0x0000006e, + 0x000000f4, 0x000000f3, 0x000300f7, 0x000000f6, 0x00000000, 0x000400fa, 0x000000f4, 0x000000f5, + 0x000000f6, 0x000200f8, 0x000000f5, 0x000500ba, 0x000000f1, 0x000000f9, 0x0000019b, 0x000000f8, + 0x0004009a, 0x0000006e, 0x000000fa, 0x000000f9, 0x000200f9, 0x000000f6, 0x000200f8, 0x000000f6, + 0x000700f5, 0x0000006e, 0x000000fb, 0x000000f3, 0x000000e9, 0x000000fa, 0x000000f5, 0x000300f7, + 0x000000fd, 0x00000000, 0x000400fa, 0x000000fb, 0x000000fc, 0x000000fd, 0x000200f8, 0x000000fc, + 0x000200f9, 0x000000d6, 0x000200f8, 0x000000fd, 0x0004003d, 0x00000086, 0x00000100, 0x00000088, + 0x0007004f, 0x00000007, 0x00000104, 0x000000aa, 0x000000aa, 0x00000000, 0x00000001, 0x00050085, + 0x00000007, 0x00000105, 0x0000019b, 0x00000104, 0x0004006e, 0x00000064, 0x00000106, 0x00000105, + 0x00040064, 0x00000085, 0x00000107, 0x00000100, 0x0007005f, 0x00000026, 0x00000108, 0x00000107, + 0x00000106, 0x00000002, 0x0000002b, 0x00050051, 0x00000006, 0x00000109, 0x00000108, 0x00000000, + 0x00050085, 0x00000006, 0x0000010c, 0x00000109, 0x0000009b, 0x00050083, 0x00000006, 0x00000112, + 0x00000188, 0x0000010c, 0x00050085, 0x00000006, 0x00000117, 0x0000009c, 0x00000116, 0x00050081, + 0x00000006, 0x00000118, 0x00000114, 0x00000117, 0x000500ba, 0x0000006e, 0x00000119, 0x00000112, + 0x00000118, 0x000500b8, 0x0000006e, 0x0000011c, 0x00000112, 0x000000c4, 0x000500a7, 0x0000006e, + 0x0000011d, 0x00000119, 0x0000011c, 0x000300f7, 0x0000011f, 0x00000000, 0x000400fa, 0x0000011d, + 0x0000011e, 0x0000011f, 0x000200f8, 0x0000011e, 0x0004006f, 0x00000006, 0x00000121, 0x000001a6, + 0x00050085, 0x00000006, 0x00000122, 0x00000121, 0x000001b0, 0x00050083, 0x00000006, 0x00000123, + 0x0000001d, 0x00000122, 0x000200f9, 0x000000d6, 0x000200f8, 0x0000011f, 0x000200f9, 0x000000d7, + 0x000200f8, 0x000000d7, 0x00050080, 0x0000002a, 0x00000126, 0x000001a6, 0x000000b4, 0x00050081, + 0x00000006, 0x00000129, 0x000001a7, 0x000000c8, 0x000200f9, 0x000000d4, 0x000200f8, 0x000000d6, + 0x000b00f5, 0x00000006, 0x000001aa, 0x0000008f, 0x000000d4, 0x0000008f, 0x000000e8, 0x0000008f, + 0x000000fc, 0x00000123, 0x0000011e, 0x0008000c, 0x00000006, 0x0000012d, 0x00000001, 0x00000031, + 0x0000012b, 0x0000009e, 0x0000009c, 0x00050083, 0x00000006, 0x0000012e, 0x0000001d, 0x0000012d, + 0x00060041, 0x0000002c, 0x00000130, 0x00000029, 0x0000002b, 0x000000b5, 0x0004003d, 0x00000006, + 0x00000131, 0x00000130, 0x00050085, 0x00000006, 0x00000133, 0x00000131, 0x000001aa, 0x00050085, + 0x00000006, 0x00000135, 0x00000133, 0x0000012e, 0x00050083, 0x00000006, 0x00000136, 0x0000001d, + 0x00000135, 0x00060041, 0x0000002c, 0x00000138, 0x00000029, 0x00000137, 0x00000021, 0x0004003d, + 0x00000006, 0x00000139, 0x00000138, 0x000500ba, 0x0000006e, 0x0000013a, 0x00000139, 0x00000043, + 0x000300f7, 0x0000013c, 0x00000000, 0x000400fa, 0x0000013a, 0x0000013b, 0x0000013c, 0x000200f8, + 0x0000013b, 0x0004003d, 0x0000013d, 0x00000140, 0x0000013f, 0x00070050, 0x00000026, 0x00000143, + 0x00000136, 0x00000136, 0x00000136, 0x0000001d, 0x00040063, 0x00000140, 0x0000006d, 0x00000143, + 0x000200f9, 0x0000015d, 0x000200f8, 0x0000013c, 0x000500be, 0x0000006e, 0x00000146, 0x00000136, + 0x00000092, 0x000300f7, 0x00000148, 0x00000000, 0x000400fa, 0x00000146, 0x00000147, 0x00000148, + 0x000200f8, 0x00000147, 0x000200f9, 0x0000015d, 0x000200f8, 0x00000148, 0x0004003d, 0x0000013d, + 0x0000014c, 0x0000013f, 0x00050062, 0x00000026, 0x0000014e, 0x0000014c, 0x0000006d, 0x0004003d, + 0x0000013d, 0x0000014f, 0x0000013f, 0x0008004f, 0x0000000a, 0x00000152, 0x0000014e, 0x0000014e, + 0x00000000, 0x00000001, 0x00000002, 0x0005008e, 0x0000000a, 0x00000154, 0x00000152, 0x00000136, + 0x00050051, 0x00000006, 0x00000156, 0x0000014e, 0x00000003, 0x00050051, 0x00000006, 0x00000157, + 0x00000154, 0x00000000, 0x00050051, 0x00000006, 0x00000158, 0x00000154, 0x00000001, 0x00050051, + 0x00000006, 0x00000159, 0x00000154, 0x00000002, 0x00070050, 0x00000026, 0x0000015a, 0x00000157, + 0x00000158, 0x00000159, 0x00000156, 0x00040063, 0x0000014f, 0x0000006d, 0x0000015a, 0x000200f9, + 0x0000015d, 0x000200f8, 0x0000015d, 0x000100fd, 0x00010038, +}; diff --git a/runtime/gfx_window.c b/runtime/gfx_window.c index f62de225..38f6476f 100644 --- a/runtime/gfx_window.c +++ b/runtime/gfx_window.c @@ -920,6 +920,7 @@ void gfx_window_release_vk(void) { g_flip_on = 0; // its blit is done (device idle); the swapchain goes away unpresented menu_vk_release(); vk_fsr_release(); + vk_contact_release(); free_capture(); free_thumbs(); for (int i = 0; i < FRAMES; i++) { diff --git a/runtime/shaders/contact_shadow.comp b/runtime/shaders/contact_shadow.comp new file mode 100644 index 00000000..78828bb4 --- /dev/null +++ b/runtime/shaders/contact_shadow.comp @@ -0,0 +1,67 @@ +#version 450 +// Screen-space contact shadows (runtime/vk_contact.c). Each pixel of the game's lit scene colour marches a short way +// toward the sun through the linear depth target; when the ray passes behind something close in front of it, the pixel +// is in a contact shadow the shadow maps are too coarse to show, and its colour is darkened. +layout(local_size_x = 8, local_size_y = 8) in; + +layout(binding = 0) uniform sampler2D lin_depth; // the game's linear depth: view distance / far +layout(binding = 1, r11f_g11f_b10f) uniform image2D scene; // the lit scene colour, darkened in place + +layout(push_constant) uniform Params { + vec4 proj; // projection x scale, y scale, far plane, strength (0..1) + vec4 light; // view-space direction toward the sun (xyz), march length in metres at 10 m (w) + vec4 size; // width, height, 1/width, 1/height + vec4 opt; // x: debug (1: write the shadow factor as grey) +} pc; + +vec3 view_pos(vec2 uv, float z) { // z: distance in front of the camera + vec2 ndc = uv * 2.0 - 1.0; + return vec3(ndc.x * z / pc.proj.x, -ndc.y * z / pc.proj.y, -z); +} + +vec2 to_uv(vec3 p) { + float z = -p.z; + return vec2(0.5 + 0.5 * p.x * pc.proj.x / z, 0.5 - 0.5 * p.y * pc.proj.y / z); +} + +float ign(vec2 px) { // interleaved gradient noise: a per-pixel start offset that hides the step pattern + return fract(52.9829189 * fract(dot(px, vec2(0.06711056, 0.00583715)))); +} + +void main() { + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + if (px.x >= int(pc.size.x) || px.y >= int(pc.size.y)) return; + float d = texelFetch(lin_depth, px, 0).x; + if (d <= 0.0 || d >= 0.999) return; // nothing drawn, or the sky + float z = d * pc.proj.z; + if (z > 80.0) return; + vec2 uv = (vec2(px) + 0.5) * pc.size.zw; + vec3 p = view_pos(uv, z); + // the march grows with distance, as one pixel covers more ground; thickness keeps thin blades from hiding the sky + float len = pc.light.w * clamp(z / 10.0, 0.4, 3.0); + float thick = 0.15 + z * 0.01; + const int STEPS = 16; + float step_len = len / float(STEPS), t = step_len * (0.25 + ign(vec2(px))); + float occ = 0.0; + for (int i = 0; i < STEPS; i++, t += step_len) { + vec3 q = p + pc.light.xyz * t; + if (q.z >= -0.05) break; + vec2 quv = to_uv(q); + if (any(lessThan(quv, vec2(0.0))) || any(greaterThan(quv, vec2(1.0)))) break; + float sz = texelFetch(lin_depth, ivec2(quv * pc.size.xy), 0).x * pc.proj.z; + float delta = -q.z - sz; // how far the scene at that pixel is in front of the ray point + if (delta > 0.02 + z * 0.002 && delta < thick) { + occ = 1.0 - float(i) / float(STEPS); // a hit close to the pixel shadows more than one at the end + break; + } + } + float fade = 1.0 - smoothstep(40.0, 80.0, z); + float k = 1.0 - pc.proj.w * occ * fade; + if (pc.opt.x > 0.5) { + imageStore(scene, px, vec4(k, k, k, 1.0)); + return; + } + if (k >= 0.999) return; + vec4 c = imageLoad(scene, px); + imageStore(scene, px, vec4(c.rgb * k, c.a)); +} diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index d3eb04f9..b82f9f2a 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -550,6 +550,7 @@ static void tab_screen(float scale) { row_aniso(); row_shadow_scale(); row_shadow_range(); + opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%"); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index d279674a..91228692 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -70,6 +70,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Shadow resolution", [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " "sharper shadow edges and leaf shadows. Takes effect at the next start.", + [UI_MENU_CONTACT_SHADOWS] = "Contact shadows", + [UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. " + "Traced on the screen after lighting. Takes effect at the next start.", [UI_MENU_SHADOW_RANGE] = "Shadow cascade range", [UI_MENU_SHADOW_RANGE_DESC] = "Moves the steps where shadows turn softer (the game's 20, 40, 80 and 160 m) further " "away. Spreads the shadow map over more ground: raise Shadow resolution with it. " @@ -299,6 +302,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Разрешение теней", [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", + [UI_MENU_CONTACT_SHADOWS] = "Контактные тени", + [UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и " + "складках. Считаются по экрану после освещения. Действует после перезапуска.", [UI_MENU_SHADOW_RANGE] = "Дальность каскадов теней", [UI_MENU_SHADOW_RANGE_DESC] = "Отодвигает границы, за которыми тени становятся мягче (в игре 20, 40, 80 и 160 м). " "Карта теней растягивается на большую площадь, поэтому вместе с этим поднимайте " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 7462a703..eb0e09cf 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -39,6 +39,7 @@ typedef enum { UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, + UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/runtime/vk.h b/runtime/vk.h index fdfaf319..94c2b62c 100644 --- a/runtime/vk.h +++ b/runtime/vk.h @@ -87,6 +87,9 @@ void vk_present_blit(VkImage src, VkImageLayout layout, VkFormat fmt, int w, int int vk_fsr_record(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, int sw, int sh, const int crop[4], VkImage dst, uint32_t dw, uint32_t dh); void vk_fsr_release(void); // before the device goes away +// vk_contact.c: screen-space contact shadows on the game's composed scene colour (TOTK_CONTACT_SHADOWS) +int vk_contact_strength(void); // percent, 0 = off +void vk_contact_release(void); // before the device goes away void vk_present_flip(void); // Every submission to ctx->gfx_queue (and xfer_queue when shared) takes this lock; vk_present_image and the swapchain // rebuild do. Recursive. diff --git a/runtime/vk_contact.c b/runtime/vk_contact.c new file mode 100644 index 00000000..74eae718 --- /dev/null +++ b/runtime/vk_contact.c @@ -0,0 +1,188 @@ +// Screen-space contact shadows (TOTK_CONTACT_SHADOWS, percent strength, 0 = off). TotK fills a full-resolution +// G-buffer whose targets include a B10G11R11 scene colour, an R32F linear depth (view distance / far) and a D32F depth +// (is_gbuffer), lights it in half resolution, and then composites the lighting into that scene colour in one pass +// whose only target is the scene colour, with a D16 depth that sorts pixels into material classes (is_composite). +// When the pass after the composite begins, or a dispatch or copy comes first, runtime/shaders/contact_shadow.comp +// marches each pixel a short way toward the sun through the linear depth and darkens the scene colour where the ray +// passes behind nearby geometry: the small shadows at feet, under stones and in grass that the shadow maps are too +// coarse for. Transparent surfaces, the sky and post-processing come after, untouched. +// +// Inputs from the game, read from the fragment stage's uniform block c4 bound in the composite pass (guest memory, +// so it may be one frame newer than the replay): the projection scales c4[7].x and c4[8].y, the far plane c4[14].y, +// and the first sun cascade's depth row c4[44].xyz, whose negated direction points from a view-space position toward +// the sun (the G-buffer shaders compare dot(c4[44].xyz, pos) + c4[44].w with the cascade map). The scene colour images +// get STORAGE usage when the setting is on (vk_texture.c create_tex). +#include "vk.h" + +#include +#include + +#include "cfg.h" +#include "contact_shadow_spv.h" +#include "host.h" +#include "vk_exec.h" + +static struct { + int tried, ok, strength, debug, logged; + PFN_vkCmdPushDescriptorSetKHR push; + VkDescriptorSetLayout dsl; + VkPipelineLayout layout; + VkPipeline pipe; + VkSampler sampler; + const VkTexImage *scene, *depth; // the last G-buffer's scene colour and linear depth + uint32_t w, h; + int pending; // the composite into scene ran; the march waits for the next pass + uint64_t c4; +} C; + +int vk_contact_strength(void) { + if (!C.tried) { + int s = cfg_int("TOTK_CONTACT_SHADOWS"); + C.strength = s < 0 ? 0 : s > 100 ? 100 : s; + } + return C.strength; +} + +static int init(VkCtx *c) { + C.tried = 1; + vk_contact_strength(); + if (!C.strength) return 0; + const char *e = cfg_get("TOTK_CONTACT_DEBUG"); // 1: the frame shows the contact shadow factor in grey + C.debug = e && *e && strcmp(e, "0"); + C.push = (PFN_vkCmdPushDescriptorSetKHR)vkGetDeviceProcAddr(c->device, "vkCmdPushDescriptorSetKHR"); + VkDescriptorSetLayoutBinding b[2] = { + {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}, + {.binding = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}}; + VkDescriptorSetLayoutCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, + .bindingCount = 2, .pBindings = b}; + VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, 64}; + VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, + .pSetLayouts = &C.dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr}; + VkSamplerCreateInfo si = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_NEAREST, + .minFilter = VK_FILTER_NEAREST, .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .maxLod = 0}; + VkShaderModuleCreateInfo mi = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof contact_shadow_spv, .pCode = contact_shadow_spv}; + VkShaderModule m = VK_NULL_HANDLE; + if (!C.push || vkCreateDescriptorSetLayout(c->device, &dci, NULL, &C.dsl) != VK_SUCCESS || + vkCreatePipelineLayout(c->device, &li, NULL, &C.layout) != VK_SUCCESS || + vkCreateSampler(c->device, &si, NULL, &C.sampler) != VK_SUCCESS || + vkCreateShaderModule(c->device, &mi, NULL, &m) != VK_SUCCESS) { + rt_log("vk: contact shadows off: their pipeline could not be created"); + return 0; + } + VkComputePipelineCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = m, .pName = "main"}, + .layout = C.layout}; + VkResult r = vkCreateComputePipelines(c->device, VK_NULL_HANDLE, 1, &ci, NULL, &C.pipe); + vkDestroyShaderModule(c->device, m, NULL); + if (r != VK_SUCCESS) { + rt_log("vk: contact shadows off: their pipeline could not be created"); + return 0; + } + rt_log("vk: contact shadows on, strength %d%%%s", C.strength, C.debug ? " (debug view)" : ""); + return C.ok = 1; +} + +// A G-buffer pass: a B10G11R11 scene colour, an R32F linear depth and a D32F depth, all one size, at least 640 wide. +static int is_gbuffer(const VkExec *ex, const VkTexImage **scene, const VkTexImage **depth) { + *scene = *depth = NULL; + if (ex->pass_noatt || ex->pass_w < 640 || ex->depth.format != VK_FORMAT_D32_SFLOAT || ex->depth.level) return 0; + for (uint32_t i = 0; i < ex->pass_ncolor && i < 8; i++) { + const VkExecTarget *t = &ex->color[i]; + if (!t->image || t->level || t->width != ex->pass_w || t->height != ex->pass_h) continue; + if (t->format == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && !*scene) *scene = t->img; + if (t->format == VK_FORMAT_R32_SFLOAT && !*depth) *depth = t->img; + } + return *scene && *depth && ((*scene)->usage & VK_IMAGE_USAGE_STORAGE_BIT); +} + +static void mem_barrier(VkCommandBuffer cb) { + VkMemoryBarrier2 mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT}; + VkDependencyInfo d = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &mb}; + vkCmdPipelineBarrier2(cb, &d); +} + +void vk_contact_flush(VkExec *ex) { + if (!C.pending) return; + C.pending = 0; + if (ex->in_pass) return; + const float *u = (const float *)(uintptr_t)C.c4; + float lx = -u[44 * 4 + 0], ly = -u[44 * 4 + 1], lz = -u[44 * 4 + 2], ll = sqrtf(lx * lx + ly * ly + lz * lz); + float px = u[7 * 4 + 0], py = u[8 * 4 + 1], zfar = u[14 * 4 + 1]; + if (!(ll > 1e-6f) || !(px > 0) || !(py > 0) || !(zfar > 1)) return; + VkImageView in = vk_exec_target_view(C.depth, VK_FORMAT_R32_SFLOAT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT, + 0, 0, 1, 0); + VkImageView out = vk_exec_target_view(C.scene, VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_VIEW_TYPE_2D, + VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1, 0); + if (!in || !out) return; + VkCommandBuffer cb = ex->cb; + float pcv[16] = {px, py, zfar, (float)C.strength / 100.0f, + lx / ll, ly / ll, lz / ll, 0.6f, + (float)C.w, (float)C.h, 1.0f / (float)C.w, 1.0f / (float)C.h, + (float)C.debug, 0, 0, 0}; + if (!C.logged) { + C.logged = 1; + rt_log("vk: contact shadows on a %ux%u scene, sun toward %.3f %.3f %.3f (view space), far %g", C.w, C.h, + pcv[4], pcv[5], pcv[6], zfar); + } + mem_barrier(cb); // the compose passes' writes, before the march reads and writes them + VkDescriptorImageInfo ii = {C.sampler, in, VK_IMAGE_LAYOUT_GENERAL}, oi = {VK_NULL_HANDLE, out, VK_IMAGE_LAYOUT_GENERAL}; + VkWriteDescriptorSet w[2] = { + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ii}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi}}; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.pipe); + rec_push(C.push, cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.layout, 0, 2, w); + vkCmdPushConstants(cb, C.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pcv, pcv); + vkCmdDispatch(cb, (C.w + 7) / 8, (C.h + 7) / 8, 1); + mem_barrier(cb); // and what follows sees the darkened colour + ex->recorded += 6; + vk_exec_draw_new_cb(); // the game's bound compute pipeline and descriptors were replaced: bind them again +} + +// The lighting composite: the remembered scene colour as the only target, with a D16 depth of its size. +static int is_composite(const VkExec *ex) { + return C.scene && ex->pass_ncolor >= 1 && ex->color[0].img == C.scene && !ex->color[0].level && + ex->depth.format == VK_FORMAT_D16_UNORM && ex->pass_w == C.w && ex->pass_h == C.h; +} + +void vk_contact_pass_begin(VkExec *ex) { + if (!C.tried && !init(vk_ctx())) return; + if (!C.ok) return; + const VkTexImage *scene, *depth; + // The camera block: c4 of the fragment stage, 0x940 bytes. The composite binds it only after its pass begins, so + // the newest one seen at any pass start serves. + const p_bind_buf *b = &ex->ubo[1][1]; + if (b->addr && b->size == 0x940) C.c4 = b->addr; + if (is_gbuffer(ex, &scene, &depth)) { + C.pending = 0; + C.scene = scene, C.depth = depth, C.w = ex->pass_w, C.h = ex->pass_h; + return; + } + if (is_composite(ex)) { + C.pending = C.c4 != 0; + return; + } + vk_contact_flush(ex); +} + +void vk_contact_release(void) { + VkCtx *c = vk_ctx(); + if (!c || !C.tried) return; + if (C.pipe) vkDestroyPipeline(c->device, C.pipe, NULL); + if (C.sampler) vkDestroySampler(c->device, C.sampler, NULL); + if (C.layout) vkDestroyPipelineLayout(c->device, C.layout, NULL); + if (C.dsl) vkDestroyDescriptorSetLayout(c->device, C.dsl, NULL); + memset(&C, 0, sizeof C); +} diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index 0abd2b63..fb227f01 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -422,6 +422,7 @@ void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); } void vk_exec_pass_begin(VkExec *ex) { if (ex->in_pass) return; resolve_rt(ex); + vk_contact_pass_begin(ex); // Learned targets (VkTexImage.fb_learned) are attached in the feedback layout VkImage want[9]; VkImageAspectFlags wasp[9]; diff --git a/runtime/vk_exec.h b/runtime/vk_exec.h index b0095f63..c4f9182e 100644 --- a/runtime/vk_exec.h +++ b/runtime/vk_exec.h @@ -176,6 +176,9 @@ VkImageView vk_exec_target_view(const VkTexImage *img, VkFormat format, VkImageV // vk_exec_xfer.c: OP_COPY_B2B, OP_COPY_B2T, OP_COPY_T2B, OP_COPY_T2T, OP_CLEAR_TEX, OP_SIGNAL_EVENT, OP_REPORT_COUNTER, // OP_RESET_COUNTER, OP_RENDER_ENABLE, OP_RENDER_COND, OP_CLEAR_BUF. void vk_exec_op_xfer(VkExec *ex, uint32_t op, const void *payload); +// vk_contact.c: a pass about to begin (its targets resolved, no pass open), and a dispatch or copy about to be recorded +void vk_contact_pass_begin(VkExec *ex); +void vk_contact_flush(VkExec *ex); // vk_exec_xfer.c, samples-passed counting: a draw about to be recorded in the open pass (begins an occlusion query // when counting and none is active), and the open pass about to end (ends the active query). void vk_exec_oq_draw(VkExec *ex); diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index e23741e9..124ebbc8 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -2069,6 +2069,7 @@ static void op_draw_idx_ind(VkExec *ex, const p_draw_idx_ind *d) { static void op_dispatch(VkExec *ex, const p_dispatch *d) { if (d->x <= 0 || d->y <= 0 || d->z <= 0) return; if (!ex->prog) return warn_once(W_PROGRAM, "a dispatch without a bound program is skipped"); + vk_contact_flush(ex); cb_res(ex); dummies_init(); int present; diff --git a/runtime/vk_exec_xfer.c b/runtime/vk_exec_xfer.c index ffb3b420..06602742 100644 --- a/runtime/vk_exec_xfer.c +++ b/runtime/vk_exec_xfer.c @@ -592,6 +592,7 @@ static void clear_tex(VkExec *ex, const p_clear_tex *p) { } void vk_exec_op_xfer(VkExec *ex, uint32_t op, const void *payload) { + if (op != OP_RENDER_ENABLE && op != OP_SIGNAL_EVENT) vk_contact_flush(ex); switch (op) { case OP_COPY_B2B: copy_b2b(ex, payload); break; case OP_COPY_B2T: copy_buffer_image(ex, payload, 1); break; diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index e2fda908..ce7619f7 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -341,6 +341,10 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) { if (!ds && (ff & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if ((d->flags & NVN_TEXTURE_FLAGS_IMAGE) && (ff & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) && samples == 1) usage |= VK_IMAGE_USAGE_STORAGE_BIT; + // contact shadows (vk_contact.c) darken the game's B10G11R11 scene colour in place from a compute shader + if (f.vk == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) && samples == 1 && + (ff & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) && w >= 640 && vk_contact_strength()) + usage |= VK_IMAGE_USAGE_STORAGE_BIT; VkImageCreateFlags flags = ds ? 0 : VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; // format-reinterpreting views if (type == VK_IMAGE_TYPE_2D && layers >= 6 && w == h && samples == 1) flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; // NVN renders into a 3D texture slice by slice (a view's min layer is the depth plane, nvn_mtl.m), e.g. the diff --git a/totk.ini.example b/totk.ini.example index d8744e73..07042f86 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -125,6 +125,10 @@ # Sun shadow cascade range in percent of the game's (its cascades end at 20, 40, 80 and 160 m), 50 to 400: higher moves # the steps where shadows turn softer further away, and spreads the shadow map over more ground. Read at start. # shadow_range = 100 +# Screen-space contact shadows, strength in percent (0 = off): after the game lights its scene, each pixel traces a +# short way toward the sun through the depth buffer and darkens where something close blocks it, adding the small +# shadows at feet, under stones and in grass that the shadow maps miss. Read at start. +# contact_shadows = 0 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 24571ec0b0f7b09c9a31f9eaf45f74ce9710c77d Mon Sep 17 00:00:00 2001 From: itaskaev2 <165683571+itaskaev2@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:00:23 +0100 Subject: [PATCH 005/177] Add soft sun shadows (PCSS) through a translator patch The deferred lighting shaders take the sun shadow as four explicit-LOD compares on the cascade array. Translator patch 0010 turns every explicit-LOD compare on a 2D array texture into a PCSS lookup when the support buffer's new pcss field has x above 0: eight raw depth fetches within pcss.w find the blockers, (receiver - blocker) * pcss.x gives the penumbra width clamped to pcss.y..pcss.z, and eight compares on a disc of that radius average to the result. With x at 0 the original single compare runs behind a branch. Radii are in UV, so they hold at any shadow_scale. The support buffer grows to 1424 bytes; support_fill writes the field from pcss (percent of the default width, 0 to 200, default 0; TOTK_PCSS_K overrides the factor at 100 percent, default 0.5). build_xlate.py expects ten patches. The setting is in totk.ini.example and on the Screen tab of the menu (English and Russian). Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 5 +- runtime/ui/menu.cpp | 1 + runtime/ui_text.c | 6 + runtime/ui_text.h | 1 + runtime/vk_exec_draw.c | 22 ++- tools/build_xlate.py | 6 +- .../0010-pcss-for-cascade-compares.patch | 135 ++++++++++++++++++ totk.ini.example | 4 + 8 files changed, 174 insertions(+), 6 deletions(-) create mode 100644 tools/xlate/patches/0010-pcss-for-cascade-compares.patch diff --git a/runtime/cfg.c b/runtime/cfg.c index 2372ad1b..bc7da7dd 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -41,7 +41,7 @@ static const char *const known[] = { "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", - "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", + "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC", "RENDER_SCALE", "REPLAY_ASYNC", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, + {"SHARPNESS", "display"}, {"ANISO", "display"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -95,6 +95,7 @@ static const CfgMeta metas[] = { {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"ANISO", "16", "game|2|4|8|16", RESTART}, {"SHADOW_SCALE", "1", "1..4", RESTART}, {"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART}, + {"PCSS", "0", "0..200", RESTART}, // Game {"FPS_LIMIT", "60", "30|60|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index b82f9f2a..3553f058 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -550,6 +550,7 @@ static void tab_screen(float scale) { row_aniso(); row_shadow_scale(); row_shadow_range(); + opt_slider("TOTK_PCSS", UI_MENU_PCSS, 0, 200, UI_MENU_PCSS_DESC, 10, "%.0f %%"); opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%"); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 91228692..056c0e4d 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -70,6 +70,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Shadow resolution", [UI_MENU_SHADOW_SCALE_DESC] = "Draws the sun's shadow maps this many times larger on each side than the game's 960x960: " "sharper shadow edges and leaf shadows. Takes effect at the next start.", + [UI_MENU_PCSS] = "Soft shadows", + [UI_MENU_PCSS_DESC] = "Sun shadows sharp where an object meets the ground and softer the further the shadow falls " + "(PCSS). 0 keeps the game's filter. Takes effect at the next start.", [UI_MENU_CONTACT_SHADOWS] = "Contact shadows", [UI_MENU_CONTACT_SHADOWS_DESC] = "Small sun shadows the shadow maps miss: at feet, under stones, in grass and creases. " "Traced on the screen after lighting. Takes effect at the next start.", @@ -302,6 +305,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SHADOW_SCALE] = "Разрешение теней", [UI_MENU_SHADOW_SCALE_DESC] = "Карты теней от солнца рисуются во столько раз больше по каждой стороне, чем 960x960 " "самой игры: края теней и тени листвы чётче. Действует после перезапуска.", + [UI_MENU_PCSS] = "Мягкие тени", + [UI_MENU_PCSS_DESC] = "Тени от солнца резкие там, где предмет касается земли, и мягче, чем дальше падает тень " + "(PCSS). 0 оставляет фильтр игры. Действует после перезапуска.", [UI_MENU_CONTACT_SHADOWS] = "Контактные тени", [UI_MENU_CONTACT_SHADOWS_DESC] = "Мелкие тени от солнца, которых нет на картах теней: у ног, под камнями, в траве и " "складках. Считаются по экрану после освещения. Действует после перезапуска.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index eb0e09cf..599cd34a 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -40,6 +40,7 @@ typedef enum { UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC, UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC, + UI_MENU_PCSS, UI_MENU_PCSS_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 124ebbc8..4f7276d0 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -32,7 +32,7 @@ #define MAX_DESC 1024 #define CHUNK_BYTES (4u << 20) #define ZERO_BYTES 65536u -#define SUPPORT_BYTES 1408u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... +#define SUPPORT_BYTES 1424u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... #define NVN_STAGE_VS 0 #define NVN_STAGE_FS 1 #define NVN_STAGE_CS 5 @@ -1246,6 +1246,25 @@ static void support_in(const VkExec *ex, float in[3]) { // what support_fill r in[2] = ex->point_size > 0 ? ex->point_size : 1.0f; } +// TOTK_PCSS (percent, 0 = off): the pcss field of the support buffer, which translator patch 0010 reads in every +// explicit-LOD compare on a 2D array texture (the sun cascades). x: penumbra width in UV per unit of light-space depth +// between receiver and blocker (0 keeps the game's single compare), y and z: the narrowest and widest disc radius, +// w: the blocker search radius, all in UV of the cascade map. Radii are in UV, so they hold at any TOTK_SHADOW_SCALE. +// TOTK_PCSS_K overrides the depth-to-penumbra factor at 100 percent, for tuning. +static const float *pcss_params(void) { + static float p[4] = {-1, 0, 0, 0}; + if (p[0] < 0) { + int pct = cfg_int("TOTK_PCSS"); + pct = pct < 0 ? 0 : pct > 200 ? 200 : pct; + const char *k = cfg_get("TOTK_PCSS_K"); + float k100 = k && *k ? (float)atof(k) : 0.5f; + p[0] = k100 * (float)pct / 100.0f; + p[1] = 0.35f / 960.0f, p[2] = 5.0f / 960.0f, p[3] = 4.0f / 960.0f; + if (pct) rt_log("vk: soft shadows (PCSS) at %d%% (depth factor %g)", pct, p[0]); + } + return p; +} + static void support_fill(uint8_t *b, float w, float h, float point_size) { memset(b, 0, SUPPORT_BYTES); float inv[4] = {w > 0 ? 2.0f / w : 0, h > 0 ? 2.0f / h : 0, 0, 0}, size[4] = {w, h, 0, 0}; @@ -1253,6 +1272,7 @@ static void support_fill(uint8_t *b, float w, float h, float point_size) { memcpy(b + 160, size, 16); const float one = 1.0f; memcpy(b + 1392, &point_size, 4); // point_size (translator patch 0008): vertex shaders that write none output it + memcpy(b + 1408, pcss_params(), 16); // pcss (translator patch 0010): soft sun shadows in the cascade compares for (int i = 0; i < 73; i++) memcpy(b + 192 + 16 * i, &one, 4); // render scale 1: the host renders at guest size } diff --git a/tools/build_xlate.py b/tools/build_xlate.py index eb455ab4..ef0d08bc 100644 --- a/tools/build_xlate.py +++ b/tools/build_xlate.py @@ -1,7 +1,7 @@ """Build the shader translator: build/xlate/totk_xlate.exe (Ryujinx 1.3.2 + patches, NativeAOT, SPIR-V for Vulkan). Copies tools/vendor/ryujinx to build/xlate/ryujinx, applies tools/xlate/patches/*.patch there (tools/vendor stays -byte-identical; 0001-0004 are MNG's, 0005-0009 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build +byte-identical; 0001-0004 are MNG's, 0005-0010 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build tools and vswhere.exe (docs/building.md). Run with .venv. Next to the exe it writes totk_xlate.id: the translator identity, a sha256 over everything the build reads (this script, @@ -96,8 +96,8 @@ def prepare_sources() -> Path: for junk in list(src.glob("src/*/obj")) + list(src.glob("src/*/bin")): shutil.rmtree(junk) patches = sorted((XLATE / "patches").glob("*.patch")) - if len(patches) != 9: - sys.exit(f"expected 9 patches, found {len(patches)}") + if len(patches) != 10: + sys.exit(f"expected 10 patches, found {len(patches)}") for patch in patches: # git apply works outside a repository when given a directory; --check first so a failure names the patch. for extra in (["--check"], []): diff --git a/tools/xlate/patches/0010-pcss-for-cascade-compares.patch b/tools/xlate/patches/0010-pcss-for-cascade-compares.patch new file mode 100644 index 00000000..4f41aaae --- /dev/null +++ b/tools/xlate/patches/0010-pcss-for-cascade-compares.patch @@ -0,0 +1,135 @@ +--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs ++++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs +@@ -1456,7 +1456,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv + } + else if (isShadow) + { +- if (hasLodLevel) ++ if (hasLodLevel && isArray && coordsCount == 2 && operandsMask == ImageOperandsMask.Lod) ++ { ++ result = GeneratePcssSample(context, declaration, image, pCoords, dRef, lod); ++ } ++ else if (hasLodLevel) + { + result = context.ImageSampleDrefExplicitLod(resultType, image, pCoords, dRef, operandsMask, operands); + } +@@ -1486,6 +1490,92 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv + return new OperationResult(swizzledResultType, result); + } + ++ // TOTK: percentage-closer soft shadows for the sun. The deferred lighting shaders take the shadow as four ++ // explicit-LOD compares on a 2D array (the cascades) around the receiver; each of those becomes a PCSS lookup ++ // when the support buffer's pcss.x is above 0 (runtime/vk_exec_draw.c support_fill, TOTK_PCSS): a blocker ++ // search reads the raw depths at eight points within pcss.w (UV), the average depth of those nearer the light ++ // than the receiver gives the penumbra width (receiver - blocker) * pcss.x, clamped to pcss.y..pcss.z (UV), and ++ // eight compares on a disc of that radius average to the result. With pcss.x at 0 the original single compare ++ // runs. The cascades are orthographic, so the depth difference is a distance along the light. ++ private static readonly float[] PcssSearch = [-0.7f, -0.7f, 0.7f, -0.7f, -0.7f, 0.7f, 0.7f, 0.7f, 0f, -1f, 0f, 1f, -1f, 0f, 1f, 0f]; ++ private static readonly float[] PcssDisk = ++ [ ++ -0.9420f, -0.3991f, 0.9456f, -0.7689f, -0.0942f, -0.9294f, 0.3450f, 0.2939f, ++ -0.9159f, 0.4577f, -0.8154f, -0.8791f, -0.3828f, 0.2768f, 0.9748f, 0.7565f, ++ ]; ++ ++ private static SpvInstruction GeneratePcssSample(CodeGenContext context, SamplerDeclaration declaration, SpvInstruction image, ++ SpvInstruction pCoords, SpvInstruction dRef, SpvInstruction lod) ++ { ++ SpvInstruction f32 = context.TypeFP32(), s32 = context.TypeS32(), b = context.TypeBool(); ++ SpvInstruction v2 = context.TypeVector(f32, 2), v3 = context.TypeVector(f32, 3), v4 = context.TypeVector(f32, 4); ++ SpvInstruction iv2 = context.TypeVector(s32, 2), iv3 = context.TypeVector(s32, 3); ++ SpvInstruction zero = context.Constant(f32, 0f), one = context.Constant(f32, 1f); ++ ++ SpvInstruction prmPtr = context.AccessChain(context.TypePointer(StorageClass.Uniform, v4), context.ConstantBuffers[SupportBuffer.Binding], ++ context.Constant(s32, (int)SupportBufferField.Pcss)); ++ SpvInstruction prm = context.Load(v4, prmPtr); ++ SpvInstruction lightSize = context.CompositeExtract(f32, prm, 0); ++ SpvInstruction minR = context.CompositeExtract(f32, prm, 1); ++ SpvInstruction maxR = context.CompositeExtract(f32, prm, 2); ++ SpvInstruction searchR = context.CompositeExtract(f32, prm, 3); ++ ++ SpvInstruction pcssLabel = context.Label(), plainLabel = context.Label(), mergeLabel = context.Label(); ++ SpvInstruction enabled = context.FOrdGreaterThan(b, lightSize, zero); // before the merge: it must precede the branch ++ context.SelectionMerge(mergeLabel, SelectionControlMask.MaskNone); ++ context.BranchConditional(enabled, pcssLabel, plainLabel); ++ ++ context.AddLabel(plainLabel); ++ SpvInstruction plain = context.ImageSampleDrefExplicitLod(f32, image, pCoords, dRef, ImageOperandsMask.Lod, lod); ++ context.Branch(mergeLabel); ++ ++ context.AddLabel(pcssLabel); ++ SpvInstruction raw = context.Image(declaration.ImageType, image); ++ SpvInstruction size3 = context.ImageQuerySizeLod(iv3, raw, context.Constant(s32, 0)); ++ SpvInstruction sizeI = context.VectorShuffle(iv2, size3, size3, 0, 1); ++ SpvInstruction sizeF = context.ConvertSToF(v2, sizeI); ++ SpvInstruction maxI = context.ISub(iv2, sizeI, context.ConstantComposite(iv2, context.Constant(s32, 1), context.Constant(s32, 1))); ++ SpvInstruction zeroI = context.ConstantComposite(iv2, context.Constant(s32, 0), context.Constant(s32, 0)); ++ SpvInstruction uv = context.VectorShuffle(v2, pCoords, pCoords, 0, 1); ++ SpvInstruction layerF = context.CompositeExtract(f32, pCoords, 2); ++ SpvInstruction layerI = context.ConvertFToS(s32, layerF); ++ SpvInstruction searchV = context.CompositeConstruct(v2, searchR, searchR); ++ ++ SpvInstruction sum = zero, count = zero; ++ for (int i = 0; i < PcssSearch.Length; i += 2) ++ { ++ SpvInstruction off = context.ConstantComposite(v2, context.Constant(f32, PcssSearch[i]), context.Constant(f32, PcssSearch[i + 1])); ++ SpvInstruction p = context.FAdd(v2, uv, context.FMul(v2, off, searchV)); ++ SpvInstruction t = context.GlslSClamp(iv2, context.ConvertFToS(iv2, context.FMul(v2, p, sizeF)), zeroI, maxI); ++ SpvInstruction c = context.CompositeConstruct(iv3, context.CompositeExtract(s32, t, 0), context.CompositeExtract(s32, t, 1), layerI); ++ SpvInstruction d = context.CompositeExtract(f32, context.ImageFetch(v4, raw, c, ImageOperandsMask.Lod, context.Constant(s32, 0)), 0); ++ SpvInstruction blocker = context.FOrdLessThan(b, d, dRef); ++ sum = context.FAdd(f32, sum, context.Select(f32, blocker, d, zero)); ++ count = context.FAdd(f32, count, context.Select(f32, blocker, one, zero)); ++ } ++ ++ SpvInstruction avg = context.FDiv(f32, sum, context.GlslFMax(f32, count, one)); ++ SpvInstruction penumbra = context.Select(f32, context.FOrdGreaterThan(b, count, zero), ++ context.FMul(f32, context.FSub(f32, dRef, avg), lightSize), zero); ++ SpvInstruction radius = context.GlslFClamp(f32, penumbra, minR, maxR); ++ SpvInstruction radiusV = context.CompositeConstruct(v2, radius, radius); ++ ++ SpvInstruction acc = zero; ++ for (int i = 0; i < PcssDisk.Length; i += 2) ++ { ++ SpvInstruction off = context.ConstantComposite(v2, context.Constant(f32, PcssDisk[i]), context.Constant(f32, PcssDisk[i + 1])); ++ SpvInstruction p = context.FAdd(v2, uv, context.FMul(v2, off, radiusV)); ++ SpvInstruction c = context.CompositeConstruct(v3, context.CompositeExtract(f32, p, 0), context.CompositeExtract(f32, p, 1), layerF); ++ acc = context.FAdd(f32, acc, context.ImageSampleDrefExplicitLod(f32, image, c, dRef, ImageOperandsMask.Lod, lod)); ++ } ++ ++ SpvInstruction pcss = context.FMul(f32, acc, context.Constant(f32, 2f / PcssDisk.Length)); ++ context.Branch(mergeLabel); ++ ++ context.AddLabel(mergeLabel); ++ return context.Phi(f32, pcss, pcssLabel, plain, plainLabel); ++ } ++ + private static OperationResult GenerateTextureQuerySamples(CodeGenContext context, AstOperation operation) + { + AstTextureOperation texOp = (AstTextureOperation)operation; +--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs ++++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs +@@ -25,6 +25,7 @@ namespace Ryujinx.Graphics.Shader + TfeOffset, + TfeVertexCount, + PointSize, ++ Pcss, + } + + public struct SupportBuffer +@@ -82,7 +83,8 @@ namespace Ryujinx.Graphics.Shader + new StructureField(AggregateType.Array | AggregateType.FP32, "render_scale", RenderScaleMaxCount), + new StructureField(AggregateType.Vector4 | AggregateType.S32, "tfe_offset"), + new StructureField(AggregateType.S32, "tfe_vertex_count"), +- new StructureField(AggregateType.FP32, "point_size") ++ new StructureField(AggregateType.FP32, "point_size"), ++ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss") + ]); + } + +@@ -98,5 +100,6 @@ namespace Ryujinx.Graphics.Shader + public Vector4 TfeOffset; + public Vector4 TfeVertexCount; + public Vector4 PointSize; ++ public Vector4 Pcss; + } + } diff --git a/totk.ini.example b/totk.ini.example index 07042f86..352f19c3 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -129,6 +129,10 @@ # short way toward the sun through the depth buffer and darkens where something close blocks it, adding the small # shadows at feet, under stones and in grass that the shadow maps miss. Read at start. # contact_shadows = 0 +# Soft sun shadows (PCSS), percent of the default penumbra width (0 to 200; 0 = the game's own four-tap filter): sharp +# where an object meets the ground and softer the further its shadow falls. Done in the translated shaders (translator +# patch 0010), so the shader cache is rebuilt once after an update. Read at start. +# pcss = 0 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. From 1512d9ed65a9ab898ce816a6b6131b36333ce58d Mon Sep 17 00:00:00 2001 From: TotK local Date: Sat, 31 Oct 2026 03:34:55 +0800 Subject: [PATCH 006/177] Add NVIDIA DLAA and a switch for the game's FXAA DLAA runs DLSS at the scene's own size on the R11G11B10F light target, right before the bloom chain's first pass, so bloom, post and HUD read the anti-aliased picture. NGX is loaded from the driver's NGX core at run time; no NVIDIA SDK code is compiled in, and nvngx_dlss.dll goes next to totk.exe. The scene's draws get a Halton(2,3) viewport jitter that steps after each DLAA run; camera motion vectors come from the scene depth reprojected through this and last frame's view-projection of the scene camera block (c4), read from the uniform snapshot. One DLSS feature per scene size keeps dynamic resolution from stalling. dlaa and fxaa switch live from the settings menu; fxaa skips the draw of the game's FXAA pass. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 5 + runtime/cfg.c | 7 +- runtime/dlaa_mv_spv.h | 119 +++++++ runtime/shaders/dlaa_mv.comp | 40 +++ runtime/ui/menu.cpp | 2 + runtime/ui_text.c | 10 + runtime/ui_text.h | 1 + runtime/vk_backend.c | 2 + runtime/vk_device.c | 9 +- runtime/vk_dlaa.c | 624 +++++++++++++++++++++++++++++++++++ runtime/vk_dlaa.h | 22 ++ runtime/vk_exec.c | 2 + runtime/vk_exec_draw.c | 4 + totk.ini.example | 7 + 14 files changed, 848 insertions(+), 6 deletions(-) create mode 100644 runtime/dlaa_mv_spv.h create mode 100644 runtime/shaders/dlaa_mv.comp create mode 100644 runtime/vk_dlaa.c create mode 100644 runtime/vk_dlaa.h diff --git a/docs/architecture.md b/docs/architecture.md index af1c6605..50154d80 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -94,6 +94,11 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app (MacNativeGames' sites); `resolution.c` sets them from `output_res` and `render_scale` and grows the texture heap and the application pool to match. When the window is larger than the output, `vk_fsr.c` runs AMD FSR 1 (EASU, RCAS) on the present. +- DLAA (`vk_dlaa.c`, `dlaa`, off by default). NVIDIA DLSS at the scene's own size, through the driver's NGX core loaded + at run time (no SDK code compiled in). It runs on the R11G11B10F light target right before the bloom chain's first + pass, so post effects and the HUD read the anti-aliased picture. The scene's draws get a sub-pixel Halton viewport + jitter; motion vectors are camera-only, reprojected from the scene depth through this and last frame's + view-projection of the scene camera block (constant bank c4). `fxaa` switches the game's own FXAA pass. - Occlusion queries never block the CPU; a result that is not ready counts as visible. - ASTC textures are uploaded as they are where the device reports `textureCompressionASTC_LDR`, and decoded by a compute shader everywhere else (`vk_astc.c`, `TOTK_ASTC`). The CPU decoder (`tex_astc*.c`) is the fallback and the test oracle. - Draw state. A draw whose program, bound state and textures repeat reuses the previous draw's shaders and skips rebuilding its descriptor sets; descriptor sets are written through update templates (`vk_exec_draw.c`, `vk_pipeline.c`). diff --git a/runtime/cfg.c b/runtime/cfg.c index 31eb9213..4fed7c46 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -35,9 +35,9 @@ static const char *const known[] = { "BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", - "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", + "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DLAA", "DLAA_JITTER", "DLAA_MV", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", - "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU", + "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", @@ -59,7 +59,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, + {"SHARPNESS", "display"}, {"DLAA", "display"}, {"FXAA", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -94,6 +94,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, + {"DLAA", "0", "0|1", LIVE}, {"FXAA", "1", "0|1", LIVE}, // Game {"FPS_LIMIT", "60", "30|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, diff --git a/runtime/dlaa_mv_spv.h b/runtime/dlaa_mv_spv.h new file mode 100644 index 00000000..e1b31e6c --- /dev/null +++ b/runtime/dlaa_mv_spv.h @@ -0,0 +1,119 @@ +// Generated by tools/build_shaders.py from runtime/shaders/dlaa_mv.comp; do not edit. +// source sha256 bfa9b6d9e0f9d5cfd4382fa5080fa46f007a1a4e2b886b8fecd9adba11767686 +#pragma once +#include +static const uint32_t dlaa_mv_spv[] = { + 0x07230203, 0x00010600, 0x0008000b, 0x00000131, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, + 0x00000000, 0x00000001, 0x000b000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00000036, + 0x00000043, 0x0000005d, 0x00000089, 0x000000a0, 0x000000e7, 0x00060010, 0x00000004, 0x00000011, + 0x00000008, 0x00000008, 0x00000001, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, + 0x6e69616d, 0x00000000, 0x00080005, 0x00000036, 0x475f6c67, 0x61626f6c, 0x766e496c, 0x7461636f, + 0x496e6f69, 0x00000044, 0x00030005, 0x00000041, 0x00000050, 0x00050006, 0x00000041, 0x00000000, + 0x657a6973, 0x00000000, 0x00050006, 0x00000041, 0x00000001, 0x7474696a, 0x00007265, 0x00030005, + 0x00000043, 0x00006370, 0x00050005, 0x0000005d, 0x74706564, 0x65745f68, 0x00000078, 0x00030005, + 0x00000087, 0x00727543, 0x00040006, 0x00000087, 0x00000000, 0x00000072, 0x00030005, 0x00000089, + 0x00727563, 0x00040005, 0x0000009e, 0x76657250, 0x00000000, 0x00040006, 0x0000009e, 0x00000000, + 0x00000072, 0x00040005, 0x000000a0, 0x76657270, 0x00000000, 0x00040005, 0x000000e7, 0x6f5f766d, + 0x00007475, 0x00040047, 0x00000036, 0x0000000b, 0x0000001c, 0x00030047, 0x00000041, 0x00000002, + 0x00050048, 0x00000041, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000041, 0x00000001, + 0x00000023, 0x00000008, 0x00040047, 0x0000005d, 0x00000021, 0x00000000, 0x00040047, 0x0000005d, + 0x00000022, 0x00000000, 0x00040047, 0x00000086, 0x00000006, 0x00000010, 0x00030047, 0x00000087, + 0x00000002, 0x00050048, 0x00000087, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000089, + 0x00000021, 0x00000002, 0x00040047, 0x00000089, 0x00000022, 0x00000000, 0x00040047, 0x0000009d, + 0x00000006, 0x00000010, 0x00030047, 0x0000009e, 0x00000002, 0x00050048, 0x0000009e, 0x00000000, + 0x00000023, 0x00000000, 0x00040047, 0x000000a0, 0x00000021, 0x00000003, 0x00040047, 0x000000a0, + 0x00000022, 0x00000000, 0x00030047, 0x000000e7, 0x00000019, 0x00040047, 0x000000e7, 0x00000021, + 0x00000001, 0x00040047, 0x000000e7, 0x00000022, 0x00000000, 0x00020013, 0x00000002, 0x00030021, + 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, + 0x00000004, 0x00040018, 0x00000009, 0x00000007, 0x00000004, 0x0004002b, 0x00000006, 0x00000015, + 0x3f800000, 0x0004002b, 0x00000006, 0x00000016, 0x00000000, 0x00040015, 0x0000002f, 0x00000020, + 0x00000001, 0x00040017, 0x00000030, 0x0000002f, 0x00000002, 0x00040015, 0x00000033, 0x00000020, + 0x00000000, 0x00040017, 0x00000034, 0x00000033, 0x00000003, 0x00040020, 0x00000035, 0x00000001, + 0x00000034, 0x0004003b, 0x00000035, 0x00000036, 0x00000001, 0x00040017, 0x00000037, 0x00000033, + 0x00000002, 0x00020014, 0x0000003b, 0x0004002b, 0x00000033, 0x0000003c, 0x00000000, 0x00040017, + 0x00000040, 0x00000006, 0x00000002, 0x0004001e, 0x00000041, 0x00000040, 0x00000040, 0x00040020, + 0x00000042, 0x00000009, 0x00000041, 0x0004003b, 0x00000042, 0x00000043, 0x00000009, 0x0004002b, + 0x0000002f, 0x00000044, 0x00000000, 0x00040020, 0x00000045, 0x00000009, 0x00000006, 0x0004002b, + 0x00000033, 0x0000004d, 0x00000001, 0x00090019, 0x0000005a, 0x00000006, 0x00000001, 0x00000000, + 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x0000005b, 0x0000005a, 0x00040020, + 0x0000005c, 0x00000000, 0x0000005b, 0x0004003b, 0x0000005c, 0x0000005d, 0x00000000, 0x0004002b, + 0x00000006, 0x00000067, 0x3f000000, 0x0004002b, 0x0000002f, 0x0000006a, 0x00000001, 0x00040020, + 0x0000006b, 0x00000009, 0x00000040, 0x0004002b, 0x00000006, 0x00000075, 0x40000000, 0x0004002b, + 0x00000033, 0x00000085, 0x00000010, 0x0004001c, 0x00000086, 0x00000007, 0x00000085, 0x0003001e, + 0x00000087, 0x00000086, 0x00040020, 0x00000088, 0x00000002, 0x00000087, 0x0004003b, 0x00000088, + 0x00000089, 0x00000002, 0x0004002b, 0x0000002f, 0x0000008a, 0x00000003, 0x0004002b, 0x0000002f, + 0x0000008b, 0x00000004, 0x0004002b, 0x0000002f, 0x0000008c, 0x00000005, 0x0004002b, 0x0000002f, + 0x0000008d, 0x00000006, 0x00040020, 0x0000008f, 0x00000002, 0x00000007, 0x0004001c, 0x0000009d, + 0x00000007, 0x00000085, 0x0003001e, 0x0000009e, 0x0000009d, 0x00040020, 0x0000009f, 0x00000002, + 0x0000009e, 0x0004003b, 0x0000009f, 0x000000a0, 0x00000002, 0x0005002c, 0x00000040, 0x000000b4, + 0x00000016, 0x00000016, 0x0004002b, 0x00000006, 0x000000b9, 0x2b8cbccc, 0x0004002b, 0x00000006, + 0x000000c7, 0x358637bd, 0x00090019, 0x000000e5, 0x00000006, 0x00000001, 0x00000000, 0x00000000, + 0x00000000, 0x00000002, 0x00000007, 0x00040020, 0x000000e6, 0x00000000, 0x000000e5, 0x0004003b, + 0x000000e6, 0x000000e7, 0x00000000, 0x0005002c, 0x00000040, 0x00000130, 0x00000067, 0x00000067, + 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7, + 0x000000f0, 0x00000000, 0x000300fb, 0x0000003c, 0x000000f1, 0x000200f8, 0x000000f1, 0x0004003d, + 0x00000034, 0x00000038, 0x00000036, 0x0007004f, 0x00000037, 0x00000039, 0x00000038, 0x00000038, + 0x00000000, 0x00000001, 0x0004007c, 0x00000030, 0x0000003a, 0x00000039, 0x00050051, 0x0000002f, + 0x0000003f, 0x0000003a, 0x00000000, 0x00060041, 0x00000045, 0x00000046, 0x00000043, 0x00000044, + 0x0000003c, 0x0004003d, 0x00000006, 0x00000047, 0x00000046, 0x0004006e, 0x0000002f, 0x00000048, + 0x00000047, 0x000500af, 0x0000003b, 0x00000049, 0x0000003f, 0x00000048, 0x000400a8, 0x0000003b, + 0x0000004a, 0x00000049, 0x000300f7, 0x0000004c, 0x00000000, 0x000400fa, 0x0000004a, 0x0000004b, + 0x0000004c, 0x000200f8, 0x0000004b, 0x00050051, 0x0000002f, 0x0000004f, 0x0000003a, 0x00000001, + 0x00060041, 0x00000045, 0x00000050, 0x00000043, 0x00000044, 0x0000004d, 0x0004003d, 0x00000006, + 0x00000051, 0x00000050, 0x0004006e, 0x0000002f, 0x00000052, 0x00000051, 0x000500af, 0x0000003b, + 0x00000053, 0x0000004f, 0x00000052, 0x000200f9, 0x0000004c, 0x000200f8, 0x0000004c, 0x000700f5, + 0x0000003b, 0x00000054, 0x00000049, 0x000000f1, 0x00000053, 0x0000004b, 0x000300f7, 0x00000056, + 0x00000000, 0x000400fa, 0x00000054, 0x00000055, 0x00000056, 0x000200f8, 0x00000055, 0x000200f9, + 0x000000f0, 0x000200f8, 0x00000056, 0x0004003d, 0x0000005b, 0x0000005e, 0x0000005d, 0x00040064, + 0x0000005a, 0x00000060, 0x0000005e, 0x0007005f, 0x00000007, 0x00000061, 0x00000060, 0x0000003a, + 0x00000002, 0x00000044, 0x00050051, 0x00000006, 0x00000062, 0x00000061, 0x00000000, 0x0004006f, + 0x00000040, 0x00000066, 0x0000003a, 0x00050081, 0x00000040, 0x00000069, 0x00000066, 0x00000130, + 0x00050041, 0x0000006b, 0x0000006c, 0x00000043, 0x0000006a, 0x0004003d, 0x00000040, 0x0000006d, + 0x0000006c, 0x00050083, 0x00000040, 0x0000006e, 0x00000069, 0x0000006d, 0x00050051, 0x00000006, + 0x00000071, 0x0000006e, 0x00000000, 0x00050088, 0x00000006, 0x00000074, 0x00000071, 0x00000047, + 0x00050085, 0x00000006, 0x00000076, 0x00000074, 0x00000075, 0x00050083, 0x00000006, 0x00000077, + 0x00000076, 0x00000015, 0x00050051, 0x00000006, 0x00000079, 0x0000006e, 0x00000001, 0x00060041, + 0x00000045, 0x0000007a, 0x00000043, 0x00000044, 0x0000004d, 0x0004003d, 0x00000006, 0x0000007b, + 0x0000007a, 0x00050088, 0x00000006, 0x0000007c, 0x00000079, 0x0000007b, 0x00050085, 0x00000006, + 0x0000007d, 0x0000007c, 0x00000075, 0x00050083, 0x00000006, 0x0000007e, 0x00000015, 0x0000007d, + 0x00050085, 0x00000006, 0x00000080, 0x00000062, 0x00000075, 0x00050083, 0x00000006, 0x00000081, + 0x00000080, 0x00000015, 0x00070050, 0x00000007, 0x00000082, 0x00000077, 0x0000007e, 0x00000081, + 0x00000015, 0x00060041, 0x0000008f, 0x00000090, 0x00000089, 0x00000044, 0x0000008a, 0x0004003d, + 0x00000007, 0x00000091, 0x00000090, 0x00060041, 0x0000008f, 0x00000093, 0x00000089, 0x00000044, + 0x0000008b, 0x0004003d, 0x00000007, 0x00000094, 0x00000093, 0x00060041, 0x0000008f, 0x00000096, + 0x00000089, 0x00000044, 0x0000008c, 0x0004003d, 0x00000007, 0x00000097, 0x00000096, 0x00060041, + 0x0000008f, 0x00000099, 0x00000089, 0x00000044, 0x0000008d, 0x0004003d, 0x00000007, 0x0000009a, + 0x00000099, 0x00070050, 0x00000009, 0x00000110, 0x00000091, 0x00000094, 0x00000097, 0x0000009a, + 0x00040054, 0x00000009, 0x00000111, 0x00000110, 0x00060041, 0x0000008f, 0x000000a2, 0x000000a0, + 0x00000044, 0x0000008a, 0x0004003d, 0x00000007, 0x000000a3, 0x000000a2, 0x00060041, 0x0000008f, + 0x000000a5, 0x000000a0, 0x00000044, 0x0000008b, 0x0004003d, 0x00000007, 0x000000a6, 0x000000a5, + 0x00060041, 0x0000008f, 0x000000a8, 0x000000a0, 0x00000044, 0x0000008c, 0x0004003d, 0x00000007, + 0x000000a9, 0x000000a8, 0x00060041, 0x0000008f, 0x000000ab, 0x000000a0, 0x00000044, 0x0000008d, + 0x0004003d, 0x00000007, 0x000000ac, 0x000000ab, 0x00070050, 0x00000009, 0x0000012c, 0x000000a3, + 0x000000a6, 0x000000a9, 0x000000ac, 0x00040054, 0x00000009, 0x0000012d, 0x0000012c, 0x0006000c, + 0x00000009, 0x000000b0, 0x00000001, 0x00000022, 0x00000111, 0x00050091, 0x00000007, 0x000000b2, + 0x000000b0, 0x00000082, 0x00050051, 0x00000006, 0x000000b7, 0x000000b2, 0x00000003, 0x0006000c, + 0x00000006, 0x000000b8, 0x00000001, 0x00000004, 0x000000b7, 0x000500ba, 0x0000003b, 0x000000ba, + 0x000000b8, 0x000000b9, 0x000300f7, 0x000000bc, 0x00000000, 0x000400fa, 0x000000ba, 0x000000bb, + 0x000000bc, 0x000200f8, 0x000000bb, 0x00070050, 0x00000007, 0x000000c2, 0x000000b7, 0x000000b7, + 0x000000b7, 0x000000b7, 0x00050088, 0x00000007, 0x000000c3, 0x000000b2, 0x000000c2, 0x00050091, + 0x00000007, 0x000000c4, 0x0000012d, 0x000000c3, 0x00050051, 0x00000006, 0x000000c6, 0x000000c4, + 0x00000003, 0x000500ba, 0x0000003b, 0x000000c8, 0x000000c6, 0x000000c7, 0x000300f7, 0x000000ca, + 0x00000000, 0x000400fa, 0x000000c8, 0x000000c9, 0x000000ca, 0x000200f8, 0x000000c9, 0x0007004f, + 0x00000040, 0x000000cd, 0x000000c4, 0x000000c4, 0x00000000, 0x00000001, 0x00050050, 0x00000040, + 0x000000d0, 0x000000c6, 0x000000c6, 0x00050088, 0x00000040, 0x000000d1, 0x000000cd, 0x000000d0, + 0x00050051, 0x00000006, 0x000000d4, 0x000000d1, 0x00000000, 0x00050085, 0x00000006, 0x000000d5, + 0x000000d4, 0x00000067, 0x00050081, 0x00000006, 0x000000d6, 0x000000d5, 0x00000067, 0x00050085, + 0x00000006, 0x000000d9, 0x000000d6, 0x00000047, 0x00050051, 0x00000006, 0x000000db, 0x000000d1, + 0x00000001, 0x00050085, 0x00000006, 0x000000dc, 0x000000db, 0x00000067, 0x00050083, 0x00000006, + 0x000000dd, 0x00000067, 0x000000dc, 0x00050085, 0x00000006, 0x000000e0, 0x000000dd, 0x0000007b, + 0x00050050, 0x00000040, 0x000000e1, 0x000000d9, 0x000000e0, 0x00050083, 0x00000040, 0x000000e4, + 0x000000e1, 0x0000006e, 0x000200f9, 0x000000ca, 0x000200f8, 0x000000ca, 0x000700f5, 0x00000040, + 0x0000012f, 0x000000b4, 0x000000bb, 0x000000e4, 0x000000c9, 0x000200f9, 0x000000bc, 0x000200f8, + 0x000000bc, 0x000700f5, 0x00000040, 0x0000012e, 0x000000b4, 0x00000056, 0x0000012f, 0x000000ca, + 0x0004003d, 0x000000e5, 0x000000e8, 0x000000e7, 0x00050051, 0x00000006, 0x000000eb, 0x0000012e, + 0x00000000, 0x00050051, 0x00000006, 0x000000ec, 0x0000012e, 0x00000001, 0x00070050, 0x00000007, + 0x000000ed, 0x000000eb, 0x000000ec, 0x00000016, 0x00000016, 0x00040063, 0x000000e8, 0x0000003a, + 0x000000ed, 0x000200f9, 0x000000f0, 0x000200f8, 0x000000f0, 0x000100fd, 0x00010038, +}; diff --git a/runtime/shaders/dlaa_mv.comp b/runtime/shaders/dlaa_mv.comp new file mode 100644 index 00000000..f7ced22c --- /dev/null +++ b/runtime/shaders/dlaa_mv.comp @@ -0,0 +1,40 @@ +#version 450 +// Camera motion vectors for DLAA (vk_dlaa.c mv_pass): each pixel's depth is taken back to the world through this +// frame's view-projection and forward through last frame's; the vector is last frame's window position minus this +// frame's, in render pixels, without the jitter (DLSS's default convention). Objects that move on their own get only +// the camera's motion. +// The camera block is TotK's scene uniform block (bound as c4 in the scene's vertex shaders): vec4 rows 3-6 are the +// view-projection, rows of a row-major 4x4 with OpenGL clip depth (-w..w). The replay's viewports have negative +// heights, so window y grows downwards from ndc y = +1, and depth is z_ndc * 0.5 + 0.5. +layout(local_size_x = 8, local_size_y = 8) in; +layout(binding = 0) uniform sampler2D depth_tex; +layout(binding = 1, rg16f) uniform writeonly image2D mv_out; +layout(binding = 2, std140) uniform Cur { vec4 r[16]; } cur; +layout(binding = 3, std140) uniform Prev { vec4 r[16]; } prev; +layout(push_constant) uniform P { + vec2 size; // render size in pixels + vec2 jitter; // this frame's jitter, pixels, as the scene was drawn (window x right, y down) +} pc; + +mat4 vp(vec4 a, vec4 b, vec4 c, vec4 d) { return transpose(mat4(a, b, c, d)); } + +void main() { + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (p.x >= int(pc.size.x) || p.y >= int(pc.size.y)) return; + float d = texelFetch(depth_tex, p, 0).r; + vec2 win = vec2(p) + 0.5 - pc.jitter; // where this pixel's surface sits without the jitter + vec4 ndc = vec4(win.x / pc.size.x * 2.0 - 1.0, 1.0 - win.y / pc.size.y * 2.0, d * 2.0 - 1.0, 1.0); + mat4 c = vp(cur.r[3], cur.r[4], cur.r[5], cur.r[6]); + mat4 q = vp(prev.r[3], prev.r[4], prev.r[5], prev.r[6]); + vec4 world = inverse(c) * ndc; + vec2 mv = vec2(0.0); + if (abs(world.w) > 1e-12) { + vec4 clip = q * (world / world.w); + if (clip.w > 1e-6) { + vec2 pn = clip.xy / clip.w; + vec2 pwin = vec2((pn.x * 0.5 + 0.5) * pc.size.x, (0.5 - pn.y * 0.5) * pc.size.y); + mv = pwin - win; + } + } + imageStore(mv_out, p, vec4(mv, 0.0, 0.0)); +} diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 7d52baa9..035631b4 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -534,6 +534,8 @@ static void tab_screen(float scale) { static const UiTextId up[] = {UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR}; opt_choice("TOTK_UPSCALER", UI_MENU_UPSCALER, up, 2, UI_MENU_UPSCALER_DESC); opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%"); + opt_toggle("TOTK_DLAA", UI_MENU_DLAA, UI_MENU_DLAA_DESC); + opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 0de0818f..3bd8c2f3 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -63,6 +63,11 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Bilinear", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", + [UI_MENU_DLAA] = "NVIDIA DLAA", + [UI_MENU_DLAA_DESC] = "DLSS anti-aliasing of the 3D scene at its own resolution (NVIDIA RTX GPUs; nvngx_dlss.dll next to " + "totk.exe). Smoother edges and less shimmer for about 3 ms a frame.", + [UI_MENU_FXAA] = "Game anti-aliasing (FXAA)", + [UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -282,6 +287,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "Билинейное", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", + [UI_MENU_DLAA] = "NVIDIA DLAA", + [UI_MENU_DLAA_DESC] = "Сглаживание 3D-сцены через DLSS в её собственном разрешении (видеокарты NVIDIA RTX; nvngx_dlss.dll " + "рядом с totk.exe). Ровнее края и меньше мерцания, около 3 мс на кадр.", + [UI_MENU_FXAA] = "Сглаживание игры (FXAA)", + [UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 96e10618..7d95c8be 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -36,6 +36,7 @@ typedef enum { UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME, UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, + UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_FXAA, UI_MENU_FXAA_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_90, UI_MENU_FPS_120, diff --git a/runtime/vk_backend.c b/runtime/vk_backend.c index a260aa69..86388618 100644 --- a/runtime/vk_backend.c +++ b/runtime/vk_backend.c @@ -29,6 +29,7 @@ #include "nvn_api.h" #include "vk.h" #include "vk_exec.h" +#include "vk_dlaa.h" #define WEAK __attribute__((weak)) @@ -104,6 +105,7 @@ static void present_image(const tex_t *t, const int crop[4], uint64_t at_ns, uin uint64_t value) { static volatile long n_skipped; vk_exec_frame_log(t, frame); + vk_dlaa_frame(); vk_mem_census(frame); if (vk_dump_armed) vk_dump_present(frame); __atomic_store_n(&gfx_counters.validation_errors, (uint64_t)vk_validation_errors_total(), __ATOMIC_RELAXED); diff --git a/runtime/vk_device.c b/runtime/vk_device.c index 98fb84f9..8df3eab0 100644 --- a/runtime/vk_device.c +++ b/runtime/vk_device.c @@ -10,6 +10,7 @@ #include "cfg.h" #include "host.h" #include "vk.h" +#include "vk_dlaa.h" static VkCtx g_vk; static int g_ready; @@ -42,7 +43,7 @@ static int layer_present(const char *name) { } static int create_instance(void) { - const char *ext[4] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; + const char *ext[12] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; uint32_t n_ext = 2; const char *layers[] = {"VK_LAYER_KHRONOS_validation"}; int validate = cfg_bool("TOTK_VK_VALIDATION"); @@ -51,6 +52,7 @@ static int create_instance(void) { validate = 0; } if (validate) ext[n_ext++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + vk_dlaa_instance_exts(ext, &n_ext, 12); VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "TotK Recomp", .pEngineName = "TotK Recomp", .apiVersion = VK_API_VERSION_1_3}; VkInstanceCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app, @@ -195,7 +197,7 @@ static int create_device(void) { vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, NULL); VkExtensionProperties *ep = calloc(ne ? ne : 1, sizeof *ep); vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, ep); - const char *ext[28]; + const char *ext[40]; uint32_t n_ext = 0; for (size_t i = 0; i < sizeof k_required_ext / sizeof *k_required_ext; i++) ext[n_ext++] = k_required_ext[i]; @@ -232,6 +234,7 @@ static int create_device(void) { CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT); CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR); } + vk_dlaa_device_exts(ep, ne, ext, &n_ext, 34); // NGX's; the six slots after it stay for the ones below if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; } // GPU breadcrumbs for a lost device (vk_crumbs.c): AMD's drivers and RADV report it. if (has_ext(ep, ne, VK_AMD_BUFFER_MARKER_EXTENSION_NAME)) { g_vk.has_buffer_marker = 1; ext[n_ext++] = VK_AMD_BUFFER_MARKER_EXTENSION_NAME; } @@ -354,7 +357,7 @@ int vk_init(void) { AcquireSRWLockExclusive(&g_lock); if (!g_ready) { memset(&g_vk, 0, sizeof g_vk); - if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_headroom_start(); + if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_headroom_start(), vk_dlaa_init(); else destroy_all(); } int ok = g_ready; diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c new file mode 100644 index 00000000..9de36e8a --- /dev/null +++ b/runtime/vk_dlaa.c @@ -0,0 +1,624 @@ +// DLAA: NVIDIA DLSS at the scene's own size (TOTK_DLAA, totk.ini dlaa). NGX is loaded at run time from the driver's +// NGX core (_nvngx.dll, found through HKLM\SOFTWARE\NVIDIA Corporation\Global\NGXCore); the DLSS model +// (nvngx_dlss.dll) is loaded by NGX from the folder of totk.exe. No NVIDIA SDK code or header is compiled in: the few +// NGX types used are declared here from the SDK's documented ABI, the way the Metroid Dread recomp's dlss.c reaches +// the core (read for behaviour only). +// +// The core's parameter object is a C++ class whose virtual functions are called through the MSVC vtable: the Set +// overloads in slots 0-7 and the Get overloads in 8-15, each group in reverse declaration order. vtable_ok checks that +// layout with a set-then-get round trip before anything relies on it. +// +// Where DLAA runs in the frame, the jitter and the motion vectors: see the sections below. +#include +#include +#include +#include +#include +#include + +#include "cfg.h" +#include "host.h" +#include "vk.h" +#include "vk_dlaa.h" +#include "vk_exec.h" +#include "vk_rec.h" +#include "dlaa_mv_spv.h" + +typedef int NgxResult; // NVSDK_NGX_Result: 1 success, 0xBAD00000 | n failures +#define NGX_OK(r) (((unsigned)(r) & 0xFFF00000u) != 0xBAD00000u) +#define NGX_VERSION_API 0x15 +#define NGX_FEATURE_SUPERSAMPLING 1 +#define NGX_PERFQ_DLAA 5 +typedef struct NgxParam NgxParam; +typedef struct NgxHandle NgxHandle; +typedef struct { void *slot[17]; } NgxParamVtbl; +struct NgxParam { const NgxParamVtbl *vt; }; +typedef struct { // NVSDK_NGX_ImageViewInfo_VK + VkImageView view; + VkImage image; + VkImageSubresourceRange range; + VkFormat format; + unsigned width, height; +} NgxImageView; +typedef struct { // NVSDK_NGX_Resource_VK + union { NgxImageView img; struct { VkBuffer buffer; unsigned bytes; } buf; } r; + int type; // 0 image view, 1 buffer + _Bool rw; +} NgxResourceVK; + +typedef NgxResult (*PFN_Init)(unsigned long long app, const wchar_t *path, VkInstance, VkPhysicalDevice, VkDevice, + PFN_vkGetInstanceProcAddr, PFN_vkGetDeviceProcAddr, int version, const void *info); +typedef NgxResult (*PFN_ReqExt)(unsigned *ni, const char ***ie, unsigned *nd, const char ***de); +typedef NgxResult (*PFN_Params)(NgxParam **); +typedef NgxResult (*PFN_DestroyParams)(NgxParam *); +typedef NgxResult (*PFN_Create)(VkCommandBuffer, int feature, NgxParam *, NgxHandle **); +typedef NgxResult (*PFN_Evaluate)(VkCommandBuffer, const NgxHandle *, const NgxParam *, void *callback); +typedef NgxResult (*PFN_Release)(NgxHandle *); + +static struct { + HMODULE core; + PFN_Init init; + PFN_ReqExt req_ext; + PFN_Params caps, alloc_params; + PFN_DestroyParams destroy_params; + PFN_Create create; + PFN_Evaluate evaluate; + PFN_Release release; + int tried, loaded, available; + int wanted; // -1 not read yet +} N = {.wanted = -1}; + +typedef void (*SetI)(NgxParam *, const char *, int); +typedef void (*SetU)(NgxParam *, const char *, unsigned); +typedef void (*SetF)(NgxParam *, const char *, float); +typedef void (*SetP)(NgxParam *, const char *, void *); +typedef NgxResult (*GetI)(const NgxParam *, const char *, int *); +typedef NgxResult (*GetU)(const NgxParam *, const char *, unsigned *); +typedef NgxResult (*GetF)(const NgxParam *, const char *, float *); +typedef NgxResult (*GetP)(const NgxParam *, const char *, void **); +enum { S_P = 0, S_D12, S_D11, S_I, S_U32, S_D, S_F, S_U64, G_P, G_D12, G_D11, G_I, G_U32, G_D, G_F, G_U64 }; +static void p_seti(NgxParam *p, const char *n, int v) { ((SetI)p->vt->slot[S_I])(p, n, v); } +static void p_setu(NgxParam *p, const char *n, unsigned v) { ((SetU)p->vt->slot[S_U32])(p, n, v); } +static void p_setf(NgxParam *p, const char *n, float v) { ((SetF)p->vt->slot[S_F])(p, n, v); } +static void p_setp(NgxParam *p, const char *n, void *v) { ((SetP)p->vt->slot[S_P])(p, n, v); } +static int p_geti(const NgxParam *p, const char *n, int *v) { return NGX_OK(((GetI)p->vt->slot[G_I])(p, n, v)); } +static int p_getu(const NgxParam *p, const char *n, unsigned *v) { return NGX_OK(((GetU)p->vt->slot[G_U32])(p, n, v)); } +static int p_getf(const NgxParam *p, const char *n, float *v) { return NGX_OK(((GetF)p->vt->slot[G_F])(p, n, v)); } +static int p_getp(const NgxParam *p, const char *n, void **v) { return NGX_OK(((GetP)p->vt->slot[G_P])(p, n, v)); } + +// NGX is brought up whenever the driver has it, whatever the setting, so dlaa can be switched on while the game runs +// (its device extensions can only be asked for at device creation). Switched off, nothing else of DLAA runs. +int vk_dlaa_wanted(void) { return 1; } + +static int core_load(void) { + if (N.tried) return N.loaded; + N.tried = 1; + char dir[MAX_PATH] = {0}, path[MAX_PATH + 32]; + DWORD n = sizeof dir; + if (RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\NVIDIA Corporation\\Global\\NGXCore", "FullPath", RRF_RT_REG_SZ, + NULL, dir, &n) != ERROR_SUCCESS) { + rt_log("dlaa: the driver has no NGX core (registry NGXCore missing): DLAA off"); + return 0; + } + snprintf(path, sizeof path, "%s\\_nvngx.dll", dir); + N.core = LoadLibraryA(path); + if (!N.core) { + rt_log("dlaa: cannot load %s (error %lu): DLAA off", path, GetLastError()); + return 0; + } +#define FN(f, name) N.f = (void *)GetProcAddress(N.core, name) + FN(init, "NVSDK_NGX_VULKAN_Init_Ext2"); + FN(req_ext, "NVSDK_NGX_VULKAN_RequiredExtensions"); + FN(caps, "NVSDK_NGX_VULKAN_GetCapabilityParameters"); + FN(alloc_params, "NVSDK_NGX_VULKAN_AllocateParameters"); + FN(destroy_params, "NVSDK_NGX_VULKAN_DestroyParameters"); + FN(create, "NVSDK_NGX_VULKAN_CreateFeature"); + FN(evaluate, "NVSDK_NGX_VULKAN_EvaluateFeature"); + FN(release, "NVSDK_NGX_VULKAN_ReleaseFeature"); +#undef FN + if (!N.init || !N.req_ext || !N.caps || !N.alloc_params || !N.create || !N.evaluate || !N.release) { + rt_log("dlaa: the NGX core %s lacks Vulkan entry points: DLAA off", path); + return 0; + } + N.loaded = 1; + rt_log("dlaa: NGX core %s", path); + return 1; +} + +static int listed(const char *const *list, uint32_t n, const char *s) { + for (uint32_t i = 0; i < n; i++) + if (!strcmp(list[i], s)) return 1; + return 0; +} + +void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max) { + unsigned ni = 0, nd = 0; + const char **ie = NULL, **de = NULL; + if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; + for (unsigned i = 0; i < ni; i++) + if (!listed(ext, *n, ie[i]) && *n < max) ext[(*n)++] = ie[i]; +} + +void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, + uint32_t max) { + unsigned ni = 0, nd = 0; + const char **ie = NULL, **de = NULL; + if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; + for (unsigned i = 0; i < nd; i++) { + int ok = 0; + for (uint32_t k = 0; k < nhave && !ok; k++) ok = !strcmp(have[k].extensionName, de[i]); + if (!ok) rt_log("dlaa: the device lacks %s, which NGX asks for", de[i]); + else if (!listed(ext, *n, de[i]) && *n < max) ext[(*n)++] = de[i]; + } +} + +static int vtable_ok(void) { + NgxParam *p = NULL; + if (!NGX_OK(N.alloc_params(&p)) || !p) return 0; + int i = 0; + unsigned u = 0; + float f = 0; + void *v = NULL; + p_seti(p, "TotK.Test.I", -12345); + p_setu(p, "TotK.Test.U", 4000000000u); + p_setf(p, "TotK.Test.F", 1.25f); + p_setp(p, "TotK.Test.P", (void *)p); + int ok = p_geti(p, "TotK.Test.I", &i) && i == -12345 && p_getu(p, "TotK.Test.U", &u) && u == 4000000000u && + p_getf(p, "TotK.Test.F", &f) && f == 1.25f && p_getp(p, "TotK.Test.P", &v) && v == (void *)p; + if (N.destroy_params) N.destroy_params(p); + if (!ok) rt_log("dlaa: NGX parameter layout check failed (i=%d u=%u f=%g p=%p): DLAA off", i, u, f, v); + return ok; +} + +void vk_dlaa_init(void) { + if (!vk_dlaa_wanted() || !core_load()) return; + wchar_t wdir[MAX_PATH]; + DWORD len = GetModuleFileNameW(NULL, wdir, MAX_PATH); + while (len && wdir[len - 1] != L'\\') len--; + wdir[len] = 0; + // 231313132: the application id NVIDIA's DLSS samples use for builds without an NVIDIA-issued id + const VkCtx *c = vk_ctx(); + NgxResult r = N.init(231313132ull, wdir, c->instance, c->phys, c->device, vkGetInstanceProcAddr, + vkGetDeviceProcAddr, NGX_VERSION_API, NULL); + if (!NGX_OK(r)) { + rt_log("dlaa: NGX init failed (%08x): DLAA off", (unsigned)r); + return; + } + if (!vtable_ok()) return; + NgxParam *caps = NULL; + int avail = 0, driver = 0; + if (NGX_OK(N.caps(&caps)) && caps) { + p_geti(caps, "SuperSampling.Available", &avail); + p_geti(caps, "SuperSampling.NeedsUpdatedDriver", &driver); + } + N.available = avail != 0; + rt_log("dlaa: NGX up; DLSS %s%s", avail ? "available" : "NOT available (is nvngx_dlss.dll next to totk.exe?)", + driver ? "; the driver needs an update" : ""); +} + +// ---------------------------------------------------------------- where DLAA runs in TotK's frame +// Measured (TOTK_DUMP, frame 2100 at Lookout Landing, 2560x1440 scene): the G-buffer passes draw into five targets with +// the scene depth (d32f at the scene size), one of them the R11G11B10F light target; lighting and the transparents +// then draw into that light target alone, the last time with the scene depth attached; the first pass narrower than a +// quarter of the scene starts the bloom chain, which reads it. After the bloom come the tonemap and post passes, then +// the HUD is drawn into the same target and a last pass copies it to the 8-bit output. +// So: after the G-buffer, a pass at the scene size with exactly one colour target (R11G11B10F or RGBA16F) and the D32F +// depth arms the frame with that pair; the next pass at most a quarter as wide runs DLAA on the armed target first. +// Bloom, tonemap, post and HUD then all work on the anti-aliased picture. +static struct { + VkExecTarget color, depth; // the armed pair, valid in the frame it was armed + int armed, done, gbuf; // this frame: armed on the light target, DLAA ran, the G-buffer was drawn + struct Size { // a DLSS feature and its work images per scene size (dynamic resolution flips it) + uint32_t w, h; + VkImage out, mv; + VmaAllocation out_mem, mv_mem; + VkImageView out_view, mv_view; + NgxHandle *feat; + uint64_t used; // evals count when it last ran + } sizes[3], *last; // last: the one the previous DLAA frame ran with + VkImage last_color; // the target DLAA ran on last frame: another one means a new history + NgxParam *params; + int failed, reset; + uint64_t evals, frames_missed; + // jitter (vk_dlaa_viewport) + VkImage jdepth; // the scene depth of the last frame DLAA ran on: passes drawing with it are jittered + float jx, jy; // the offset the next scene draws take, render pixels (window x right, y down) + float ux, uy; // the offset this frame's scene draws took (DLSS and the motion vectors get these) + uint32_t jframe; + int jit_ok, jit_used, hold; // jitter allowed this frame / a draw used it / frames left without it + uint64_t holds; + // camera (vk_dlaa_draw) and motion vectors (mv_pass) + uint64_t cam_addr; // this frame's scene camera block (c4 of a scene draw's vertex stage), 0: none seen + VkBuffer camb; // two 256-byte slots: this frame's block and last frame's + VmaAllocation camb_mem; + int cam_slot, cam_prev_ok; // the slot this frame writes / the other slot holds last frame's camera + VkDescriptorSetLayout mv_dsl; + VkPipelineLayout mv_layout; + VkPipeline mv_pipe; + VkSampler mv_samp; + int mv_ok; // -1 not built, 0 failed, 1 ready + uint64_t mv_frames, mv_none; + uint64_t why[3]; // history resets: scene size changed, no camera, scene target changed + int on; // the dlaa setting, read at each present (the menu switches it live) +} D = {.mv_ok = -1}; + +static int dl_active(void) { return N.available && !D.failed && D.on; } + +static void dl_fail(const char *what, NgxResult r) { + rt_log("dlaa: %s failed (%08x): DLAA off for this run", what, (unsigned)r); + D.failed = 1; +} + +static int image2d(uint32_t w, uint32_t h, VkFormat f, VkImageUsageFlags usage, VkImage *img, VmaAllocation *mem, + VkImageView *view) { + const VkCtx *c = vk_ctx(); + VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = f, + .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = usage, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; + VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}; + if (vmaCreateImage(c->vma, &ii, &ai, img, mem, NULL) != VK_SUCCESS) return 0; + VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = *img, + .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = f, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + return vkCreateImageView(c->device, &vi, NULL, view) == VK_SUCCESS; +} + +static void free_size(struct Size *e) { + const VkCtx *c = vk_ctx(); + vkDeviceWaitIdle(c->device); // a third scene size: the evicted images may still be in flight + if (e->out_view) vkDestroyImageView(c->device, e->out_view, NULL); + if (e->mv_view) vkDestroyImageView(c->device, e->mv_view, NULL); + if (e->out) vmaDestroyImage(c->vma, e->out, e->out_mem); + if (e->mv) vmaDestroyImage(c->vma, e->mv, e->mv_mem); + if (e->feat) N.release(e->feat); + memset(e, 0, sizeof *e); +} + +// The entry for a scene size: its output (RGBA16F, written by DLSS, then blitted back into the scene target) and +// motion vectors (RG16F, render pixels), both kept in GENERAL like every image of the back end. TotK's dynamic +// resolution switches between a few sizes; each keeps its feature, the least recently used goes for a new one. +static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { + struct Size *e = NULL, *lru = &D.sizes[0]; + for (int i = 0; i < 3; i++) { + if (D.sizes[i].w == w && D.sizes[i].h == h) return &D.sizes[i]; + if (!D.sizes[i].out && !e) e = &D.sizes[i]; + if (D.sizes[i].used < lru->used) lru = &D.sizes[i]; + } + if (!e) { + if (D.last == lru) D.last = NULL; + free_size(e = lru); + } + VkImageUsageFlags u = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT; + if (!image2d(w, h, VK_FORMAT_R16G16B16A16_SFLOAT, u, &e->out, &e->out_mem, &e->out_view) || + !image2d(w, h, VK_FORMAT_R16G16_SFLOAT, u, &e->mv, &e->mv_mem, &e->mv_view)) + return NULL; + VkImageMemoryBarrier2 ib[2]; + VkImage im[2] = {e->out, e->mv}; + for (int i = 0; i < 2; i++) + ib[i] = (VkImageMemoryBarrier2){.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = im[i], + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + VkDependencyInfo di = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .imageMemoryBarrierCount = 2, + .pImageMemoryBarriers = ib}; + vkCmdPipelineBarrier2(cb, &di); + e->w = w, e->h = h; + return e; +} + +static void full_barrier(VkCommandBuffer cb) { + VkMemoryBarrier2 mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + .dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT}; + VkDependencyInfo di = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &mb}; + vkCmdPipelineBarrier2(cb, &di); +} + +static NgxResourceVK res_image(VkImageView v, VkImage img, VkFormat f, uint32_t w, uint32_t h, VkImageAspectFlags a, + int rw) { + NgxResourceVK r; + memset(&r, 0, sizeof r); + r.r.img = (NgxImageView){v, img, {a, 0, 1, 0, 1}, f, w, h}; + r.type = 0; + r.rw = rw; + return r; +} + +// ---------------------------------------------------------------- motion vectors +// Camera motion only (runtime/shaders/dlaa_mv.comp): this frame's scene camera block is copied out of the replay's +// uniform snapshot (vk_usnap.c, as of the submit call) into one slot of camb, last frame's stays in the other, and the +// compute pass reprojects every pixel's depth through both. Characters and anything else that moves on its own get +// the camera's motion only, which DLSS mostly copes with by rejecting their history. +#define CAM_BYTES 256u // vec4 rows 0-15: view, view-projection (3-6), projection, inverse view + +static int mv_init(void) { + if (D.mv_ok >= 0) return D.mv_ok; + D.mv_ok = 0; + const VkCtx *c = vk_ctx(); + VkDescriptorSetLayoutBinding b[4] = { + {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}, + {1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}, + {2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}, + {3, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}}; + VkDescriptorSetLayoutCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, + .bindingCount = 4, .pBindings = b}; + VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, 16}; + VkSamplerCreateInfo si = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_NEAREST, + .minFilter = VK_FILTER_NEAREST, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE}; + VkShaderModuleCreateInfo mi = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = sizeof dlaa_mv_spv, + .pCode = dlaa_mv_spv}; + VkShaderModule m = VK_NULL_HANDLE; + VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = 2 * CAM_BYTES, + .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT}; + VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}; + if (vkCreateDescriptorSetLayout(c->device, &dci, NULL, &D.mv_dsl) != VK_SUCCESS) goto fail; + VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, + .pSetLayouts = &D.mv_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr}; + if (vkCreatePipelineLayout(c->device, &li, NULL, &D.mv_layout) != VK_SUCCESS || + vkCreateSampler(c->device, &si, NULL, &D.mv_samp) != VK_SUCCESS || + vkCreateShaderModule(c->device, &mi, NULL, &m) != VK_SUCCESS || + vmaCreateBuffer(c->vma, &bi, &ai, &D.camb, &D.camb_mem, NULL) != VK_SUCCESS) + goto fail; + VkComputePipelineCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = m, .pName = "main"}, + .layout = D.mv_layout}; + VkResult r = vkCreateComputePipelines(c->device, VK_NULL_HANDLE, 1, &ci, NULL, &D.mv_pipe); + vkDestroyShaderModule(c->device, m, NULL); + if (r != VK_SUCCESS) goto fail; + return D.mv_ok = 1; +fail: + rt_log("dlaa: the motion-vector pass could not be set up: DLAA runs with zero motion"); + return 0; +} + +// The pass, recorded through the recorder like the replay's own commands. 0: no camera this frame (the vectors stay +// zero and DLSS starts a new history). +static int mv_pass(VkCommandBuffer cb, const struct Size *e, VkImageView zv, float jx, float jy) { + uint32_t w = e->w, h = e->h; + VkDescriptorBufferInfo cam; + if (!mv_init() || !D.cam_addr || !vk_usnap_find(D.cam_addr, CAM_BYTES, 4, &cam)) { + D.mv_none++; + D.cam_prev_ok = 0; + return 0; + } + int s = D.cam_slot, had_prev = D.cam_prev_ok; + VkBufferCopy bc = {cam.offset, (VkDeviceSize)s * CAM_BYTES, CAM_BYTES}; + vkCmdCopyBuffer(cb, cam.buffer, D.camb, 1, &bc); + full_barrier(cb); + D.cam_slot ^= 1, D.cam_prev_ok = 1; + if (!had_prev) return 0; // nothing to reproject into: zero motion, new history + VkDescriptorImageInfo zi = {D.mv_samp, zv, VK_IMAGE_LAYOUT_GENERAL}; + VkDescriptorImageInfo oi = {VK_NULL_HANDLE, e->mv_view, VK_IMAGE_LAYOUT_GENERAL}; + VkDescriptorBufferInfo cur = {D.camb, (VkDeviceSize)s * CAM_BYTES, CAM_BYTES}; + VkDescriptorBufferInfo prev = {D.camb, (VkDeviceSize)(s ^ 1) * CAM_BYTES, CAM_BYTES}; + VkWriteDescriptorSet wr[4] = { + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &zi}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 2, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &cur}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 3, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &prev}}; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, D.mv_pipe); + rec_push(vk_pipeline_push_fn(), cb, VK_PIPELINE_BIND_POINT_COMPUTE, D.mv_layout, 0, 4, wr); + float pc[4] = {(float)w, (float)h, jx, jy}; + vkCmdPushConstants(cb, D.mv_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, pc); + vkCmdDispatch(cb, (w + 7) / 8, (h + 7) / 8, 1); + full_barrier(cb); + D.mv_frames++; + return 1; +} + +// ---------------------------------------------------------------- jitter +// The scene's draws (every pass drawing with the scene depth, until the DLAA point) have their viewport moved by a +// sub-pixel Halton(2,3) offset, which shifts what they rasterise as a jittered projection would; full-screen passes +// that shade by window position are unaffected. Jitter only follows a frame DLSS ran on: a jittered frame that DLSS +// does not resolve shakes on screen, so a missed DLAA point stops the jitter for a second. +static float halton(uint32_t i, uint32_t b) { + float f = 1, r = 0; + for (; i; i /= b) f /= (float)b, r += f * (float)(i % b); + return r; +} + +void vk_dlaa_viewport(VkExec *ex, VkViewport *v) { + if (!D.jit_ok || D.done || !ex->depth.image || ex->depth.image != D.jdepth) return; + v->x += D.jx, v->y += D.jy; + D.ux = D.jx, D.uy = D.jy, D.jit_used = 1; +} + +void vk_dlaa_draw(VkExec *ex) { + if (!dl_active() || D.done) return; + const p_bind_buf *b = &ex->ubo[0][1]; // constant bank c4: the replay keeps user banks from c3 on + const VkExecTarget *z = &ex->depth; + if (b->size == 0x940 && b->addr && z->image && z->width >= 640 && z->format == VK_FORMAT_D32_SFLOAT && + (!D.jdepth || z->image == D.jdepth)) + D.cam_addr = b->addr; +} + +// The jitter moves on right after DLAA ran, not at the present: the replay can record the next frame's scene before +// the present of this one is handled, and a step taken there landed in the middle of a frame (worse after an off/on +// switch, which shifted that order). Jitter needs a frame DLSS ran on; a frame without the DLAA point stops it. +static void next_jitter(void) { + static int nj = -1; + if (nj < 0) nj = !rt_knob("DLAA_JITTER", "1"); // TOTK_DLAA_JITTER=0: no jitter (test) + uint32_t i = D.jframe++ % 16 + 1; + D.jx = halton(i, 2) - 0.5f, D.jy = halton(i, 3) - 0.5f; + D.jit_ok = !D.hold && !nj; +} + +static void evaluate(VkExec *ex) { + const VkExecTarget *t = &D.color, *z = &D.depth; + uint32_t w = t->width, h = t->height; + VkCommandBuffer cb = ex->cb; + vk_exec_barrier(ex); // what drew the scene is done (no pass is open here) + struct Size *e = size_for(cb, w, h); + if (!e) return dl_fail("work image creation", 0); + if (e != D.last) D.reset = 1, D.why[0]++; // another size's history is from another moment + if (!D.params && !NGX_OK(N.alloc_params(&D.params))) return dl_fail("parameter allocation", 0); + NgxParam *p = D.params; + VkImageView zv = vk_exec_target_view(z->img, z->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_DEPTH_BIT, z->level, + z->base_layer, 1, 0); + float jx = D.jit_used ? D.ux : 0.0f, jy = D.jit_used ? D.uy : 0.0f; + static int no_mv = -1; + if (no_mv < 0) no_mv = !rt_knob("DLAA_MV", "1"); // TOTK_DLAA_MV=0: zero motion (test) + if (no_mv || !mv_pass(cb, e, zv, jx, jy)) { + VkClearColorValue zero = {{0, 0, 0, 0}}; + VkImageSubresourceRange all = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + vkCmdClearColorImage(cb, e->mv, VK_IMAGE_LAYOUT_GENERAL, &zero, 1, &all); + full_barrier(cb); + if (!no_mv) D.reset = 1, D.why[1]++; // no camera: the history cannot be moved along + } + rec_drain(); // NGX records into the command buffer itself: the recorder thread must have made every call so far + if (!e->feat) { + p_setu(p, "CreationNodeMask", 1); + p_setu(p, "VisibilityNodeMask", 1); + p_setu(p, "Width", w); + p_setu(p, "Height", h); + p_setu(p, "OutWidth", w); + p_setu(p, "OutHeight", h); + p_seti(p, "PerfQualityValue", NGX_PERFQ_DLAA); + // IsHDR | MVLowRes | AutoExposure: linear scene light, motion vectors at the render size, no exposure texture + p_seti(p, "DLSS.Feature.Create.Flags", (1 << 0) | (1 << 1) | (1 << 6)); + p_seti(p, "DLSS.Enable.Output.Subrects", 0); + NgxResult r = N.create(cb, NGX_FEATURE_SUPERSAMPLING, p, &e->feat); + if (!NGX_OK(r) || !e->feat) return dl_fail("DLSS feature creation", r); + D.reset = 1; + rt_log("dlaa: DLSS feature created at %ux%u (scene format %d, depth format %d)", w, h, (int)t->format, + (int)z->format); + } + if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image; + VkImageView cv = vk_exec_target_view(t->img, t->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT, t->level, + t->base_layer, 1, 0); + NgxResourceVK rc = res_image(cv, t->image, t->format, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); + NgxResourceVK ro = res_image(e->out_view, e->out, VK_FORMAT_R16G16B16A16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 1); + NgxResourceVK rz = res_image(zv, z->image, z->format, w, h, VK_IMAGE_ASPECT_DEPTH_BIT, 0); + NgxResourceVK rm = res_image(e->mv_view, e->mv, VK_FORMAT_R16G16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); + p_setp(p, "Color", &rc); + p_setp(p, "Output", &ro); + p_setp(p, "Depth", &rz); + p_setp(p, "MotionVectors", &rm); + p_setf(p, "Jitter.Offset.X", jx); + p_setf(p, "Jitter.Offset.Y", jy); + p_setf(p, "Sharpness", 0.0f); + p_seti(p, "Reset", D.reset); + p_setf(p, "MV.Scale.X", 1.0f); + p_setf(p, "MV.Scale.Y", 1.0f); + p_setu(p, "DLSS.Render.Subrect.Dimensions.Width", w); + p_setu(p, "DLSS.Render.Subrect.Dimensions.Height", h); + p_setf(p, "DLSS.Pre.Exposure", 1.0f); + p_setf(p, "DLSS.Exposure.Scale", 1.0f); + p_setf(p, "FrameTimeDeltaInMsec", 16.67f); + NgxResult r = N.evaluate(cb, e->feat, p, NULL); + if (!NGX_OK(r)) return dl_fail("DLSS evaluation", r); + D.reset = 0; + D.last = e, e->used = D.evals + 1; + full_barrier(cb); + // the result back into the scene target, which the bloom, the post passes and the HUD read and draw over + VkImageBlit b = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, t->level, t->base_layer, 1}, + .dstOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}}; + vkCmdBlitImage(cb, e->out, VK_IMAGE_LAYOUT_GENERAL, t->image, VK_IMAGE_LAYOUT_GENERAL, 1, &b, VK_FILTER_NEAREST); + full_barrier(cb); + ex->recorded += 4; + vk_exec_draw_new_cb(); // NGX bound pipelines and descriptor sets of its own: the next draw binds everything again + D.jdepth = z->image; + next_jitter(); + if (++D.evals == 1 || D.evals % 3600 == 0) + rt_log("dlaa: %llu frames anti-aliased (scene %ux%u; %llu frames without the DLAA point, %llu with camera " + "motion, %llu without a camera, %llu jitter holds; resets: %llu size, %llu camera, %llu target)", + (unsigned long long)D.evals, w, h, (unsigned long long)D.frames_missed, + (unsigned long long)D.mv_frames, (unsigned long long)D.mv_none, (unsigned long long)D.holds, + (unsigned long long)D.why[0], (unsigned long long)D.why[1], (unsigned long long)D.why[2]); +} + +static int scene_color(VkFormat f) { + return f == VK_FORMAT_B10G11R11_UFLOAT_PACK32 || f == VK_FORMAT_R16G16B16A16_SFLOAT; +} + +void vk_dlaa_pass(VkExec *ex) { + const VkExecTarget *c = &ex->color[0], *z = &ex->depth; + if (!dl_active() || D.done) return; + // The G-buffer: several colour targets with a D32F depth of at least 640 wide. Only the light target drawn after it + // arms the frame; at night the game draws into the light target alone with the scene depth before the G-buffer too, + // and DLAA then ran at a small pass ahead of the whole scene, which reached the screen jittered. + if (ex->pass_ncolor >= 3 && z->image && z->format == VK_FORMAT_D32_SFLOAT && z->width >= 640) { + D.gbuf = 1, D.armed = 0; + return; + } + // the scene depth is D32F; a D16 target of the scene size also serves one composite pass before the transparents + if (D.gbuf && ex->pass_ncolor == 1 && c->image && scene_color(c->format) && z->image && z->format == VK_FORMAT_D32_SFLOAT && + c->width == z->width && c->height == z->height && c->width >= 640 && + c->samples <= 1 && !c->is3d) { + D.color = *c, D.depth = *z, D.armed = 1; + return; + } + if (!D.armed) return; + if (!ex->pass_w || ex->pass_w * 4 > D.color.width) return; + D.done = 1; + evaluate(ex); +} + +void vk_dlaa_frame(void) { + int on = N.available && cfg_bool("TOTK_DLAA"); + if (on != D.on) { + rt_log("dlaa: %s", on ? "on" : "off"); + D.on = on; + // either way the next DLAA frame starts a new history from an unjittered frame + D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = 0, D.hold = 0; + return; + } + if (!dl_active()) return; + if (!D.done) D.frames_missed++; + if (D.jit_used && !D.done) D.hold = 60, D.holds++; // jittered but not resolved: that frame shook + else if (D.hold) D.hold--; + if (!D.done) D.jit_ok = 0; + D.armed = D.done = D.jit_used = D.gbuf = 0; + D.cam_addr = 0; +} + +// ---------------------------------------------------------------- the game's FXAA (TOTK_FXAA, live) +// TotK's FXAA is two full-screen passes after the bloom, just before the HUD: one copies the scene target into a +// scratch target, the other draws the anti-aliased result back over the scene (found by diffing frame dumps with the +// game's own switch, ModelSceneExtensionParam EnableFXAA, on and off). With fxaa = 0 the draws of that second pass's +// fragment shader are skipped, so the scene reaches the HUD as it was. Shaders are known by the FNV-1a hash of their +// SPIR-V, as vk_dump.c names them; a translator change gives new hashes and the switch then does nothing. +#define FXAA_FS 0xf450003ebeb3dc52ull + +static uint64_t spirv_hash(const GfxShader *s) { + static struct { const GfxShader *s; uint64_t h; } tab[8192]; + uintptr_t k = ((uintptr_t)s >> 4) * 0x9E3779B97F4A7C15ull; + for (uint32_t i = 0, j = (uint32_t)(k >> 51); i < 8192; i++, j = (j + 1) & 8191) { + if (tab[j].s == s) return tab[j].h; + if (!tab[j].s) { + uint64_t words = 0, h = 0xcbf29ce484222325ull; + const uint8_t *b = (const uint8_t *)gfx_shader_spirv(s, &words); + for (uint64_t n = 0; b && n < words * 4; n++) h = (h ^ b[n]) * 0x100000001b3ull; + tab[j].s = s, tab[j].h = h; + return h; + } + } + return 0; // table full: no skip +} + +int vk_dlaa_skip_draw(const GfxShader *fs) { + static uint64_t frame_read = ~0ull; + static int fxaa = 1; + uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED); + if (f != frame_read) frame_read = f, fxaa = cfg_bool("TOTK_FXAA"); // once a frame: the menu switches it live + return !fxaa && fs && spirv_hash(fs) == FXAA_FS; +} diff --git a/runtime/vk_dlaa.h b/runtime/vk_dlaa.h new file mode 100644 index 00000000..4eb7ff3d --- /dev/null +++ b/runtime/vk_dlaa.h @@ -0,0 +1,22 @@ +// DLAA (vk_dlaa.c): NVIDIA DLSS at the scene's own size, behind TOTK_DLAA (totk.ini dlaa = 1). +#pragma once +#include "vk.h" + +int vk_dlaa_wanted(void); // the setting is on (the device may still lack DLSS) +// vk_device.c: NGX's instance and device extensions join the lists (room for max names); vk_dlaa_init after the +// device exists brings NGX up and checks that DLSS is available. +void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max); +void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max); +void vk_dlaa_init(void); +// vk_exec.c vk_exec_pass_begin, once the pass's targets are resolved and before its barrier: arms the frame on the +// scene's light target or, at the first quarter-width pass after it, runs DLAA on that target. Each present ends the +// frame (vk_dlaa_frame). +typedef struct VkExec VkExec; +void vk_dlaa_pass(VkExec *ex); +void vk_dlaa_frame(void); +// vk_exec_draw.c, each draw before its fixed state is recorded: notes the scene camera block (vk_dlaa_draw), and moves +// the viewport of the scene's draws by the frame's jitter (vk_dlaa_viewport, when the viewport is recorded). +void vk_dlaa_draw(VkExec *ex); +void vk_dlaa_viewport(VkExec *ex, VkViewport *v); +// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0). +int vk_dlaa_skip_draw(const GfxShader *fs); diff --git a/runtime/vk_exec.c b/runtime/vk_exec.c index d82c0574..572a9760 100644 --- a/runtime/vk_exec.c +++ b/runtime/vk_exec.c @@ -26,6 +26,7 @@ #include "tex.h" #include "vk.h" #include "vk_exec.h" +#include "vk_dlaa.h" #define WEAK __attribute__((weak)) #define CALL_DEPTH 8 @@ -418,6 +419,7 @@ void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); } void vk_exec_pass_begin(VkExec *ex) { if (ex->in_pass) return; resolve_rt(ex); + vk_dlaa_pass(ex); // DLAA runs before the bloom chain's first pass (vk_dlaa.c) // Learned targets (VkTexImage.fb_learned) are attached in the feedback layout VkImage want[9]; VkImageAspectFlags wasp[9]; diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 59ff9cbb..0f2fc2ec 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -27,6 +27,7 @@ #include "nvn_hmap.h" #include "vk.h" #include "vk_exec.h" +#include "vk_dlaa.h" #define MAX_BINDINGS 128 #define MAX_DESC 1024 @@ -1850,6 +1851,7 @@ static void record_fixed(VkExec *ex) { if (w < 1) w = 1; if (h < 1) h = 1; VkViewport v = {x, y + h, w, -h, ex->depth_range[0], ex->depth_range[1]}; // the y flip: negative height + vk_dlaa_viewport(ex, &v); // the scene's draws move by the DLAA jitter vkCmdSetViewportWithCount(cb, 1, &v); ex->recorded++; } @@ -2038,6 +2040,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { if (fs_wait) fs = shader_for(ex, NVN_STAGE_FS, &has_fs, NULL, 1); } if (!vs || (has_fs && !fs)) return 0; + if (vk_dlaa_skip_draw(fs)) return 0; // the game's FXAA, switched off (vk_dlaa.c) uint32_t fbl = feedback_prepare(ex, fs); VkPipeState s = ex->pipe; s.vs = vs, s.fs = fs; @@ -2108,6 +2111,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { ex->recorded++; B.st = s, B.st_valid = 1; } + vk_dlaa_draw(ex); record_fixed(ex); repeat_stats(ex, info); bind_resources(ex, info); diff --git a/totk.ini.example b/totk.ini.example index 30c3a2af..cb9e952f 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -118,6 +118,13 @@ # from 0 (off) to 100. Changes while the game runs take effect at once. # upscaler = fsr # sharpness = 80 +# NVIDIA DLAA: DLSS anti-aliasing of the 3D scene at its own resolution, on NVIDIA RTX GPUs with nvngx_dlss.dll (from +# NVIDIA's DLSS SDK) next to totk.exe; elsewhere the setting does nothing. Changes while the game runs take effect at +# once. +# dlaa = 0 +# The game's own FXAA after the post effects; with DLAA on it is not needed. Changes while the game runs take effect at +# once. +# fxaa = 1 [language] # Language: a Windows locale such as de-DE, or a Switch code (en-US, ja, zh-Hant, ...). Default: the Windows locale. 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 007/177] 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 bc5eb0cb15ceea409d1dc447e73036e73b16f557 Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 21:10:27 -0700 Subject: [PATCH 008/177] Narrow the sun shadow filter by the shadow map scale The deferred lighting shaders soften the sun shadow with four compares around the receiver, offset by element 56 .xy of their lighting block. The offset is in UV and the game sized it for its own 960x960 cascades, so with shadow_scale above 1 it spans that many more texels and the near cascade shows four separate copies of each edge. Translator patch 0011 multiplies those reads by the support buffer's new shadow_spread field in fragment shaders that sample a 2D array shadow texture, leaving fp_c4 (the cascade matrices) alone. support_fill writes 1 / shadow_scale there, so the spacing stays the game's in texels; at shadow_scale 1 the shaders behave as before. The support buffer grows to 1440 bytes and build_xlate.py expects eleven patches. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_exec_draw.c | 19 ++++- tools/build_xlate.py | 6 +- .../patches/0011-shadow-filter-spread.patch | 82 +++++++++++++++++++ totk.ini.example | 4 +- 4 files changed, 106 insertions(+), 5 deletions(-) create mode 100644 tools/xlate/patches/0011-shadow-filter-spread.patch diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 4f7276d0..4323d05d 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -32,7 +32,7 @@ #define MAX_DESC 1024 #define CHUNK_BYTES (4u << 20) #define ZERO_BYTES 65536u -#define SUPPORT_BYTES 1424u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... +#define SUPPORT_BYTES 1440u // Ryujinx SupportBuffer (std140): alpha_test, is_bgra[8], viewport_inverse, viewport_size, ... #define NVN_STAGE_VS 0 #define NVN_STAGE_FS 1 #define NVN_STAGE_CS 5 @@ -1265,6 +1265,22 @@ static const float *pcss_params(void) { return p; } +// The shadow_spread field of the support buffer: the factor translator patch 0011 applies to the lighting shaders' sun +// shadow filter offset (element 56 .xy of their lighting block), 1 / TOTK_SHADOW_SCALE. The game spaces its four +// compares for its own shadow map texels; with maps TOTK_SHADOW_SCALE times larger, the same offset in UV spans that +// many more texels and the near cascade shows four separate copies of each edge. Dividing by the scale keeps the game's +// spacing in texels. The offset is in UV of the shadow map, so the output resolution plays no part. The scale is read +// once, as vk_texture.c shadow_scale reads it: the maps keep the size they were made with. +static const float *shadow_spread_params(void) { + static float p[4] = {0, 0, 0, 0}; + if (p[0] == 0) { + int scale = cfg_int("TOTK_SHADOW_SCALE"); + scale = scale < 1 ? 1 : scale > 4 ? 4 : scale; + p[0] = 1.0f / (float)scale; + } + return p; +} + static void support_fill(uint8_t *b, float w, float h, float point_size) { memset(b, 0, SUPPORT_BYTES); float inv[4] = {w > 0 ? 2.0f / w : 0, h > 0 ? 2.0f / h : 0, 0, 0}, size[4] = {w, h, 0, 0}; @@ -1273,6 +1289,7 @@ static void support_fill(uint8_t *b, float w, float h, float point_size) { const float one = 1.0f; memcpy(b + 1392, &point_size, 4); // point_size (translator patch 0008): vertex shaders that write none output it memcpy(b + 1408, pcss_params(), 16); // pcss (translator patch 0010): soft sun shadows in the cascade compares + memcpy(b + 1424, shadow_spread_params(), 16); // shadow_spread (translator patch 0011): sun shadow filter width for (int i = 0; i < 73; i++) memcpy(b + 192 + 16 * i, &one, 4); // render scale 1: the host renders at guest size } diff --git a/tools/build_xlate.py b/tools/build_xlate.py index ef0d08bc..d721a8ed 100644 --- a/tools/build_xlate.py +++ b/tools/build_xlate.py @@ -1,7 +1,7 @@ """Build the shader translator: build/xlate/totk_xlate.exe (Ryujinx 1.3.2 + patches, NativeAOT, SPIR-V for Vulkan). Copies tools/vendor/ryujinx to build/xlate/ryujinx, applies tools/xlate/patches/*.patch there (tools/vendor stays -byte-identical; 0001-0004 are MNG's, 0005-0010 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build +byte-identical; 0001-0004 are MNG's, 0005-0011 are ours), then runs `dotnet publish`. Needs the .NET 10 SDK, the MSVC build tools and vswhere.exe (docs/building.md). Run with .venv. Next to the exe it writes totk_xlate.id: the translator identity, a sha256 over everything the build reads (this script, @@ -96,8 +96,8 @@ def prepare_sources() -> Path: for junk in list(src.glob("src/*/obj")) + list(src.glob("src/*/bin")): shutil.rmtree(junk) patches = sorted((XLATE / "patches").glob("*.patch")) - if len(patches) != 10: - sys.exit(f"expected 10 patches, found {len(patches)}") + if len(patches) != 11: + sys.exit(f"expected 11 patches, found {len(patches)}") for patch in patches: # git apply works outside a repository when given a directory; --check first so a failure names the patch. for extra in (["--check"], []): diff --git a/tools/xlate/patches/0011-shadow-filter-spread.patch b/tools/xlate/patches/0011-shadow-filter-spread.patch new file mode 100644 index 00000000..cd952174 --- /dev/null +++ b/tools/xlate/patches/0011-shadow-filter-spread.patch @@ -0,0 +1,82 @@ +--- a/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs ++++ b/src/Ryujinx.Graphics.Shader/CodeGen/Spirv/Instructions.cs +@@ -853,7 +853,51 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv + + private static OperationResult GenerateLoad(CodeGenContext context, AstOperation operation) + { +- return GenerateLoadOrStore(context, operation, isStore: false); ++ OperationResult result = GenerateLoadOrStore(context, operation, isStore: false); ++ if (result.Type == AggregateType.FP32 && IsShadowSpread(context, operation)) ++ { ++ SpvInstruction f32 = context.TypeFP32(), v4 = context.TypeVector(f32, 4); ++ SpvInstruction prmPtr = context.AccessChain(context.TypePointer(StorageClass.Uniform, v4), context.ConstantBuffers[SupportBuffer.Binding], ++ context.Constant(context.TypeS32(), (int)SupportBufferField.ShadowSpread)); ++ SpvInstruction factor = context.CompositeExtract(f32, context.Load(v4, prmPtr), 0); ++ result = new OperationResult(AggregateType.FP32, context.FMul(f32, result.Value, factor)); ++ } ++ ++ return result; ++ } ++ ++ // TOTK: the spread of the sun shadow filter. The deferred lighting shaders take the sun shadow as four compares ++ // at the receiver ± h on the cascade map, h = 0.5 * c[56].xy (UV) of their lighting block (fp_c9, or fp_c5 in ++ // some), the same in every cascade. In the near cascade the map is sharp enough that the four copies of an edge ++ // show apart. In a fragment shader that has a 2D array shadow sampler, reads of element 56 .x and .y from any ++ // constant buffer but fp_c4 (which holds the cascade matrices, row 56 being cascade 3's depth row) are multiplied ++ // by the support buffer's shadow_spread.x (runtime/vk_exec_draw.c support_fill, TOTK_SHADOW_SPREAD; 1 keeps the ++ // game's spread). ++ private static bool IsShadowSpread(CodeGenContext context, AstOperation load) ++ { ++ if (context.Definitions.Stage != ShaderStage.Fragment || ++ load.StorageKind != StorageKind.ConstantBuffer || ++ load.SourcesCount != 4 || ++ load.GetSource(0) is not AstOperand { Type: OperandType.Constant } binding || ++ load.GetSource(1) is not AstOperand { Type: OperandType.Constant, Value: 0 } || ++ load.GetSource(2) is not AstOperand { Type: OperandType.Constant, Value: 56 } || ++ load.GetSource(3) is not AstOperand { Type: OperandType.Constant, Value: < 2 } || ++ !context.Properties.ConstantBuffers.TryGetValue(binding.Value, out BufferDefinition buffer) || ++ buffer.Name == "fp_c4") ++ { ++ return false; ++ } ++ ++ foreach (TextureDefinition texture in context.Properties.Textures.Values) ++ { ++ if ((texture.Type & (SamplerType.Mask | SamplerType.Array | SamplerType.Shadow)) == ++ (SamplerType.Texture2D | SamplerType.Array | SamplerType.Shadow)) ++ { ++ return true; ++ } ++ } ++ ++ return false; + } + + private static OperationResult GenerateLod(CodeGenContext context, AstOperation operation) +--- a/src/Ryujinx.Graphics.Shader/SupportBuffer.cs ++++ b/src/Ryujinx.Graphics.Shader/SupportBuffer.cs +@@ -26,6 +26,7 @@ namespace Ryujinx.Graphics.Shader + TfeVertexCount, + PointSize, + Pcss, ++ ShadowSpread, + } + + public struct SupportBuffer +@@ -84,7 +85,8 @@ namespace Ryujinx.Graphics.Shader + new StructureField(AggregateType.Vector4 | AggregateType.S32, "tfe_offset"), + new StructureField(AggregateType.S32, "tfe_vertex_count"), + new StructureField(AggregateType.FP32, "point_size"), +- new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss") ++ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "pcss"), ++ new StructureField(AggregateType.Vector4 | AggregateType.FP32, "shadow_spread") + ]); + } + +@@ -101,5 +103,6 @@ namespace Ryujinx.Graphics.Shader + public Vector4 TfeVertexCount; + public Vector4 PointSize; + public Vector4 Pcss; ++ public Vector4 ShadowSpread; + } + } diff --git a/totk.ini.example b/totk.ini.example index 352f19c3..5722f8d1 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -120,7 +120,9 @@ # game's setting. Read at start. # aniso = 16 # Shadow map resolution: the game's sun cascades are 960x960 (and its static shadow maps 1440 and 720) whatever the game -# resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. Read at start. +# resolution; 2 to 4 draws them that many times larger on each side, for sharper shadows. 1 = the game's. The game's +# shadow edge filter is narrowed by the same factor (translator patch 0011), so close shadow edges don't look doubled. +# Read at start. # shadow_scale = 1 # Sun shadow cascade range in percent of the game's (its cascades end at 20, 40, 80 and 160 m), 50 to 400: higher moves # the steps where shadows turn softer further away, and spreads the shadow map over more ground. Read at start. From 45f24a72e391b8e77e2957355d2a7545fb0a56ba Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 21:10:35 -0700 Subject: [PATCH 009/177] Let TOTK_DUMP_UBO set how many vec4 of each uniform block are printed The value is now a count (1 still means 16, capped at 4096), so blocks such as the deferred lighting shaders' camera block, whose shadow cascade matrices sit at vec4 42 to 58, can be read from a frame dump. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_dump.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/runtime/vk_dump.c b/runtime/vk_dump.c index 151f39f3..f80dce4b 100644 --- a/runtime/vk_dump.c +++ b/runtime/vk_dump.c @@ -18,8 +18,8 @@ // as x/2+1/2, UNORM and sRGB bytes written as stored. Caps: MAX_PASSES passes copied, PNG_CAP bytes of PNGs. // TOTK_DUMP_TEX=|x[,...]: those texture slots, or 2D textures of that size, are copied where first sampled, // whatever their format. -// TOTK_DUMP_UBO=1: each listed pipeline also prints the first 16 vec4 of its user uniform blocks (c3 and up), read from -// guest memory when the entry is listed. A block the submission rewrites with UpdateUniformBuffer shows its value from +// TOTK_DUMP_UBO=: each listed pipeline also prints the first n vec4 of its user uniform blocks (c3 and up; 1 means 16, +// the cap is 4096), read from guest memory when the entry is listed. A block the submission rewrites with UpdateUniformBuffer shows its value from // before the submission (vk_exec_draw.c upd_note). // TOTK_DUMP_SKIP_RUNS=1: a render pass with the same targets as the render pass before it is logged but not copied // (the terrain decals draw one pass each into the G-buffer and would use up both caps). @@ -48,7 +48,7 @@ static uint64_t dump_frame, log_from; // log_from: TOTK_DUMP_LOG, first frame static char dir[400]; static FILE *passes_f, *images_f; static int seq, finished, copied; // copied: passes and dispatches of the dump frame whose images were copied -static int skip_runs, dump_ubo; // TOTK_DUMP_SKIP_RUNS, TOTK_DUMP_UBO +static int skip_runs, dump_ubo; // TOTK_DUMP_SKIP_RUNS, TOTK_DUMP_UBO (vec4 per block, 0 for none) static uint32_t want_tex[16][2]; // TOTK_DUMP_TEX: slot id and 0, or width and height static int nwant_tex; static uint64_t last_targets; // targets_sig of the last render pass; 0 after a dispatch @@ -576,7 +576,7 @@ static void describe_bindings(Str *b, const VkExec *ex, const VkPipeInfo *info) if (u->addr && vk_mem_resolve(u->addr, 1, &ms)) { uint64_t n = u->size && u->size < ms.avail ? u->size : ms.avail; const float *f = (const float *)(uintptr_t)u->addr; - for (uint64_t k = 0; k < 16 && (k + 1) * 16 <= n; k++) + for (uint64_t k = 0; k < (uint64_t)dump_ubo && (k + 1) * 16 <= n; k++) sp(b, "%s[%llu] %g %g %g %g", k % 4 ? " " : "\n ", (unsigned long long)k, f[4 * k], f[4 * k + 1], f[4 * k + 2], f[4 * k + 3]); } else { @@ -879,7 +879,10 @@ void vk_dump_init(void) { const char *sr = cfg_get("TOTK_DUMP_SKIP_RUNS"); skip_runs = sr && *sr && *sr != '0'; const char *du = cfg_get("TOTK_DUMP_UBO"); - dump_ubo = du && *du && *du != '0'; + dump_ubo = du && *du ? atoi(du) : 0; + if (dump_ubo == 1) dump_ubo = 16; + if (dump_ubo > 4096) dump_ubo = 4096; + if (dump_ubo < 0) dump_ubo = 0; const char *wt = cfg_get("TOTK_DUMP_TEX"); for (char *q = (char *)wt; q && *q && nwant_tex < 16; q += *q == ',') { uint32_t *w = want_tex[nwant_tex++]; From c193b2aefac0c62c1e49088f8d6c8ad3dbeb288f Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 21:58:22 -0700 Subject: [PATCH 010/177] Give each gamepad stick its own dead zone and show where the stick rests stick_deadzone sets one dead zone for both sticks, and finding the value that stops a drift means guessing. A worn stick usually drifts on its own while the other one is fine. lstick_deadzone and rstick_deadzone (0 to 50 percent, live) set one stick each and fall back to stick_deadzone while unset, so existing totk.ini files behave as before. input_pad_deadzone in input_map.c picks the value; input_pad_stick and its scaling stay as they are. The Controls tab shows Left and Right stick dead zone rows in place of the single one. With a gamepad connected each row shows its stick's deflection now, before the dead zone ("stick now"), so a drifting stick's resting value can be read off and the zone set just above it. opt_slider takes the note line and a fallback key for that: a row whose key is unset shows the fallback's value, and a change sets the key. probe-cfg checks the fallback, the clamp and input_stick_percent. The menu text is in English and Russian. Co-Authored-By: Claude Opus 5.5 --- docs/controls.md | 2 +- runtime/cfg.c | 9 +++++---- runtime/cfg_probe.c | 17 +++++++++++++++++ runtime/input.h | 4 ++++ runtime/input_map.c | 10 ++++++++++ runtime/input_map.h | 6 ++++++ runtime/input_win.c | 35 +++++++++++++++++++++++++---------- runtime/ui/menu.cpp | 11 ++++++++++- runtime/ui/option_rows.cpp | 11 +++++++---- runtime/ui/option_rows.h | 4 +++- runtime/ui_text.c | 10 ++++++---- runtime/ui_text.h | 2 +- totk.ini.example | 4 ++++ 13 files changed, 99 insertions(+), 26 deletions(-) diff --git a/docs/controls.md b/docs/controls.md index b80fc89c..2333d41c 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -68,7 +68,7 @@ Mouse motion (raw input) becomes right-stick deflection. Each presented frame ta `TOTK_MOUSE_SENS` (0 to 10, default 1; higher turns faster, 0 turns the mouse camera and the cursor capture off). While the window is the foreground window the cursor is hidden and confined to the client area. It is released on focus loss, minimise, while F11 changes the window, during a size or move loop and while a text entry is open. Esc releases it by hand: the cursor shows, the mouse camera and mouse buttons stop, and the window can be moved, minimised or closed. A mouse click inside the client area captures it again; that click does not reach the game. Activating the window by a click on its title bar or border does not capture, so it can be dragged or closed right away; Alt+Tab or a click in the client area captures as before. `TOTK_INPUT=none` disables the capture too. -`TOTK_STICK_DEADZONE` (0 to 50, default 8) is the gamepad stick dead zone in percent of full deflection, the same for both sticks. It is round: a stick inside the circle reads centred, and the rest of its travel is scaled to start at 0 at the edge, so full deflection still reaches full. Raise it for a stick that drifts. The game's own dead zone applies after it. +`TOTK_STICK_DEADZONE` (0 to 50, default 8) is the gamepad stick dead zone in percent of full deflection, the same for both sticks. It is round: a stick inside the circle reads centred, and the rest of its travel is scaled to start at 0 at the edge, so full deflection still reaches full. Raise it for a stick that drifts. The game's own dead zone applies after it. `TOTK_LSTICK_DEADZONE` and `TOTK_RSTICK_DEADZONE` (the *Left/Right stick dead zone* rows on the Controls tab) set one stick each and fall back to `TOTK_STICK_DEADZONE` while unset, so a worn stick can get a larger zone than the other. With a gamepad connected each row shows its stick's deflection now, before the dead zone (*stick now*): let go of the stick and set the row a few percent above the value it rests at. The stick direction bits (`StickLLeft` to `StickRDown`) are derived from the sticks at 50% deflection. A gamepad plugged in later is picked up within one second; with none connected the log says `input: no gamepad`. diff --git a/runtime/cfg.c b/runtime/cfg.c index e9d8fc13..f51a5eda 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -39,14 +39,14 @@ static const char *const known[] = { "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", - "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST", + "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MENU_LANG", "MENU_TEST", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC", "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", + "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "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", "STICK_DEADZONE", "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", @@ -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"}, {"STICK_DEADZONE", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"}, + {"PAD_LAYOUT", "input"}, {"STICK_DEADZONE", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "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,8 @@ 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}, - {"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, + {"STICK_DEADZONE", "8", "0..50", LIVE}, + {"LSTICK_DEADZONE", "", "0..50", LIVE}, {"RSTICK_DEADZONE", "", "0..50", LIVE}, {"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/cfg_probe.c b/runtime/cfg_probe.c index 0fc40a42..6f733469 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -1,4 +1,5 @@ // --probe-cfg: totk.ini parsing, the environment override and a missing file (cfg.c). Needs no game files. +#include #include #include #include @@ -272,6 +273,22 @@ int probe_cfg(void) { "pad stick: a square gate's corner stays on the unit circle"); input_pad_stick(0, 32767 / 2 + 1, 0.2f, st); CHECK(abs(st[1] - 32767 * 3 / 8) <= 3, "pad stick: half deflection past a 20% zone is (0.5 - 0.2) / 0.8 of full"); + _putenv_s("TOTK_STICK_DEADZONE", "12"); + _putenv_s("TOTK_LSTICK_DEADZONE", ""); + _putenv_s("TOTK_RSTICK_DEADZONE", ""); + CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.12f) < 1e-6f, + "pad dead zone: both sticks follow stick_deadzone while lstick/rstick are unset"); + _putenv_s("TOTK_RSTICK_DEADZONE", "20"); + CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.20f) < 1e-6f, + "pad dead zone: rstick_deadzone sets the right stick alone"); + _putenv_s("TOTK_LSTICK_DEADZONE", "80"); + CHECK(fabsf(input_pad_deadzone(0) - 0.5f) < 1e-6f, "pad dead zone: clamped to 50%"); + _putenv_s("TOTK_STICK_DEADZONE", ""); + _putenv_s("TOTK_LSTICK_DEADZONE", ""); + _putenv_s("TOTK_RSTICK_DEADZONE", ""); + CHECK(input_stick_percent(32767, 0) > 99.99 && input_stick_percent(32767, 0) < 100.01 && + input_stick_percent(0, 0) == 0 && fabs(input_stick_percent(3000, -4000) - 5000 * 100.0 / 32767) < 1e-9, + "stick percent: an axis's end is 100%, the centre 0%, round in between"); // Gamepad layouts (input_map.c) CHECK(input_pad_layout_pick("auto", 1) == PAD_LAYOUT_NINTENDO && input_pad_layout_pick(NULL, 0) == PAD_LAYOUT_XBOX, "pad layout: automatic is Nintendo for an east button labelled A, Xbox otherwise"); diff --git a/runtime/input.h b/runtime/input.h index 5efc17ac..7bf0a37e 100644 --- a/runtime/input.h +++ b/runtime/input.h @@ -23,6 +23,10 @@ int input_menu_gate(int *held, int menu_open, uint64_t *buttons, int32_t sticks[ int input_pad_read(uint64_t *buttons, int32_t *lx, int32_t *ly); // The gamepad layout in effect (PAD_LAYOUT_*, input_map.h; TOTK_PAD_LAYOUT, live); -1 without a gamepad. Any thread. int input_pad_layout(void); +// How far the open gamepad's left (pct[0]) and right (pct[1]) sticks are from the centre now, in percent of full +// deflection, before the dead zone: the menu shows it on the dead zone rows, so a drifting stick's resting value can be +// read off. 0 (and both 0) without a connected gamepad. Any thread. +int input_pad_stick_percent(double pct[2]); // The label on a face button of the open gamepad (input_map.h PAD_SOUTH..PAD_NORTH, as SDL reports it); PAD_LABEL_NONE for another // button, an unknown label or no gamepad. Any thread. enum { PAD_LABEL_NONE, PAD_LABEL_A, PAD_LABEL_B, PAD_LABEL_X, PAD_LABEL_Y, PAD_LABEL_CROSS, PAD_LABEL_CIRCLE, diff --git a/runtime/input_map.c b/runtime/input_map.c index 5c5e06c8..780114a7 100644 --- a/runtime/input_map.c +++ b/runtime/input_map.c @@ -334,6 +334,16 @@ void input_pad_stick(int32_t x, int32_t y, float dead, int32_t out[2]) { out[1] = (int32_t)lrint(fmax(-1, fmin(1, fy * k)) * STICK_MAX); } +float input_pad_deadzone(int stick) { + const char *own = stick ? "TOTK_RSTICK_DEADZONE" : "TOTK_LSTICK_DEADZONE", *set = cfg_get(own); + double v = cfg_double(set && *set ? own : "TOTK_STICK_DEADZONE"); + return (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f; +} + +double input_stick_percent(int32_t x, int32_t y) { + return sqrt((double)x * x + (double)y * y) * 100.0 / STICK_MAX; +} + // Minus and Plus held together open or close the menu. *held: latched from the poll where both go down until neither is // down (the caller keeps it). Every poll of the latch reports neither to the game, so releasing one button first does not // leak the other; Minus alone before Plus reaches the game unchanged. With the menu open the game sees a neutral pad. diff --git a/runtime/input_map.h b/runtime/input_map.h index fe524fa6..18db80df 100644 --- a/runtime/input_map.h +++ b/runtime/input_map.h @@ -95,6 +95,12 @@ void input_mouse_stick(int32_t dx, int32_t dy, double dt_s, float sens, int32_t // 0..0.5): inside the circle the stick reads 0, and the rest of the travel is scaled to start at 0 at the edge, so a // drifting stick rests at 0 and full deflection still reaches full. The result stays inside the unit square. void input_pad_stick(int32_t x, int32_t y, float dead, int32_t out[2]); +// The dead zone of gamepad stick 0 (left) or 1 (right) for input_pad_stick, as a fraction of full deflection: +// TOTK_LSTICK_DEADZONE or TOTK_RSTICK_DEADZONE when set, else TOTK_STICK_DEADZONE (both sticks), percent clamped to 0..50. +float input_pad_deadzone(int stick); +// How far a stick (x, y in -32768..32767) is from the centre, in percent of full deflection (100 at an axis's end; a +// square gate's corner reads more). +double input_stick_percent(int32_t x, int32_t y); // ---- the remapping rows' edits, on a copy of input_map. Pure. // action's keys (table order) / its gamepad buttons in layout, at most max; returns how many. diff --git a/runtime/input_win.c b/runtime/input_win.c index 096fef53..14041341 100644 --- a/runtime/input_win.c +++ b/runtime/input_win.c @@ -428,16 +428,17 @@ static void mouse_camera(int32_t out[2]) { out[1] = held[1]; } -static float stick_dead = -1; // TOTK_STICK_DEADZONE as a fraction of full deflection; live (cfg_version) +static float stick_dead[2] = {-1, -1}; // input_pad_deadzone of the left and right stick; live (cfg_version) static unsigned stick_dead_seen; -static float stick_dead_get(void) { +static float stick_dead_get(int s) { unsigned ver = cfg_version(); - if (stick_dead >= 0 && ver == stick_dead_seen) return stick_dead; - stick_dead_seen = ver; - double v = cfg_double("TOTK_STICK_DEADZONE"); - stick_dead = (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f; - return stick_dead; + if (stick_dead[0] < 0 || ver != stick_dead_seen) { + stick_dead_seen = ver; + stick_dead[0] = input_pad_deadzone(0); + stick_dead[1] = input_pad_deadzone(1); + } + return stick_dead[s]; } // One gamepad stick through the dead zone; SDL's Y grows downwards, the Switch's upwards. @@ -557,12 +558,26 @@ static int pad_read(uint64_t *b, int32_t sl[2], int32_t sr[2]) { uint8_t pd[PAD_COUNT] = {0}; if (!pad_physical(pd)) return 0; *b |= input_map_pad_buttons(pd, pad_layout_get()); - float dead = stick_dead_get(); - stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, dead, sl); - stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, dead, sr); + stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, stick_dead_get(0), sl); + stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, stick_dead_get(1), sr); return 1; } +int input_pad_stick_percent(double pct[2]) { + int ok = 0; + pct[0] = pct[1] = 0; + AcquireSRWLockExclusive(&lock); + if (state == 1 && pad && SDL_GamepadConnected(pad)) { // the game's poll keeps the state fresh (SDL_UpdateGamepads) + pct[0] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX), + SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY)); + pct[1] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX), + SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY)); + ok = 1; + } + ReleaseSRWLockExclusive(&lock); + return ok; +} + static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) { uint64_t b = 0; int32_t sl[2] = {0, 0}, sr[2] = {0, 0}; diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 86c2bc5f..d6b7dd80 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -573,7 +573,16 @@ 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_DEADZONE", UI_MENU_STICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%"); + // One row per stick, falling back to TOTK_STICK_DEADZONE (both sticks) while unset. With a gamepad connected each + // row shows its stick's deflection now, before the dead zone: a drifting stick's resting value, to set it above. + double now[2]; + bool pad = input_pad_stick_percent(now) != 0; + char note[2][64]; + for (int s = 0; s < 2; s++) snprintf(note[s], sizeof note[s], menu_text(UI_MENU_STICK_DEADZONE_NOW), now[s]); + opt_slider("TOTK_LSTICK_DEADZONE", UI_MENU_LSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%", + pad ? note[0] : nullptr, "TOTK_STICK_DEADZONE"); + opt_slider("TOTK_RSTICK_DEADZONE", UI_MENU_RSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%", + pad ? note[1] : nullptr, "TOTK_STICK_DEADZONE"); 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/option_rows.cpp b/runtime/ui/option_rows.cpp index f0f82b36..895c14b1 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -294,12 +294,15 @@ bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, U return opt_choice_list(key, label, values, shown, n, desc, -1, note); } -bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt) { - const CfgMeta *m = cfg_meta(key); - double v = cfg_double(key), def = m ? strtod(m->def, NULL) : lo; +bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt, + const char *note, const char *fallback) { + const char *set = cfg_get(key); + const char *src = fallback && !(set && *set) ? fallback : key; // unset: show the value in effect, the fallback's + const CfgMeta *m = cfg_meta(src); + double v = cfg_double(src), def = m ? strtod(m->def, NULL) : lo; char shown[48]; snprintf(shown, sizeof shown, fmt, v); - RowView rv = {shown, fabs(v - def) < step * 0.01, true, NULL}; + RowView rv = {shown, fabs(v - def) < step * 0.01, true, note}; int s = row(key, label, desc, rv); if (!s) return false; int steps = g_held && (hi - lo) > 40 * step ? 10 : 1; // held: ten steps at a time over a long range diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 6e03faf8..07f32ddc 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -46,8 +46,10 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values, // shown on the right ("" none). bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value = ""); // lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%"). +// note: a short line under the value in place of the "default" mark (NULL: none). fallback: the setting that applies +// while key is unset; the row shows its value then, and a change sets key. bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1, - const char *fmt = "%g"); + const char *fmt = "%g", const char *note = nullptr, const char *fallback = nullptr); // Binding rows (remapping on the Controls tab): a label and three cells, each selectable on its own (left / right move between them). // opt_bind_header: the column titles above them. opt_bind_row: key is the setting's name without TOTK_ (BIND_A; the diff --git a/runtime/ui_text.c b/runtime/ui_text.c index b17ebb02..2bd03bb1 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -97,8 +97,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { "Nintendo for controllers with Nintendo labels and Xbox for the others.", [UI_MENU_PAD_LAYOUT_AUTO] = "Automatic", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A right)", [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s", - [UI_MENU_STICK_DEADZONE] = "Stick dead zone", - [UI_MENU_STICK_DEADZONE_DESC] = "How far a gamepad stick moves before the game sees it. Raise it if the character or the camera moves on its own.", + [UI_MENU_LSTICK_DEADZONE] = "Left stick dead zone", [UI_MENU_RSTICK_DEADZONE] = "Right stick dead zone", + [UI_MENU_STICK_DEADZONE_DESC] = "How far a gamepad stick moves before the game sees it. Raise it if the character or the camera moves on its own: let go of the stick, read \"stick now\" and set the dead zone a few percent above it.", + [UI_MENU_STICK_DEADZONE_NOW] = "stick now: %.0f %%", [UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity", [UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.", @@ -317,8 +318,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных.", [UI_MENU_PAD_LAYOUT_AUTO] = "Автоматически", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo (A справа)", [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", - [UI_MENU_STICK_DEADZONE] = "Мёртвая зона стиков", - [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами.", + [UI_MENU_LSTICK_DEADZONE] = "Мёртвая зона левого стика", [UI_MENU_RSTICK_DEADZONE] = "Мёртвая зона правого стика", + [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами: отпустите стик, посмотрите «стик сейчас» и поставьте мёртвую зону на несколько процентов выше.", + [UI_MENU_STICK_DEADZONE_NOW] = "стик сейчас: %.0f %%", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", [UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 24975758..d7250b02 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_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, + UI_MENU_LSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, UI_MENU_STICK_DEADZONE_NOW, UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, // Controls tab: the remapping rows (ui/binds_page.cpp) diff --git a/totk.ini.example b/totk.ini.example index 522e247b..03a4d0e1 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -153,6 +153,10 @@ # Gamepad stick dead zone in percent of full deflection (0 to 50). Raise it for a stick that drifts: inside the circle # the stick reads centred, and the rest of its travel is scaled to start there. # stick_deadzone = 8 +# The dead zone of one stick, in place of stick_deadzone for that stick (0 to 50; unset = stick_deadzone). The Controls +# tab shows each stick's deflection now, so a drifting stick's resting value can be read off. +# lstick_deadzone = 8 +# rstick_deadzone = 8 # 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 5dcac19982a8ee4a69ab6cc16c26f0f38659f254 Mon Sep 17 00:00:00 2001 From: applezra Date: Fri, 30 Oct 2026 22:56:47 -0700 Subject: [PATCH 011/177] Force anisotropic filtering only on samplers that tile The aniso setting raised every filtered, mipmapped colour sampler to the chosen level. Some of those read screen-sized buffers, among them the ones the inventory's character preview is drawn from. Their coordinates stretch steeply at the model's edges, so the anisotropic taps reach across the edge and leave a speckled fringe around the character. The level is now raised only for samplers that repeat on U and V, which the surface textures it is meant for do; clamped samplers keep the game's level. Distant ground stays as sharp as before. Co-Authored-By: Claude Opus 5.5 --- runtime/vk_texture.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index ce7619f7..14d11067 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -1505,9 +1505,14 @@ static VkSampler make_sampler(VkCtx *c, const samp_par *d) { float lim = c->props.limits.maxSamplerLodBias; si.mipLodBias = fmaxf(-lim, fminf(lim, d->lod_bias)); float aniso = d->aniso; - // TOTK_ANISO raises the level for filtered, mipmapped colour samplers only: depth-compare (shadow) samplers and - // nearest or unmipmapped ones (data maps, LUTs) keep what the game set. - if (aniso_force > 1 && !d->cmp_mode && si.magFilter == VK_FILTER_LINEAR && si.minFilter == VK_FILTER_LINEAR && + // TOTK_ANISO raises the level for filtered, mipmapped colour samplers that repeat on U and V only: the surface + // textures it is for tile. Depth-compare (shadow) samplers, nearest or unmipmapped ones (data maps, LUTs) and clamped + // ones keep what the game set. Clamped samplers read screen-sized buffers, whose coordinates can stretch steeply at + // an object's edge; there anisotropic taps reach across the edge and leave a speckled fringe (the inventory's + // character preview). + int tiled = (modes[0] == VK_SAMPLER_ADDRESS_MODE_REPEAT || modes[0] == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT) && + (modes[1] == VK_SAMPLER_ADDRESS_MODE_REPEAT || modes[1] == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); + if (aniso_force > 1 && tiled && !d->cmp_mode && si.magFilter == VK_FILTER_LINEAR && si.minFilter == VK_FILTER_LINEAR && (mf == NVN_MIN_FILTER_LINEAR_MIPMAP_NEAREST || mf == NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR) && aniso < aniso_force) aniso = aniso_force; if (aniso > 1) { 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 012/177] 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 2e8b4ff1b1f3becd4ddc505b1a0ffba895f45fdb Mon Sep 17 00:00:00 2001 From: DizzyMan1337 Date: Sat, 31 Oct 2026 14:39:20 +0800 Subject: [PATCH 013/177] DLSS upscaling: quality, balanced and performance modes TOTK_DLSS (dlaa|quality|balanced|performance, read at start) sets the scene to 67, 58 or 50 % of the output. DLSS then runs at the begin of the game's scaling pass (the FXAA shader drawing the light target into the output-sized target, before the HUD) and its result replaces that draw; the HUD is drawn afterwards and never jittered or passed through DLSS. The jitter now ends where the scene ends (the bloom), separately from where DLSS runs. Scaled modes add a mip bias of log2(scale) to repeating, mipmapped material samplers. With a scene smaller than the output, fxaa = 0 no longer skips the game's scaling draw (it left the 3D picture out). Co-Authored-By: Claude Opus 5.5 --- runtime/cfg.c | 6 +-- runtime/host.h | 1 + runtime/resolution.c | 19 ++++++- runtime/ui/menu.cpp | 3 ++ runtime/ui_text.c | 24 ++++++--- runtime/ui_text.h | 3 +- runtime/vk_dlaa.c | 114 ++++++++++++++++++++++++++++------------- runtime/vk_dlaa.h | 5 +- runtime/vk_exec_draw.c | 2 +- runtime/vk_texture.c | 10 +++- totk.ini.example | 10 ++-- 11 files changed, 141 insertions(+), 56 deletions(-) diff --git a/runtime/cfg.c b/runtime/cfg.c index 46af3931..d495c1fb 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -36,7 +36,7 @@ static const char *const known[] = { "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DLAA", - "DLAA_JITTER", "DLAA_MV", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", + "DLAA_JITTER", "DLAA_MV", "DLSS", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", @@ -60,7 +60,7 @@ static const struct { const char *key, *section; } sections[] = { {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, - {"SHARPNESS", "display"}, {"ASPECT", "display"}, {"DLAA", "display"}, {"FXAA", "display"}, + {"SHARPNESS", "display"}, {"ASPECT", "display"}, {"DLAA", "display"}, {"DLSS", "display"}, {"FXAA", "display"}, {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"VOLUME", "audio"}, {"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, @@ -95,7 +95,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, - {"DLAA", "0", "0|1", LIVE}, {"FXAA", "1", "0|1", LIVE}, + {"DLAA", "0", "0|1", LIVE}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance", RESTART}, {"FXAA", "1", "0|1", LIVE}, {"ASPECT", "fit", "fit|stretch", LIVE}, // Game {"FPS_LIMIT", "60", "30|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, diff --git a/runtime/host.h b/runtime/host.h index 7e4a1939..5f427bde 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -240,6 +240,7 @@ int res_heapdef_build(const void *in, size_t n, void **out, size_t *out_n); // // the grown heaps, malloc'd; 0 = cannot (logged) void res_heapdef_served(void); // romfs.c serves the grown table void res_init(void); // after rt_patches_init: the patch page and the sets +float res_dlss_lod_bias(void); // TOTK_DLSS upscaling: texture LOD bias (<= 0) void res_sizes(unsigned out[2], unsigned scene[2]); // the output and scene sizes in effect (the game's own // until res_init switched the sets on) int res_is_16x9(unsigned w, unsigned h); // within 1% of 16:9 (the test res_init and romfs.c share) diff --git a/runtime/resolution.c b/runtime/resolution.c index 514b3e6e..ca2e9aee 100644 --- a/runtime/resolution.c +++ b/runtime/resolution.c @@ -49,6 +49,7 @@ static struct { int scene_set; // the scene differs from the game's 5/6 of the output int heapdef_ok; // romfs.c serves the grown HeapDef int on; // res_init switched the patch sets on + double dlss_k; // TOTK_DLSS quality/balanced/performance: the scene's share of the output, else 0 } R; static void decide(void) { @@ -67,7 +68,16 @@ static void decide(void) { } const char *s = cfg_value("TOTK_RENDER_SCALE"); double k = 5.0 / 6.0; - if (strcmp(s, "game")) { + const char *m = cfg_value("TOTK_DLSS"); // a DLSS mode other than dlaa sets the scene size + static const struct { const char *name; double k; } dlss[] = { + {"quality", 2.0 / 3.0}, {"balanced", 0.58}, {"performance", 0.5}}; + for (int i = 0; i < 3; i++) + if (!strcmp(m, dlss[i].name)) R.dlss_k = dlss[i].k; + if (R.dlss_k) { + k = R.dlss_k; + R.scene_set = 1; + rt_log("resolution: DLSS %s: the scene at %.0f %% of the output (render_scale ignored)", m, k * 100); + } else if (strcmp(s, "game")) { char *end; double pct = strtod(s, &end); if (end != s && !*end && pct >= 25 && pct <= 400) { @@ -241,6 +251,13 @@ void res_init(void) { scene_on ? "" : " (the game's own 5/6 of the output)", (unsigned long long)res_heap_extra_kib()); } +// DLSS upscaling: textures are sampled for the output's resolution, not the scene's (NVIDIA's DLSS guide: a mip bias +// of log2(render / output)), so their detail survives the scaling. 0 without a DLSS mode. +float res_dlss_lod_bias(void) { + decide(); + return R.dlss_k ? (float)log2(R.dlss_k) : 0.0f; +} + // 16:9 within 1% (1366x768 counts): the shape the game's own layouts and camera are made for. int res_is_16x9(unsigned w, unsigned h) { double rel = ((double)w / h) / ((double)BASE_W / BASE_H); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 7b7a83e2..ba8f8b1d 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -542,6 +542,9 @@ static void tab_screen(float scale) { static const UiTextId aspect[] = {UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH}; opt_choice("TOTK_ASPECT", UI_MENU_ASPECT, aspect, 2, UI_MENU_ASPECT_DESC); opt_toggle("TOTK_DLAA", UI_MENU_DLAA, UI_MENU_DLAA_DESC); + static const UiTextId dlss[] = {UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED, + UI_MENU_DLSS_PERFORMANCE}; + opt_choice("TOTK_DLSS", UI_MENU_DLSS, dlss, 4, UI_MENU_DLSS_DESC); opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC); opt_end(); } diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 87daf846..11358991 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -68,9 +68,15 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_ASPECT_FIT] = "Black bars", [UI_MENU_ASPECT_STRETCH] = "Stretch", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", - [UI_MENU_DLAA] = "NVIDIA DLAA", - [UI_MENU_DLAA_DESC] = "DLSS anti-aliasing of the 3D scene at its own resolution (NVIDIA RTX GPUs; nvngx_dlss.dll next to " - "totk.exe). Smoother edges and less shimmer for about 3 ms a frame.", + [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", + [UI_MENU_DLAA_DESC] = "NVIDIA DLSS for the 3D scene (NVIDIA RTX GPUs; nvngx_dlss.dll next to totk.exe): smoother edges " + "and less shimmer. The HUD is not touched. The mode below sets the resolution it works from.", + [UI_MENU_DLSS] = "DLSS mode", + [UI_MENU_DLSS_DESC] = "DLAA draws the 3D scene at full resolution. Quality, Balanced and Performance draw it at 67, 58 " + "and 50 % and let DLSS scale it up, for more frames per second; they replace the 3D render " + "scale. Takes effect after a restart.", + [UI_MENU_DLSS_DLAA] = "DLAA (native)", [UI_MENU_DLSS_QUALITY] = "Quality", [UI_MENU_DLSS_BALANCED] = "Balanced", + [UI_MENU_DLSS_PERFORMANCE] = "Performance", [UI_MENU_FXAA] = "Game anti-aliasing (FXAA)", [UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.", @@ -308,9 +314,15 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_ASPECT_FIT] = "Чёрные полосы", [UI_MENU_ASPECT_STRETCH] = "Растянуть", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", - [UI_MENU_DLAA] = "NVIDIA DLAA", - [UI_MENU_DLAA_DESC] = "Сглаживание 3D-сцены через DLSS в её собственном разрешении (видеокарты NVIDIA RTX; nvngx_dlss.dll " - "рядом с totk.exe). Ровнее края и меньше мерцания, около 3 мс на кадр.", + [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", + [UI_MENU_DLAA_DESC] = "NVIDIA DLSS для 3D-сцены (видеокарты NVIDIA RTX; nvngx_dlss.dll рядом с totk.exe): ровнее края и " + "меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он работает.", + [UI_MENU_DLSS] = "Режим DLSS", + [UI_MENU_DLSS_DESC] = "DLAA рисует 3D-сцену в полном разрешении. «Качество», «Баланс» и «Производительность» рисуют её " + "в 67, 58 и 50 % и масштабируют через DLSS ради большего числа кадров; они заменяют масштаб " + "3D-отрисовки. Действует после перезапуска.", + [UI_MENU_DLSS_DLAA] = "DLAA (родное)", [UI_MENU_DLSS_QUALITY] = "Качество", [UI_MENU_DLSS_BALANCED] = "Баланс", + [UI_MENU_DLSS_PERFORMANCE] = "Производительность", [UI_MENU_FXAA] = "Сглаживание игры (FXAA)", [UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index e1e55dba..66b45db6 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -37,7 +37,8 @@ typedef enum { UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR, UI_MENU_ASPECT, UI_MENU_ASPECT_DESC, UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, - UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_FXAA, UI_MENU_FXAA_DESC, + UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_DLSS, UI_MENU_DLSS_DESC, UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, + UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_FXAA, UI_MENU_FXAA_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_90, UI_MENU_FPS_120, diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c index 9de36e8a..41de947d 100644 --- a/runtime/vk_dlaa.c +++ b/runtime/vk_dlaa.c @@ -28,7 +28,7 @@ typedef int NgxResult; // NVSDK_NGX_Result: 1 success, 0xBAD00000 | n failures #define NGX_OK(r) (((unsigned)(r) & 0xFFF00000u) != 0xBAD00000u) #define NGX_VERSION_API 0x15 #define NGX_FEATURE_SUPERSAMPLING 1 -#define NGX_PERFQ_DLAA 5 +#define NGX_PERFQ_DLAA 5 // NVSDK_NGX_PerfQuality_Value: 0 performance, 1 balanced, 2 quality, 3 ultra performance typedef struct NgxParam NgxParam; typedef struct NgxHandle NgxHandle; typedef struct { void *slot[17]; } NgxParamVtbl; @@ -203,13 +203,21 @@ void vk_dlaa_init(void) { // quarter of the scene starts the bloom chain, which reads it. After the bloom come the tonemap and post passes, then // the HUD is drawn into the same target and a last pass copies it to the 8-bit output. // So: after the G-buffer, a pass at the scene size with exactly one colour target (R11G11B10F or RGBA16F) and the D32F -// depth arms the frame with that pair; the next pass at most a quarter as wide runs DLAA on the armed target first. -// Bloom, tonemap, post and HUD then all work on the anti-aliased picture. +// depth arms the frame with that pair; the next pass at most a quarter as wide ends the scene (no jitter after it) and, +// when the scene is as wide as the output, runs DLAA on the armed target first. Bloom, tonemap, post and HUD then all +// work on the anti-aliased picture. +// Upscaling (a scene smaller than the output: TOTK_DLSS quality/balanced/performance, or the game's own 5/6): measured +// at a 960x536 scene, 1920x1080 output, the bloom and its composite write back into the light target at the scene size, +// then one full-screen draw (the FXAA shader below, which also scales) reads it into an output-sized R11G11B10F target +// with no depth, and the HUD is drawn over that target at the output size. DLSS runs at the begin of that pass: it +// reads the light target and its result is blitted into the pass's target, whose scaling draw is then skipped. The +// HUD, drawn afterwards into the same target, is never jittered nor passed through DLSS. static struct { VkExecTarget color, depth; // the armed pair, valid in the frame it was armed int armed, done, gbuf; // this frame: armed on the light target, DLAA ran, the G-buffer was drawn + int ended, up; // this frame: the scene is drawn (jitter over), DLSS wrote the scaled output struct Size { // a DLSS feature and its work images per scene size (dynamic resolution flips it) - uint32_t w, h; + uint32_t w, h, ow, oh; // render size, output size VkImage out, mv; VmaAllocation out_mem, mv_mem; VkImageView out_view, mv_view; @@ -275,13 +283,14 @@ static void free_size(struct Size *e) { memset(e, 0, sizeof *e); } -// The entry for a scene size: its output (RGBA16F, written by DLSS, then blitted back into the scene target) and -// motion vectors (RG16F, render pixels), both kept in GENERAL like every image of the back end. TotK's dynamic -// resolution switches between a few sizes; each keeps its feature, the least recently used goes for a new one. -static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { +// The entry for a scene and output size: its output (RGBA16F at the output size, written by DLSS, then blitted into +// the target) and motion vectors (RG16F at the scene size, render pixels), both kept in GENERAL like every image of the +// back end. TotK's dynamic resolution switches between a few sizes; each keeps its feature, the least recently used +// goes for a new one. +static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h, uint32_t ow, uint32_t oh) { struct Size *e = NULL, *lru = &D.sizes[0]; for (int i = 0; i < 3; i++) { - if (D.sizes[i].w == w && D.sizes[i].h == h) return &D.sizes[i]; + if (D.sizes[i].w == w && D.sizes[i].h == h && D.sizes[i].ow == ow && D.sizes[i].oh == oh) return &D.sizes[i]; if (!D.sizes[i].out && !e) e = &D.sizes[i]; if (D.sizes[i].used < lru->used) lru = &D.sizes[i]; } @@ -291,7 +300,7 @@ static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { } VkImageUsageFlags u = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (!image2d(w, h, VK_FORMAT_R16G16B16A16_SFLOAT, u, &e->out, &e->out_mem, &e->out_view) || + if (!image2d(ow, oh, VK_FORMAT_R16G16B16A16_SFLOAT, u, &e->out, &e->out_mem, &e->out_view) || !image2d(w, h, VK_FORMAT_R16G16_SFLOAT, u, &e->mv, &e->mv_mem, &e->mv_view)) return NULL; VkImageMemoryBarrier2 ib[2]; @@ -308,7 +317,7 @@ static struct Size *size_for(VkCommandBuffer cb, uint32_t w, uint32_t h) { VkDependencyInfo di = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .imageMemoryBarrierCount = 2, .pImageMemoryBarriers = ib}; vkCmdPipelineBarrier2(cb, &di); - e->w = w, e->h = h; + e->w = w, e->h = h, e->ow = ow, e->oh = oh; return e; } @@ -435,13 +444,13 @@ static float halton(uint32_t i, uint32_t b) { } void vk_dlaa_viewport(VkExec *ex, VkViewport *v) { - if (!D.jit_ok || D.done || !ex->depth.image || ex->depth.image != D.jdepth) return; + if (!D.jit_ok || D.ended || !ex->depth.image || ex->depth.image != D.jdepth) return; v->x += D.jx, v->y += D.jy; D.ux = D.jx, D.uy = D.jy, D.jit_used = 1; } void vk_dlaa_draw(VkExec *ex) { - if (!dl_active() || D.done) return; + if (!dl_active() || D.ended) return; const p_bind_buf *b = &ex->ubo[0][1]; // constant bank c4: the replay keeps user banks from c3 on const VkExecTarget *z = &ex->depth; if (b->size == 0x940 && b->addr && z->image && z->width >= 640 && z->format == VK_FORMAT_D32_SFLOAT && @@ -460,12 +469,21 @@ static void next_jitter(void) { D.jit_ok = !D.hold && !nj; } -static void evaluate(VkExec *ex) { +// The quality setting DLSS is created with, from the scene's share of the output width. +static int perf_quality(uint32_t w, uint32_t ow) { + if (w >= ow) return NGX_PERFQ_DLAA; + double k = (double)w / ow; + return k >= 0.66 ? 2 : k >= 0.57 ? 1 : k >= 0.49 ? 0 : 3; +} + +// dst: the target DLSS's picture goes to, NULL for the light target itself (DLAA in place). +static void evaluate(VkExec *ex, const VkExecTarget *dst) { const VkExecTarget *t = &D.color, *z = &D.depth; - uint32_t w = t->width, h = t->height; + if (!dst) dst = t; + uint32_t w = t->width, h = t->height, ow = dst->width, oh = dst->height; VkCommandBuffer cb = ex->cb; vk_exec_barrier(ex); // what drew the scene is done (no pass is open here) - struct Size *e = size_for(cb, w, h); + struct Size *e = size_for(cb, w, h, ow, oh); if (!e) return dl_fail("work image creation", 0); if (e != D.last) D.reset = 1, D.why[0]++; // another size's history is from another moment if (!D.params && !NGX_OK(N.alloc_params(&D.params))) return dl_fail("parameter allocation", 0); @@ -488,23 +506,23 @@ static void evaluate(VkExec *ex) { p_setu(p, "VisibilityNodeMask", 1); p_setu(p, "Width", w); p_setu(p, "Height", h); - p_setu(p, "OutWidth", w); - p_setu(p, "OutHeight", h); - p_seti(p, "PerfQualityValue", NGX_PERFQ_DLAA); + p_setu(p, "OutWidth", ow); + p_setu(p, "OutHeight", oh); + p_seti(p, "PerfQualityValue", perf_quality(w, ow)); // IsHDR | MVLowRes | AutoExposure: linear scene light, motion vectors at the render size, no exposure texture p_seti(p, "DLSS.Feature.Create.Flags", (1 << 0) | (1 << 1) | (1 << 6)); p_seti(p, "DLSS.Enable.Output.Subrects", 0); NgxResult r = N.create(cb, NGX_FEATURE_SUPERSAMPLING, p, &e->feat); if (!NGX_OK(r) || !e->feat) return dl_fail("DLSS feature creation", r); D.reset = 1; - rt_log("dlaa: DLSS feature created at %ux%u (scene format %d, depth format %d)", w, h, (int)t->format, - (int)z->format); + rt_log("dlaa: DLSS feature created at %ux%u -> %ux%u, quality value %d (scene format %d, depth format %d)", w, + h, ow, oh, perf_quality(w, ow), (int)t->format, (int)z->format); } if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image; VkImageView cv = vk_exec_target_view(t->img, t->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT, t->level, t->base_layer, 1, 0); NgxResourceVK rc = res_image(cv, t->image, t->format, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); - NgxResourceVK ro = res_image(e->out_view, e->out, VK_FORMAT_R16G16B16A16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 1); + NgxResourceVK ro = res_image(e->out_view, e->out, VK_FORMAT_R16G16B16A16_SFLOAT, ow, oh, VK_IMAGE_ASPECT_COLOR_BIT, 1); NgxResourceVK rz = res_image(zv, z->image, z->format, w, h, VK_IMAGE_ASPECT_DEPTH_BIT, 0); NgxResourceVK rm = res_image(e->mv_view, e->mv, VK_FORMAT_R16G16_SFLOAT, w, h, VK_IMAGE_ASPECT_COLOR_BIT, 0); p_setp(p, "Color", &rc); @@ -527,21 +545,22 @@ static void evaluate(VkExec *ex) { D.reset = 0; D.last = e, e->used = D.evals + 1; full_barrier(cb); - // the result back into the scene target, which the bloom, the post passes and the HUD read and draw over + // the result into the scene target (DLAA: the bloom, the post passes and the HUD read it and draw over it) or into + // the scaling pass's target (the HUD draws over it) VkImageBlit b = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}, - .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, t->level, t->base_layer, 1}, - .dstOffsets = {{0, 0, 0}, {(int32_t)w, (int32_t)h, 1}}}; - vkCmdBlitImage(cb, e->out, VK_IMAGE_LAYOUT_GENERAL, t->image, VK_IMAGE_LAYOUT_GENERAL, 1, &b, VK_FILTER_NEAREST); + .srcOffsets = {{0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, dst->level, dst->base_layer, 1}, + .dstOffsets = {{0, 0, 0}, {(int32_t)ow, (int32_t)oh, 1}}}; + vkCmdBlitImage(cb, e->out, VK_IMAGE_LAYOUT_GENERAL, dst->image, VK_IMAGE_LAYOUT_GENERAL, 1, &b, VK_FILTER_NEAREST); full_barrier(cb); ex->recorded += 4; vk_exec_draw_new_cb(); // NGX bound pipelines and descriptor sets of its own: the next draw binds everything again D.jdepth = z->image; next_jitter(); if (++D.evals == 1 || D.evals % 3600 == 0) - rt_log("dlaa: %llu frames anti-aliased (scene %ux%u; %llu frames without the DLAA point, %llu with camera " + rt_log("dlaa: %llu frames anti-aliased (scene %ux%u, output %ux%u; %llu frames without the DLAA point, %llu with camera " "motion, %llu without a camera, %llu jitter holds; resets: %llu size, %llu camera, %llu target)", - (unsigned long long)D.evals, w, h, (unsigned long long)D.frames_missed, + (unsigned long long)D.evals, w, h, ow, oh, (unsigned long long)D.frames_missed, (unsigned long long)D.mv_frames, (unsigned long long)D.mv_none, (unsigned long long)D.holds, (unsigned long long)D.why[0], (unsigned long long)D.why[1], (unsigned long long)D.why[2]); } @@ -568,9 +587,20 @@ void vk_dlaa_pass(VkExec *ex) { return; } if (!D.armed) return; - if (!ex->pass_w || ex->pass_w * 4 > D.color.width) return; - D.done = 1; - evaluate(ex); + if (!D.ended) { + if (!ex->pass_w || ex->pass_w * 4 > D.color.width) return; + D.ended = 1; + unsigned o[2], s[2]; + res_sizes(o, s); + if (D.color.width >= o[0]) D.done = 1, evaluate(ex, NULL); // DLAA in place; else wait for the scaling pass + return; + } + // the game's scaling pass: one colour target wider than the scene, no depth + if (ex->pass_ncolor == 1 && c->image && !z->image && scene_color(c->format) && c->width > D.color.width && + c->samples <= 1 && !c->is3d) { + D.done = D.up = 1; + evaluate(ex, c); + } } void vk_dlaa_frame(void) { @@ -579,7 +609,8 @@ void vk_dlaa_frame(void) { rt_log("dlaa: %s", on ? "on" : "off"); D.on = on; // either way the next DLAA frame starts a new history from an unjittered frame - D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = 0, D.hold = 0; + D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = D.ended = D.up = 0; + D.hold = 0; return; } if (!dl_active()) return; @@ -587,7 +618,7 @@ void vk_dlaa_frame(void) { if (D.jit_used && !D.done) D.hold = 60, D.holds++; // jittered but not resolved: that frame shook else if (D.hold) D.hold--; if (!D.done) D.jit_ok = 0; - D.armed = D.done = D.jit_used = D.gbuf = 0; + D.armed = D.done = D.jit_used = D.gbuf = D.ended = D.up = 0; D.cam_addr = 0; } @@ -597,7 +628,12 @@ void vk_dlaa_frame(void) { // game's own switch, ModelSceneExtensionParam EnableFXAA, on and off). With fxaa = 0 the draws of that second pass's // fragment shader are skipped, so the scene reaches the HUD as it was. Shaders are known by the FNV-1a hash of their // SPIR-V, as vk_dump.c names them; a translator change gives new hashes and the switch then does nothing. -#define FXAA_FS 0xf450003ebeb3dc52ull +// With a scene smaller than the output (the game's own 5/6 render scale, or a DLSS mode) the same shader draws the +// scaled picture into the output-sized target, in a pass without the depth attachment the in-place FXAA has: there it +// is always drawn, whatever fxaa says (skipping it would leave the 3D picture out), unless DLSS already wrote that +// target this frame. +// The stock translator's hash, and the one with tools/xlate patch 0010 (PCSS, PR #89) applied. +static const uint64_t FXAA_FS[] = {0xf450003ebeb3dc52ull, 0x0a12f4bc2a9a4fbeull}; static uint64_t spirv_hash(const GfxShader *s) { static struct { const GfxShader *s; uint64_t h; } tab[8192]; @@ -615,10 +651,14 @@ static uint64_t spirv_hash(const GfxShader *s) { return 0; // table full: no skip } -int vk_dlaa_skip_draw(const GfxShader *fs) { +int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) { static uint64_t frame_read = ~0ull; static int fxaa = 1; uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED); if (f != frame_read) frame_read = f, fxaa = cfg_bool("TOTK_FXAA"); // once a frame: the menu switches it live - return !fxaa && fs && spirv_hash(fs) == FXAA_FS; + if (!fs) return 0; + uint64_t h = spirv_hash(fs); + if (h != FXAA_FS[0] && h != FXAA_FS[1]) return 0; + if (!ex->depth.image) return D.up; // the scaling pass + return !fxaa; } diff --git a/runtime/vk_dlaa.h b/runtime/vk_dlaa.h index 4eb7ff3d..dc291b10 100644 --- a/runtime/vk_dlaa.h +++ b/runtime/vk_dlaa.h @@ -18,5 +18,6 @@ void vk_dlaa_frame(void); // the viewport of the scene's draws by the frame's jitter (vk_dlaa_viewport, when the viewport is recorded). void vk_dlaa_draw(VkExec *ex); void vk_dlaa_viewport(VkExec *ex, VkViewport *v); -// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0). -int vk_dlaa_skip_draw(const GfxShader *fs); +// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0, its +// scaling draw when DLSS wrote the scaled picture). +int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs); diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index db9f2ef2..bc4aa989 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -2041,7 +2041,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { if (fs_wait) fs = shader_for(ex, NVN_STAGE_FS, &has_fs, NULL, 1); } if (!vs || (has_fs && !fs)) return 0; - if (vk_dlaa_skip_draw(fs)) return 0; // the game's FXAA, switched off (vk_dlaa.c) + if (vk_dlaa_skip_draw(ex, fs)) return 0; // the game's FXAA off, or its scaling replaced by DLSS (vk_dlaa.c) uint32_t fbl = feedback_prepare(ex, fs); VkPipeState s = ex->pipe; s.vs = vs, s.fs = fs; diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index 99db3f5c..bf5ab49c 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -1565,8 +1565,14 @@ static VkSampler make_sampler(VkCtx *c, const samp_par *d) { si.maxLod = d->lod_max > 1000 ? VK_LOD_CLAMP_NONE : d->lod_max; if (mf <= NVN_MIN_FILTER_LINEAR) si.maxLod = si.minLod + 0.25f; // not mipmapped: stay on the base level if (si.maxLod < si.minLod) si.maxLod = si.minLod; - float lim = c->props.limits.maxSamplerLodBias; - si.mipLodBias = fmaxf(-lim, fminf(lim, d->lod_bias)); + float lim = c->props.limits.maxSamplerLodBias, bias = d->lod_bias; + // DLSS upscaling (resolution.c): the scene's material textures, the filtered mipmapped ones that repeat, are + // sampled for the output's resolution; clamped ones (post effects, LUTs, the UI) keep the game's bias. + if (!d->cmp_mode && mf == NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR && + (si.addressModeU == VK_SAMPLER_ADDRESS_MODE_REPEAT || si.addressModeU == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT || + si.addressModeV == VK_SAMPLER_ADDRESS_MODE_REPEAT || si.addressModeV == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT)) + bias += res_dlss_lod_bias(); + si.mipLodBias = fmaxf(-lim, fminf(lim, bias)); if (d->aniso > 1) { si.anisotropyEnable = VK_TRUE; si.maxAnisotropy = fminf(d->aniso, c->props.limits.maxSamplerAnisotropy); diff --git a/totk.ini.example b/totk.ini.example index 6aa8801c..b9dcc044 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -127,10 +127,14 @@ # window is no longer stretched as it used to be; stretch fills the window. Changes while the game runs take effect at # once. # aspect = fit -# NVIDIA DLAA: DLSS anti-aliasing of the 3D scene at its own resolution, on NVIDIA RTX GPUs with nvngx_dlss.dll (from -# NVIDIA's DLSS SDK) next to totk.exe; elsewhere the setting does nothing. Changes while the game runs take effect at -# once. +# NVIDIA DLSS / DLAA for the 3D scene, on NVIDIA RTX GPUs with nvngx_dlss.dll (from NVIDIA's DLSS SDK) next to +# totk.exe; elsewhere the setting does nothing. The HUD is drawn after it and is not touched. Changes while the game +# runs take effect at once. # dlaa = 0 +# What DLSS works from: dlaa (the 3D scene at full size), quality, balanced or performance (the scene at 67, 58 or +# 50 % of the output, scaled up by DLSS; these replace render_scale and sharpen texture filtering to match). With dlaa +# = 0 the game's own scaling is used at that size. Read at start. +# dlss = dlaa # The game's own FXAA after the post effects; with DLAA on it is not needed. Changes while the game runs take effect at # once. # fxaa = 1 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 014/177] 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 1e32d605ce9239f38883c0e4d1ec47a5ab7b68ec Mon Sep 17 00:00:00 2001 From: Lucas-blip-png <177052392+Lucas-blip-png@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:01:30 -0400 Subject: [PATCH 015/177] Add a Brazilian Portuguese catalog for the installer window and the launcher The installer had English and Russian. installer/text/pt-BR.json covers every id with the same placeholders; the window offers PT-BR beside EN and RU and picks it when the Windows display language is Portuguese (Brazil), LANGID 0x0416; Portugal's Portuguese stays English. make_release.py writes LAUNCHER_*_PT_BR into launcher_text.h and the launcher shows it on the same LANGID. The catalog tests check every window language against English. --- docs/installer.md | 7 +- installer/gui.py | 8 +- installer/guilogic.py | 7 +- installer/launcher/launcher.c | 13 ++- installer/text/pt-BR.json | 175 ++++++++++++++++++++++++++++++++++ tests/installer_gui_test.py | 26 ++--- tools/make_release.py | 10 +- 7 files changed, 217 insertions(+), 29 deletions(-) create mode 100644 installer/text/pt-BR.json diff --git a/docs/installer.md b/docs/installer.md index e6ad004c..a18373b6 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -79,9 +79,10 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR the merged RomFS (15.9 GiB) before it deletes them. The check computes the exact figure. - Window (`python -m installer.gui`, `installer/gui.py` draws, `installer/guilogic.py` decides): form, step list with progress, space line, collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit), - finish screen with Open folder. English or Russian, chosen from the Windows display language, switchable in the - window; every sentence is an id in `installer/text/.json`. A folder with `totk-install.json` needs only the - folder. `--selftest [--shots DIR]` builds every screen in both languages and closes itself. + finish screen with Open folder. English, Russian or Brazilian Portuguese, chosen from the Windows display language, + switchable in the window; every sentence is an id in `installer/text/.json`. A folder with + `totk-install.json` needs only the folder. `--selftest [--shots DIR]` builds every screen in every language and + closes itself. - `tests/installer_gui_test.py`: event model, form, catalogs, cancel, the self-closing window and one end-to-end run of the CLI in `--verify` mode (needs `build/install-test` and `build/extracted/v121`; see its docstring). - `tests/installer_test.py`: bookkeeping with fake steps. `tests/installer_e2e.py`: a dev-mode run with the files of diff --git a/installer/gui.py b/installer/gui.py index bbda6a2d..8a6c551e 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -2,10 +2,10 @@ A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the game language and the install folder, runs `python -m installer ...` as a subprocess and shows its JSON events. Decisions live in guilogic.py; -this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. +this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. - --selftest [--shots DIR] build every screen in both languages and close by itself (PNG per screen with --shots) - --lang en|ru window language (default: the Windows display language) + --selftest [--shots DIR] build every screen in every language and close by itself (PNG per screen with --shots) + --lang en|ru|pt-BR window language (default: the Windows display language) """ import argparse import json @@ -523,7 +523,7 @@ def grab(root, path): def selftest(layout, shots=None): - """Every screen in both languages; the window closes itself. Returns 0 when nothing raised.""" + """Every screen in every language; the window closes itself. Returns 0 when nothing raised.""" fix_tcl_paths() root = tk.Tk() root.geometry('+60+40') diff --git a/installer/guilogic.py b/installer/guilogic.py index 7d517024..4725dc18 100644 --- a/installer/guilogic.py +++ b/installer/guilogic.py @@ -23,11 +23,12 @@ from . import state as statefile from .events import render TEXT = Path(__file__).resolve().parent / 'text' -UI_LANGUAGES = ('en', 'ru') +UI_LANGUAGES = ('en', 'ru', 'pt-BR') STEP_ORDER = ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup') # message parameter -> catalog id prefix of the names that replace its raw values PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'} LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID +LANG_PT_BR = 0x0416 # Portuguese (Brazil), the whole LANGID: Portugal's Portuguese stays English def load_texts(lang): @@ -75,12 +76,12 @@ def flat(value): def windows_ui_language(): - """'ru' when the Windows display language is Russian, else 'en'.""" + """'ru' when the Windows display language is Russian, 'pt-BR' when it is Brazilian Portuguese, else 'en'.""" try: langid = ctypes.windll.kernel32.GetUserDefaultUILanguage() except (AttributeError, OSError): return 'en' - return 'ru' if langid & 0x3ff == LANG_RU else 'en' + return 'ru' if langid & 0x3ff == LANG_RU else 'pt-BR' if langid == LANG_PT_BR else 'en' def default_game_language(ui): diff --git a/installer/launcher/launcher.c b/installer/launcher/launcher.c index 11994cd9..ce3a2d2c 100644 --- a/installer/launcher/launcher.c +++ b/installer/launcher/launcher.c @@ -9,14 +9,19 @@ #include "launcher_text.h" -#define LANGID_RUSSIAN 0x19 +#define LANGID_RUSSIAN 0x19 /* primary language id */ +#define LANGID_PT_BR 0x0416 /* the whole LANGID: Portugal's Portuguese stays English */ #define PATH_CHARS (MAX_PATH * 2) static void fail(void) { - int russian = (GetUserDefaultUILanguage() & 0x3ff) == LANGID_RUSSIAN; - MessageBoxW(NULL, russian ? LAUNCHER_PYTHON_MISSING_RU : LAUNCHER_PYTHON_MISSING_EN, - russian ? LAUNCHER_TITLE_RU : LAUNCHER_TITLE_EN, MB_OK | MB_ICONERROR); + LANGID id = GetUserDefaultUILanguage(); + int russian = (id & 0x3ff) == LANGID_RUSSIAN, brazilian = id == LANGID_PT_BR; + MessageBoxW(NULL, + russian ? LAUNCHER_PYTHON_MISSING_RU : brazilian ? LAUNCHER_PYTHON_MISSING_PT_BR + : LAUNCHER_PYTHON_MISSING_EN, + russian ? LAUNCHER_TITLE_RU : brazilian ? LAUNCHER_TITLE_PT_BR : LAUNCHER_TITLE_EN, + MB_OK | MB_ICONERROR); } int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show) diff --git a/installer/text/pt-BR.json b/installer/text/pt-BR.json new file mode 100644 index 00000000..882391e7 --- /dev/null +++ b/installer/text/pt-BR.json @@ -0,0 +1,175 @@ +{ + "step.check": "Verificando o computador e os arquivos do jogo", + "step.extract": "Extraindo o jogo", + "step.lift": "Traduzindo o código do jogo para C", + "step.compile": "Compilando o totk.exe", + "step.prepare": "Preparando os shaders", + "step.cleanup": "Finalizando", + + "phase.check.host": "Verificando o processador e a placa de vídeo", + "phase.check.verify": "Verificando os arquivos já instalados", + "phase.check.verify_romfs": "Verificando os dados do jogo instalados", + "phase.check.inputs": "Abrindo os arquivos do jogo com as chaves", + "phase.check.versions": "Verificando as versões do jogo", + "phase.extract.hash_base": "Calculando o checksum do jogo base", + "phase.extract.hash_update": "Calculando o checksum da atualização", + "phase.extract.exefs": "Extraindo o código do jogo", + "phase.extract.copy": "Copiando os dados do jogo", + "phase.extract.merge": "Aplicando a atualização aos dados do jogo", + "phase.extract.diagnose": "Procurando o arquivo do jogo danificado", + "phase.extract.index": "Verificando os dados do jogo", + "phase.lift.discover": "Encontrando as funções", + "phase.lift.emit": "Gerando o código C", + "phase.compile.compile": "Compilando", + "phase.compile.link": "Ligando o totk.exe", + "phase.prepare.romfs_patches": "Gravando os patches de 60 fps nos dados do jogo", + "phase.prepare.seed": "Lendo os shaders dos dados do jogo", + "phase.prepare.translate": "Traduzindo os shaders", + "phase.prepare.libraries": "Montando os shaders para o driver de vídeo", + "phase.prepare.pack": "Juntando o cache de shaders num único arquivo", + "phase.cleanup.ini": "Gravando o totk.ini", + "phase.cleanup.temp": "Removendo os arquivos temporários", + + "cli.usage": "Linha de comando inválida: {detail}", + "internal": "Erro inesperado ({exception}): {detail}", + "state.unreadable": "Não foi possível ler {path}. Escolha outra pasta ou apague esse arquivo.", + "state.newer_format": "{path} foi gravado por um instalador mais novo. Use esse instalador ou outra pasta.", + "state.output_changed": "Os arquivos instalados da etapa '{step}' mudaram desde que foram criados; essa etapa será executada de novo.", + + "check.release_incomplete": "A pasta do instalador está incompleta; faltam: {paths}. Extraia o pacote de novo.", + "check.dest_not_folder": "O local de instalação {path} é um arquivo, não uma pasta.", + "check.dest_not_empty": "A pasta de instalação {path} não está vazia e não tem uma instalação anterior. Escolha uma pasta vazia.", + "check.lang_missing": "Escolha o idioma do jogo.", + "check.lang_unknown": "Idioma desconhecido '{lang}'. Conhecidos: {known}.", + "check.toolchain_broken": "O compilador incluído não funciona: {detail}", + "check.host_probe_failed": "A verificação do computador não rodou (código de saída {code}).", + "check.cpu_no_avx2": "Este processador não tem AVX2 (x86-64-v3), que o jogo exige. Intel Haswell (2013) ou AMD Excavator / Zen e mais novos têm.", + "check.vulkan_missing": "Nenhum driver Vulkan está instalado. Instale o driver mais recente da sua placa de vídeo.", + "check.vulkan_no_device": "O Vulkan não encontra nenhuma placa de vídeo. Instale o driver mais recente da sua placa de vídeo.", + "check.vulkan_too_old": "O jogo precisa de uma placa de vídeo com Vulkan 1.3; encontrado: {devices}. Atualize o driver de vídeo.", + "check.inputs_needed": "Os arquivos do jogo são necessários: escolha o jogo base, a atualização 1.2.1 ou 1.4.3 e o prod.keys.", + "check.input_missing": "Arquivo não encontrado ({input}): {path}", + "check.keys_unreadable": "Não foi possível ler o arquivo de chaves. Escolha um arquivo prod.keys.", + "check.keys_no_header_key": "O arquivo de chaves não tem header_key. Extraia o prod.keys do seu console de novo.", + "check.keys_wrong": "As chaves não abrem o arquivo de {input}. Use o prod.keys do seu console.", + "check.keys_too_old": "O arquivo de chaves é antigo demais para o arquivo de {input} (precisa da geração de chaves {generation}). Extraia o prod.keys de um console com firmware mais novo.", + "check.not_game_file": "O arquivo de {input} não é um arquivo de jogo XCI ou NSP.", + "check.file_unreadable": "Não foi possível ler o arquivo de {input}: {detail}", + "check.ticket_personalized": "O arquivo de {input} tem um ticket personalizado; é preciso um ticket comum.", + "check.ticket_missing": "O arquivo de {input} não tem o ticket de que o conteúdo precisa.", + "check.base_not_totk": "O arquivo do jogo base não é The Legend of Zelda: Tears of the Kingdom ({detail}).", + "check.update_not_nsp": "A atualização precisa ser um arquivo NSP.", + "check.update_is_base": "O arquivo de atualização contém um jogo base. Escolha o NSP da atualização 1.2.1 ou 1.4.3.", + "check.update_not_totk": "O arquivo de atualização não é uma atualização de Tears of the Kingdom ({detail}).", + "check.exefs_failed": "O código do jogo no arquivo de {input} falhou nas verificações; veja {log}.", + "check.input_damaged": "O arquivo de {input} está danificado ou incompleto: {path} ({detail}). Copie esse arquivo de novo da origem, ou extraia-o de novo, e então execute a instalação outra vez.", + "check.base_wrong_version": "O jogo base não é a versão 1.0.0 ({modules} diferem).", + "check.update_wrong_version": "A atualização é a versão {found}; esta versão do instalador aceita {wanted}.", + "check.disk_space": "Espaço livre insuficiente em {path}: são necessários {need_gb} GB, há {free_gb} GB livres.", + + "extract.exefs_mismatch": "O código do jogo extraído não corresponde à versão {version} ({modules}).", + "extract.romfs_merge_failed": "Falha ao aplicar a atualização aos dados do jogo: {detail}. Detalhes: {log}", + "extract.romfs_mismatch": "Os dados do jogo extraídos não correspondem à versão {version} (tamanho {size}, checksum {sha256}...).", + "lift.failed": "Falha ao traduzir o código do jogo (código de saída {code}). Detalhes: {log}", + "compile.failed": "Falha ao compilar o totk.exe (código de saída {code}). Detalhes: {log}", + "compile.exe_in_use": "{path} está em uso. Feche o jogo e execute o instalador de novo.", + "prepare.shader_list_missing": "A lista de shaders está faltando.", + "prepare.romfs_patches_failed": "Falha ao gravar os patches nos dados do jogo (código de saída {code}). Detalhes: {log}", + "prepare.shaders_failed": "Falha ao preparar os shaders (código de saída {code}). Detalhes: {log}", + "cleanup.romfs_unreadable": "Os dados do jogo em {path} estão faltando ou não podem ser lidos depois da instalação. Reinicie o Windows e execute o instalador de novo na mesma pasta: ele extrai os dados do jogo outra vez e mantém o resto.", + "prepare.pack_failed": "Falha ao juntar o cache de shaders (código de saída {code}). Detalhes: {log}", + "cleanup.ini_failed": "Não foi possível gravar o totk.ini: {detail}", + + "warn.lang_needs_fonts": "Textos em {lang} precisam das fontes de sistema do Switch, que o instalador não extrai; parte do texto pode não aparecer.", + "warn.npdm_differs": "O main.npdm difere do dump de referência da versão {version}; só os módulos de código são usados.", + "warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}", + + "ui.title": "Instalação do TotK", + "ui.version": "versão {version}", + "ui.intro": "Monta uma pasta jogável de Tears of the Kingdom a partir dos seus próprios arquivos do jogo. Isso demora um pouco e só precisa ser feito uma vez.", + "ui.notice": "A pasta que esta instalação monta contém o jogo. Ela é só para seu uso pessoal; não compartilhe nem envie para a internet.", + "ui.keys_private": "O arquivo de chaves é lido no lugar. O conteúdo dele nunca é mostrado, copiado nem guardado.", + "ui.base": "Jogo base (NSP ou XCI)", + "ui.update": "Atualização 1.2.1 ou 1.4.3 (NSP)", + "ui.keys": "prod.keys", + "ui.game_language": "Idioma do jogo", + "ui.dest": "Pasta de instalação", + "ui.browse": "Procurar...", + "ui.pick_game": "Escolha o arquivo do jogo base", + "ui.pick_update": "Escolha o arquivo da atualização 1.2.1 ou 1.4.3", + "ui.pick_keys": "Escolha o prod.keys", + "ui.pick_dest": "Escolha a pasta de instalação", + "ui.type_game": "Arquivos de jogo (NSP, XCI)", + "ui.type_nsp": "Arquivos NSP", + "ui.type_keys": "Arquivos de chaves (*.keys)", + "ui.type_all": "Todos os arquivos", + "ui.start": "Iniciar", + "ui.cancel": "Cancelar", + "ui.cancelling": "Cancelando...", + "ui.show_log": "Mostrar log", + "ui.hide_log": "Ocultar log", + "ui.close": "Fechar", + "ui.back": "Voltar", + "ui.open_folder": "Abrir pasta", + "ui.update_mode": "Esta pasta tem uma instalação anterior. A instalação vai continuar ou atualizá-la; os arquivos do jogo só são pedidos se forem necessários de novo.", + "ui.need_dest": "Escolha a pasta de instalação.", + "ui.need_base": "Escolha o arquivo do jogo base.", + "ui.need_update": "Escolha o arquivo da atualização 1.2.1 ou 1.4.3.", + "ui.need_keys": "Escolha o arquivo prod.keys.", + "ui.need_lang": "Escolha o idioma do jogo.", + "ui.missing_base": "O arquivo do jogo base não existe.", + "ui.missing_update": "O arquivo de atualização não existe.", + "ui.missing_keys": "O arquivo de chaves não existe.", + "ui.running_install": "Instalando", + "ui.running_resume": "Continuando a instalação anterior", + "ui.running_update": "Atualizando a instalação", + "ui.state_started": "iniciada", + "ui.state_done": "concluída", + "ui.state_skipped": "pulada", + "ui.state_pending": "aguardando", + "ui.state_running": "em andamento", + "ui.state_failed": "falhou", + "ui.log_warning": "Aviso", + "ui.log_error": "Erro", + "ui.log_space": "Espaço necessário: {need} GB, livre: {free} GB", + "ui.log_end": "Concluído", + "ui.result_ok": "O jogo está pronto", + "ui.result_failed": "A instalação falhou", + "ui.result_cancelled": "A instalação foi cancelada", + "ui.done_text": "Abra o totk.exe em {dest}. O programa de instalação e os arquivos do jogo que você escolheu não são mais necessários.", + "ui.cancelled_text": "As etapas concluídas são mantidas. Inicie a instalação de novo com a mesma pasta para continuar.", + "ui.log_file": "Arquivo de log: {path}", + "ui.process_died": "A instalação parou de forma inesperada (código de saída {code}).", + "ui.confirm_cancel": "A instalação está em andamento. Cancelar e fechar a janela?", + "ui.space_one": "Espaço livre necessário em {path}: {need} GB (livre: {free} GB).", + "ui.space_two": "Espaço livre necessário em {path}: {need} GB (livre: {free} GB); em {temp}: {temp_need} GB (livre: {temp_free} GB).", + "ui.amount_bytes": "{done} / {total} GB", + "ui.amount_chunks": "{done} / {total} partes", + "ui.amount_objects": "{done} / {total} arquivos", + "ui.amount_shaders": "{done} / {total} shaders", + "ui.amount_other": "{done} / {total} {unit}", + "ui.seconds": "{n} s", + "param.input.base": "jogo base", + "param.input.update": "atualização", + "param.input.keys": "chaves", + + "launcher.title": "Instalação do TotK", + "launcher.python_missing": "Os arquivos de instalação estão incompletos: a pasta python ao lado do TotK-Setup.exe não existe. Extraia o arquivo compactado inteiro de novo e abra o TotK-Setup.exe a partir da pasta extraída.", + + "lang.ja": "Japonês", + "lang.en-US": "Inglês (EUA)", + "lang.en-GB": "Inglês (Reino Unido)", + "lang.fr": "Francês", + "lang.fr-CA": "Francês (Canadá)", + "lang.de": "Alemão", + "lang.it": "Italiano", + "lang.es": "Espanhol", + "lang.es-419": "Espanhol (América Latina)", + "lang.nl": "Holandês", + "lang.pt": "Português", + "lang.pt-BR": "Português (Brasil)", + "lang.ru": "Russo", + "lang.ko": "Coreano", + "lang.zh-Hans": "Chinês (Simplificado)", + "lang.zh-Hant": "Chinês (Tradicional)" +} diff --git a/tests/installer_gui_test.py b/tests/installer_gui_test.py index 4eb9c228..6eb17786 100644 --- a/tests/installer_gui_test.py +++ b/tests/installer_gui_test.py @@ -31,8 +31,8 @@ from installer import state as statefile # noqa: E402 from installer.events import Reporter # noqa: E402 from installer.runner import Context # noqa: E402 from installer.steps import all_steps # noqa: E402 -from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, Catalog, Form, Model, Process, # noqa: E402 - amount, describe_event, parse_line, windows_ui_language) +from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGES, Catalog, Form, Model, # noqa: E402 + Process, amount, describe_event, parse_line, windows_ui_language) INSTALLED = ROOT / 'build' / 'install-test' FIXTURE = ROOT / 'build' / 'inst-gui' / 'e2e-install' @@ -233,12 +233,16 @@ class FormTest(unittest.TestCase): class CatalogTest(unittest.TestCase): - def test_russian_covers_english_with_the_same_placeholders(self): - en, ru = Catalog('en').english, Catalog('ru').texts - self.assertEqual(sorted(set(en) - set(ru)), []) - self.assertEqual(sorted(set(ru) - set(en)), []) - holes = [k for k in en if sorted(re.findall(r'\{\w+\}', en[k])) != sorted(re.findall(r'\{\w+\}', ru[k]))] - self.assertEqual(holes, []) + def test_every_language_covers_english_with_the_same_placeholders(self): + en = Catalog('en').english + for lang in UI_LANGUAGES[1:]: + with self.subTest(lang=lang): + other = Catalog(lang).texts + self.assertEqual(sorted(set(en) - set(other)), []) + self.assertEqual(sorted(set(other) - set(en)), []) + holes = [k for k in en + if sorted(re.findall(r'\{\w+\}', en[k])) != sorted(re.findall(r'\{\w+\}', other[k]))] + self.assertEqual(holes, []) def test_every_id_the_window_uses_exists(self): cat = Catalog('en') @@ -246,12 +250,12 @@ class CatalogTest(unittest.TestCase): 'process_died', 'result_ok', 'result_failed', 'result_cancelled')] ids += [f'step.{s}' for s in ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup')] ids += ['ui.state_' + n for n in ('started', 'done', 'skipped', 'pending', 'running', 'failed')] - for lang in ('en', 'ru'): + for lang in UI_LANGUAGES: cat.set_language(lang) self.assertEqual([i for i in ids if not cat.has(i)], []) def test_codes_become_names(self): - for lang, korean in (('en', 'Korean'), ('ru', 'Корейский')): + for lang, korean in (('en', 'Korean'), ('ru', 'Корейский'), ('pt-BR', 'Coreano')): cat = Catalog(lang) self.assertIn(korean, cat('warn.lang_needs_fonts', lang='ko')) self.assertNotIn(' ko ', cat('warn.lang_needs_fonts', lang='ko')) @@ -280,7 +284,7 @@ class CatalogTest(unittest.TestCase): self.assertEqual(describe_event(cat, {'type': 'start'}), '') def test_windows_language_is_a_known_value(self): - self.assertIn(windows_ui_language(), ('en', 'ru')) + self.assertIn(windows_ui_language(), UI_LANGUAGES) BREAK_CHILD = 'import time\nprint("ready", flush=True)\ntime.sleep(60)\n' diff --git a/tools/make_release.py b/tools/make_release.py index 067c2b34..18546ac3 100644 --- a/tools/make_release.py +++ b/tools/make_release.py @@ -390,12 +390,14 @@ def c_wide(text): def launcher_header(path): - """launcher_text.h: the launcher's two messages in English and Russian, taken from the installer's catalog.""" - lines = ['/* generated by tools/make_release.py from installer/text/{en,ru}.json */'] - for lang in ('en', 'ru'): + """launcher_text.h: the launcher's two messages in English, Russian and Brazilian Portuguese, taken from the + installer's catalog (LAUNCHER_TITLE_PT_BR for pt-BR.json).""" + lines = ['/* generated by tools/make_release.py from installer/text/{en,ru,pt-BR}.json */'] + for lang in ('en', 'ru', 'pt-BR'): texts = json.loads((ROOT / 'installer' / 'text' / f'{lang}.json').read_text(encoding='utf-8')) for key in ('title', 'python_missing'): - lines.append(f'#define LAUNCHER_{key.upper()}_{lang.upper()} {c_wide(texts["launcher." + key])}') + macro = f'LAUNCHER_{key.upper()}_{lang.upper().replace("-", "_")}' + lines.append(f'#define {macro} {c_wide(texts["launcher." + key])}') path.parent.mkdir(parents=True, exist_ok=True) path.write_text('\n'.join(lines) + '\n', encoding='ascii') From 859ed28735cc349dd7563c9300c6ff7f4a6be9e3 Mon Sep 17 00:00:00 2001 From: tuwary <47059291+tuwary@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:33:53 +0800 Subject: [PATCH 016/177] Add Simplified Chinese to the setup window and the in-game menu The setup window gets installer/text/zh-Hans.json, a full copy of the English catalog, and a third entry in its language switch. A Windows display language of zh-CN or zh-SG picks it; zh-TW, zh-HK and zh-MO write Traditional Chinese and stay on English. A Chinese window still starts with English as the game language, because Chinese game text needs the Switch shared fonts the installer does not extract. The launcher's message box and make_release.py's launcher_text.h carry the Chinese strings too. The menu and the performance overlay get a text_zh_hans table for every menu id, and TOTK_MENU_LANG takes zh-Hans. Left unset, the menu follows the system UI language with the same Simplified Chinese regions. The font atlas merges in every glyph of the menu language's text from the system font (Microsoft YaHei, else SimSun) and is built again when the menu language changes. ov_probe checks that every menu id has Chinese text, that the printf formats keep the English conversions, and how system language tags map to menu languages; installer_gui_test checks the new catalog the same way as the Russian one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DcYzeu7eb2tXZMU4bRVcGh --- README.md | 1 + docs/architecture.md | 4 +- docs/installer.md | 11 +- installer/gui.py | 14 +- installer/guilogic.py | 23 +++- installer/launcher/launcher.c | 14 +- installer/text/zh-Hans.json | 175 +++++++++++++++++++++++++ runtime/cfg.c | 2 +- runtime/ov_probe.c | 71 ++++++++--- runtime/ui/menu.cpp | 27 ++-- runtime/ui_text.c | 232 ++++++++++++++++++++++++++++++++-- runtime/ui_text.h | 12 +- tests/installer_gui_test.py | 48 +++++-- tools/make_release.py | 10 +- totk.ini.example | 4 +- 15 files changed, 574 insertions(+), 74 deletions(-) create mode 100644 installer/text/zh-Hans.json diff --git a/README.md b/README.md index 089d3f2b..560352d9 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - 60 fps by default; up to 144 fps or the monitor's refresh rate (experimental) - Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling - In-game settings menu (F1) and performance overlay (F10) +- Setup and in-game menu in English, Russian and Simplified Chinese - Keyboard, mouse and gamepad with remapping, rumble and gyro - Xbox button prompts: a layout that keeps the Switch button positions and shows the Xbox labels - Shaders prepared at install instead of during play diff --git a/docs/architecture.md b/docs/architecture.md index 29967538..5fd80294 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,7 +54,9 @@ 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, Simplified Chinese). + The Chinese glyphs come from a system font (Microsoft YaHei, `plat_font_path`) merged into the font atlas for the menu + language. - 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/docs/installer.md b/docs/installer.md index e6ad004c..cf123dd6 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -79,9 +79,12 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR the merged RomFS (15.9 GiB) before it deletes them. The check computes the exact figure. - Window (`python -m installer.gui`, `installer/gui.py` draws, `installer/guilogic.py` decides): form, step list with progress, space line, collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit), - finish screen with Open folder. English or Russian, chosen from the Windows display language, switchable in the - window; every sentence is an id in `installer/text/.json`. A folder with `totk-install.json` needs only the - folder. `--selftest [--shots DIR]` builds every screen in both languages and closes itself. + finish screen with Open folder. English, Russian or Simplified Chinese, chosen from the Windows display language + (zh-CN and zh-SG give Chinese; the Traditional Chinese regions give English), switchable in the window; every + sentence is an id in `installer/text/.json`. A Chinese window still starts with English as the game + language, because Chinese game text needs the Switch shared fonts the installer does not extract. A folder with + `totk-install.json` needs only the folder. `--selftest [--shots DIR]` builds every screen in every language and + closes itself. - `tests/installer_gui_test.py`: event model, form, catalogs, cancel, the self-closing window and one end-to-end run of the CLI in `--verify` mode (needs `build/install-test` and `build/extracted/v121`; see its docstring). - `tests/installer_test.py`: bookkeeping with fake steps. `tests/installer_e2e.py`: a dev-mode run with the files of @@ -93,7 +96,7 @@ The unpacked release; `tools/make_release.py` assembles it and `--zip` packs it: ``` TotK-Setup.exe starts python/pythonw.exe -m installer.gui (installer/launcher/launcher.c, no console) -installer/ the installer: steps, CLI, window, en/ru text catalog +installer/ the installer: steps, CLI, window, en/ru/zh-Hans text catalog python/ Python 3.14.9 embeddable + numpy, lz4, cryptography, cffi, pycparser (+ tkinter for the window) recomp/, tools/ the lifter and the build, extraction and shader scripts the steps run (copied from the repo) llvm/ llvm-mingw, x86_64-only subset (Apache-2.0 with LLVM exception; mingw-w64 parts permissive) diff --git a/installer/gui.py b/installer/gui.py index bbda6a2d..c93215db 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -2,10 +2,10 @@ A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the game language and the install folder, runs `python -m installer ...` as a subprocess and shows its JSON events. Decisions live in guilogic.py; -this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. +this file only draws. The window text is in installer/text/.json under "ui.*" and "launcher.*" ids. - --selftest [--shots DIR] build every screen in both languages and close by itself (PNG per screen with --shots) - --lang en|ru window language (default: the Windows display language) + --selftest [--shots DIR] build every screen in every language and close by itself (PNG per screen with --shots) + --lang en|ru|zh-Hans window language (default: the Windows display language) """ import argparse import json @@ -22,8 +22,8 @@ except ImportError: from . import ini from . import layout as layouts -from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGES, Catalog, Form, Model, Process, - amount, default_game_language, describe_event, parse_line, windows_ui_language) +from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, UI_LANGUAGES, Catalog, Form, Model, + Process, amount, default_game_language, describe_event, parse_line, windows_ui_language) POLL_MS = 100 GLYPH = {PENDING: '\u25cb', RUNNING: '\u25b6', DONE: '\u2714', SKIPPED: '\u2013', FAILED: '\u2716'} @@ -78,7 +78,7 @@ class App: sw.pack(side='right') self.ui_var = tk.StringVar(value=self.cat.lang) for code in UI_LANGUAGES: - ttk.Radiobutton(sw, text=code.upper(), value=code, variable=self.ui_var, style='Toolbutton', + ttk.Radiobutton(sw, text=UI_LANGUAGE_LABELS[code], value=code, variable=self.ui_var, style='Toolbutton', command=self.switch_language).pack(side='left', padx=1) self.body = ttk.Frame(root, padding=PAD) self.body.pack(fill='both', expand=True) @@ -523,7 +523,7 @@ def grab(root, path): def selftest(layout, shots=None): - """Every screen in both languages; the window closes itself. Returns 0 when nothing raised.""" + """Every screen in every language; the window closes itself. Returns 0 when nothing raised.""" fix_tcl_paths() root = tk.Tk() root.geometry('+60+40') diff --git a/installer/guilogic.py b/installer/guilogic.py index 7d517024..6f9157ab 100644 --- a/installer/guilogic.py +++ b/installer/guilogic.py @@ -23,11 +23,16 @@ from . import state as statefile from .events import render TEXT = Path(__file__).resolve().parent / 'text' -UI_LANGUAGES = ('en', 'ru') +UI_LANGUAGES = ('en', 'ru', 'zh-Hans') +# what the language switch in the window's corner shows for each +UI_LANGUAGE_LABELS = {'en': 'EN', 'ru': 'RU', 'zh-Hans': '中文'} STEP_ORDER = ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup') # message parameter -> catalog id prefix of the names that replace its raw values PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'} LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID +# Windows LANGIDs that write Simplified Chinese: zh-CN, zh-SG. zh-TW, zh-HK and zh-MO write Traditional Chinese, which +# the window does not have. +LANGIDS_ZH_HANS = (0x0804, 0x1004) def load_texts(lang): @@ -75,15 +80,27 @@ def flat(value): def windows_ui_language(): - """'ru' when the Windows display language is Russian, else 'en'.""" + """The window language for the Windows display language (ui_language_for_langid).""" try: langid = ctypes.windll.kernel32.GetUserDefaultUILanguage() except (AttributeError, OSError): return 'en' - return 'ru' if langid & 0x3ff == LANG_RU else 'en' + return ui_language_for_langid(langid) + + +def ui_language_for_langid(langid): + """'ru' for a Russian Windows LANGID, 'zh-Hans' for a Simplified Chinese one, else 'en'.""" + if langid & 0x3ff == LANG_RU: + return 'ru' + if langid in LANGIDS_ZH_HANS: + return 'zh-Hans' + return 'en' def default_game_language(ui): + """The game language the form starts with. A Chinese window still starts with English: Chinese game text needs + the Switch shared fonts (ini.NEED_SHARED_FONTS), which the installer does not extract, and the game stops when + they are missing; the player can still pick Chinese.""" return 'ru' if ui == 'ru' else 'en-US' diff --git a/installer/launcher/launcher.c b/installer/launcher/launcher.c index 11994cd9..9571b70f 100644 --- a/installer/launcher/launcher.c +++ b/installer/launcher/launcher.c @@ -12,11 +12,19 @@ #define LANGID_RUSSIAN 0x19 #define PATH_CHARS (MAX_PATH * 2) +/* The language of the window (installer/guilogic.py ui_language_for_langid): Russian, Simplified Chinese (zh-CN and + zh-SG; the Traditional Chinese regions get English, as the window has no Traditional Chinese), else English. */ static void fail(void) { - int russian = (GetUserDefaultUILanguage() & 0x3ff) == LANGID_RUSSIAN; - MessageBoxW(NULL, russian ? LAUNCHER_PYTHON_MISSING_RU : LAUNCHER_PYTHON_MISSING_EN, - russian ? LAUNCHER_TITLE_RU : LAUNCHER_TITLE_EN, MB_OK | MB_ICONERROR); + LANGID ui = GetUserDefaultUILanguage(); + int russian = (ui & 0x3ff) == LANGID_RUSSIAN; + int chinese = ui == MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) || + ui == MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SINGAPORE); + MessageBoxW(NULL, + russian ? LAUNCHER_PYTHON_MISSING_RU : chinese ? LAUNCHER_PYTHON_MISSING_ZH_HANS + : LAUNCHER_PYTHON_MISSING_EN, + russian ? LAUNCHER_TITLE_RU : chinese ? LAUNCHER_TITLE_ZH_HANS : LAUNCHER_TITLE_EN, + MB_OK | MB_ICONERROR); } int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show) diff --git a/installer/text/zh-Hans.json b/installer/text/zh-Hans.json new file mode 100644 index 00000000..54facdea --- /dev/null +++ b/installer/text/zh-Hans.json @@ -0,0 +1,175 @@ +{ + "step.check": "检查电脑和游戏文件", + "step.extract": "解包游戏", + "step.lift": "将游戏代码转换为 C 代码", + "step.compile": "编译 totk.exe", + "step.prepare": "准备着色器", + "step.cleanup": "清理", + + "phase.check.host": "检查处理器和显卡", + "phase.check.verify": "检查已安装的文件", + "phase.check.verify_romfs": "检查已安装的游戏数据", + "phase.check.inputs": "用密钥打开游戏文件", + "phase.check.versions": "检查游戏版本", + "phase.extract.hash_base": "计算游戏本体的校验和", + "phase.extract.hash_update": "计算更新的校验和", + "phase.extract.exefs": "解包游戏代码", + "phase.extract.copy": "复制游戏数据", + "phase.extract.merge": "将更新应用到游戏数据", + "phase.extract.diagnose": "查找损坏的游戏文件", + "phase.extract.index": "校验游戏数据", + "phase.lift.discover": "查找函数", + "phase.lift.emit": "生成 C 代码", + "phase.compile.compile": "编译", + "phase.compile.link": "链接 totk.exe", + "phase.prepare.romfs_patches": "写入 60 帧游戏数据补丁", + "phase.prepare.seed": "从游戏数据中读取着色器", + "phase.prepare.translate": "转译着色器", + "phase.prepare.libraries": "为显卡驱动构建着色器", + "phase.prepare.pack": "将着色器缓存打包成一个文件", + "phase.cleanup.ini": "写入 totk.ini", + "phase.cleanup.temp": "删除临时文件", + + "cli.usage": "命令行无效:{detail}", + "internal": "意外错误({exception}):{detail}", + "state.unreadable": "无法读取 {path}。请选择其他文件夹,或删除该文件。", + "state.newer_format": "{path} 是由更新版本的安装程序写入的。请使用那个安装程序,或选择其他文件夹。", + "state.output_changed": "步骤“{step}”生成的已安装文件在生成后被改动过;该步骤将重新运行。", + + "check.release_incomplete": "安装程序文件夹不完整,缺少:{paths}。请重新解压发布包。", + "check.dest_not_folder": "安装位置 {path} 是一个文件,而不是文件夹。", + "check.dest_not_empty": "安装文件夹 {path} 不是空的,其中也没有之前的安装。请选择一个空文件夹。", + "check.lang_missing": "请选择游戏语言。", + "check.lang_unknown": "未知语言“{lang}”。可用语言:{known}。", + "check.toolchain_broken": "自带的编译器无法工作:{detail}", + "check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。", + "check.cpu_no_avx2": "此处理器不支持游戏所需的 AVX2(x86-64-v3)。Intel Haswell(2013 年)或 AMD Excavator / Zen 及更新的处理器才支持。", + "check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。", + "check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。", + "check.vulkan_too_old": "游戏需要支持 Vulkan 1.3 的显卡;检测到:{devices}。请更新显卡驱动程序。", + "check.inputs_needed": "需要游戏文件:请选择游戏本体、1.2.1 或 1.4.3 更新以及 prod.keys。", + "check.input_missing": "找不到文件({input}):{path}", + "check.keys_unreadable": "无法读取密钥文件。请选择一个 prod.keys 文件。", + "check.keys_no_header_key": "密钥文件中没有 header_key。请从你的主机重新导出 prod.keys。", + "check.keys_wrong": "这些密钥无法打开{input}文件。请使用你自己主机的 prod.keys。", + "check.keys_too_old": "密钥文件对{input}文件来说太旧(需要密钥代数 {generation})。请从固件更新的主机导出 prod.keys。", + "check.not_game_file": "{input}文件不是 XCI 或 NSP 游戏文件。", + "check.file_unreadable": "无法读取{input}文件:{detail}", + "check.ticket_personalized": "{input}文件带有个人化票据(personalized ticket);需要通用票据(common ticket)。", + "check.ticket_missing": "{input}文件缺少其内容所需的票据(ticket)。", + "check.base_not_totk": "游戏本体文件不是《塞尔达传说 王国之泪》({detail})。", + "check.update_not_nsp": "更新必须是 NSP 文件。", + "check.update_is_base": "更新文件里是游戏本体。请选择 1.2.1 或 1.4.3 的更新 NSP。", + "check.update_not_totk": "更新文件不是《王国之泪》的更新({detail})。", + "check.exefs_failed": "{input}文件的游戏代码未通过检查;详见 {log}。", + "check.input_damaged": "{input}文件已损坏或不完整:{path}({detail})。请从来源重新复制该文件或重新导出,然后再次运行安装程序。", + "check.base_wrong_version": "游戏本体不是 1.0.0 版本({modules} 不一致)。", + "check.update_wrong_version": "更新的版本是 {found};此发布版需要 {wanted}。", + "check.disk_space": "{path} 的可用空间不足:需要 {need_gb} GB,可用 {free_gb} GB。", + + "extract.exefs_mismatch": "解包出的游戏代码与 {version} 版本不符({modules})。", + "extract.romfs_merge_failed": "将更新应用到游戏数据失败:{detail}。详情:{log}", + "extract.romfs_mismatch": "解包出的游戏数据与 {version} 版本不符(大小 {size},校验和 {sha256}...)。", + "lift.failed": "游戏代码转换失败(退出代码 {code})。详情:{log}", + "compile.failed": "编译 totk.exe 失败(退出代码 {code})。详情:{log}", + "compile.exe_in_use": "{path} 正在使用中。请关闭游戏后重新运行安装程序。", + "prepare.shader_list_missing": "缺少着色器列表。", + "prepare.romfs_patches_failed": "写入游戏数据补丁失败(退出代码 {code})。详情:{log}", + "prepare.shaders_failed": "准备着色器失败(退出代码 {code})。详情:{log}", + "cleanup.romfs_unreadable": "安装完成后,{path} 中的游戏数据缺失或无法读取。请重启 Windows,然后对同一文件夹再次运行安装程序:它会重新提取游戏数据,其余内容保留。", + "prepare.pack_failed": "打包着色器缓存失败(退出代码 {code})。详情:{log}", + "cleanup.ini_failed": "无法写入 totk.ini:{detail}", + + "warn.lang_needs_fonts": "{lang}文本需要 Switch 系统字体,而安装程序不会提取这些字体;部分文字可能无法显示。", + "warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。", + "warn.xbox_prompts_failed": "无法准备 Xbox 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}", + + "ui.title": "TotK 安装程序", + "ui.version": "版本 {version}", + "ui.intro": "用你自己的游戏文件构建一个可以游玩的《王国之泪》文件夹。耗时较长,只需运行一次。", + "ui.notice": "此安装程序构建的文件夹包含游戏本身,仅供你个人使用;请勿分享或上传。", + "ui.keys_private": "密钥文件只在原位置读取,其内容绝不会被显示、复制或保存。", + "ui.base": "游戏本体(NSP 或 XCI)", + "ui.update": "1.2.1 或 1.4.3 更新(NSP)", + "ui.keys": "prod.keys", + "ui.game_language": "游戏语言", + "ui.dest": "安装文件夹", + "ui.browse": "浏览...", + "ui.pick_game": "选择游戏本体文件", + "ui.pick_update": "选择 1.2.1 或 1.4.3 更新文件", + "ui.pick_keys": "选择 prod.keys", + "ui.pick_dest": "选择安装文件夹", + "ui.type_game": "游戏文件(NSP、XCI)", + "ui.type_nsp": "NSP 文件", + "ui.type_keys": "密钥文件(*.keys)", + "ui.type_all": "所有文件", + "ui.start": "开始", + "ui.cancel": "取消", + "ui.cancelling": "正在取消...", + "ui.show_log": "显示日志", + "ui.hide_log": "隐藏日志", + "ui.close": "关闭", + "ui.back": "返回", + "ui.open_folder": "打开文件夹", + "ui.update_mode": "此文件夹中已有之前的安装。安装程序会继续或更新它;只有在需要时才会再次要求提供游戏文件。", + "ui.need_dest": "请选择安装文件夹。", + "ui.need_base": "请选择游戏本体文件。", + "ui.need_update": "请选择 1.2.1 或 1.4.3 更新文件。", + "ui.need_keys": "请选择 prod.keys 文件。", + "ui.need_lang": "请选择游戏语言。", + "ui.missing_base": "游戏本体文件不存在。", + "ui.missing_update": "更新文件不存在。", + "ui.missing_keys": "密钥文件不存在。", + "ui.running_install": "正在安装", + "ui.running_resume": "正在继续之前的安装", + "ui.running_update": "正在更新安装", + "ui.state_started": "已开始", + "ui.state_done": "完成", + "ui.state_skipped": "已跳过", + "ui.state_pending": "等待中", + "ui.state_running": "进行中", + "ui.state_failed": "失败", + "ui.log_warning": "警告", + "ui.log_error": "错误", + "ui.log_space": "所需空间:{need} GB,可用:{free} GB", + "ui.log_end": "已结束", + "ui.result_ok": "游戏已准备就绪", + "ui.result_failed": "安装失败", + "ui.result_cancelled": "安装已取消", + "ui.done_text": "从 {dest} 启动 totk.exe。安装程序和你选择的游戏文件都不再需要了。", + "ui.cancelled_text": "已完成的步骤会保留。用同一个文件夹再次运行安装程序即可继续。", + "ui.log_file": "日志文件:{path}", + "ui.process_died": "安装程序意外停止(退出代码 {code})。", + "ui.confirm_cancel": "安装正在进行。要取消安装并关闭窗口吗?", + "ui.space_one": "{path} 需要的可用空间:{need} GB(可用:{free} GB)。", + "ui.space_two": "{path} 需要的可用空间:{need} GB(可用:{free} GB);{temp} 需要:{temp_need} GB(可用:{temp_free} GB)。", + "ui.amount_bytes": "{done} / {total} GB", + "ui.amount_chunks": "{done} / {total} 部分", + "ui.amount_objects": "{done} / {total} 个文件", + "ui.amount_shaders": "{done} / {total} 个着色器", + "ui.amount_other": "{done} / {total} {unit}", + "ui.seconds": "{n} 秒", + "param.input.base": "游戏本体", + "param.input.update": "更新", + "param.input.keys": "密钥", + + "launcher.title": "TotK 安装程序", + "launcher.python_missing": "安装文件不完整:TotK-Setup.exe 旁边缺少 python 文件夹。请重新解压整个压缩包,然后从解压出的文件夹中启动 TotK-Setup.exe。", + + "lang.ja": "日语", + "lang.en-US": "英语(美国)", + "lang.en-GB": "英语(英国)", + "lang.fr": "法语", + "lang.fr-CA": "法语(加拿大)", + "lang.de": "德语", + "lang.it": "意大利语", + "lang.es": "西班牙语", + "lang.es-419": "西班牙语(拉丁美洲)", + "lang.nl": "荷兰语", + "lang.pt": "葡萄牙语", + "lang.pt-BR": "葡萄牙语(巴西)", + "lang.ru": "俄语", + "lang.ko": "韩语", + "lang.zh-Hans": "中文(简体)", + "lang.zh-Hant": "中文(繁体)" +} diff --git a/runtime/cfg.c b/runtime/cfg.c index 25a30f18..12718200 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|zh-Hans", 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..6ee6b153 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -814,13 +814,47 @@ 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 printf conversions of a format, in order and without the text between them: "%s, game %.0f%%" -> "%s%.0f%%". +static void conversions(const char *fmt, char *out, size_t cap) { + size_t n = 0; + for (const char *p = fmt; *p;) { + if (*p++ != '%') continue; + const char *start = p - 1; + while (*p && strchr(".-+ #0123456789", *p)) p++; + if (*p) p++; // the conversion letter, or the second '%' of "%%" + for (; start < p; start++) + if (n + 1 < cap) out[n++] = *start; + } + out[n] = 0; +} + +// The host catalog (ui_text.c): every menu id has its own English, Russian and Simplified Chinese text, the formats +// keep the English conversions, 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"}; - 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); + static const char *const menu_langs[] = {"en", "ru", "zh-Hans"}; + for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) + for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++) + CHECK(ui_text_defined(menu_langs[i], (UiTextId)id) && *ui_text_in(menu_langs[i], (UiTextId)id), + "menu text id %d lacks %s", id, menu_langs[i]); + // the texts the host passes to printf + static const UiTextId formats[] = { + UI_MENU_VERSION, UI_MENU_PRESENT_IN_USE, UI_PERF_LINE_FPS, UI_MENU_FPS_DISPLAY_HZ, UI_MENU_PAD_LAYOUT_IN_USE, + UI_BINDS_PRESS_KEY, UI_BINDS_PRESS_PAD, UI_BINDS_CANCEL_HINT, UI_BINDS_TAKEN, UI_BINDS_SWAPPED, UI_KEY_NUM_FMT, + UI_MENU_OV_FPS, UI_MENU_OV_FRAME_MS, UI_MENU_OV_GAME_PCT, UI_MENU_OV_MAX_MS, UI_MENU_OV_FMT_PCT, + UI_MENU_OV_FMT_TEMP, UI_MENU_OV_FMT_POWER, UI_MENU_OV_FMT_MHZ, UI_MENU_OV_FMT_GB, UI_MENU_OV_FMT_GB_OF, + UI_MENU_OV_GAME_GB, UI_MENU_OV_FMT_MS, UI_MENU_OV_PER_FRAME, UI_MENU_OV_FMT_SIZE, UI_MENU_OV_FMT_SCENE, + UI_MENU_OV_FMT_FSR, + }; + for (size_t f = 0; f < sizeof formats / sizeof *formats; f++) { + char want[64], got[64]; + conversions(ui_text_in("en", formats[f]), want, sizeof want); + for (size_t i = 1; i < sizeof menu_langs / sizeof *menu_langs; i++) { + conversions(ui_text_in(menu_langs[i], formats[f]), got, sizeof got); + CHECK(!strcmp(want, got), "format id %d in %s has conversions '%s', English '%s'", (int)formats[f], + menu_langs[i], got, want); + } } 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 @@ -832,18 +866,25 @@ static void probe_menu_text(void) { 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"); + // the system UI language picks the menu language when the setting is unset + static const struct { const char *tag, *lang; } sys_langs[] = { + {"ru", "ru"}, {"ru-RU", "ru"}, {"zh-CN", "zh-Hans"}, {"zh-SG", "zh-Hans"}, {"zh-Hans-CN", "zh-Hans"}, + {"zh-TW", "en"}, {"zh-HK", "en"}, {"zh-Hant-TW", "en"}, {"en-US", "en"}, {"rue", "en"}, {"", "en"}, + }; + for (size_t i = 0; i < sizeof sys_langs / sizeof *sys_langs; i++) + CHECK(!strcmp(menu_lang_for_system(sys_langs[i].tag), sys_langs[i].lang), "system language '%s' gives menu %s", + sys_langs[i].tag, menu_lang_for_system(sys_langs[i].tag)); // 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", "en"); - CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en"); + for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++) { + cfg_set("TOTK_MENU_LANG", menu_langs[i]); + CHECK(!strcmp(menu_language(), menu_langs[i]) && + menu_text(UI_MENU_CONTINUE) == ui_text_in(menu_langs[i], UI_MENU_CONTINUE), + "menu_text did not follow MENU_LANG=%s", menu_langs[i]); + } 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 *auto_lang = menu_lang_for_system(plat_ui_language()); + CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(auto_lang, 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..b73a59e6 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -169,6 +169,7 @@ static int g_failed_flag() { return g_failed.load(std::memory_order_relaxed); } static int g_vk_ok; // back end initialised for g_vk_fmt static VkFormat g_vk_fmt; static float g_font_scale; // the scale of the uploaded font atlas; 0 when none is uploaded +static const char *g_font_lang; // the menu language whose glyphs the uploaded atlas holds static float g_style_scale; // the scale the style was last sized for static ImGuiStyle g_base_style; // the menu's style at 1080 lines static uint64_t g_last_ns; @@ -253,16 +254,18 @@ static int vk_up(const MenuTarget *t) { return 1; } -// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean -// and Chinese language names merged in from a system font when there is one (each language is named in its own script). -// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture). +// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines. For the Japanese, Korean and Chinese +// languages, glyphs are merged in from a system font when there is one: those of the language's own name (each language +// is named in its own script in the language lists) and, for the menu language, every glyph of the menu and overlay +// text. Made again when the window height or the menu language changes; the old texture goes after the queue is idle +// (CreateFontsTexture). static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0}; static const struct { const char *lang; UiTextId name; } kCjk[] = { {"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS}, {"zh-Hant", UI_MENU_LANGNAME_ZH_HANT}, }; -static int fonts_up(float scale) { +static int fonts_up(float scale, const char *menu_lang) { enum { N = sizeof kCjk / sizeof *kCjk }; ImFontAtlas *fa = ImGui::GetIO().Fonts; fa->Clear(); @@ -279,6 +282,8 @@ static int fonts_up(float scale) { merged++; ImFontGlyphRangesBuilder b; b.AddText(ui_text_in("en", kCjk[i].name)); + if (!strcmp(kCjk[i].lang, menu_lang)) + for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) b.AddText(ui_text_in(menu_lang, (UiTextId)id)); b.BuildRanges(&ranges[i]); ImFontConfig mc; mc.MergeMode = true; @@ -291,8 +296,10 @@ static int fonts_up(float scale) { fa->ClearInputData(); // the glyphs are in the texture: the font files and the pixels are not needed again fa->ClearTexData(); for (uint8_t *d : data) free(d); - rt_log("menu: font atlas at %.1f px, language names from %d of %d system fonts", 26.0f * scale, merged, (int)N); + rt_log("menu: font atlas at %.1f px for menu language %s, CJK glyphs from %d of %d system fonts", 26.0f * scale, + menu_lang, merged, (int)N); g_font_scale = ok ? scale : 0; + g_font_lang = menu_lang; return ok; } @@ -596,8 +603,10 @@ 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); + // one name per TOTK_MENU_LANG value (cfg.c), after the automatic choice + static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU, + UI_MENU_LANGNAME_ZH_HANS}; + opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, (int)(sizeof langs / sizeof *langs), UI_MENU_MENU_LANG_DESC); opt_end(); } @@ -1112,7 +1121,9 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha uint64_t t0 = plat_now_ns(); if (!g_ctx_ok) make_context(); float scale = menu_scale(t->height); - if (!vk_up(t) || (g_font_scale != scale && !fonts_up(scale))) { + const char *lang = menu_language(); + // vk_up first: a new back end drops the atlas (g_font_scale 0) + if (!vk_up(t) || ((g_font_scale != scale || !g_font_lang || strcmp(g_font_lang, lang)) && !fonts_up(scale, lang))) { rt_log("menu: Dear ImGui Vulkan back end set-up failed; the menu stays closed"); g_failed.store(1); set_open(0); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 65a1926e..272483b9 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 Simplified Chinese. #include #include @@ -496,6 +496,198 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_OV_SCALE_BILINEAR] = "билинейное", }; +static const char *const text_zh_hans[UI_TEXT_COUNT] = { + SWKBD("文字输入", "请输入名字", "马儿", "确定", "取消", "手柄:A 确定,B 取消"), + + [UI_MENU_TITLE] = "设置", [UI_MENU_TAB_SCREEN] = "显示", [UI_MENU_TAB_GAME] = "游戏", [UI_MENU_TAB_SOUND] = "声音", + [UI_MENU_TAB_CONTROLS] = "操作", [UI_MENU_TAB_MENU] = "菜单", [UI_MENU_TAB_ADVANCED] = "高级", + [UI_MENU_CONTINUE] = "继续", [UI_MENU_QUIT] = "退出游戏", [UI_MENU_ON] = "开", [UI_MENU_OFF] = "关", + [UI_MENU_AUTO] = "自动", [UI_MENU_DEFAULT_MARK] = "默认", [UI_MENU_AFTER_RESTART] = "重启后生效", + [UI_MENU_SET_BY_ENV] = "由环境变量设定", [UI_MENU_SAVE_FAILED] = "无法保存设置", + [UI_MENU_VERSION] = "TotK Recomp %s,游戏 %s", + + [UI_MENU_FULLSCREEN] = "全屏", [UI_MENU_FULLSCREEN_DESC] = "让游戏画面铺满屏幕;按 F11 切换。", + [UI_MENU_WINDOW_SIZE] = "窗口大小", [UI_MENU_WINDOW_SIZE_DESC] = "非全屏时游戏窗口的大小。", + [UI_MENU_WINDOW_SIZE_CUSTOM] = "自定义", [UI_MENU_PRESENT] = "呈现方式", + [UI_MENU_PRESENT_DESC] = "渲染完成的帧如何显示到屏幕上。", [UI_MENU_PRESENT_MAILBOX] = "Mailbox", + [UI_MENU_PRESENT_VSYNC] = "垂直同步", [UI_MENU_PRESENT_IMMEDIATE] = "立即", + [UI_MENU_PRESENT_IN_USE] = "实际使用:%s", [UI_MENU_GPU] = "显卡", + [UI_MENU_GPU_DESC] = "用于渲染游戏的 Vulkan 设备。", [UI_MENU_GPU_AUTO] = "自动", + [UI_MENU_PERF_OVERLAY] = "性能叠加层", + [UI_MENU_PERF_OVERLAY_DESC] = "在右上角显示帧率。“完整”模式还会显示帧时间曲线、CPU、GPU 和内存占用、温度," + "以及渲染线程的等待时间。按 F10 循环切换模式。", + [UI_MENU_PERF_OFF] = "关", [UI_MENU_PERF_FPS] = "帧率", [UI_MENU_PERF_FULL] = "完整", + [UI_PERF_LINE_FPS] = "%.0f FPS", [UI_MENU_GRAPHICS] = "画面", [UI_MENU_OUTPUT_RES] = "游戏分辨率", + [UI_MENU_OUTPUT_RES_DESC] = "游戏绘制画面和界面所用的尺寸。高于 1920 x 1080 时,游戏需要更多显存和 GPU 时间。" + "更宽的尺寸(21:9)会拓宽镜头视野,并把 HUD 移到屏幕四角。", + [UI_MENU_RENDER_SCALE] = "3D 渲染比例", + [UI_MENU_RENDER_SCALE_DESC] = "3D 场景相对于游戏分辨率的大小;游戏自带的 FSR 会把它缩放到游戏分辨率。高于 100 % " + "时可平滑锯齿边缘(超级采样),但 GPU 开销很大。", + [UI_MENU_RENDER_SCALE_GAME] = "游戏默认(83 %)", [UI_MENU_UPSCALER] = "缩放到窗口", + [UI_MENU_UPSCALER_DESC] = "窗口大于游戏分辨率时画面的缩放方式。FSR 比双线性保留更锐利的边缘和细节。", + [UI_MENU_UPSCALER_FSR] = "AMD FSR 1", [UI_MENU_UPSCALER_BILINEAR] = "双线性", [UI_MENU_ASPECT] = "画面比例", + [UI_MENU_ASPECT_DESC] = "窗口的比例与游戏分辨率不同时(例如 21:9 屏幕上的 16:9 画面):保持画面比例并加黑边," + "或拉伸铺满窗口。", + [UI_MENU_ASPECT_FIT] = "黑边", [UI_MENU_ASPECT_STRETCH] = "拉伸", [UI_MENU_SHARPNESS] = "FSR 锐度", + [UI_MENU_SHARPNESS_DESC] = "FSR 缩放后的锐化强度;0 为关闭。", + + [UI_MENU_FPS_LIMIT] = "帧率上限", + [UI_MENU_FPS_LIMIT_DESC] = "游戏每秒最多绘制的帧数。高于 60 为实验性功能,且需要开启“游戏速度跟随时钟”。", + [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] = "显示器刷新率", + [UI_MENU_FPS_DISPLAY_HZ] = "显示器刷新率(%.0f Hz)", [UI_MENU_REALTIME] = "游戏速度跟随时钟", + [UI_MENU_REALTIME_DESC] = "按真实时间推进游戏,帧变慢时游戏不会随之变慢。", + [UI_MENU_CLOTH_REALTIME] = "布料跟随时钟", [UI_MENU_CLOTH_REALTIME_DESC] = "布料和头发也按真实时间推进。", + [UI_MENU_HIGHFPS_FIX] = "高帧率修正", + [UI_MENU_HIGHFPS_FIX_DESC] = "修正帧率高于 30 时出现异常的物理效果,以及帧率高于 60 时一直半透明或不可见的物体。", + [UI_MENU_GAME_LANG] = "游戏语言", [UI_MENU_GAME_LANG_DESC] = "游戏文本和语音的语言。", + [UI_MENU_GAME_LANG_AUTO] = "自动", [UI_MENU_OPERATION_MODE] = "运行模式", + [UI_MENU_OPERATION_MODE_DESC] = "让游戏认为自己处于 TV 模式(插在底座上)还是掌机模式。", + [UI_MENU_MODE_DOCKED] = "TV 模式", [UI_MENU_MODE_HANDHELD] = "掌机模式", + + [UI_MENU_VOLUME] = "音量", [UI_MENU_VOLUME_DESC] = "游戏的主音量。", + + [UI_MENU_MOTION] = "体感操作", [UI_MENU_MOTION_DESC] = "使用手柄的陀螺仪瞄准。", + [UI_MENU_RUMBLE_STRENGTH] = "振动强度", [UI_MENU_RUMBLE_STRENGTH_DESC] = "手柄振动的强弱。", + [UI_MENU_RUMBLE_CURVE] = "振动曲线", [UI_MENU_RUMBLE_CURVE_DESC] = "数值越低,弱振动越明显。", + [UI_MENU_RUMBLE_TRIGGERS] = "扳机振动(Xbox)", [UI_MENU_RUMBLE_TRIGGERS_DESC] = "同时让 Xbox 手柄的扳机键振动。", + [UI_MENU_PAD_LAYOUT] = "按键布局", + [UI_MENU_PAD_LAYOUT_DESC] = "哪个按键作为 A。Nintendo:右侧按键,与 Switch 相同。Xbox:下方按键,即 Xbox " + "手柄上标着 A 的键(PlayStation 手柄上为叉键)。自动:带 Nintendo 标注的手柄用 " + "Nintendo,其他手柄用 Xbox。Xbox 按键提示:A 与 Nintendo 布局一样在右侧,游戏显示 " + "Xbox 的按键标注(A 显示为 B,B 显示为 A,X 显示为 Y,Y 显示为 X);" + "按键提示重启后更改。这些字母属于游戏文件,所以在“操作”中重新映射过的按键," + "屏幕上仍显示原来的字母。", + [UI_MENU_PAD_LAYOUT_AUTO] = "自动", [UI_MENU_PAD_LAYOUT_NINTENDO] = "Nintendo(A 在右)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox(A 在下)", [UI_MENU_PAD_LAYOUT_XBOX_PROMPTS] = "Xbox 按键提示(A 在右)", + [UI_MENU_PAD_LAYOUT_IN_USE] = "实际使用:%s", + [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "缺少按键提示文件:请重新运行安装程序", + [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "按键提示重启后更改", [UI_MENU_STICK_DEADZONE] = "摇杆死区", + [UI_MENU_STICK_DEADZONE_DESC] = "手柄摇杆推动多远后游戏才会识别。如果角色或视角会自行移动,请调高此值。", + [UI_MENU_MOUSE_SENS] = "鼠标视角灵敏度", [UI_MENU_MOUSE_SENS_DESC] = "鼠标转动视角的速度。", + + [UI_BINDS_HELP] = "选中一个格子并按 A 或 Enter,然后按下键盘按键、鼠标按键或手柄按键。按 Delete 或 X 清空格子。" + "已被占用的键盘按键会移到这里;手柄按键则与被替换的按键互换。", + [UI_BINDS_COL_KEY1] = "按键 1", [UI_BINDS_COL_KEY2] = "按键 2", [UI_BINDS_COL_PAD] = "手柄", + [UI_BINDS_GROUP_BUTTONS] = "按钮", [UI_BINDS_GROUP_MOVE] = "移动", [UI_BINDS_GROUP_CAMERA] = "视角", + [UI_BINDS_PRESS_KEY] = "请为“%s”按下键盘按键或鼠标按键", [UI_BINDS_PRESS_PAD] = "请为“%s”按下手柄按键", + [UI_BINDS_CANCEL_HINT] = "按 Esc 取消,或等待 %d 秒", [UI_BINDS_TAKEN] = "%s 已从“%s”上移走", + [UI_BINDS_SWAPPED] = "“%s”与“%s”已互换", [UI_BINDS_RESET] = "重置所有按键", + [UI_BINDS_RESET_DESC] = "恢复默认的键盘按键和手柄按键。上方的按键布局将重新生效:在执行此重置之前," + "重新映射过的手柄按键会一直保持在你设定的位置。", + [UI_BIND_A] = "A", [UI_BIND_B] = "B", [UI_BIND_X] = "X", [UI_BIND_Y] = "Y", [UI_BIND_LCLICK] = "按下左摇杆", + [UI_BIND_RCLICK] = "按下右摇杆", [UI_BIND_L] = "L", [UI_BIND_R] = "R", [UI_BIND_ZL] = "ZL", [UI_BIND_ZR] = "ZR", + [UI_BIND_PLUS] = "+ 键", [UI_BIND_MINUS] = "- 键", [UI_BIND_LEFT] = "十字键左", [UI_BIND_UP] = "十字键上", + [UI_BIND_RIGHT] = "十字键右", [UI_BIND_DOWN] = "十字键下", [UI_BIND_LSTICK_LEFT] = "向左移动", + [UI_BIND_LSTICK_UP] = "向前移动", [UI_BIND_LSTICK_RIGHT] = "向右移动", [UI_BIND_LSTICK_DOWN] = "向后移动", + [UI_BIND_RSTICK_LEFT] = "视角向左", [UI_BIND_RSTICK_UP] = "视角向上", [UI_BIND_RSTICK_RIGHT] = "视角向右", + [UI_BIND_RSTICK_DOWN] = "视角向下", [UI_BIND_DESC_A] = "调查、拾取、对话。", + [UI_BIND_DESC_B] = "奔跑、取消、返回。", [UI_BIND_DESC_X] = "跳跃。", [UI_BIND_DESC_Y] = "攻击。", + [UI_BIND_DESC_LCLICK] = "蹲下。", [UI_BIND_DESC_RCLICK] = "第一人称视角。", [UI_BIND_DESC_L] = "能力。", + [UI_BIND_DESC_R] = "投掷武器。", [UI_BIND_DESC_ZL] = "举盾、锁定。", [UI_BIND_DESC_ZR] = "弓。", + [UI_BIND_DESC_PLUS] = "菜单、道具。", [UI_BIND_DESC_MINUS] = "地图。", [UI_BIND_DESC_DPAD] = "快捷选择。", + [UI_BIND_DESC_MOVE] = "像左摇杆一样移动林克。手柄的左摇杆也始终可用。", + [UI_BIND_DESC_CAMERA] = "像右摇杆一样转动视角。鼠标和手柄的右摇杆也始终可用。", [UI_KEY_SPACE] = "空格", + [UI_KEY_TAB] = "Tab", [UI_KEY_LSHIFT] = "左 Shift", [UI_KEY_LCTRL] = "左 Ctrl", [UI_KEY_UP] = "上方向键", + [UI_KEY_DOWN] = "下方向键", [UI_KEY_LEFT] = "左方向键", [UI_KEY_RIGHT] = "右方向键", [UI_KEY_MOUSE_L] = "鼠标左键", + [UI_KEY_MOUSE_R] = "鼠标右键", [UI_KEY_MOUSE_M] = "鼠标中键", [UI_KEY_MOUSE_X1] = "鼠标侧键 4", + [UI_KEY_MOUSE_X2] = "鼠标侧键 5", [UI_KEY_ENTER] = "Enter", [UI_KEY_BACKSPACE] = "Backspace", + [UI_KEY_RSHIFT] = "右 Shift", [UI_KEY_RCTRL] = "右 Ctrl", [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] = "小键盘 %s", + [UI_PAD_SOUTH] = "下方按键", [UI_PAD_EAST] = "右侧按键", [UI_PAD_WEST] = "左侧按键", [UI_PAD_NORTH] = "上方按键", + [UI_PAD_LSTICK] = "左摇杆", [UI_PAD_RSTICK] = "右摇杆", [UI_PAD_L] = "左肩键", [UI_PAD_R] = "右肩键", + [UI_PAD_START] = "Start 键", [UI_PAD_BACK] = "Back 键", [UI_PAD_DPAD_LEFT] = "十字键左", + [UI_PAD_DPAD_UP] = "十字键上", [UI_PAD_DPAD_RIGHT] = "十字键右", [UI_PAD_DPAD_DOWN] = "十字键下", + [UI_PAD_ZL] = "左扳机", [UI_PAD_ZR] = "右扳机", [UI_PAD_LPADDLE1] = "左背键", [UI_PAD_RPADDLE1] = "右背键", + [UI_PAD_LPADDLE2] = "左背键 2", [UI_PAD_RPADDLE2] = "右背键 2", [UI_PAD_CROSS] = "叉键", [UI_PAD_CIRCLE] = "圆圈键", + [UI_PAD_SQUARE] = "方块键", [UI_PAD_TRIANGLE] = "三角键", + + [UI_MENU_MENU_LANG] = "菜单语言", [UI_MENU_MENU_LANG_DESC] = "本菜单和性能叠加层的语言。", + [UI_MENU_MENU_LANG_AUTO] = "自动(跟随 Windows)", + + [UI_MENU_ADV_WARNING] = "这些设置用于测试和排查问题。除非清楚修改的原因,否则请勿改动。", + [UI_MENU_GROUP_SCHED] = "调度", [UI_MENU_GROUP_SHADERS] = "着色器与管线", [UI_MENU_GROUP_TEXMEM] = "纹理与内存", + [UI_MENU_GROUP_FIXES] = "渲染修正", [UI_MENU_GROUP_VULKAN] = "Vulkan", [UI_MENU_GROUP_DIAG] = "诊断", + [UI_MENU_ASYNC_PREEMPT] = "虚拟核心抢占", + [UI_MENU_ASYNC_PREEMPT_DESC] = "允许一个游戏线程打断同一虚拟核心上的另一个线程。", [UI_MENU_PREEMPT_OFF] = "关", + [UI_MENU_PREEMPT_ON] = "开", [UI_MENU_PREEMPT_INHERIT] = "仅继承", + [UI_MENU_REPLAY_ASYNC] = "在独立线程上准备 GPU 帧", + [UI_MENU_REPLAY_ASYNC_DESC] = "在独立线程而不是游戏线程上为 GPU 准备帧。最多增加一帧延迟。", + [UI_MENU_FREE_CORES] = "虚拟核心闸门", [UI_MENU_FREE_CORES_DESC] = "每个虚拟核心只允许运行一个线程,与主机上相同。", + [UI_MENU_TIMER_1MS] = "1 ms Windows 计时器", + [UI_MENU_TIMER_1MS_DESC] = "将系统计时器精度提高到 1 ms,使帧间隔更平稳。", + [UI_MENU_PIPE_WAIT] = "等待中绘制的处理", + [UI_MENU_PIPE_WAIT_DESC] = "“默认”保持当前的调度方式,并为等待中的绘制保留一个工作线程;“旧版(draw)”" + "使用之前的调度方式。", + [UI_MENU_PIPE_WAIT_DEFAULT] = "默认", [UI_MENU_PIPE_WAIT_DRAW] = "旧版(draw)", + [UI_MENU_PIPE_SKIP] = "管线构建期间跳过的绘制", + [UI_MENU_PIPE_SKIP_DESC] = "哪些绘制会被直接丢弃,而不是等待其管线构建完成。", [UI_MENU_PIPE_SKIP_STRICT] = "严格", + [UI_MENU_PIPE_SKIP_ANY] = "任意", [UI_MENU_PIPE_SKIP_FULLSCREEN] = "全屏通道", + [UI_MENU_LIB_PREBUILD] = "阶段库预构建", [UI_MENU_LIB_PREBUILD_DESC] = "在后台提前构建着色器阶段库。", + [UI_MENU_LIB_PREBUILD_THREADS] = "阶段库预构建线程数", + [UI_MENU_LIB_PREBUILD_THREADS_DESC] = "预构建使用的线程数;“自动”会根据你的 CPU 选择。", + [UI_MENU_PIPE_PREBUILD] = "管线预构建", [UI_MENU_PIPE_PREBUILD_DESC] = "提前构建已知的管线。", + [UI_MENU_PREWARM_XLATE] = "着色器转译预热", + [UI_MENU_PREWARM_XLATE_DESC] = "启动时转译已知着色器的线程数;“自动”使用 CPU 线程数的一半,最多 16 个。", + [UI_MENU_GPL] = "图形管线库", + [UI_MENU_GPL_DESC] = "使用 Vulkan 管线库扩展;如果你的驱动程序在此模式下出现异常,请关闭。", + [UI_MENU_ASTC] = "ASTC 纹理解码", [UI_MENU_ASTC_DESC] = "压缩的 ASTC 纹理在何处解码。", + [UI_MENU_ASTC_AUTO] = "自动", [UI_MENU_ASTC_GPU] = "GPU 着色器", [UI_MENU_ASTC_NATIVE] = "原生", + [UI_MENU_ASTC_CPU] = "CPU", [UI_MENU_MEMORY] = "GPU 内存模式", + [UI_MENU_MEMORY_DESC] = "游戏内存与 GPU 的共享方式。", [UI_MENU_MEMORY_AUTO] = "自动", + [UI_MENU_MEMORY_IMPORT] = "导入", [UI_MENU_MEMORY_MIRROR] = "镜像", [UI_MENU_MEMORY_VERIFY] = "校验", + [UI_MENU_TEX_ALIAS] = "纹理别名", + [UI_MENU_TEX_ALIAS_DESC] = "在仍在使用的纹理内存上新建纹理时,新纹理沿用原有内容,而不是从空白开始。", + [UI_MENU_TEX_VRAM_PRESSURE] = "纹理显存上限", + [UI_MENU_TEX_VRAM_PRESSURE_DESC] = "显存占用超过这个百分比时,丢弃游戏已释放的纹理(再次用到时会从存储重新载入)。" + "0 表示一律保留。", + [UI_MENU_ASTC_BC] = "ASTC 压缩为 BC3", + [UI_MENU_ASTC_BC_DESC] = "配合 GPU 解码器使用:把解码后的 ASTC 纹理重新编码为 BC3,显存占用只有四分之一。适合显存 " + "4 GB 及以下的显卡;纹理会略显块状。", + [UI_MENU_LOD_GUARD] = "LOD 保护", + [UI_MENU_LOD_GUARD_DESC] = "等游戏改写完细节层次(LOD)数据后再让 GPU 读取,防止物体在错误位置闪现," + "或远景在某一帧变平。", + [UI_MENU_FIX_C0] = "常量缓冲区修正", + [UI_MENU_FIX_C0_DESC] = "填充驱动保留的常量库 c0(存储大小、调度大小、点大小、基础实例),而不是读到零。", + [UI_MENU_FIX_ZERO] = "新 GPU 内存清零", + [UI_MENU_FIX_ZERO_DESC] = "新的 GPU 内存池初始内容为零,与 Switch 内存一致。", [UI_MENU_BIND_SKIP] = "跳过重复绑定", + [UI_MENU_BIND_SKIP_DESC] = "优化:跳过没有变化的绑定。", [UI_MENU_SHADER_MEMO] = "着色器查找缓存", + [UI_MENU_SHADER_MEMO_DESC] = "优化:记住着色器的查找结果。", [UI_MENU_PIPE_MEMO] = "管线缓存", + [UI_MENU_PIPE_MEMO_DESC] = "优化:状态重复时复用上一次绘制的管线。", [UI_MENU_TEX_MEMO] = "纹理绑定缓存", + [UI_MENU_TEX_MEMO_DESC] = "优化:在多次绘制之间记住纹理描述符。", [UI_MENU_DESC_TEMPLATE] = "描述符模板", + [UI_MENU_DESC_TEMPLATE_DESC] = "优化:批量更新描述符。", [UI_MENU_PUSH_SKIP] = "跳过重复的推送常量", + [UI_MENU_PUSH_SKIP_DESC] = "优化:跳过没有变化的推送常量。", [UI_MENU_SPLIT_DRAWS] = "提前提交 GPU 工作", + [UI_MENU_SPLIT_DRAWS_DESC] = "在渲染通道之间每隔 N 次绘制分批提交 GPU 工作,让 GPU 更早开始;0 为关闭。", + [UI_MENU_VK_VALIDATION] = "验证层", [UI_MENU_VK_VALIDATION_DESC] = "检查每一次 Vulkan 调用,会让游戏明显变慢。", + [UI_MENU_VK_VALIDATION_MISSING] = "未安装验证层。", [UI_MENU_VK_DYN_VERTEX] = "动态顶点状态", + [UI_MENU_VK_DYN_VERTEX_DESC] = "强制开启或关闭动态顶点输入;默认值取决于 GPU。", + [UI_MENU_VK_SUBGROUP_PIN] = "固定子组大小", [UI_MENU_VK_SUBGROUP_PIN_DESC] = "固定着色器的子组大小。", + [UI_MENU_TRACE] = "性能日志", [UI_MENU_TRACE_DESC] = "将每帧耗时写入文件。", [UI_MENU_FLIGHT] = "飞行记录器", + [UI_MENU_FLIGHT_DESC] = "保留一小段近期记录,在画面卡住时存盘。", [UI_MENU_FLIGHT_SPIKE_MS] = "卡顿阈值(毫秒)", + [UI_MENU_FLIGHT_SPIKE_MS_DESC] = "帧时间超过多少算作卡顿。", [UI_MENU_INPUT_RECORD] = "输入录制", + [UI_MENU_INPUT_RECORD_DESC] = "将你的输入写入文件,用于报告问题。", [UI_MENU_OPEN_LOG] = "打开日志文件夹", + [UI_MENU_OPEN_LOG_DESC] = "打开存放日志文件的文件夹。", [UI_MENU_COPY_INFO] = "复制系统信息", + [UI_MENU_COPY_INFO_DESC] = "将 GPU、驱动程序、CPU、内存和已修改的设置复制到剪贴板。", + [UI_MENU_COPY_INFO_DONE] = "已复制", [UI_MENU_ACTION_FAILED] = "操作失败", + [UI_MENU_RESET] = "将所有设置恢复为默认值", [UI_MENU_RESET_DESC] = "对所有标签页生效。", + [UI_MENU_RESET_CONFIRM] = "要将所有设置恢复为默认值吗?", [UI_MENU_RESET_YES] = "重置", [UI_MENU_RESET_NO] = "取消", + + [UI_MENU_OV_FPS] = "%.0f FPS", [UI_MENU_OV_FRAME_MS] = "%.1f ms", [UI_MENU_OV_GAME_PCT] = "游戏 %.0f%%", + [UI_MENU_OV_MAX_MS] = "最大 %.1f ms", [UI_MENU_OV_GPU] = "GPU", [UI_MENU_OV_CPU] = "CPU", [UI_MENU_OV_RAM] = "内存", + [UI_MENU_OV_VRAM] = "显存", [UI_MENU_OV_TEMP] = "温度", [UI_MENU_OV_POWER] = "功耗", [UI_MENU_OV_CLOCK] = "频率", + [UI_MENU_OV_NONE] = "-", [UI_MENU_OV_REPLAY] = "GPU 帧准备", [UI_MENU_OV_GPU_TIME] = "每帧 GPU 忙碌时间", + [UI_MENU_OV_PIPE_WAIT] = "管线等待", [UI_MENU_OV_SHADER_WAIT] = "着色器等待", [UI_MENU_OV_TEX_UPLOADS] = "纹理上传", + [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] = "游戏 %.1f GB", [UI_MENU_OV_FMT_MS] = "%.2f ms", [UI_MENU_OV_PER_FRAME] = "每帧 %.1f", + [UI_MENU_OV_WINDOW] = "窗口", [UI_MENU_OV_OUTPUT] = "游戏画面", [UI_MENU_OV_SCENE] = "3D 场景", + [UI_MENU_OV_SCALING] = "缩放", [UI_MENU_OV_LIMIT] = "帧率上限", [UI_MENU_OV_PRESENT] = "呈现方式", + [UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u,%.0f%%", + [UI_MENU_OV_FMT_FSR] = "AMD FSR 1,锐度 %d%%", [UI_MENU_OV_SCALE_NONE] = "无(1:1)", + [UI_MENU_OV_SCALE_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"); @@ -505,7 +697,6 @@ SWKBD_ONLY(text_es, "Introducir texto", "Introduce un nombre", "Caballo", "Acept "Mando: A = Aceptar, B = Cancelar"); SWKBD_ONLY(text_nl, "Tekstinvoer", "Voer een naam in", "Paard", "OK", "Annuleren", "Controller: A = OK, B = Annuleren"); SWKBD_ONLY(text_pt, "Inserir texto", "Introduz um nome", "Cavalo", "OK", "Cancelar", "Comando: A = OK, B = Cancelar"); -SWKBD_ONLY(text_zh_hans, "文字输入", "请输入名字", "马儿", "确定", "取消", "手柄:A 确定,B 取消"); SWKBD_ONLY(text_zh_hant, "文字輸入", "請輸入名字", "馬兒", "確定", "取消", "手把:A 確定,B 取消"); SWKBD_ONLY(text_ko, "문자 입력", "이름을 입력하세요", "말", "확인", "취소", "컨트롤러: A 확인, B 취소"); @@ -543,17 +734,32 @@ 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. -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, "en")) return "en"; - const char *sys = plat_ui_language(); - return sys && (!strcmp(sys, "ru") || !strncmp(sys, "ru-", 3)) ? "ru" : "en"; +// Matches "" and "-..." (a BCP 47 tag with that primary subtag or prefix). +static int tag_is(const char *tag, const char *lang) { + size_t n = strlen(lang); + return !strncmp(tag, lang, n) && (tag[n] == 0 || tag[n] == '-'); } -const char *menu_text(UiTextId id) { +const char *menu_lang_for_system(const char *tag) { + if (!tag) return "en"; + if (tag_is(tag, "ru")) return "ru"; + // Simplified Chinese: the script subtag when Windows gives one, else the regions that write it (China, Singapore). + // zh-TW, zh-HK and zh-MO write Traditional Chinese, which the menu does not have: English. + if (tag_is(tag, "zh-Hans") || tag_is(tag, "zh-CN") || tag_is(tag, "zh-SG")) return "zh-Hans"; + return "en"; +} + +// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG "en", "ru" or "zh-Hans"; anything else (unset +// included) follows the system UI language (menu_lang_for_system). +static const char *resolve_menu_lang(void) { + static const char *const langs[] = {"en", "ru", "zh-Hans"}; + const char *v = cfg_value("TOTK_MENU_LANG"); + for (size_t i = 0; v && i < sizeof langs / sizeof *langs; i++) + if (!strcmp(v, langs[i])) return langs[i]; + return menu_lang_for_system(plat_ui_language()); +} + +const char *menu_language(void) { static _Atomic(const char *) lang = "en"; static _Atomic unsigned seen = ~0u; unsigned v = cfg_version(); @@ -561,5 +767,7 @@ const char *menu_text(UiTextId id) { atomic_store_explicit(&lang, resolve_menu_lang(), memory_order_relaxed); atomic_store_explicit(&seen, v, memory_order_relaxed); } - return ui_text_in(atomic_load_explicit(&lang, memory_order_relaxed), id); + return atomic_load_explicit(&lang, memory_order_relaxed); } + +const char *menu_text(UiTextId id) { return ui_text_in(menu_language(), id); } diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 13a328b6..d4361cad 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 Simplified Chinese + // 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, @@ -173,6 +174,11 @@ 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). const char *menu_text(UiTextId id); +// The menu's catalog language: TOTK_MENU_LANG ("en", "ru" or "zh-Hans"); unset, menu_lang_for_system of the system UI +// language. Follows a live change of the setting. +const char *menu_language(void); +// The menu language for a system UI language tag: "ru" for Russian, "zh-Hans" for Simplified Chinese (zh-Hans..., +// zh-CN, zh-SG), else "en". +const char *menu_lang_for_system(const char *tag); diff --git a/tests/installer_gui_test.py b/tests/installer_gui_test.py index 4eb9c228..6df0d1c0 100644 --- a/tests/installer_gui_test.py +++ b/tests/installer_gui_test.py @@ -31,8 +31,9 @@ from installer import state as statefile # noqa: E402 from installer.events import Reporter # noqa: E402 from installer.runner import Context # noqa: E402 from installer.steps import all_steps # noqa: E402 -from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, Catalog, Form, Model, Process, # noqa: E402 - amount, describe_event, parse_line, windows_ui_language) +from installer.guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, # noqa: E402 + UI_LANGUAGES, Catalog, Form, Model, Process, amount, default_game_language, + describe_event, parse_line, ui_language_for_langid, windows_ui_language) INSTALLED = ROOT / 'build' / 'install-test' FIXTURE = ROOT / 'build' / 'inst-gui' / 'e2e-install' @@ -233,12 +234,27 @@ class FormTest(unittest.TestCase): class CatalogTest(unittest.TestCase): - def test_russian_covers_english_with_the_same_placeholders(self): - en, ru = Catalog('en').english, Catalog('ru').texts - self.assertEqual(sorted(set(en) - set(ru)), []) - self.assertEqual(sorted(set(ru) - set(en)), []) - holes = [k for k in en if sorted(re.findall(r'\{\w+\}', en[k])) != sorted(re.findall(r'\{\w+\}', ru[k]))] - self.assertEqual(holes, []) + def test_every_language_covers_english_with_the_same_placeholders(self): + en = Catalog('en').english + for lang in UI_LANGUAGES[1:]: + with self.subTest(lang=lang): + other = Catalog(lang).texts + self.assertEqual(sorted(set(en) - set(other)), []) + self.assertEqual(sorted(set(other) - set(en)), []) + holes = [k for k in en + if sorted(re.findall(r'\{\w+\}', en[k])) != sorted(re.findall(r'\{\w+\}', other[k]))] + self.assertEqual(holes, []) + + def test_language_names_tell_the_codes_apart(self): + # gui.App.selected_lang maps the shown name back to its code across every window language + names = {} + for lang in UI_LANGUAGES: + cat = Catalog(lang) + for id in cat.english: + if id.startswith('lang.'): + names.setdefault(cat(id), set()).add(id) + self.assertEqual({n: ids for n, ids in names.items() if len(ids) > 1}, {}) + self.assertEqual(sorted(UI_LANGUAGE_LABELS), sorted(UI_LANGUAGES)) def test_every_id_the_window_uses_exists(self): cat = Catalog('en') @@ -246,12 +262,13 @@ class CatalogTest(unittest.TestCase): 'process_died', 'result_ok', 'result_failed', 'result_cancelled')] ids += [f'step.{s}' for s in ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup')] ids += ['ui.state_' + n for n in ('started', 'done', 'skipped', 'pending', 'running', 'failed')] - for lang in ('en', 'ru'): + for lang in UI_LANGUAGES: cat.set_language(lang) + self.assertEqual(cat.lang, lang) self.assertEqual([i for i in ids if not cat.has(i)], []) def test_codes_become_names(self): - for lang, korean in (('en', 'Korean'), ('ru', 'Корейский')): + for lang, korean in (('en', 'Korean'), ('ru', 'Корейский'), ('zh-Hans', '韩语')): cat = Catalog(lang) self.assertIn(korean, cat('warn.lang_needs_fonts', lang='ko')) self.assertNotIn(' ko ', cat('warn.lang_needs_fonts', lang='ko')) @@ -280,7 +297,16 @@ class CatalogTest(unittest.TestCase): self.assertEqual(describe_event(cat, {'type': 'start'}), '') def test_windows_language_is_a_known_value(self): - self.assertIn(windows_ui_language(), ('en', 'ru')) + self.assertIn(windows_ui_language(), UI_LANGUAGES) + + def test_windows_langid_picks_the_window_language(self): + for langid, lang in ((0x0419, 'ru'), (0x0819, 'ru'), (0x0804, 'zh-Hans'), (0x1004, 'zh-Hans'), + (0x0404, 'en'), (0x0c04, 'en'), (0x1404, 'en'), (0x0409, 'en'), (0x0411, 'en')): + self.assertEqual(ui_language_for_langid(langid), lang, hex(langid)) + + def test_chinese_window_starts_with_a_game_language_that_needs_no_shared_fonts(self): + self.assertEqual(default_game_language('zh-Hans'), 'en-US') + self.assertEqual(default_game_language('ru'), 'ru') BREAK_CHILD = 'import time\nprint("ready", flush=True)\ntime.sleep(60)\n' diff --git a/tools/make_release.py b/tools/make_release.py index 067c2b34..85483a5e 100644 --- a/tools/make_release.py +++ b/tools/make_release.py @@ -390,12 +390,14 @@ def c_wide(text): def launcher_header(path): - """launcher_text.h: the launcher's two messages in English and Russian, taken from the installer's catalog.""" - lines = ['/* generated by tools/make_release.py from installer/text/{en,ru}.json */'] - for lang in ('en', 'ru'): + """launcher_text.h: the launcher's two messages in English, Russian and Simplified Chinese, taken from the + installer's catalog (macro suffixes EN, RU, ZH_HANS).""" + lines = ['/* generated by tools/make_release.py from installer/text/{en,ru,zh-Hans}.json */'] + for lang in ('en', 'ru', 'zh-Hans'): texts = json.loads((ROOT / 'installer' / 'text' / f'{lang}.json').read_text(encoding='utf-8')) + suffix = lang.upper().replace('-', '_') for key in ('title', 'python_missing'): - lines.append(f'#define LAUNCHER_{key.upper()}_{lang.upper()} {c_wide(texts["launcher." + key])}') + lines.append(f'#define LAUNCHER_{key.upper()}_{suffix} {c_wide(texts["launcher." + key])}') path.parent.mkdir(parents=True, exist_ok=True) path.write_text('\n'.join(lines) + '\n', encoding='ascii') diff --git a/totk.ini.example b/totk.ini.example index aba2432d..fb2d9704 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 zh-Hans (Simplified Chinese). Default: the Windows display +# language, English if it is none of them (Traditional Chinese included). # menu_lang = en [audio] From f7d563db05eefcfc12afeb12d7490ac60dd89051 Mon Sep 17 00:00:00 2001 From: Deon Fouche Date: Sat, 31 Oct 2026 18:55:39 +1000 Subject: [PATCH 017/177] 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-