diff --git a/README.md b/README.md index 01f98617..fb6a7dc2 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,12 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - Game updates 1.1.1, 1.2.1 and 1.4.3; 1.2.1 and 1.4.3 saves carry over between them - 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 +- HDR10 output with peak, game and HUD brightness settings - 16:10 (Steam Deck, handhelds), 21:9 and 32:9 (ultrawide) game resolutions, with the camera and the interface in that shape +- Anisotropic texture filtering up to 16x, for sharp ground into the distance - In-game settings menu (F1) and performance overlay (F10) - 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 +- Xbox button prompts: LB, RB, LT, RT, Menu and View, and A, B, X and Y as labelled on the button to press, with either button layout - Shaders prepared at install instead of during play ## Planned @@ -34,7 +36,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). ### Windows -Requirements: Windows 10 or later, an x86-64 CPU with AVX2, a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, about 36 GiB free during setup (20 GiB after). +Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines get a faster build), a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, about 36 GiB free during setup (20 GiB after). 1. Download `TotK-Setup--windows.zip` from [Releases](../../releases/latest) and unpack it. 2. Start `TotK-Setup.exe`. If SmartScreen warns about an unsigned app, choose *More info*, then *Run anyway*. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 27c6106e..2d890f97 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -11,6 +11,8 @@ 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) | +| RenoDX TotK mod (game mod by souperman9, tonemapper by Musa, RenoDX framework by ShortFuse, RenoVK fork by Ritsu): the approach of the HDR tonemap (the game's 1 - e^-x curve kept below a pivot and continued along its tangent above it, the saturation grade applied to the colour scaled into 0..1) and the observation that the passes after the tonemap keep values above 1. No code copied; the shader is our own | https://github.com/clshortfuse/renodx @ `b6f87272ad1bfdc0e6444910a93606815944a085` (`src/games/totk/tonemap.slang`, `addon.cpp`), Copyright (c) 2025 Carlos Lopez Jr. | MIT | `runtime/shaders/hdr_tonemap.frag`, `runtime/vk_hdr.c` | | 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` | @@ -37,6 +39,7 @@ Code copied or adapted from another project is listed here with its source, the | AMD FidelityFX Super Resolution 1.0 (`ffx_a.h`, `ffx_fsr1.h`, unmodified; licence text in `runtime/shaders/ffx/LICENSE.txt`) | https://github.com/GPUOpen-Effects/FidelityFX-FSR @ `a21ffb8f6c13233ba336352bdff293894c706575`, Copyright (c) 2021 Advanced Micro Devices, Inc. | MIT | `runtime/shaders/ffx/`, `runtime/shaders/fsr_easu.comp`, `runtime/shaders/fsr_rcas.comp` (compiled into `runtime/fsr_easu_spv.h`, `runtime/fsr_rcas_spv.h`) | | AMD Display Library (ADL) declarations: `AdapterInfo`, `ADLSingleSensorData`, `ADLPMLogDataOutput`, the `ADL_PMLOG_*` sensor numbers and the `ADL2_*` function signatures | https://github.com/GPUOpen-LibrariesAndSDKs/display-library @ `84c881cb2136f04287eb3af12de00a9e2867aa9e` (`include/adl_structures.h`, `include/adl_defines.h`, `include/adl_sdk.h`), Copyright (c) 2016 - 2022 Advanced Micro Devices, Inc. | MIT | `runtime/perfmon.c` | | Zstandard 1.5.7 (MSYS2 `mingw-w64-ucrt-x86_64-zstd`), static link | https://github.com/facebook/zstd, Copyright (c) Meta Platforms, Inc. and affiliates | BSD-3-Clause | `runtime/resolution.c` (the HeapDef table), `runtime/ov_zstd.c` (the game's zstd frames decoded on the host) | +| musl `fma.c`, `fmaf.c` and `scalbn.c`, adapted into one file for the x86-64-v2 build | https://github.com/kraj/musl @ `5a56ad13e1e0790c06122978aad2a14d6b9efc1a` (mirror of https://git.musl-libc.org/cgit/musl), Copyright (c) 2005-2020 Rich Felker and contributors | MIT | `runtime/fma.c` (the correctly rounded fma/fmaf the FP lowering needs on CPUs without FMA3) | ## Compiler runtime in a source build @@ -67,7 +70,7 @@ These tools run on the developer's or player's machine during the build. They ar | Tcl/Tk 9.0.4, rebuilt with Xft for the Linux installer | https://github.com/tcltk/tcl and https://github.com/tcltk/tk, tag `core-9-0-4`; archives pinned by SHA-256 in `tools/make_release_linux.py` | Tcl/Tk licence (BSD-style) | `python/lib/`; licence texts in `licenses/tcl-license.terms` and `licenses/tk-license.terms` | | libXft 2 and libXrender 1, the sniper SDK sysroot's shared libraries, bundled beside the Xft Tk of the Linux installer; their Debian `copyright` files go into `licenses/` | https://repo.steampowered.com/steamrt-images-sniper/snapshots/3.0.20261021.266025/ | HPND (MIT-style) | `python/lib/`; `licenses/libXft-copyright.txt`, `licenses/libXrender-copyright.txt` | | 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/docs/architecture.md b/docs/architecture.md index 0b8ac510..1d814f1a 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 @@ -103,6 +103,15 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app HUD stretched over it. The `aspect` setting (`fit`, the default; `stretch`) decides what the present does when the window's shape differs from the output's: `fit` letterboxes, where a 16:9 game in a wider window used to be stretched. +- HDR (`hdr = 1`, `vk_hdr.c`). The game tonemaps its scene into an r11g11b10f target, upscales it and draws the HUD + into another float target, and a last draw copies that into the 8-bit sRGB window texture it presents. With HDR on, + the tonemap's fragment shader (recognised by its constants and resource names, not a hash) runs as + `shaders/hdr_tonemap.frag`, which keeps highlights up to the display's peak; the present reads the float target the + window texture was copied from (any other last draw into it, such as a menu or a movie, leaves the window texture, + shown at the HUD's white); a compute pass turns the picture into PQ code values in Rec. 2020 for an HDR10 + swapchain, which FSR 1 or the blit then scale; the in-game menu is drawn into an RGBA8 image and blended on at the + HUD's white. Without an HDR10 surface format (Windows with "Use HDR" off, a compositor without colour management) + the swapchain stays SDR. `TOTK_SHOTS` reads the window texture, so its pictures clip highlights in HDR. - 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/docs/building.md b/docs/building.md index 0c881d0c..e63b60d3 100644 --- a/docs/building.md +++ b/docs/building.md @@ -1,7 +1,9 @@ # Building from source -Windows 10 or later, an x86-64 CPU with AVX2, and a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`. Allow about -60 GB for the work folder. Extraction wants about 55 GB free while it runs and keeps about 35 GB afterwards. +Windows 10 or later, an x86-64 CPU with SSE4.2, and a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`. The +default build targets x86-64-v3 (AVX2/FMA); a CPU without them builds with `--cpu v2` instead and runs slower (see +"Build"). Allow about 60 GB for the work folder. Extraction wants about 55 GB free while it runs and keeps about 35 GB +afterwards. Players who only want to play can use the [installer](installer.md) instead: it builds the game on their machine without this toolchain. @@ -91,6 +93,9 @@ of them. .venv\Scripts\python tools\build_game.py --version ``` + `--cpu v2` targets x86-64-v2 (SSE4.2, no AVX2/FMA) for older CPUs; the default `v3` needs AVX2. The v2 build links + `runtime/fma.c`, a correctly rounded software fma the FP lowering needs, and runs slower. + Lifting takes about 15 s, a clean compile about 200 s on 24 threads; later builds recompile only what changed. A compiler cache in front of clang shortens it further: with `SCCACHE` set to an sccache executable, `build_game.py` writes it into the ninja file ahead of `cc`, and every lift rewrites the generated chunks with the same contents, so @@ -102,9 +107,9 @@ of them. ``` `--patches` builds in the frame-rate, resolution and other patch sets, switchable at run time. The link copies `SDL3.dll`, `libiconv-2.dll` and `libopus-0.dll` next to the exe. - For Xbox button prompts, run `make_romfs_patches.py` once more with `--xbox-prompts`: it writes - `build\\romfs-patches-xbox` ([controls.md](controls.md), "Xbox button prompts"); `build_game.py` copies it next - to `totk.exe` like `romfs-patches`. + For Xbox button prompts, run `make_romfs_patches.py` twice more, with `--prompts xbox` and `--prompts xbox-label`: + they write `build\\romfs-patches-xbox` and `romfs-patches-xbox-label` ([controls.md](controls.md), "Xbox + button prompts"), which `build_game.py` copies next to `totk.exe` like `romfs-patches`. 6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`) for the shared shader list: @@ -189,6 +194,10 @@ Before a commit: `git config core.hooksPath .githooks` runs it before each local commit. - `build\\totk.exe --selftest`: layout, dispatch table and host-function registry, without game files. +A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes +`.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game +files); a change to the settings passes `totk.exe --probe-cfg`. + The lifter (`recomp/`) and the CPU headers (`runtime/cpu.h`, `runtime/simd.h`) are checked against Unicorn. Every lifter change passes these, all run with `.venv`: @@ -202,6 +211,9 @@ change passes these, all run with `.venv`: | `tests\excl_mt.py` | the exclusive monitor helpers under contention and ABA, on several threads | no | | `tests\jumptables_check.py` | `recomp/jumptables.py` against a Unicorn oracle; must report 0 disagreements, on 1.4.3 too | yes | +A `--cpu v2` build passes the same differential tests with `--cflags=-march=x86-64-v2`; they compile `runtime/fma.c` +too, so they check the software fma the v2 build links rather than the C runtime's. + Runtime probes, each a mode of `totk.exe` (the list is at the top of `runtime/main.c`): `--probe-kernel`, `--probe-vkexec`, `--probe-nvn-tex` and `--probe-shader` cover most runtime changes. `--probe-shader` and the draw part of `--probe-vkexec` translate shaders of the census below: they look for `build//shaders/jobs.json` of the diff --git a/docs/controls.md b/docs/controls.md index 3cd4082c..c1c9cead 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -7,9 +7,8 @@ Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into - `nintendo`: by position, as on a Switch (the table below). - `xbox`: south A, east B, west X, north Y, as an Xbox pad labels them; on a PlayStation pad cross is A, circle B, square X, triangle Y. - `auto` (default): `nintendo` for a pad whose east button SDL reports labelled A (Switch Pro Controller, Nintendo-layout pads), `xbox` for the others. -- `xbox_prompts`: the buttons as `nintendo`, and the game's prompts name the Xbox labels (see Xbox button prompts below). -The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. With `nintendo`, `xbox` and `auto` the game's button prompts stay Switch letters; `xbox_prompts` changes them. +The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. Which controller's buttons the game's prompts show is `TOTK_PROMPTS` (see Xbox button prompts below). 0.1.9's `pad_layout = xbox_prompts` is read as `pad_layout = nintendo` with `prompts = xbox`, and the menu writes it that way. | Switch | Gamepad (by position, Nintendo layout) | Keyboard and mouse | Action in the world | |---|---|---|---| @@ -33,16 +32,29 @@ Esc is unbound in the game; it opens the settings menu and releases the mouse cu ## Xbox button prompts -`pad_layout = xbox_prompts` (*Xbox prompts (A right)* on the Controls tab) is for an Xbox pad played by position. The buttons work as with `nintendo`: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel). The letters the game shows are swapped to match the labels, A with B and X with Y, so each prompt names the button to press. The other layouts leave the prompts alone: with `xbox` the Switch letters already match the labels. +`TOTK_PROMPTS` (`prompts`, the *Button prompts* row on the Controls tab, read at start) picks the controller whose buttons the game's prompts show: `nintendo` (default) keeps the game's own, `xbox` shows an Xbox controller's. -The swapped letters are part of the game's textures, fonts and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the letter the game draws for it, and the prompt then names the wrong button. Use `xbox_prompts` with the default bindings. +- L, R, ZL, ZR, Plus and Minus become LB, RB, LT, RT, Menu and View, and the d-pad prompts a cross with an arrow for each direction meant. The letters on the keys are cut out in the game's own text font. +- A, B, X and Y name the label of the button the pad layout presses, so each prompt names the button to press. `pad_layout = nintendo` plays an Xbox pad by position: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel), so the prompts swap A with B and X with Y. `xbox` and `auto` put Switch A on the button labelled A, and the letters stay. -The buttons change at once, but the game reads its UI archive and fonts once at boot, so the prompts change at the next start (the menu says *prompts change after restart*). `xbox_prompts` loads `romfs-patches-xbox` next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`): the same 60 fps patches, with the swap made from the game's own files by `tools/make_romfs_patches.py --xbox-prompts`, which the setup runs next to the plain one: +| Switch | `nintendo` layout | `xbox` or `auto` layout | +|---|---|---| +| A, B, X, Y | B, A, Y, X | A, B, X, Y | +| L, R | LB, RB | LB, RB | +| ZL, ZR | LT, RT | LT, RT | +| Plus, Minus | Menu, View | Menu, View | +| D-pad | cross | cross | -- the action prompt (`DoCommand_00`) draws the letter images `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped, in a diamond that names the other face buttons. The diamond's letters are text the game takes from `LayoutMsg/DoCommand_00.msbt` of each language's `Mals` archive (and the layout's own text panes behind it); both are swapped. The diamond's shape shows the button's position and stays. -- every other prompt is text in the button font (`scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`, glyphs U+E040 to U+E043); the A and B, X and Y glyphs are swapped. +The action prompt (`DoCommand_00`) shows its button in a diamond whose shape gives the face buttons' positions as on a Switch, with the other three letters around it. With `nintendo` its letters are swapped with the rest and every one names the button in that place. With `xbox` and `auto` the letters are right but the diamond keeps the Switch positions: A shows on its right, while the button labelled A is at the bottom. The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations). -Without the folder (an install made by an older setup, or one where the setup could not prepare it and showed a warning) the menu says the files are missing, the log has `RomFS overlay: pad_layout = xbox_prompts, but ...`, and the Switch prompts stay; running the setup again on the install folder writes it. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version --xbox-prompts` writes `build\\romfs-patches-xbox`. +The prompts are part of the game's fonts, textures and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the prompt the game draws for it, which then names the wrong button. Use the Xbox prompts with the default bindings. + +The game reads its UI archive and fonts once at boot, so the prompts change at the next start, also after `pad_layout` changes between `nintendo` and the others (the menu says *prompts change after restart*); the buttons change at once. Under that note the menu offers *Restart now*: after a confirmation it writes `totk.ini`, closes the game as *Quit game* does and starts the game again with the same command line, which waits until the old process is gone before it opens the log and the saves (`runtime/gfx_present.c`, `gfx_window_closed`; `plat_restart` and `plat_restart_wait` in `runtime/platform/win32.c` and `linux.c`). Progress since the last save is lost, as with *Quit game*; while the game writes a save, the confirmation waits. With `prompts = xbox` the game loads `romfs-patches-xbox` (`pad_layout = nintendo`) or `romfs-patches-xbox-label` (`xbox`, `auto`) next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`; `runtime/input_map.c`, `input_prompts_folder`): the same 60 fps patches, with the prompts drawn from the game's own files by `tools/make_romfs_patches.py --prompts xbox` or `--prompts xbox-label` (`tools/button_icons.py`, after MacNativeGames' `make_button_icons.py`), which the setup runs next to the plain one: + +- every prompt but the button guide in play is text in the button font, `scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`: glyphs U+E040 to U+E043 (A B X Y), U+E044 to U+E047 (L R ZL ZR), U+E04B and U+E04C (Plus, Minus), U+E049 and U+E060 to U+E065 (the d-pad). fontTools writes the font again, so the archives grow and the folder also carries the resource size table (`System/Resource/ResourceSizeTable.Product....rsizetable.zs`) with their entries raised by as much; without that the game stops at start. +- the button guide in play draws L and ZL from the images `Nt_KeyTexL_00` and `Nt_KeyTexZL_00` of the Common archive's `timg/__Combined.bntx`, painted with the same icons. The action prompt draws its button from `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped for `nintendo`, and the diamond's letters are text the game takes from `LayoutMsg/DoCommand_00.msbt` of each language's `Mals` archive (and the layout's own text panes behind it), swapped the same way. + +The Switch prompts stay, with a note under *Button prompts* and a `RomFS overlay: ...` line in the log, when the folder is missing (an install made by an older setup, or one where the setup could not prepare it and showed a warning; running the setup again on the install folder writes it), when it fails its check, with a game resolution of another shape than 16:9 (its own UI layout wins; 16:10 and 21:9), and when the `romfs_mods` folder replaces one of its files: `romfs-patches` then loads in its place, where two overlays replacing one file would stop the game. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version --prompts xbox` (and `--prompts xbox-label`) writes `build\\romfs-patches-xbox` (`-label`); it needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`. ## Window keys diff --git a/docs/installer.md b/docs/installer.md index 792f7453..fd7ba3b1 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -42,20 +42,22 @@ loads the saves 1.4.3 wrote. 1. **Check** before writing anything: the files open with the keys, the update is 1.1.1, 1.2.1 or 1.4.3 (by hash, as `tools/extract.py`), the keys are new enough for the update, enough space is free on the target disk (about 36 GiB at the peak of a - first install, 20 GiB after it), the CPU has - AVX2 (`-march=x86-64-v3`), a Vulkan 1.3 GPU exists. Each failure is one clear message. + first install, 20 GiB after it), the CPU is at least x86-64-v2 (SSE4.2; with AVX2/FMA the faster `v3` build is used, + otherwise the `v2` one), a Vulkan 1.3 GPU exists. Each failure is one clear message. 2. **Extract** ExeFS and RomFS into the install folder and verify the hashes. 3. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into a temp folder next to the installer. 4. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS hashes and the game version's patch page) and link - them with the prebuilt runtime library into `totk.exe` (`build_game.py --runtime-lib`; about 3 min on 24 cores). + them with the prebuilt runtime library for the host's level (`libtotkrt.a` or `libtotkrt-v2.a`) into `totk.exe` + (`build_game.py --runtime-lib`; about 3 min on 24 cores). 5. **Prepare** the RomFS patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`, `totk.exe --prepare-shaders`) in the install folder, then fold the shader cache's loose files (four per shader, about 117,000) into `shader-cache/shader-cache.pack` (`tools/pack_shader_cache.py`). totk.exe reads the pack first and writes the translations it makes in play as loose files; running the tool again with the game closed folds those in. - The patches are written twice: `romfs-patches` and `romfs-patches-xbox` (`--xbox-prompts`, the A/B and X/Y prompts - swapped for `pad_layout = xbox_prompts`). + The patches are written three times: `romfs-patches`, and `romfs-patches-xbox` and `romfs-patches-xbox-label` + (`--prompts`: Xbox button prompts for `prompts = xbox`, the first for `pad_layout = nintendo`, the second for `xbox` + and `auto`). The two Xbox folders are optional: when one cannot be made, the setup warns and finishes. When the graphics driver crashes while building the shaders, `prepare_shaders.py` runs that part again without the variants it was building ([building.md](building.md), step 6), and the setup finishes with a warning that names how many were left out. @@ -102,7 +104,8 @@ installer/ the installer: steps, CLI, window, en/ru 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) -runtime/ libtotkrt.a and the headers the generated code and modules.c/romfs.c/patches.c include +runtime/ libtotkrt.a, libtotkrt-v2.a and the headers the generated code and modules.c/romfs.c/patches.c + include bin/ totk_xlate.exe, hactool.exe, SDL3.dll, libopus-0.dll, ninja.exe data/ shader_list.tsv (MacNativeGames, MIT) THIRD_PARTY_NOTICES.md @@ -130,8 +133,8 @@ python/ python-build-standalone 3.14 (with tkinter) + the installe tools/ and recomp/ on sys.path llvm/ LLVM 23 (clang, lld, llvm-ar) and llvm/sysroot: the files of the Steam Runtime 3 "sniper" SDK the game's compile and link read (about 130 files) -runtime/ libtotkrt.a, headers, the install-side sources, totk.png; deps/ with the Vulkan headers, VMA and a - static zstd +runtime/ libtotkrt.a, libtotkrt-v2.a, headers, the install-side sources, totk.png; deps/ with the Vulkan + headers, VMA and a static zstd bin/ totk_xlate, hactool, ninja, libSDL3.so.0 ``` diff --git a/docs/tester-guide.md b/docs/tester-guide.md index a1cab09e..08607ae6 100644 --- a/docs/tester-guide.md +++ b/docs/tester-guide.md @@ -6,7 +6,8 @@ from it may be shared. ## What you need -- Windows 10 or later, an x86-64 CPU with AVX2, about 60 GB free. +- Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA recommended: they build the default, faster version), about + 60 GB free. - A GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, with a current driver. - *Tears of the Kingdom* base game (1.0.0) and the 1.1.1, 1.2.1 or 1.4.3 update, dumped from your own Switch as NSP or XCI. - `prod.keys` dumped from your own Switch. Never send it to anyone, and never paste it into a log or an issue. diff --git a/installer/hostcheck.c b/installer/hostcheck.c index 6cd08332..d3099271 100644 --- a/installer/hostcheck.c +++ b/installer/hostcheck.c @@ -1,5 +1,5 @@ // Host check of the installer's first step, compiled with the bundled clang at install time: does the CPU run -// -march=x86-64-v3 code, and does a Vulkan 1.3 device exist. Prints one JSON object on stdout. +// -march=x86-64-v3 code (or only x86-64-v2), and does a Vulkan 1.3 device exist. Prints one JSON object on stdout. // The Vulkan loader is opened at run time, so a machine without one gets "loader": false instead of a failed start. #include #include @@ -25,10 +25,24 @@ static void json_string(const char *s) { putchar('"'); } +// The x86-64-v2 level from CPUID: SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CMPXCHG16B and LAHF/SAHF. Every CPU with +// SSE4.2 has the others, but the level is what the v2 build is compiled for, so check them all. +static int x86_64_v2(void) { + unsigned a, b, c, d; + if (!__get_cpuid(1, &a, &b, &c, &d)) return 0; + const unsigned sse3 = 1u << 0, ssse3 = 1u << 9, cx16 = 1u << 13, sse41 = 1u << 19, sse42 = 1u << 20, + popcnt = 1u << 23; + if ((c & (sse3 | ssse3 | cx16 | sse41 | sse42 | popcnt)) != (sse3 | ssse3 | cx16 | sse41 | sse42 | popcnt)) + return 0; + if (!__get_cpuid(0x80000001, &a, &b, &c, &d)) return 0; + return (c & (1u << 0)) != 0; // LAHF/SAHF +} + // The x86-64-v3 level from CPUID: AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT and MOVBE, with the OS saving the YMM state. // Not __builtin_cpu_supports("x86-64-v3"): clang reads that from the C runtime's CPU model, and libgcc before GCC 12 // (the Linux release's sysroot has GCC 10) has no level bits, so it answers false on every CPU. static int x86_64_v3(void) { + if (!x86_64_v2()) return 0; unsigned a, b, c, d; if (!__get_cpuid(1, &a, &b, &c, &d)) return 0; const unsigned fma = 1u << 12, movbe = 1u << 22, osxsave = 1u << 27, avx = 1u << 28, f16c = 1u << 29; @@ -44,7 +58,8 @@ static int x86_64_v3(void) { } int main(void) { - printf("{\"x86_64_v3\": %s, ", x86_64_v3() ? "true" : "false"); + printf("{\"x86_64_v2\": %s, \"x86_64_v3\": %s, ", x86_64_v2() ? "true" : "false", + x86_64_v3() ? "true" : "false"); void *lib = open_lib(); PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)lib_sym(lib, "vkGetInstanceProcAddr") : NULL; if (!gipa) { diff --git a/installer/layout.py b/installer/layout.py index 7f31443e..0bd49839 100644 --- a/installer/layout.py +++ b/installer/layout.py @@ -7,7 +7,8 @@ Release (docs/installer.md "Release layout"), root = the unpacked folder: recomp/, tools/ the lifter and the scripts; recomp/patches-.txt, tools/data/expected-v.json for each supported update (SUPPORTED) llvm/ llvm-mingw (bin/clang.exe) - runtime/ libtotkrt.a, the headers, install-side sources (romfs.c, patches.c, ov_zstd.c) and totk.ico; runtime/deps/ holds + runtime/ libtotkrt.a and libtotkrt-v2.a (x86-64-v3 / v2), the headers, install-side sources (romfs.c, + patches.c, ov_zstd.c) and totk.ico; runtime/deps/ holds include/ + lib/ of Vulkan, SDL3, Opus, libvpx and VMA (build_game.py --deps) bin/ totk_xlate.exe (+ totk_xlate.id), hactool.exe, ninja.exe, SDL3.dll, libopus-0.dll data/shader_list.tsv the MacNativeGames shader list @@ -21,8 +22,8 @@ against), runtime/deps/ with include/ and the static Opus, libvpx and zstd, bin/ Dev mode, root = a repository checkout (no python/python.exe): build/py314-embed/py/python.exe (the embeddable Python the release ships, with the same packages), else this Python; toolchain/llvm-mingw-*/ and toolchain/deps-mingw; -runtime/ as the sources with build/install-rtlib/libtotkrt.a (tools/build_game.py --make-runtime-lib --out -build/install-rtlib); MSYS2 UCRT64 ninja.exe; toolchain/hactool; build/xlate/totk_xlate.exe; the shader list from +runtime/ as the sources with build/install-rtlib/libtotkrt.a and libtotkrt-v2.a (tools/build_game.py --make-runtime-lib +--out build/install-rtlib, once per --cpu); MSYS2 UCRT64 ninja.exe; toolchain/hactool; build/xlate/totk_xlate.exe; the shader list from refs/MacNativeGames; build/install-temp. The version is VERSION with -dev and the commit: 0.1.0-dev+973c626. On Linux, dev mode takes clang, lld and ninja from PATH and the system's libraries (no deps folder, no SDL3 copy). """ @@ -64,11 +65,20 @@ class Layout: ini_example: Path | None = None temp: Path | None = None sysroot: Path | None = None # Linux release: what the game links against, instead of the host's + runtime_lib_v2: Path | None = None # libtotkrt-v2.a: the runtime for CPUs without AVX2 (build_game.py --cpu v2) @property def clang(self): return self.llvm / 'bin' / ('clang' + EXE) + def runtime_lib_for(self, cpu): + """The prebuilt runtime library for cpu (v2 or v3). None in dev mode when it was not built: the runtime is + then compiled from the sources in runtime/ instead.""" + lib = self.runtime_lib_v2 if cpu == 'v2' else self.runtime_lib + if lib and lib.is_file(): + return lib + return None if self.dev else lib + def patches(self, version): """The code patch table for recomp/gen.py.""" return self.recomp / f'patches-{version_tag(version)}.txt' @@ -77,13 +87,16 @@ class Layout: """The expected hashes of the update.""" return self.tools / 'data' / f'expected-v{version}.json' - def missing(self): - """Paths the steps need that do not exist.""" + def missing(self, cpu='v3'): + """Paths the steps need that do not exist. cpu picks the runtime library the host will use.""" + lib = self.runtime_lib_for(cpu) need = [self.python, self.tools / 'extract.py', self.tools / 'build_game.py', self.tools / 'prepare_shaders.py', self.tools / 'pack_shader_cache.py', self.tools / 'make_romfs_patches.py', self.tools / 'ultrawide_layout.py', + self.tools / 'button_icons.py', self.recomp / 'gen.py', self.clang, - *((self.deps / 'include', self.deps / 'lib') if self.deps else ()), self.runtime, self.runtime_lib, self.ninja, self.hactool, + *((self.deps / 'include', self.deps / 'lib') if self.deps else ()), self.runtime, *([lib] if lib else ()), + self.ninja, self.hactool, self.xlate, *self.dlls, *(f(v) for v in SUPPORTED for f in (self.patches, self.expected))] if self.shader_list: need.append(self.shader_list) @@ -109,6 +122,7 @@ def release_layout(root): tools=root / 'tools', recomp=root / 'recomp', llvm=root / 'llvm', deps=root / 'runtime' / 'deps', runtime=root / 'runtime', runtime_lib=root / 'runtime' / 'libtotkrt.a', + runtime_lib_v2=root / 'runtime' / 'libtotkrt-v2.a', ninja=root / 'bin' / ('ninja' + EXE), hactool=root / 'bin' / ('hactool' + EXE), xlate=root / 'bin' / ('totk_xlate' + EXE), dlls=(root / 'bin' / 'SDL3.dll', root / 'bin' / 'libopus-0.dll') if WIN else (root / 'bin' / 'libSDL3.so.0',), @@ -134,6 +148,7 @@ def dev_layout(root): tools=root / 'tools', recomp=root / 'recomp', llvm=trees[-1] if trees else root / 'toolchain' / 'llvm-mingw-missing', deps=deps, runtime=root / 'runtime', runtime_lib=root / 'build' / 'install-rtlib' / 'libtotkrt.a', + runtime_lib_v2=root / 'build' / 'install-rtlib' / 'libtotkrt-v2.a', ninja=UCRT / ('ninja' + EXE), hactool=root / 'toolchain' / 'hactool' / ('hactool' + EXE), xlate=root / 'build' / 'xlate' / ('totk_xlate' + EXE), dlls=tuple(sorted((deps / 'bin').glob('*.dll'))), @@ -153,6 +168,7 @@ def dev_layout_posix(root): python=Path(sys.executable), tools=root / 'tools', recomp=root / 'recomp', llvm=Path(clang).parent.parent if clang else root / 'toolchain' / 'clang-missing', deps=None, runtime=root / 'runtime', runtime_lib=root / 'build' / 'install-rtlib' / 'libtotkrt.a', + runtime_lib_v2=root / 'build' / 'install-rtlib' / 'libtotkrt-v2.a', ninja=Path(ninja) if ninja else root / 'toolchain' / 'ninja-missing', hactool=root / 'toolchain' / 'hactool' / 'hactool', xlate=root / 'build' / 'xlate' / 'totk_xlate', shader_list=None, ini_example=root / 'totk.ini.example', temp=root / 'build' / 'install-temp') diff --git a/installer/steps.py b/installer/steps.py index 5ef4874d..2f38f351 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -6,8 +6,8 @@ tools/prepare_shaders.py, whose output goes to /logs/-.log and here: the host check is a small C program built with the bundled clang (hostcheck.c). Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, totk.exe and its DLLs, romfs-index.bin, -romfs-patches/, romfs-patches-xbox/, totk_xlate.exe, the shader state of totk.exe --prepare-shaders, totk.ini, -totk-install.json. +romfs-patches/, romfs-patches-xbox/, romfs-patches-xbox-label/, totk_xlate.exe, the shader state of totk.exe +--prepare-shaders, totk.ini, totk-install.json. Temp folder (/-): check/ (ExeFS of both inputs, the host check), gen/ (C), build/ (objects), logs/ (kept by the cleanup). """ @@ -240,9 +240,19 @@ class Check(Step): id = 'check' always = True + def key(self, ctx): + # The compile step fingerprints the CPU level, and every key is computed before a step runs: probe the host + # here, once, so both steps see the same answer (the check step itself is always run). A failed probe is + # reported by run(), where the error names this step. + try: + self.host(ctx) + except InstallError: + pass + return '' + def run(self, ctx): layout, rep, dest = ctx.layout, ctx.reporter, ctx.dest - missing = layout.missing() + missing = layout.missing(getattr(ctx, 'cpu', 'v3')) if missing: raise InstallError('check.release_incomplete', paths=missing[:5]) if dest.exists() and not dest.is_dir(): @@ -275,6 +285,8 @@ class Check(Step): return {} def host(self, ctx): + if getattr(ctx, 'host', None) is not None: + return layout, work = ctx.layout, ctx.temp / 'check' glibc = linux_glibc() if glibc and glibc < GLIBC_NEEDED and not layout.dev: @@ -299,8 +311,10 @@ class Check(Step): except ValueError: raise InstallError('check.host_probe_failed', code=r.returncode) from None ctx.reporter.log(f'host: {r.stdout.strip()}') - if not host['x86_64_v3']: - raise InstallError('check.cpu_no_avx2') + if not host['x86_64_v2']: + raise InstallError('check.cpu_too_old') + # v3 is the faster build; v2 runs on CPUs without AVX2/FMA (runtime/fma.c supplies the fused multiply-add). + ctx.cpu = 'v3' if host['x86_64_v3'] else 'v2' if not host['loader']: raise InstallError('check.vulkan_missing') devices = host['devices'] @@ -593,11 +607,12 @@ class Compile(Step): id = 'compile' def key(self, ctx): - layout = ctx.layout + layout, cpu = ctx.layout, getattr(ctx, 'cpu', 'v3') clang = subprocess.run([str(layout.clang), '--version'], capture_output=True, text=True).stdout tools = [layout.tools / n for n in ('build_game.py', 'romfs_index.py', 'check_content.py')] - return fingerprint('compile-1', ctx.keys['lift'], layout.runtime, layout.runtime_lib, layout.deps or 'system', - layout.sysroot or 'host', *tools, clang, *[d.name for d in layout.dlls]) + return fingerprint('compile-2', cpu, layout.runtime_lib_for(cpu), ctx.keys['lift'], layout.runtime, + layout.deps or 'system', layout.sysroot or 'host', *tools, clang, + *[d.name for d in layout.dlls]) def current(self, ctx, record): exe = ctx.dest / ('totk' + EXE) @@ -621,10 +636,12 @@ class Compile(Step): rep.progress('compile', 'link', force=True) rep.progress('compile', 'compile', force=True) + cpu = getattr(ctx, 'cpu', 'v3') + lib = layout.runtime_lib_for(cpu) code, log = run_tool(ctx, 'compile', layout.tools / 'build_game.py', [ - '--gen', ctx.temp / 'gen', '--out', build, '--toolchain', layout.llvm, + '--gen', ctx.temp / 'gen', '--out', build, '--toolchain', layout.llvm, '--cpu', cpu, *(['--deps', layout.deps] if layout.deps else []), *(['--sysroot', layout.sysroot] if layout.sysroot else []), - '--runtime', layout.runtime, '--runtime-lib', layout.runtime_lib, '--ninja', layout.ninja, + '--runtime', layout.runtime, *(['--runtime-lib', lib] if lib else ()), '--ninja', layout.ninja, '--version', version_tag(game_version(ctx)), '--expected', layout.expected(game_version(ctx)), '--exefs', dest / 'exefs', '--romfs', dest / 'romfs', '--profile', dest / 'profile'], parse) @@ -638,7 +655,7 @@ class Compile(Step): replace_file(build / 'romfs-index.bin', dest / 'romfs-index.bin') for dll in layout.dlls: replace_file(dll, dest / dll.name) - return {'exe_sha256': file_sha256(dest / exe.name)} + return {'exe_sha256': file_sha256(dest / exe.name), 'cpu': cpu} # ---- 5. prepare @@ -662,7 +679,7 @@ class Prepare(Step): layout = ctx.layout xlate_id = layout.xlate.with_suffix('.id') tools = [layout.tools / n for n in ('prepare_shaders.py', 'shader_census.py', 'make_romfs_patches.py', - 'pack_shader_cache.py', 'ultrawide_layout.py')] + 'pack_shader_cache.py', 'ultrawide_layout.py', 'button_icons.py')] return fingerprint('prepare-1', ctx.keys['compile'], layout.xlate, xlate_id, shader_list_text(layout), *tools) def current(self, ctx, record): @@ -702,16 +719,23 @@ class Prepare(Step): dest / f'romfs-patches-{size}', '--aspect', size]) if code: raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log)) - # romfs-patches-xbox: the same with the A/B and X/Y prompts swapped, for pad_layout = xbox_prompts (written on - # every install, so the menu choice works without another run of the setup). Optional: when it fails, the game - # keeps the Switch prompts and the menu says the files are missing, so the setup warns and goes on. - remove(dest / 'romfs-patches-xbox') - code, log = run_tool(ctx, 'prepare-xbox', layout.tools / 'make_romfs_patches.py', - ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', - dest / 'romfs-patches-xbox', '--xbox-prompts']) - if code: - remove(dest / 'romfs-patches-xbox') - rep.warning('warn.xbox_prompts_failed', code=code, log=str(log)) + # The same with Xbox button icons in the prompts, for prompts = xbox (make_romfs_patches.py --prompts): + # romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label for xbox and auto (runtime/input_map.c + # input_prompts_folder). Both are written on every install, so the menu choices work without another run of + # the setup. Optional: when one fails, the game keeps the Switch prompts with that layout and the menu says the + # files are missing, so the setup warns once and goes on. + failed = None + for style in ('xbox', 'xbox-label'): + out = dest / f'romfs-patches-{style}' + remove(out) + code, log = run_tool(ctx, f'prepare-{style}', layout.tools / 'make_romfs_patches.py', + ['--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--out', out, + '--prompts', style]) + if code: + remove(out) + failed = failed or (code, log) + if failed: + rep.warning('warn.xbox_prompts_failed', code=failed[0], log=str(failed[1])) shader_list = layout.shader_list if not shader_list: diff --git a/installer/text/en.json b/installer/text/en.json index 167cdcfa..5833d9e7 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -44,7 +44,7 @@ "check.toolchain_broken": "The bundled compiler does not work: {detail}", "check.glibc_old": "This system's C library is glibc {version}; the setup's compiler needs {need} or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 and newer have it). Updating the system fixes this.", "check.host_probe_failed": "The computer check did not run (exit code {code}).", - "check.cpu_no_avx2": "This processor lacks AVX2 (x86-64-v3), which the game needs. Intel Haswell (2013) or AMD Excavator / Zen and newer have it.", + "check.cpu_too_old": "This processor lacks x86-64-v2 (SSE4.2, POPCNT and CMPXCHG16B), the oldest level the game is built for. Intel Nehalem (2008) or AMD Bulldozer (2011) and newer have it.", "check.vulkan_missing": "No Vulkan driver is installed. Install the latest driver for your graphics card.", "check.vulkan_no_device": "Vulkan finds no graphics card. Install the latest driver for your graphics card.", "check.vulkan_too_old": "The game needs a graphics card with Vulkan 1.3; found: {devices}. Update the graphics driver.", diff --git a/installer/text/pt-BR.json b/installer/text/pt-BR.json index 0f9791a8..b64ce005 100644 --- a/installer/text/pt-BR.json +++ b/installer/text/pt-BR.json @@ -44,7 +44,7 @@ "check.toolchain_broken": "O compilador incluído não funciona: {detail}", "check.glibc_old": "A biblioteca C deste sistema é a glibc {version}; o compilador da instalação precisa da {need} ou mais nova (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e mais novos têm). Atualizar o sistema resolve.", "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.cpu_too_old": "Este processador não tem x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), o nível mais antigo para o qual o jogo é compilado. Intel Nehalem (2008) ou AMD Bulldozer (2011) 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.", diff --git a/installer/text/ru.json b/installer/text/ru.json index f7778dee..3bf4cef4 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -44,7 +44,7 @@ "check.toolchain_broken": "Встроенный компилятор не работает: {detail}", "check.glibc_old": "Библиотека C этой системы — glibc {version}; компилятору установщика нужна {need} или новее (она есть в Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 и новее). Обновление системы это исправит.", "check.host_probe_failed": "Проверка компьютера не выполнилась (код выхода {code}).", - "check.cpu_no_avx2": "Этому процессору не хватает AVX2 (x86-64-v3), который нужен игре. AVX2 есть у Intel Haswell (2013) и новее, у AMD Excavator и Zen и новее.", + "check.cpu_too_old": "Этому процессору не хватает x86-64-v2 (SSE4.2, POPCNT и CMPXCHG16B) — минимального уровня, под который собрана игра. Он есть у Intel Nehalem (2008) и AMD Bulldozer (2011) и новее.", "check.vulkan_missing": "Драйвер Vulkan не установлен. Установите свежий драйвер видеокарты.", "check.vulkan_no_device": "Vulkan не находит видеокарту. Установите свежий драйвер видеокарты.", "check.vulkan_too_old": "Игре нужна видеокарта с Vulkan 1.3; найдено: {devices}. Обновите драйвер видеокарты.", diff --git a/runtime/camera_speed.c b/runtime/camera_speed.c new file mode 100644 index 00000000..30b21ce6 --- /dev/null +++ b/runtime/camera_speed.c @@ -0,0 +1,159 @@ +// 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.c, mouse_camera), +// which 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 4bc12865..d1fc9085 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", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", + "AB", "ANISO", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "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", @@ -38,16 +38,16 @@ static const char *const known[] = { "BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA", "COLOR_PRESET", "COLOR_SATURATION", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DEVICE_PROFILE", "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", "FOV", "FOV_PATCH", "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", + "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", "HDR_PEAK_NITS", "HDR_UI_NITS", "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", "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", + "PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "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", + "REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "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_RES", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "SWKBD_ANSWER", + "SHADER_MEMO", "SHADOW_RES", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "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", "WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", @@ -60,15 +60,17 @@ 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"}, {"FOV", "display"}, {"COLOR_PRESET", "display"}, + {"SHARPNESS", "display"}, {"ASPECT", "display"}, {"FOV", "display"}, {"ANISO", "display"}, + {"COLOR_PRESET", "display"}, {"COLOR_BRIGHTNESS", "display"}, {"COLOR_CONTRAST", "display"}, {"COLOR_SATURATION", "display"}, - {"COLOR_GAMMA", "display"}, {"SHADOW_RES", "display"}, + {"COLOR_GAMMA", "display"}, {"HDR", "display"}, {"HDR_PEAK_NITS", "display"}, {"HDR_GAME_NITS", "display"}, + {"HDR_UI_NITS", "display"}, {"SHADOW_RES", "display"}, {"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"}, {"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"}, - {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "input"}, + {"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"STICK_SENS", "input"}, + {"MOUSE_SENS", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "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"}, @@ -100,10 +102,14 @@ 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}, {"ASPECT", "fit", "fit|stretch", LIVE}, {"FOV", "100", "70..140", LIVE}, + {"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features // colour adjustment (vk_color.c); the preset is the menu's, the four values are what the present uses {"COLOR_PRESET", "default", "default|vivid|clarity|custom", LIVE}, {"COLOR_BRIGHTNESS", "0", "-30..30", LIVE}, {"COLOR_CONTRAST", "100", "70..150", LIVE}, {"COLOR_SATURATION", "100", "50..200", LIVE}, {"COLOR_GAMMA", "1", "0.8..1.2", LIVE}, + // HDR output (vk_hdr.c): on at start (the tonemap shader is swapped as shaders load); the nits apply at once + {"HDR", "0", "0|1", RESTART}, {"HDR_PEAK_NITS", "1000", "400..10000", LIVE}, {"HDR_GAME_NITS", "203", "80..500", LIVE}, + {"HDR_UI_NITS", "203", "80..500", LIVE}, {"DEVICE_PROFILE", "auto", "auto|desktop|deck", RESTART}, {"SHADOW_RES", "game", "game|512|768|1024|1536|2048", RESTART}, // Game @@ -116,10 +122,12 @@ static const CfgMeta metas[] = { // Sound, Controls, Menu {"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|xbox_prompts", LIVE}, - {"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE}, + {"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox", LIVE}, + {"PROMPTS", "nintendo", "nintendo|xbox", RESTART}, + {"STICK_DEADZONE", "8", "0..50", LIVE}, {"STICK_SENS", "1", "0.1..3", RESTART}, + {"MOUSE_SENS", "1", "0..10", LIVE}, {"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE}, - {"MENU_LANG", "", "en|ru", LIVE}, + {"MENU_LANG", "", "en|ru|pt-BR|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}, @@ -186,6 +194,24 @@ static void add(char *key, char *value, int line) { entries[n_entries++] = (CfgEntry){strdup(key), strdup(value), 0, 0}; } +// 0.1.9 had the Xbox prompts as a pad layout: pad_layout = xbox_prompts is pad_layout = nintendo with prompts = xbox. +// Read as those two, which the menu shows and the next cfg_save writes; a prompts line of the file's own wins. The +// value still works from the environment (input_pad_layout_pick, input_prompts_pick). +static void migrate(void) { + CfgEntry *layout = NULL, *prompts = NULL; + for (int i = 0; i < n_entries; i++) { + if (!strcmp(entries[i].key, "PAD_LAYOUT")) layout = &entries[i]; + if (!strcmp(entries[i].key, "PROMPTS")) prompts = &entries[i]; + } + if (!layout || strcasecmp(layout->value, "xbox_prompts")) return; + free(layout->value); + layout->value = strdup("nintendo"); + layout->dirty = 1; + if (!prompts && n_entries < CFG_MAX_KEYS) entries[n_entries++] = (CfgEntry){strdup("PROMPTS"), strdup("xbox"), 1, 0}; + rt_log("cfg: totk.ini pad_layout = xbox_prompts is read as pad_layout = nintendo and prompts = %s", + prompts ? prompts->value : "xbox"); +} + int cfg_load(const char *path) { clear(); uint64_t size = 0; @@ -209,6 +235,7 @@ int cfg_load(const char *path) { p = eol + 1; } free(data); + migrate(); return 1; } diff --git a/runtime/cfg_probe.c b/runtime/cfg_probe.c index ca7449b2..0473ce5a 100644 --- a/runtime/cfg_probe.c +++ b/runtime/cfg_probe.c @@ -279,7 +279,30 @@ int probe_cfg(void) { "pad layout: a set layout wins over the labels"); CHECK(input_pad_layout_pick("xbox_prompts", 0) == PAD_LAYOUT_NINTENDO && input_pad_layout_pick("Xbox_Prompts", 1) == PAD_LAYOUT_NINTENDO, - "pad layout: Xbox prompts keep the Nintendo positions (only the prompts change, romfs.c overlay_init)"); + "pad layout: 0.1.9's xbox_prompts keeps the Nintendo positions (only the prompts change, romfs.c overlay_init)"); + // Button prompts (input_map.c) + CHECK(input_prompts_pick(NULL, "auto") == PROMPTS_NINTENDO && input_prompts_pick("", "xbox") == PROMPTS_NINTENDO && + input_prompts_pick("Xbox", "nintendo") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox") == PROMPTS_NINTENDO, + "prompts: the game's own unless set to Xbox"); + CHECK(input_prompts_pick(NULL, "xbox_prompts") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox_prompts") == PROMPTS_NINTENDO, + "prompts: 0.1.9's pad_layout = xbox_prompts means Xbox while prompts is unset"); + CHECK(!input_prompts_folder(PROMPTS_NINTENDO, "nintendo") && !input_prompts_folder(PROMPTS_NINTENDO, "xbox"), + "prompts: the game's own need no folder"); + CHECK(EQ(input_prompts_folder(PROMPTS_XBOX, "nintendo"), "romfs-patches-xbox") && + EQ(input_prompts_folder(PROMPTS_XBOX, "xbox_prompts"), "romfs-patches-xbox") && + EQ(input_prompts_folder(PROMPTS_XBOX, "xbox"), "romfs-patches-xbox-label") && + EQ(input_prompts_folder(PROMPTS_XBOX, "auto"), "romfs-patches-xbox-label") && + EQ(input_prompts_folder(PROMPTS_XBOX, NULL), "romfs-patches-xbox-label"), + "prompts: the face buttons by position for the Nintendo layout, by label for xbox and auto"); + // romfs-patches-xbox shows A as B (tests/romfs_prompts_test.py checks the folders' contents). It is right exactly + // where the layout puts A on the east button, which an Xbox pad labels B. + input_map_reset(); + static const char *const layouts[] = {"nintendo", "xbox", "auto", "xbox_prompts"}; + for (int i = 0; i < 4; i++) { + int a_east = input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_EAST] = 1}, input_pad_layout_pick(layouts[i], 0)) == 1ull << B_A; + CHECK(a_east == EQ(input_prompts_folder(PROMPTS_XBOX, layouts[i]), "romfs-patches-xbox"), + "prompts: the folder names A as B exactly when the layout puts A on the button labelled B"); + } uint8_t pd[PAD_COUNT] = {0}; pd[PAD_SOUTH] = pd[PAD_NORTH] = 1; CHECK(input_map_pad_buttons(pd, PAD_LAYOUT_NINTENDO) == (1ull << B_B | 1ull << B_X) && @@ -370,6 +393,24 @@ int probe_cfg(void) { plat_setenv("TOTK_FREE_CORES", "1"); CHECK(cfg_bool("TOTK_FREE_CORES") == 1, "free_cores 1: on"); plat_setenv("TOTK_FREE_CORES", NULL); + // 0.1.9's pad_layout = xbox_prompts (cfg.c migrate): read as the Nintendo layout with the Xbox prompts, saved so + plat_setenv("TOTK_PAD_LAYOUT", NULL); + plat_setenv("TOTK_PROMPTS", NULL); + static const char old_layout[] = "[input]\r\npad_layout = xbox_prompts\r\n"; + CHECK(plat_file_write(path, old_layout, sizeof old_layout - 1) && cfg_load(path) == 1 && + EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "xbox"), + "0.1.9's pad_layout = xbox_prompts reads as nintendo with prompts = xbox"); + CHECK(cfg_save_to(path) == 1, "the read pad layout and prompts save"); + uint64_t saved_n = 0; + char *saved = (char *)plat_file_read(path, &saved_n); + CHECK(saved && strstr(saved, "pad_layout = nintendo") && strstr(saved, "prompts = xbox") && !strstr(saved, "xbox_prompts"), + "the next save writes the pad layout and the prompts"); + free(saved); + static const char old_layout_own[] = "[input]\r\npad_layout = xbox_prompts\r\nprompts = nintendo\r\n"; + CHECK(plat_file_write(path, old_layout_own, sizeof old_layout_own - 1) && cfg_load(path) == 1 && + EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "nintendo"), + "a prompts line of the file's own wins over 0.1.9's pad_layout = xbox_prompts"); + plat_file_delete(path); cfg_load("cfg-probe-missing.ini"); int listed = 0; for (int i = 0; cfg_meta_at(i); i++) { @@ -383,9 +424,10 @@ int probe_cfg(void) { int ok = 0; if (!m->values) ok = 1; else if (strstr(m->values, "..")) { - long lo = strtol(m->values, NULL, 10), hi = strtol(strstr(m->values, "..") + 2, NULL, 10); + // strtod: ranges such as 0.2..0.9 have fractional ends + double lo = strtod(m->values, NULL), hi = strtod(strstr(m->values, "..") + 2, NULL); double d = strtod(m->def, NULL); - ok = d >= (double)lo && d <= (double)hi; + ok = d >= lo && d <= hi; } else { size_t dl = strlen(m->def); for (const char *v = m->values; *v;) { diff --git a/runtime/cpu.h b/runtime/cpu.h index a3be39f4..207f4901 100644 --- a/runtime/cpu.h +++ b/runtime/cpu.h @@ -109,7 +109,7 @@ EXCL(16, uint16_t) EXCL(32, uint32_t) EXCL(64, uint64_t) -// Exclusive pair of two X registers: one 16-byte-aligned 128-bit access (cmpxchg16b; x86-64-v3 has CX16). +// Exclusive pair of two X registers: one 16-byte-aligned 128-bit access (cmpxchg16b; x86-64-v2 has CX16). // A pair of two W registers is a 64-bit exclusive and uses ldx64/stx64. static inline __uint128_t ldxp128(Cpu *c, uint64_t a) { __uint128_t v = __atomic_load_n((__uint128_t *)(uintptr_t)a, __ATOMIC_ACQUIRE); diff --git a/runtime/fma.c b/runtime/fma.c new file mode 100644 index 00000000..dbebdc12 --- /dev/null +++ b/runtime/fma.c @@ -0,0 +1,246 @@ +// Correctly rounded fma/fmaf for x86-64 builds without FMA3: the -march=x86-64-v2 build (docs/building.md). +// +// runtime/simd.h lowers AArch64 FMADD/FMSUB and the RECPS/RSQRTS helpers to __builtin_elementwise_fma, which clang +// turns into a call to fma/fmaf when the target has no FMA instruction. The C runtime is not a substitute: on CPUs +// without FMA3 the UCRT's software fallback is documented as rounding incorrectly by up to half an ulp, while the FP +// lowering needs the single rounding the ARM instruction gives. This file supplies it. +// +// Adapted from musl src/math/fma.c and src/math/fmaf.c (MIT, Copyright (c) 2005-2020 Rich Felker and contributors). +// The result is rounded in the MXCSR rounding mode the caller set (simd.h simd_rm_enter), and MXCSR FTZ and DAZ are +// honoured as the hardware FMA would, so runtime/simd.h's fast paths keep their assumptions: denormal inputs read as +// zero and denormal results as zero under FPCR.FZ, without a trip through the slow path. +// +// The definitions exist only where the compiler would emit the calls. A -march=x86-64-v3 build defines __FMA__ and +// emits vfmadd instead, so this file contributes nothing there. +#include + +#if defined(__x86_64__) && !defined(__FMA__) + +#include +#include + +#define MXCSR_DAZ 0x0040u +#define MXCSR_FTZ 0x8000u + +static double fma_flush_d(double x) { + union { double f; uint64_t i; } u = {x}; + if (!(u.i & 0x7ff0000000000000ull) && (u.i & 0x000fffffffffffffull)) u.i &= 0x8000000000000000ull; + return u.f; +} + +static float fma_flush_f(float x) { + union { float f; uint32_t i; } u = {x}; + if (!(u.i & 0x7f800000u) && (u.i & 0x007fffffu)) u.i &= 0x80000000u; + return u.f; +} + +// ---- float: the exact product fits in a double, so one extra term and a round-to-odd step decide the float +// rounding. Halfway and tiny results are the only ones where rounding the double first can change the float result. +float fmaf(float x, float y, float z) { + unsigned csr = _mm_getcsr(); + if (csr & MXCSR_DAZ) x = fma_flush_f(x), y = fma_flush_f(y), z = fma_flush_f(z); + double xy = (double)x * y; // exact + union { double r; uint64_t i; } u = {xy + z}; + int e = u.i >> 52 & 0x7ff; + int halfway = (u.i & 0x1fffffff) == 0x10000000; + int tiny = e <= 0x3ff - 126 && e >= 0x3ff - 149; + if (halfway || tiny) { + if (e != 0x7ff) { + // r+t is the exact sum in nearest rounding; otherwise t keeps its sign and whether it is zero, which + // is all the round-to-odd step needs. An odd sticky bit makes the final conversion round once, in + // whichever mode MXCSR asks for. + int s = u.i >> 63; + double t = s == (xy < z) ? xy - u.r + z : z - u.r + xy; + if (t) { + u.i -= s ^ (t < 0); + u.i |= 1; + } + } + } + float r = (float)u.r; + if (csr & MXCSR_FTZ) r = fma_flush_f(r); + return r; +} + +// ---- double: the significands are multiplied and aligned as integers, then converted back with one rounding. +#define ASUINT64(x) ((union { double f; uint64_t i; }){x}).i +#define ZEROINFNAN (0x7ff - 0x3ff - 52 - 1) + +struct fma_num { uint64_t m; int e; int sign; }; + +static struct fma_num fma_normalize(double x) { + uint64_t ix = ASUINT64(x); + int e = ix >> 52; + int sign = e & 0x800; + e &= 0x7ff; + if (!e) { + ix = ASUINT64(x * 0x1p63); + e = ix >> 52 & 0x7ff; + e = e ? e - 63 : 0x800; + } + ix &= (1ull << 52) - 1; + ix |= 1ull << 52; + ix <<= 1; + e -= 0x3ff + 52 + 1; + return (struct fma_num){ix, e, sign}; +} + +static void fma_mul(uint64_t *hi, uint64_t *lo, uint64_t x, uint64_t y) { + uint64_t xlo = (uint32_t)x, xhi = x >> 32; + uint64_t ylo = (uint32_t)y, yhi = y >> 32; + uint64_t t1 = xlo * ylo; + uint64_t t2 = xlo * yhi + xhi * ylo; + uint64_t t3 = xhi * yhi; + *lo = t1 + (t2 << 32); + *hi = t3 + (t2 >> 32) + (t1 > *lo); +} + +// scalbn from musl src/math/scalbn.c (MIT): the fma's final scaling, kept here so the result does not depend on the +// C runtime's version. Its multiplications honour MXCSR like any other host FP operation. +static double fma_scalbn(double x, int n) { + union { double f; uint64_t i; } u; + double y = x; + if (n > 1023) { + y *= 0x1p1023; + n -= 1023; + if (n > 1023) { + y *= 0x1p1023; + n -= 1023; + if (n > 1023) n = 1023; + } + } else if (n < -1022) { + // Make sure the final n < -53, so the subnormal range rounds only once. + y *= 0x1p-1022 * 0x1p53; + n += 1022 - 53; + if (n < -1022) { + y *= 0x1p-1022 * 0x1p53; + n += 1022 - 53; + if (n < -1022) n = -1022; + } + } + u.i = (uint64_t)(0x3ff + n) << 52; + return y * u.f; +} + +double fma(double x, double y, double z) { +#pragma STDC FENV_ACCESS ON + unsigned csr = _mm_getcsr(); + if (csr & MXCSR_DAZ) x = fma_flush_d(x), y = fma_flush_d(y), z = fma_flush_d(z); + + struct fma_num nx = fma_normalize(x), ny = fma_normalize(y), nz = fma_normalize(z); + if (nx.e >= ZEROINFNAN || ny.e >= ZEROINFNAN) return x * y + z; + if (nz.e >= ZEROINFNAN) { + if (nz.e > ZEROINFNAN) return x * y; // z == 0 + return z; + } + + uint64_t rhi, rlo, zhi, zlo; + fma_mul(&rhi, &rlo, nx.m, ny.m); + + // Align the exponents: shift z left by kz and r right by kr with kz + kr == d. + int e = nx.e + ny.e; + int d = nz.e - e; + if (d > 0) { + if (d < 64) { + zlo = nz.m << d; + zhi = nz.m >> (64 - d); + } else { + zlo = 0; + zhi = nz.m; + e = nz.e - 64; + d -= 64; + if (d == 0) { + } else if (d < 64) { + rlo = rhi << (64 - d) | rlo >> d | !!(rlo << (64 - d)); + rhi = rhi >> d; + } else { + rlo = 1; + rhi = 0; + } + } + } else { + zhi = 0; + d = -d; + if (d == 0) { + zlo = nz.m; + } else if (d < 64) { + zlo = nz.m >> d | !!(nz.m << (64 - d)); + } else { + zlo = 1; + } + } + + int sign = nx.sign ^ ny.sign; + int samesign = !(sign ^ nz.sign); + int nonzero = 1; + if (samesign) { + rlo += zlo; + rhi += zhi + (rlo < zlo); + } else { + uint64_t t = rlo; + rlo -= zlo; + rhi = rhi - zhi - (t < rlo); + if (rhi >> 63) { + rlo = -rlo; + rhi = -rhi - !!rlo; + sign = !sign; + } + nonzero = !!rhi; + } + + // Keep the top 63 bits in rhi; the last bit is sticky. + if (nonzero) { + e += 64; + d = __builtin_clzll(rhi) - 1; + rhi = rhi << d | rlo >> (64 - d) | !!(rlo << d); + } else if (rlo) { + d = __builtin_clzll(rlo) - 1; + if (d < 0) + rhi = rlo >> 1 | (rlo & 1); + else + rhi = rlo << d; + } else { + return x * y + z; // exact +-0 + } + e -= d; + + int64_t i = rhi; + if (sign) i = -i; + double r = i; // |r| is in [0x1p62, 0x1p63] + + if (e < -1022 - 62) { + // The result is subnormal before rounding. + if (e == -1022 - 63) { + double c = 0x1p63; + if (sign) c = -c; + if (r == c) { + // The smallest normal after rounding: whether it underflows depends on the architecture. A double + // to float conversion imitates the before-rounding rule the guest has. + float fltmin = 0x0.ffffff8p-63 * FLT_MIN * r; + r = DBL_MIN / FLT_MIN * fltmin; + return (csr & MXCSR_FTZ) ? fma_flush_d(r) : r; + } + // One bit is lost when scaled: add another top bit so the conversion rounds only once if inexact. + if (rhi << 53) { + i = rhi >> 1 | (rhi & 1) | 1ull << 62; + if (sign) i = -i; + r = i; + r = 2 * r - c; + // Raise underflow portably, so the compiler cannot optimize the expression away. + double tiny = DBL_MIN / FLT_MIN * r; + r += (double)(tiny * tiny) * (r - r); + } + } else { + // Only round once when scaled. + d = 10; + i = (rhi >> d | !!(rhi << (64 - d))) << d; + if (sign) i = -i; + r = i; + } + } + r = fma_scalbn(r, e); + if (csr & MXCSR_FTZ) r = fma_flush_d(r); + return r; +} + +#endif diff --git a/runtime/fs.h b/runtime/fs.h index a780e1e1..5c857e24 100644 --- a/runtime/fs.h +++ b/runtime/fs.h @@ -38,8 +38,14 @@ uint64_t romfs_file_count(void); // files in the index const char *romfs_entry(uint64_t i, uint64_t *offset, uint64_t *size); // path, image offset and size of index row i const char *romfs_image_path(void); // the romfs.bin path fs_init opened size_t romfs_overlay_count(void); -int romfs_xbox_prompts_ready(void); // romfs-patches-xbox was there at start -int romfs_xbox_prompts_active(void); // and was loaded (pad_layout = xbox_prompts at start) +// The button prompts (input_prompts_folder): the folder loaded at start, NULL for the game's own prompts; whether a +// folder had a manifest at start; and why the folder the settings asked for at start was not loaded (ROMFS_PROMPTS_OK +// for any other folder: it was not asked for). +enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROMPTS_SHAPE, ROMFS_PROMPTS_MODS, + ROMFS_PROMPTS_PATCHES }; +const char *romfs_prompts(void); +int romfs_prompts_ready(const char *folder); +int romfs_prompts_off(const char *folder); const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added); // RomFS path of overlay k void fs_trace(const char *what, const char *path); // TOTK_TRACE=fs: one line per open diff --git a/runtime/gfx.h b/runtime/gfx.h index b875bffb..f21d0d51 100644 --- a/runtime/gfx.h +++ b/runtime/gfx.h @@ -73,6 +73,9 @@ size_t gfx_shader_warm_list(GfxWarmEnt **out); // malloc'd; recorde const GfxShader *gfx_shader_load_private(const uint8_t iid[32], int *owned); void gfx_shader_release_private(const GfxShader *s); const uint32_t *gfx_shader_spirv(const GfxShader *s, uint64_t *words); +// vk_hdr.c: with TOTK_HDR=1, replaces a fragment shader's SPIR-V (malloc'd, *words long) by the HDR tonemap when it is +// the game's tonemap; gfx_shader.c calls it for every fragment shader entering the cache. +void vk_hdr_shader_swap(uint32_t **spirv, uint64_t *words); uint64_t gfx_shader_failures(void); // failed translations; feeds GfxStats.shader_failures // Reflection: parsed once per shader from the translator's .res.json and the SPIR-V before it enters the cache. enum { GFX_RES_UBO, GFX_RES_SSBO, GFX_RES_TEX, GFX_RES_IMG, GFX_RES_KINDS }; diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index cb8e7189..79d91e14 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -23,9 +23,9 @@ #include "gfx.h" #include "gfx_wsys.h" #include "nvn_api.h" +#include "platform/platform.h" #include "ui/menu.h" #include "vk.h" -#include "platform/platform.h" #define FRAMES 2 #define MAX_IMAGES 16 @@ -40,6 +40,7 @@ void vk_queue_unlock(void) { plat_rmutex_unlock(&g_ql); } // ---- window state shared with the back end static VkSurfaceKHR g_surface; static volatile int32_t g_dirty; // the window was resized; swapchain stale +static volatile int32_t g_restart; // gfx_window_request_restart: closing the window starts the game again static volatile int32_t g_focused = 1; static volatile int32_t g_focus_msgs; static PlatRMutex g_start_lock; // gfx_window_start / vsync start @@ -63,15 +64,27 @@ void gfx_window_focus_changed(int in) { } // The window was closed: the process ends with it, as in MNG, once a save Commit still running in the background is -// done. +// done. After gfx_window_request_restart the executable then starts again with the same command line and environment +// (plat_restart), and the new process waits until this one is gone (main.c) before it moves the log and opens the +// RomFS and the saves. void gfx_window_closed(void) { - rt_log("gfx: window closed; exiting"); + int restart = plat_cas32(&g_restart, 0, 0) != 0; + rt_log("gfx: window closed; %s", restart ? "restarting" : "exiting"); fs_save_flush(); vk_pipeline_save(); prof_write(); // plat_exit runs no atexit handlers + if (restart) { + plat_setenv("TOTK_REEXEC", NULL); // the new process counts its own address-space retries (memory.c) + if (!plat_restart()) rt_log("gfx: the restart could not start the game again"); + } plat_exit(0); } +void gfx_window_request_restart(void) { + plat_xchg32(&g_restart, 1); + gfx_window_request_close(); +} + // TOTK_FULLSCREEN=1: borderless window over the monitor. TOTK_WINDOW_SIZE=x: client area of the window (the // swapchain follows the window; the game image is scaled to it). int gfx_cfg_fullscreen(void) { return cfg_bool("TOTK_FULLSCREEN"); } @@ -99,6 +112,7 @@ double gfx_window_refresh_hz(void) { return plat_cas32(&g_rate_mhz, 0, 0) / 1000 static PlatRMutex g_pl; static VkSwapchainKHR g_sc; static VkFormat g_sc_fmt; +static int g_sc_hdr; // HDR10 (TOTK_HDR, vk_hdr.c): PQ code values in Rec. 2020 static VkExtent2D g_sc_ext; static int g_scaler; // the last present: 0 the game image 1:1, 1 scaled by the blit, 2 by FSR static uint32_t g_sc_n; @@ -298,9 +312,9 @@ static int create_swapchain(void) { if (nf > 64) nf = 64; vkGetPhysicalDeviceSurfaceFormatsKHR(c->phys, g_surface, &nf, fmts); if (!nf) return 0; - // UNORM: the blit writes the bytes the game wrote (no sRGB encode). + // UNORM: the blit writes the bytes the game wrote (no sRGB encode). TOTK_HDR: HDR10 when the surface offers it. VkSurfaceFormatKHR sf = fmts[0]; - int found = 0; + int hdr = vk_hdr_surface_format(fmts, nf, &sf), found = hdr; for (uint32_t i = 0; i < nf && !found; i++) if (fmts[i].format == VK_FORMAT_B8G8R8A8_UNORM && fmts[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { sf = fmts[i]; found = 1; } for (uint32_t i = 0; i < nf && !found; i++) @@ -334,6 +348,9 @@ static int create_swapchain(void) { } if (old) vkDestroySwapchainKHR(c->device, old, NULL); g_sc_fmt = sf.format; + g_sc_hdr = hdr; + vk_hdr_set_active(hdr); + if (hdr) vk_hdr_metadata(g_sc, 1); g_sc_ext = ext; g_sc_n = MAX_IMAGES; vkGetSwapchainImagesKHR(c->device, g_sc, &g_sc_n, g_sc_img); @@ -417,12 +434,14 @@ static int ensure_thumbs(void) { } g_th_ptr = info.pMappedData; } - if (g_th_img && g_th_fmt != g_sc_fmt) { + // an HDR10 swapchain blits into RGBA8: its PQ codes, flat-looking but readable as bytes + VkFormat tf = g_sc_hdr ? VK_FORMAT_R8G8B8A8_UNORM : g_sc_fmt; + if (g_th_img && g_th_fmt != tf) { vmaDestroyImage(c->vma, g_th_img, g_th_img_alloc); // the previous present's fence was waited for: idle g_th_img = VK_NULL_HANDLE; } if (!g_th_img) { - VkImageCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = g_sc_fmt, + VkImageCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = tf, .extent = {FLIGHT_THUMB_W, FLIGHT_THUMB_H, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, @@ -434,7 +453,7 @@ static int ensure_thumbs(void) { rt_log("gfx: flight thumbnails off: no %ux%u image", FLIGHT_THUMB_W, FLIGHT_THUMB_H); return 0; } - g_th_fmt = g_sc_fmt; + g_th_fmt = tf; } return 1; } @@ -508,7 +527,8 @@ static void save_capture(const char *path) { uint8_t *px = malloc(n); if (!px) return; int bgra = g_sc_fmt == VK_FORMAT_B8G8R8A8_UNORM || g_sc_fmt == VK_FORMAT_B8G8R8A8_SRGB; - for (size_t i = 0; i < n; i += 4) { + if (g_sc_hdr) vk_hdr_to_srgb8(g_cap_ptr, px, n / 4, g_sc_fmt == VK_FORMAT_A2R10G10B10_UNORM_PACK32); + else for (size_t i = 0; i < n; i += 4) { px[i] = g_cap_ptr[i + (bgra ? 2 : 0)]; px[i + 1] = g_cap_ptr[i + 1]; px[i + 2] = g_cap_ptr[i + (bgra ? 0 : 2)]; @@ -560,6 +580,7 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) goto out; // lost, not ready: skip the frame if (r == VK_SUBOPTIMAL_KHR) plat_xchg32(&g_dirty, 1); vkResetFences(c->device, 1, &g_fence[slot]); + if (g_sc_hdr) vk_hdr_metadata(g_sc, 0); // a changed peak or white goes to the display if (g_th_pending[slot]) { // that fence has signalled: the thumbnail its submission wrote is complete g_th_tag[g_th_pending[slot] % (uint64_t)g_th_n] = g_th_pending[slot]; g_th_pending[slot] = 0; @@ -574,7 +595,8 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w window_settings_live(); // The menu overlay: laid out before recording (its first frame starts the ImGui back end and uploads the font) const char *menu_shot = NULL; - MenuTarget mt = {c->instance, c->phys, c->device, c->gfx_family, c->gfx_queue, g_sc_fmt, g_sc_ext.width, + MenuTarget mt = {c->instance, c->phys, c->device, c->gfx_family, c->gfx_queue, + g_sc_hdr ? VK_FORMAT_R8G8B8A8_UNORM : g_sc_fmt, g_sc_ext.width, g_sc_ext.height, cw, ch, g_scaler}; int overlay = g_sc_view[idx] && menu_overlay_frame(__atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED), &mt, &menu_shot); @@ -602,8 +624,10 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT); } - // Colour adjustment (TOTK_COLOR_*, vk_color.c): an adjusted copy of the crop takes the game image's place below - VkImage graded = general ? vk_color_record(cb, slot, src, fmt, rect) : VK_NULL_HANDLE; + // Colour adjustment (TOTK_COLOR_*, vk_color.c), or on an HDR10 swapchain the PQ encode (vk_hdr.c; the adjustment is + // for SDR): a copy of the crop takes the game image's place below + VkImage graded = !general ? VK_NULL_HANDLE : g_sc_hdr ? vk_hdr_encode(cb, slot, src, fmt, rect) + : vk_color_record(cb, slot, src, fmt, rect); const int grect[4] = {0, 0, cw, ch}; VkImage psrc = graded ? graded : src; VkFormat pfmt = graded ? VK_FORMAT_R16G16B16A16_SFLOAT : fmt; @@ -629,18 +653,24 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w VkImageLayout last = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkPipelineStageFlags2 last_stage = VK_PIPELINE_STAGE_2_TRANSFER_BIT; VkAccessFlags2 last_write = VK_ACCESS_2_TRANSFER_WRITE_BIT; + // HDR10: the menu goes into vk_hdr.c's RGBA8 image, which is then blended onto the swapchain image at the HUD's white + VkImageView menu_view = overlay && g_sc_hdr ? vk_hdr_ui_target(cb, g_sc_ext.width, g_sc_ext.height) : VK_NULL_HANDLE; + if (overlay && g_sc_hdr && !menu_view) overlay = 0; if (overlay) { sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, last_stage, last_write, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT); - VkRenderingAttachmentInfo ca = {.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, .imageView = g_sc_view[idx], + VkRenderingAttachmentInfo ca = {.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, + .imageView = menu_view ? menu_view : g_sc_view[idx], .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp = VK_ATTACHMENT_STORE_OP_STORE}; + .loadOp = menu_view ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE}; VkRenderingInfo ri = {.sType = VK_STRUCTURE_TYPE_RENDERING_INFO, .renderArea = {{0, 0}, g_sc_ext}, .layerCount = 1, .colorAttachmentCount = 1, .pColorAttachments = &ca}; vkCmdBeginRendering(cb, &ri); menu_overlay_draw(cb); vkCmdEndRendering(cb); + if (menu_view) vk_hdr_ui_compose(cb, g_sc_view[idx], g_sc_fmt, g_sc_ext.width, g_sc_ext.height); last = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; last_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; last_write = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT; @@ -734,6 +764,7 @@ void gfx_window_release_vk(void) { menu_vk_release(); vk_fsr_release(); vk_color_release(); + vk_hdr_release(); free_capture(); free_thumbs(); for (int i = 0; i < FRAMES; i++) { diff --git a/runtime/gfx_shader.c b/runtime/gfx_shader.c index a38d6741..3388935b 100644 --- a/runtime/gfx_shader.c +++ b/runtime/gfx_shader.c @@ -589,6 +589,7 @@ static GfxShader *disk_load_from(const uint8_t key[32], const uint8_t *iid, int s->reflection = (char *)res; s->reflection_size = res_size; reflect(s); + if (s->stage == GFX_STAGE_FS) vk_hdr_shader_swap(&s->spirv, &s->words); // the in-memory copy; the cache keeps its own return s; } diff --git a/runtime/gfx_window_probe.c b/runtime/gfx_window_probe.c index 0757171b..336bd617 100644 --- a/runtime/gfx_window_probe.c +++ b/runtime/gfx_window_probe.c @@ -131,6 +131,7 @@ static int present_and_check(Source *s, int first, int i, int *w_out, int *h_out } int probe_window(void) { + vk_hdr_off(); // the checks read 8-bit swapchain pixels if (!menu_font_check()) return fail("the menu's font check takes a damaged font or refuses a good one"); gfx_window_start(); VkCtx *c = vk_ctx(); diff --git a/runtime/hdr_encode_spv.h b/runtime/hdr_encode_spv.h new file mode 100644 index 00000000..d2e5073f --- /dev/null +++ b/runtime/hdr_encode_spv.h @@ -0,0 +1,97 @@ +// Generated by tools/build_shaders.py from runtime/shaders/hdr_encode.comp; do not edit. +// source sha256 08e1d94f9041b32d4183286db39941eec9cde41412babb197c0303fd64bb07a7 +#pragma once +#include +static const uint32_t hdr_encode_spv[] = { + 0x07230203, 0x00010300, 0x000d000b, 0x000000dd, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, + 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, + 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000004c, 0x00060010, 0x00000004, + 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00040047, 0x0000004c, 0x0000000b, 0x0000001c, + 0x00030047, 0x00000053, 0x00000002, 0x00050048, 0x00000053, 0x00000000, 0x00000023, 0x00000000, + 0x00050048, 0x00000053, 0x00000001, 0x00000023, 0x00000008, 0x00050048, 0x00000053, 0x00000002, + 0x00000023, 0x00000010, 0x00040047, 0x00000064, 0x00000021, 0x00000000, 0x00040047, 0x00000064, + 0x00000022, 0x00000000, 0x00030047, 0x0000009c, 0x00000019, 0x00040047, 0x0000009c, 0x00000021, + 0x00000001, 0x00040047, 0x0000009c, 0x00000022, 0x00000000, 0x00040047, 0x000000a7, 0x0000000b, + 0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, + 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000003, 0x0004002b, 0x00000006, 0x00000015, + 0x3d6147ae, 0x0004002b, 0x00000006, 0x0000001b, 0x4019999a, 0x0006002c, 0x00000007, 0x0000001c, + 0x0000001b, 0x0000001b, 0x0000001b, 0x0004002b, 0x00000006, 0x0000001f, 0x3d25aee6, 0x0006002c, + 0x00000007, 0x00000020, 0x0000001f, 0x0000001f, 0x0000001f, 0x00020014, 0x00000021, 0x00040017, + 0x00000022, 0x00000021, 0x00000003, 0x0004002b, 0x00000006, 0x0000002c, 0x00000000, 0x0004002b, + 0x00000006, 0x0000002d, 0x3f800000, 0x0004002b, 0x00000006, 0x00000031, 0x3e232000, 0x0006002c, + 0x00000007, 0x00000032, 0x00000031, 0x00000031, 0x00000031, 0x0004002b, 0x00000006, 0x00000034, + 0x3f560000, 0x0004002b, 0x00000006, 0x00000035, 0x4196d000, 0x0004002b, 0x00000006, 0x0000003a, + 0x41958000, 0x0004002b, 0x00000006, 0x00000040, 0x429db000, 0x0006002c, 0x00000007, 0x00000041, + 0x00000040, 0x00000040, 0x00000040, 0x00040015, 0x00000045, 0x00000020, 0x00000001, 0x00040017, + 0x00000046, 0x00000045, 0x00000002, 0x00040015, 0x00000049, 0x00000020, 0x00000000, 0x00040017, + 0x0000004a, 0x00000049, 0x00000003, 0x00040020, 0x0000004b, 0x00000001, 0x0000004a, 0x0004003b, + 0x0000004b, 0x0000004c, 0x00000001, 0x00040017, 0x0000004d, 0x00000049, 0x00000002, 0x00040017, + 0x00000052, 0x00000006, 0x00000004, 0x0005001e, 0x00000053, 0x00000046, 0x00000046, 0x00000052, + 0x00040020, 0x00000054, 0x00000009, 0x00000053, 0x0004003b, 0x00000054, 0x00000055, 0x00000009, + 0x0004002b, 0x00000045, 0x00000056, 0x00000001, 0x00040020, 0x00000057, 0x00000009, 0x00000046, + 0x00040017, 0x0000005a, 0x00000021, 0x00000002, 0x00090019, 0x00000061, 0x00000006, 0x00000001, + 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000062, 0x00000061, + 0x00040020, 0x00000063, 0x00000000, 0x00000062, 0x0004003b, 0x00000063, 0x00000064, 0x00000000, + 0x0004002b, 0x00000045, 0x00000067, 0x00000000, 0x0006002c, 0x00000007, 0x0000006e, 0x0000002c, + 0x0000002c, 0x0000002c, 0x0004002b, 0x00000045, 0x00000070, 0x00000002, 0x0004002b, 0x00000049, + 0x00000071, 0x00000002, 0x00040020, 0x00000072, 0x00000009, 0x00000006, 0x0004002b, 0x00000006, + 0x00000075, 0x3f000000, 0x00040018, 0x00000080, 0x00000007, 0x00000003, 0x0004002b, 0x00000006, + 0x00000081, 0x3f209d49, 0x0004002b, 0x00000006, 0x00000082, 0x3d8d844d, 0x0004002b, 0x00000006, + 0x00000083, 0x3c86594b, 0x0006002c, 0x00000007, 0x00000084, 0x00000081, 0x00000082, 0x00000083, + 0x0004002b, 0x00000006, 0x00000085, 0x3ea89a02, 0x0004002b, 0x00000006, 0x00000086, 0x3f6b645a, + 0x0004002b, 0x00000006, 0x00000087, 0x3db43958, 0x0006002c, 0x00000007, 0x00000088, 0x00000085, + 0x00000086, 0x00000087, 0x0004002b, 0x00000006, 0x00000089, 0x3d315b57, 0x0004002b, 0x00000006, + 0x0000008a, 0x3c3ac711, 0x0004002b, 0x00000006, 0x0000008b, 0x3f65460b, 0x0006002c, 0x00000007, + 0x0000008c, 0x00000089, 0x0000008a, 0x0000008b, 0x0006002c, 0x00000080, 0x0000008d, 0x00000084, + 0x00000088, 0x0000008c, 0x0004002b, 0x00000049, 0x00000091, 0x00000000, 0x0004002b, 0x00000049, + 0x00000095, 0x00000001, 0x00090019, 0x0000009a, 0x00000006, 0x00000001, 0x00000000, 0x00000000, + 0x00000000, 0x00000002, 0x00000002, 0x00040020, 0x0000009b, 0x00000000, 0x0000009a, 0x0004003b, + 0x0000009b, 0x0000009c, 0x00000000, 0x0004002b, 0x00000049, 0x000000a6, 0x00000008, 0x0006002c, + 0x0000004a, 0x000000a7, 0x000000a6, 0x000000a6, 0x00000095, 0x0006002c, 0x00000007, 0x000000d1, + 0x0000002d, 0x0000002d, 0x0000002d, 0x0006002c, 0x00000007, 0x000000d3, 0x00000015, 0x00000015, + 0x00000015, 0x0006002c, 0x00000007, 0x000000d6, 0x00000034, 0x00000034, 0x00000034, 0x0004002b, + 0x00000006, 0x000000d7, 0x3d9e8391, 0x0006002c, 0x00000007, 0x000000d8, 0x000000d7, 0x000000d7, + 0x000000d7, 0x0004002b, 0x00000006, 0x000000d9, 0x3f72a76f, 0x0006002c, 0x00000007, 0x000000da, + 0x000000d9, 0x000000d9, 0x000000d9, 0x0004002b, 0x00000006, 0x000000db, 0x38d1b717, 0x0006002c, + 0x00000007, 0x000000dc, 0x000000db, 0x000000db, 0x000000db, 0x00050036, 0x00000002, 0x00000004, + 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7, 0x000000a8, 0x00000000, 0x000300fb, + 0x00000091, 0x000000a9, 0x000200f8, 0x000000a9, 0x0004003d, 0x0000004a, 0x0000004e, 0x0000004c, + 0x0007004f, 0x0000004d, 0x0000004f, 0x0000004e, 0x0000004e, 0x00000000, 0x00000001, 0x0004007c, + 0x00000046, 0x00000050, 0x0000004f, 0x00050041, 0x00000057, 0x00000058, 0x00000055, 0x00000056, + 0x0004003d, 0x00000046, 0x00000059, 0x00000058, 0x000500af, 0x0000005a, 0x0000005b, 0x00000050, + 0x00000059, 0x0004009a, 0x00000021, 0x0000005c, 0x0000005b, 0x000300f7, 0x0000005e, 0x00000000, + 0x000400fa, 0x0000005c, 0x0000005d, 0x0000005e, 0x000200f8, 0x0000005d, 0x000200f9, 0x000000a8, + 0x000200f8, 0x0000005e, 0x0004003d, 0x00000062, 0x00000065, 0x00000064, 0x00050041, 0x00000057, + 0x00000068, 0x00000055, 0x00000067, 0x0004003d, 0x00000046, 0x00000069, 0x00000068, 0x00050080, + 0x00000046, 0x0000006a, 0x00000050, 0x00000069, 0x00040064, 0x00000061, 0x0000006b, 0x00000065, + 0x0007005f, 0x00000052, 0x0000006c, 0x0000006b, 0x0000006a, 0x00000002, 0x00000067, 0x0008004f, + 0x00000007, 0x0000006d, 0x0000006c, 0x0000006c, 0x00000000, 0x00000001, 0x00000002, 0x0007000c, + 0x00000007, 0x0000006f, 0x00000001, 0x00000028, 0x0000006d, 0x0000006e, 0x00060041, 0x00000072, + 0x00000073, 0x00000055, 0x00000070, 0x00000071, 0x0004003d, 0x00000006, 0x00000074, 0x00000073, + 0x000500ba, 0x00000021, 0x00000076, 0x00000074, 0x00000075, 0x000300f7, 0x00000078, 0x00000000, + 0x000400fa, 0x00000076, 0x00000077, 0x00000078, 0x000200f8, 0x00000077, 0x0008000c, 0x00000007, + 0x0000007c, 0x00000001, 0x0000002b, 0x0000006f, 0x0000006e, 0x000000d1, 0x00050085, 0x00000007, + 0x000000b2, 0x0000007c, 0x000000d8, 0x00050081, 0x00000007, 0x000000b5, 0x0000007c, 0x000000d3, + 0x00050085, 0x00000007, 0x000000b7, 0x000000b5, 0x000000da, 0x0007000c, 0x00000007, 0x000000b8, + 0x00000001, 0x0000001a, 0x000000b7, 0x0000001c, 0x000500ba, 0x00000022, 0x000000ba, 0x0000007c, + 0x00000020, 0x000600a9, 0x00000007, 0x000000bb, 0x000000ba, 0x000000b8, 0x000000b2, 0x000200f9, + 0x00000078, 0x000200f8, 0x00000078, 0x000700f5, 0x00000007, 0x000000d0, 0x0000006f, 0x0000005e, + 0x000000bb, 0x00000077, 0x00050091, 0x00000007, 0x0000008f, 0x0000008d, 0x000000d0, 0x0007000c, + 0x00000007, 0x00000090, 0x00000001, 0x00000028, 0x0000008f, 0x0000006e, 0x00060041, 0x00000072, + 0x00000092, 0x00000055, 0x00000070, 0x00000091, 0x0004003d, 0x00000006, 0x00000093, 0x00000092, + 0x0005008e, 0x00000007, 0x00000094, 0x00000090, 0x00000093, 0x00060041, 0x00000072, 0x00000096, + 0x00000055, 0x00000070, 0x00000095, 0x0004003d, 0x00000006, 0x00000097, 0x00000096, 0x00060050, + 0x00000007, 0x00000098, 0x00000097, 0x00000097, 0x00000097, 0x0007000c, 0x00000007, 0x00000099, + 0x00000001, 0x00000025, 0x00000094, 0x00000098, 0x0004003d, 0x0000009a, 0x0000009d, 0x0000009c, + 0x00050085, 0x00000007, 0x000000c1, 0x00000099, 0x000000dc, 0x0008000c, 0x00000007, 0x000000c4, + 0x00000001, 0x0000002b, 0x000000c1, 0x0000006e, 0x000000d1, 0x0007000c, 0x00000007, 0x000000c5, + 0x00000001, 0x0000001a, 0x000000c4, 0x00000032, 0x0005008e, 0x00000007, 0x000000c7, 0x000000c5, + 0x00000035, 0x00050081, 0x00000007, 0x000000c9, 0x000000d6, 0x000000c7, 0x0005008e, 0x00000007, + 0x000000cb, 0x000000c5, 0x0000003a, 0x00050081, 0x00000007, 0x000000cd, 0x000000d1, 0x000000cb, + 0x00050088, 0x00000007, 0x000000ce, 0x000000c9, 0x000000cd, 0x0007000c, 0x00000007, 0x000000cf, + 0x00000001, 0x0000001a, 0x000000ce, 0x00000041, 0x00050051, 0x00000006, 0x000000a2, 0x000000cf, + 0x00000000, 0x00050051, 0x00000006, 0x000000a3, 0x000000cf, 0x00000001, 0x00050051, 0x00000006, + 0x000000a4, 0x000000cf, 0x00000002, 0x00070050, 0x00000052, 0x000000a5, 0x000000a2, 0x000000a3, + 0x000000a4, 0x0000002d, 0x00040063, 0x0000009d, 0x00000050, 0x000000a5, 0x000200f9, 0x000000a8, + 0x000200f8, 0x000000a8, 0x000100fd, 0x00010038, +}; diff --git a/runtime/hdr_fullscreen_spv.h b/runtime/hdr_fullscreen_spv.h new file mode 100644 index 00000000..93e809ba --- /dev/null +++ b/runtime/hdr_fullscreen_spv.h @@ -0,0 +1,36 @@ +// Generated by tools/build_shaders.py from runtime/shaders/hdr_fullscreen.vert; do not edit. +// source sha256 3474de7753260cdbc5df61bbd96074c566f98c9be15be4791ae7cbea32542b03 +#pragma once +#include +static const uint32_t hdr_fullscreen_spv[] = { + 0x07230203, 0x00010300, 0x000d000b, 0x0000002c, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, + 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, + 0x0008000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000c, 0x0000001d, + 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000c, 0x0000000b, 0x0000002a, + 0x00030047, 0x0000001b, 0x00000002, 0x00050048, 0x0000001b, 0x00000000, 0x0000000b, 0x00000000, + 0x00050048, 0x0000001b, 0x00000001, 0x0000000b, 0x00000001, 0x00050048, 0x0000001b, 0x00000002, + 0x0000000b, 0x00000003, 0x00050048, 0x0000001b, 0x00000003, 0x0000000b, 0x00000004, 0x00020013, + 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, + 0x00000007, 0x00000006, 0x00000002, 0x00040020, 0x00000008, 0x00000003, 0x00000007, 0x0004003b, + 0x00000008, 0x00000009, 0x00000003, 0x00040015, 0x0000000a, 0x00000020, 0x00000001, 0x00040020, + 0x0000000b, 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000001, 0x0004002b, + 0x0000000a, 0x0000000e, 0x00000001, 0x0004002b, 0x0000000a, 0x00000010, 0x00000002, 0x00040017, + 0x00000017, 0x00000006, 0x00000004, 0x00040015, 0x00000018, 0x00000020, 0x00000000, 0x0004002b, + 0x00000018, 0x00000019, 0x00000001, 0x0004001c, 0x0000001a, 0x00000006, 0x00000019, 0x0006001e, + 0x0000001b, 0x00000017, 0x00000006, 0x0000001a, 0x0000001a, 0x00040020, 0x0000001c, 0x00000003, + 0x0000001b, 0x0004003b, 0x0000001c, 0x0000001d, 0x00000003, 0x0004002b, 0x0000000a, 0x0000001e, + 0x00000000, 0x0004002b, 0x00000006, 0x00000020, 0x40000000, 0x0004002b, 0x00000006, 0x00000022, + 0x3f800000, 0x0004002b, 0x00000006, 0x00000025, 0x00000000, 0x00040020, 0x00000029, 0x00000003, + 0x00000017, 0x0005002c, 0x00000007, 0x0000002b, 0x00000022, 0x00000022, 0x00050036, 0x00000002, + 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x0000000a, 0x0000000d, + 0x0000000c, 0x000500c4, 0x0000000a, 0x0000000f, 0x0000000d, 0x0000000e, 0x000500c7, 0x0000000a, + 0x00000011, 0x0000000f, 0x00000010, 0x0004006f, 0x00000006, 0x00000012, 0x00000011, 0x000500c7, + 0x0000000a, 0x00000014, 0x0000000d, 0x00000010, 0x0004006f, 0x00000006, 0x00000015, 0x00000014, + 0x00050050, 0x00000007, 0x00000016, 0x00000012, 0x00000015, 0x0003003e, 0x00000009, 0x00000016, + 0x0004003d, 0x00000007, 0x0000001f, 0x00000009, 0x0005008e, 0x00000007, 0x00000021, 0x0000001f, + 0x00000020, 0x00050083, 0x00000007, 0x00000024, 0x00000021, 0x0000002b, 0x00050051, 0x00000006, + 0x00000026, 0x00000024, 0x00000000, 0x00050051, 0x00000006, 0x00000027, 0x00000024, 0x00000001, + 0x00070050, 0x00000017, 0x00000028, 0x00000026, 0x00000027, 0x00000025, 0x00000022, 0x00050041, + 0x00000029, 0x0000002a, 0x0000001d, 0x0000001e, 0x0003003e, 0x0000002a, 0x00000028, 0x000100fd, + 0x00010038, +}; diff --git a/runtime/hdr_tonemap_spv.h b/runtime/hdr_tonemap_spv.h new file mode 100644 index 00000000..d267aa62 --- /dev/null +++ b/runtime/hdr_tonemap_spv.h @@ -0,0 +1,145 @@ +// Generated by tools/build_shaders.py from runtime/shaders/hdr_tonemap.frag; do not edit. +// source sha256 4427b14028dd2c00245a97a20185b72275970ea1836957632c214abddac798eb +#pragma once +#include +static const uint32_t hdr_tonemap_spv[] = { + 0x07230203, 0x00010300, 0x000d000b, 0x000001bf, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, + 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, + 0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000053, 0x0000011c, 0x00030010, + 0x00000004, 0x00000007, 0x00040047, 0x0000004f, 0x00000021, 0x00000001, 0x00040047, 0x0000004f, + 0x00000022, 0x00000000, 0x00040047, 0x00000053, 0x0000001e, 0x00000000, 0x00040047, 0x0000005c, + 0x00000021, 0x00000002, 0x00040047, 0x0000005c, 0x00000022, 0x00000000, 0x00040047, 0x00000066, + 0x00000006, 0x00000010, 0x00030047, 0x00000067, 0x00000002, 0x00050048, 0x00000067, 0x00000000, + 0x00000023, 0x00000000, 0x00040047, 0x00000069, 0x00000021, 0x00000003, 0x00040047, 0x00000069, + 0x00000022, 0x00000000, 0x00040047, 0x00000070, 0x00000006, 0x00000010, 0x00030047, 0x00000071, + 0x00000002, 0x00050048, 0x00000071, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000073, + 0x00000021, 0x00000004, 0x00040047, 0x00000073, 0x00000022, 0x00000000, 0x00040047, 0x00000078, + 0x00000006, 0x00000010, 0x00030047, 0x00000079, 0x00000002, 0x00050048, 0x00000079, 0x00000000, + 0x00000023, 0x00000000, 0x00050048, 0x00000079, 0x00000001, 0x00000023, 0x00000580, 0x00040047, + 0x0000007b, 0x00000021, 0x00000000, 0x00040047, 0x0000007b, 0x00000022, 0x00000000, 0x00040047, + 0x0000011c, 0x0000001e, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, + 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x0000000c, 0x00000006, 0x00000003, 0x0004002b, + 0x00000006, 0x00000017, 0x3e28aeed, 0x0004002b, 0x00000006, 0x00000019, 0x3e3851ec, 0x00020014, + 0x0000001a, 0x0004002b, 0x00000006, 0x0000001f, 0x3f800000, 0x0004002b, 0x00000006, 0x00000026, + 0x3f55d445, 0x00040015, 0x0000002f, 0x00000020, 0x00000000, 0x0004002b, 0x0000002f, 0x00000030, + 0x00000000, 0x0004002b, 0x0000002f, 0x00000035, 0x00000001, 0x00090019, 0x0000004c, 0x00000006, + 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x0000004d, + 0x0000004c, 0x00040020, 0x0000004e, 0x00000000, 0x0000004d, 0x0004003b, 0x0000004e, 0x0000004f, + 0x00000000, 0x00040017, 0x00000051, 0x00000006, 0x00000004, 0x00040020, 0x00000052, 0x00000001, + 0x00000051, 0x0004003b, 0x00000052, 0x00000053, 0x00000001, 0x00040017, 0x00000054, 0x00000006, + 0x00000002, 0x0004002b, 0x00000006, 0x00000059, 0x461c4000, 0x0006002c, 0x0000000c, 0x0000005a, + 0x00000059, 0x00000059, 0x00000059, 0x0004003b, 0x0000004e, 0x0000005c, 0x00000000, 0x0004002b, + 0x0000002f, 0x00000065, 0x00001000, 0x0004001c, 0x00000066, 0x00000051, 0x00000065, 0x0003001e, + 0x00000067, 0x00000066, 0x00040020, 0x00000068, 0x00000002, 0x00000067, 0x0004003b, 0x00000068, + 0x00000069, 0x00000002, 0x00040015, 0x0000006a, 0x00000020, 0x00000001, 0x0004002b, 0x0000006a, + 0x0000006b, 0x00000000, 0x00040020, 0x0000006c, 0x00000002, 0x00000051, 0x0004001c, 0x00000070, + 0x00000051, 0x00000065, 0x0003001e, 0x00000071, 0x00000070, 0x00040020, 0x00000072, 0x00000002, + 0x00000071, 0x0004003b, 0x00000072, 0x00000073, 0x00000002, 0x0004002b, 0x0000002f, 0x00000077, + 0x00000058, 0x0004001c, 0x00000078, 0x00000051, 0x00000077, 0x0004001e, 0x00000079, 0x00000078, + 0x00000051, 0x00040020, 0x0000007a, 0x00000002, 0x00000079, 0x0004003b, 0x0000007a, 0x0000007b, + 0x00000002, 0x0004002b, 0x0000006a, 0x0000007c, 0x00000001, 0x00040020, 0x0000007d, 0x00000002, + 0x00000006, 0x0004002b, 0x00000006, 0x00000080, 0x00000000, 0x0004002b, 0x00000006, 0x00000097, + 0x3e99096c, 0x0006002c, 0x0000000c, 0x000000c5, 0x00000080, 0x00000080, 0x00000080, 0x0004002b, + 0x00000006, 0x000000d8, 0x3f2aaaab, 0x0004002b, 0x00000006, 0x000000ff, 0x3f000000, 0x00040020, + 0x0000011b, 0x00000003, 0x00000051, 0x0004003b, 0x0000011b, 0x0000011c, 0x00000003, 0x00050036, + 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x0000004d, + 0x00000050, 0x0000004f, 0x0004003d, 0x00000051, 0x00000055, 0x00000053, 0x0007004f, 0x00000054, + 0x00000056, 0x00000055, 0x00000055, 0x00000000, 0x00000001, 0x00050057, 0x00000051, 0x00000057, + 0x00000050, 0x00000056, 0x0008004f, 0x0000000c, 0x00000058, 0x00000057, 0x00000057, 0x00000000, + 0x00000001, 0x00000002, 0x0007000c, 0x0000000c, 0x0000005b, 0x00000001, 0x00000025, 0x00000058, + 0x0000005a, 0x0004003d, 0x0000004d, 0x0000005d, 0x0000005c, 0x00050057, 0x00000051, 0x00000060, + 0x0000005d, 0x00000056, 0x0008004f, 0x0000000c, 0x00000061, 0x00000060, 0x00000060, 0x00000000, + 0x00000001, 0x00000002, 0x00050081, 0x0000000c, 0x00000062, 0x0000005b, 0x00000061, 0x00060041, + 0x0000006c, 0x0000006d, 0x00000069, 0x0000006b, 0x0000006b, 0x0004003d, 0x00000051, 0x0000006e, + 0x0000006d, 0x00060041, 0x0000006c, 0x00000074, 0x00000073, 0x0000006b, 0x0000006b, 0x0004003d, + 0x00000051, 0x00000075, 0x00000074, 0x00060041, 0x0000007d, 0x0000007e, 0x0000007b, 0x0000007c, + 0x00000030, 0x0004003d, 0x00000006, 0x0000007f, 0x0000007e, 0x000500ba, 0x0000001a, 0x00000081, + 0x0000007f, 0x00000080, 0x000600a9, 0x00000006, 0x000001bd, 0x00000081, 0x0000007f, 0x0000001f, + 0x00060041, 0x0000007d, 0x0000008a, 0x0000007b, 0x0000007c, 0x00000035, 0x0004003d, 0x00000006, + 0x0000008b, 0x0000008a, 0x000500ba, 0x0000001a, 0x0000008c, 0x0000008b, 0x0000001f, 0x000600a9, + 0x00000006, 0x000001be, 0x0000008c, 0x0000008b, 0x0000001f, 0x00050051, 0x00000006, 0x00000096, + 0x00000062, 0x00000000, 0x00050085, 0x00000006, 0x00000098, 0x00000096, 0x00000097, 0x00050051, + 0x00000006, 0x0000009a, 0x00000062, 0x00000001, 0x00050051, 0x00000006, 0x0000009c, 0x0000006e, + 0x00000000, 0x00050085, 0x00000006, 0x0000009d, 0x0000009a, 0x0000009c, 0x00050081, 0x00000006, + 0x0000009e, 0x00000098, 0x0000009d, 0x00050051, 0x00000006, 0x000000a0, 0x00000062, 0x00000002, + 0x00050051, 0x00000006, 0x000000a2, 0x0000006e, 0x00000001, 0x00050085, 0x00000006, 0x000000a3, + 0x000000a0, 0x000000a2, 0x00050081, 0x00000006, 0x000000a4, 0x0000009e, 0x000000a3, 0x0007000c, + 0x00000006, 0x000000a5, 0x00000001, 0x00000028, 0x000000a4, 0x00000080, 0x0004007f, 0x00000006, + 0x000000a8, 0x000000a5, 0x0006000c, 0x00000006, 0x000000a9, 0x00000001, 0x0000001b, 0x000000a8, + 0x00050083, 0x00000006, 0x000000aa, 0x0000001f, 0x000000a9, 0x000500ba, 0x0000001a, 0x000000ad, + 0x000000a5, 0x00000080, 0x000300f7, 0x000000b0, 0x00000000, 0x000400fa, 0x000000ad, 0x000000af, + 0x000000b8, 0x000200f8, 0x000000af, 0x000500bc, 0x0000001a, 0x0000012a, 0x000000a5, 0x00000019, + 0x000300f7, 0x00000136, 0x00000000, 0x000400fa, 0x0000012a, 0x0000012b, 0x00000130, 0x000200f8, + 0x0000012b, 0x000200f9, 0x00000136, 0x000200f8, 0x00000130, 0x00050083, 0x00000006, 0x00000133, + 0x000000a5, 0x00000019, 0x00050085, 0x00000006, 0x00000134, 0x00000026, 0x00000133, 0x00050081, + 0x00000006, 0x00000135, 0x00000017, 0x00000134, 0x000200f9, 0x00000136, 0x000200f8, 0x00000136, + 0x000700f5, 0x00000006, 0x000001b7, 0x000000aa, 0x0000012b, 0x00000135, 0x00000130, 0x00050088, + 0x00000006, 0x000000b6, 0x000001b7, 0x000000a5, 0x0005008e, 0x0000000c, 0x000000b7, 0x00000062, + 0x000000b6, 0x000200f9, 0x000000b0, 0x000200f8, 0x000000b8, 0x000200f9, 0x000000b0, 0x000200f8, + 0x000000b0, 0x000700f5, 0x0000000c, 0x000001b8, 0x000000b7, 0x00000136, 0x00000062, 0x000000b8, + 0x000500bc, 0x0000001a, 0x0000014c, 0x00000096, 0x00000019, 0x000300f7, 0x00000158, 0x00000000, + 0x000400fa, 0x0000014c, 0x0000014d, 0x00000152, 0x000200f8, 0x0000014d, 0x0004007f, 0x00000006, + 0x0000014f, 0x00000096, 0x0006000c, 0x00000006, 0x00000150, 0x00000001, 0x0000001b, 0x0000014f, + 0x00050083, 0x00000006, 0x00000151, 0x0000001f, 0x00000150, 0x000200f9, 0x00000158, 0x000200f8, + 0x00000152, 0x00050083, 0x00000006, 0x00000155, 0x00000096, 0x00000019, 0x00050085, 0x00000006, + 0x00000156, 0x00000026, 0x00000155, 0x00050081, 0x00000006, 0x00000157, 0x00000017, 0x00000156, + 0x000200f9, 0x00000158, 0x000200f8, 0x00000158, 0x000700f5, 0x00000006, 0x000001b9, 0x00000151, + 0x0000014d, 0x00000157, 0x00000152, 0x000500bc, 0x0000001a, 0x0000015f, 0x0000009a, 0x00000019, + 0x000300f7, 0x0000016b, 0x00000000, 0x000400fa, 0x0000015f, 0x00000160, 0x00000165, 0x000200f8, + 0x00000160, 0x0004007f, 0x00000006, 0x00000162, 0x0000009a, 0x0006000c, 0x00000006, 0x00000163, + 0x00000001, 0x0000001b, 0x00000162, 0x00050083, 0x00000006, 0x00000164, 0x0000001f, 0x00000163, + 0x000200f9, 0x0000016b, 0x000200f8, 0x00000165, 0x00050083, 0x00000006, 0x00000168, 0x0000009a, + 0x00000019, 0x00050085, 0x00000006, 0x00000169, 0x00000026, 0x00000168, 0x00050081, 0x00000006, + 0x0000016a, 0x00000017, 0x00000169, 0x000200f9, 0x0000016b, 0x000200f8, 0x0000016b, 0x000700f5, + 0x00000006, 0x000001ba, 0x00000164, 0x00000160, 0x0000016a, 0x00000165, 0x000500bc, 0x0000001a, + 0x00000172, 0x000000a0, 0x00000019, 0x000300f7, 0x0000017e, 0x00000000, 0x000400fa, 0x00000172, + 0x00000173, 0x00000178, 0x000200f8, 0x00000173, 0x0004007f, 0x00000006, 0x00000175, 0x000000a0, + 0x0006000c, 0x00000006, 0x00000176, 0x00000001, 0x0000001b, 0x00000175, 0x00050083, 0x00000006, + 0x00000177, 0x0000001f, 0x00000176, 0x000200f9, 0x0000017e, 0x000200f8, 0x00000178, 0x00050083, + 0x00000006, 0x0000017b, 0x000000a0, 0x00000019, 0x00050085, 0x00000006, 0x0000017c, 0x00000026, + 0x0000017b, 0x00050081, 0x00000006, 0x0000017d, 0x00000017, 0x0000017c, 0x000200f9, 0x0000017e, + 0x000200f8, 0x0000017e, 0x000700f5, 0x00000006, 0x000001bb, 0x00000177, 0x00000173, 0x0000017d, + 0x00000178, 0x00060050, 0x0000000c, 0x00000146, 0x000001b9, 0x000001ba, 0x000001bb, 0x00050085, + 0x00000006, 0x000000c2, 0x000000aa, 0x000000aa, 0x00060050, 0x0000000c, 0x000000c3, 0x000000c2, + 0x000000c2, 0x000000c2, 0x0008000c, 0x0000000c, 0x000000c4, 0x00000001, 0x0000002e, 0x000001b8, + 0x00000146, 0x000000c3, 0x0007000c, 0x0000000c, 0x000000c6, 0x00000001, 0x00000028, 0x000000c4, + 0x000000c5, 0x00050051, 0x00000006, 0x00000183, 0x000000c6, 0x00000000, 0x00050051, 0x00000006, + 0x00000185, 0x000000c6, 0x00000001, 0x00050051, 0x00000006, 0x00000187, 0x000000c6, 0x00000002, + 0x0007000c, 0x00000006, 0x00000188, 0x00000001, 0x00000028, 0x00000185, 0x00000187, 0x0007000c, + 0x00000006, 0x00000189, 0x00000001, 0x00000028, 0x00000183, 0x00000188, 0x0007000c, 0x00000006, + 0x000000cb, 0x00000001, 0x00000028, 0x00000189, 0x0000001f, 0x00060050, 0x0000000c, 0x000000cf, + 0x000000cb, 0x000000cb, 0x000000cb, 0x00050088, 0x0000000c, 0x000000d0, 0x000000c6, 0x000000cf, + 0x00050051, 0x00000006, 0x0000018d, 0x000000d0, 0x00000000, 0x00050051, 0x00000006, 0x0000018f, + 0x000000d0, 0x00000001, 0x00050051, 0x00000006, 0x00000191, 0x000000d0, 0x00000002, 0x0007000c, + 0x00000006, 0x00000192, 0x00000001, 0x00000028, 0x0000018f, 0x00000191, 0x0007000c, 0x00000006, + 0x00000193, 0x00000001, 0x00000028, 0x0000018d, 0x00000192, 0x00050085, 0x00000006, 0x000000d9, + 0x0000018d, 0x000000d8, 0x00050081, 0x00000006, 0x000000de, 0x0000018f, 0x00000191, 0x00050051, + 0x00000006, 0x000000e0, 0x0000006e, 0x00000002, 0x00050085, 0x00000006, 0x000000e1, 0x000000de, + 0x000000e0, 0x00050081, 0x00000006, 0x000000e2, 0x000000d9, 0x000000e1, 0x00050083, 0x00000006, + 0x000000e3, 0x000000e2, 0x0000001f, 0x00050051, 0x00000006, 0x000000e6, 0x00000075, 0x00000001, + 0x00050085, 0x00000006, 0x000000e9, 0x000000e3, 0x000000e3, 0x00050083, 0x00000006, 0x000000ea, + 0x0000001f, 0x000000e9, 0x00050085, 0x00000006, 0x000000eb, 0x000000e6, 0x000000ea, 0x00050051, + 0x00000006, 0x000000ed, 0x00000075, 0x00000000, 0x00050081, 0x00000006, 0x000000ee, 0x000000eb, + 0x000000ed, 0x00060050, 0x0000000c, 0x000000f2, 0x00000193, 0x00000193, 0x00000193, 0x00050083, + 0x0000000c, 0x000000f3, 0x000000d0, 0x000000f2, 0x0005008e, 0x0000000c, 0x000000f5, 0x000000f3, + 0x000000ee, 0x00050081, 0x0000000c, 0x000000f8, 0x000000f5, 0x000000f2, 0x0005008e, 0x0000000c, + 0x000000f9, 0x000000f8, 0x000000cb, 0x00050051, 0x00000006, 0x00000197, 0x000000f9, 0x00000000, + 0x00050051, 0x00000006, 0x00000199, 0x000000f9, 0x00000001, 0x00050051, 0x00000006, 0x0000019b, + 0x000000f9, 0x00000002, 0x0007000c, 0x00000006, 0x0000019c, 0x00000001, 0x00000028, 0x00000199, + 0x0000019b, 0x0007000c, 0x00000006, 0x0000019d, 0x00000001, 0x00000028, 0x00000197, 0x0000019c, + 0x00050085, 0x00000006, 0x00000101, 0x000000ff, 0x000001be, 0x000500ba, 0x0000001a, 0x00000104, + 0x0000019d, 0x00000101, 0x000300f7, 0x00000106, 0x00000000, 0x000400fa, 0x00000104, 0x00000105, + 0x00000106, 0x000200f8, 0x00000105, 0x00050083, 0x00000006, 0x0000010a, 0x000001be, 0x00000101, + 0x00050083, 0x00000006, 0x0000010f, 0x0000019d, 0x00000101, 0x0004007f, 0x00000006, 0x00000110, + 0x0000010f, 0x00050088, 0x00000006, 0x00000112, 0x00000110, 0x0000010a, 0x0006000c, 0x00000006, + 0x00000113, 0x00000001, 0x0000001b, 0x00000112, 0x00050083, 0x00000006, 0x00000114, 0x0000001f, + 0x00000113, 0x00050085, 0x00000006, 0x00000115, 0x0000010a, 0x00000114, 0x00050081, 0x00000006, + 0x00000116, 0x00000101, 0x00000115, 0x00050088, 0x00000006, 0x00000118, 0x00000116, 0x0000019d, + 0x0005008e, 0x0000000c, 0x0000011a, 0x000000f9, 0x00000118, 0x000200f9, 0x00000106, 0x000200f8, + 0x00000106, 0x000700f5, 0x0000000c, 0x000001bc, 0x000000f9, 0x0000017e, 0x0000011a, 0x00000105, + 0x0007000c, 0x0000000c, 0x0000011e, 0x00000001, 0x00000028, 0x000001bc, 0x000000c5, 0x0005008e, + 0x0000000c, 0x00000120, 0x0000011e, 0x000001bd, 0x00050051, 0x00000006, 0x00000121, 0x00000120, + 0x00000000, 0x00050051, 0x00000006, 0x00000122, 0x00000120, 0x00000001, 0x00050051, 0x00000006, + 0x00000123, 0x00000120, 0x00000002, 0x00070050, 0x00000051, 0x00000124, 0x00000121, 0x00000122, + 0x00000123, 0x00000080, 0x0003003e, 0x0000011c, 0x00000124, 0x000100fd, 0x00010038, +}; diff --git a/runtime/hdr_ui_spv.h b/runtime/hdr_ui_spv.h new file mode 100644 index 00000000..1854ac8a --- /dev/null +++ b/runtime/hdr_ui_spv.h @@ -0,0 +1,73 @@ +// Generated by tools/build_shaders.py from runtime/shaders/hdr_ui.frag; do not edit. +// source sha256 59cfbb1ab5393fdb743016cbf75a085ee8a05929c7ea67a69b4ab77f26a14303 +#pragma once +#include +static const uint32_t hdr_ui_spv[] = { + 0x07230203, 0x00010300, 0x000d000b, 0x000000be, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, + 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, + 0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x0000004f, 0x00000068, 0x00030010, + 0x00000004, 0x00000007, 0x00040047, 0x0000004b, 0x00000021, 0x00000000, 0x00040047, 0x0000004b, + 0x00000022, 0x00000000, 0x00040047, 0x0000004f, 0x0000001e, 0x00000000, 0x00040047, 0x00000068, + 0x0000001e, 0x00000000, 0x00030047, 0x0000007b, 0x00000002, 0x00050048, 0x0000007b, 0x00000000, + 0x00000023, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, + 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000003, 0x0004002b, 0x00000006, + 0x00000015, 0x3d6147ae, 0x0004002b, 0x00000006, 0x0000001b, 0x4019999a, 0x0006002c, 0x00000007, + 0x0000001c, 0x0000001b, 0x0000001b, 0x0000001b, 0x0004002b, 0x00000006, 0x0000001f, 0x3d25aee6, + 0x0006002c, 0x00000007, 0x00000020, 0x0000001f, 0x0000001f, 0x0000001f, 0x00020014, 0x00000021, + 0x00040017, 0x00000022, 0x00000021, 0x00000003, 0x0004002b, 0x00000006, 0x0000002c, 0x00000000, + 0x0004002b, 0x00000006, 0x0000002d, 0x3f800000, 0x0004002b, 0x00000006, 0x00000031, 0x3e232000, + 0x0006002c, 0x00000007, 0x00000032, 0x00000031, 0x00000031, 0x00000031, 0x0004002b, 0x00000006, + 0x00000034, 0x3f560000, 0x0004002b, 0x00000006, 0x00000035, 0x4196d000, 0x0004002b, 0x00000006, + 0x0000003a, 0x41958000, 0x0004002b, 0x00000006, 0x00000040, 0x429db000, 0x0006002c, 0x00000007, + 0x00000041, 0x00000040, 0x00000040, 0x00000040, 0x00040017, 0x00000045, 0x00000006, 0x00000004, + 0x00090019, 0x00000048, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, + 0x00000000, 0x0003001b, 0x00000049, 0x00000048, 0x00040020, 0x0000004a, 0x00000000, 0x00000049, + 0x0004003b, 0x0000004a, 0x0000004b, 0x00000000, 0x00040017, 0x0000004d, 0x00000006, 0x00000002, + 0x00040020, 0x0000004e, 0x00000001, 0x0000004d, 0x0004003b, 0x0000004e, 0x0000004f, 0x00000001, + 0x00040015, 0x00000052, 0x00000020, 0x00000000, 0x00040020, 0x00000067, 0x00000003, 0x00000045, + 0x0004003b, 0x00000067, 0x00000068, 0x00000003, 0x00040018, 0x00000069, 0x00000007, 0x00000003, + 0x0004002b, 0x00000006, 0x0000006a, 0x3f209d49, 0x0004002b, 0x00000006, 0x0000006b, 0x3d8d844d, + 0x0004002b, 0x00000006, 0x0000006c, 0x3c86594b, 0x0006002c, 0x00000007, 0x0000006d, 0x0000006a, + 0x0000006b, 0x0000006c, 0x0004002b, 0x00000006, 0x0000006e, 0x3ea89a02, 0x0004002b, 0x00000006, + 0x0000006f, 0x3f6b645a, 0x0004002b, 0x00000006, 0x00000070, 0x3db43958, 0x0006002c, 0x00000007, + 0x00000071, 0x0000006e, 0x0000006f, 0x00000070, 0x0004002b, 0x00000006, 0x00000072, 0x3d315b57, + 0x0004002b, 0x00000006, 0x00000073, 0x3c3ac711, 0x0004002b, 0x00000006, 0x00000074, 0x3f65460b, + 0x0006002c, 0x00000007, 0x00000075, 0x00000072, 0x00000073, 0x00000074, 0x0006002c, 0x00000069, + 0x00000076, 0x0000006d, 0x00000071, 0x00000075, 0x0006002c, 0x00000007, 0x00000079, 0x0000002c, + 0x0000002c, 0x0000002c, 0x0003001e, 0x0000007b, 0x00000045, 0x00040020, 0x0000007c, 0x00000009, + 0x0000007b, 0x0004003b, 0x0000007c, 0x0000007d, 0x00000009, 0x00040015, 0x0000007e, 0x00000020, + 0x00000001, 0x0004002b, 0x0000007e, 0x0000007f, 0x00000000, 0x0004002b, 0x00000052, 0x00000080, + 0x00000000, 0x00040020, 0x00000081, 0x00000009, 0x00000006, 0x0006002c, 0x00000007, 0x000000b2, + 0x0000002d, 0x0000002d, 0x0000002d, 0x0006002c, 0x00000007, 0x000000b4, 0x00000015, 0x00000015, + 0x00000015, 0x0006002c, 0x00000007, 0x000000b7, 0x00000034, 0x00000034, 0x00000034, 0x0004002b, + 0x00000006, 0x000000b8, 0x3d9e8391, 0x0006002c, 0x00000007, 0x000000b9, 0x000000b8, 0x000000b8, + 0x000000b8, 0x0004002b, 0x00000006, 0x000000ba, 0x3f72a76f, 0x0006002c, 0x00000007, 0x000000bb, + 0x000000ba, 0x000000ba, 0x000000ba, 0x0004002b, 0x00000006, 0x000000bc, 0x38d1b717, 0x0006002c, + 0x00000007, 0x000000bd, 0x000000bc, 0x000000bc, 0x000000bc, 0x00050036, 0x00000002, 0x00000004, + 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000049, 0x0000004c, 0x0000004b, + 0x0004003d, 0x0000004d, 0x00000050, 0x0000004f, 0x00050057, 0x00000045, 0x00000051, 0x0000004c, + 0x00000050, 0x00050051, 0x00000006, 0x00000056, 0x00000051, 0x00000003, 0x000500bc, 0x00000021, + 0x00000057, 0x00000056, 0x0000002c, 0x000300f7, 0x00000059, 0x00000000, 0x000400fa, 0x00000057, + 0x00000058, 0x00000059, 0x000200f8, 0x00000058, 0x000100fc, 0x000200f8, 0x00000059, 0x0008004f, + 0x00000007, 0x0000005d, 0x00000051, 0x00000051, 0x00000000, 0x00000001, 0x00000002, 0x00060050, + 0x00000007, 0x00000060, 0x00000056, 0x00000056, 0x00000056, 0x00050088, 0x00000007, 0x00000061, + 0x0000005d, 0x00000060, 0x0008000c, 0x00000007, 0x00000064, 0x00000001, 0x0000002b, 0x00000061, + 0x00000079, 0x000000b2, 0x00050085, 0x00000007, 0x00000091, 0x00000064, 0x000000b9, 0x00050081, + 0x00000007, 0x00000094, 0x00000064, 0x000000b4, 0x00050085, 0x00000007, 0x00000096, 0x00000094, + 0x000000bb, 0x0007000c, 0x00000007, 0x00000097, 0x00000001, 0x0000001a, 0x00000096, 0x0000001c, + 0x000500ba, 0x00000022, 0x00000099, 0x00000064, 0x00000020, 0x000600a9, 0x00000007, 0x0000009a, + 0x00000099, 0x00000097, 0x00000091, 0x00050091, 0x00000007, 0x00000078, 0x00000076, 0x0000009a, + 0x0007000c, 0x00000007, 0x0000007a, 0x00000001, 0x00000028, 0x00000078, 0x00000079, 0x00060041, + 0x00000081, 0x00000082, 0x0000007d, 0x0000007f, 0x00000080, 0x0004003d, 0x00000006, 0x00000083, + 0x00000082, 0x0005008e, 0x00000007, 0x00000084, 0x0000007a, 0x00000083, 0x00050085, 0x00000007, + 0x000000a0, 0x00000084, 0x000000bd, 0x0008000c, 0x00000007, 0x000000a3, 0x00000001, 0x0000002b, + 0x000000a0, 0x00000079, 0x000000b2, 0x0007000c, 0x00000007, 0x000000a4, 0x00000001, 0x0000001a, + 0x000000a3, 0x00000032, 0x0005008e, 0x00000007, 0x000000a6, 0x000000a4, 0x00000035, 0x00050081, + 0x00000007, 0x000000a8, 0x000000b7, 0x000000a6, 0x0005008e, 0x00000007, 0x000000aa, 0x000000a4, + 0x0000003a, 0x00050081, 0x00000007, 0x000000ac, 0x000000b2, 0x000000aa, 0x00050088, 0x00000007, + 0x000000ad, 0x000000a8, 0x000000ac, 0x0007000c, 0x00000007, 0x000000ae, 0x00000001, 0x0000001a, + 0x000000ad, 0x00000041, 0x00050051, 0x00000006, 0x00000089, 0x000000ae, 0x00000000, 0x00050051, + 0x00000006, 0x0000008a, 0x000000ae, 0x00000001, 0x00050051, 0x00000006, 0x0000008b, 0x000000ae, + 0x00000002, 0x00070050, 0x00000045, 0x0000008c, 0x00000089, 0x0000008a, 0x0000008b, 0x00000056, + 0x0003003e, 0x00000068, 0x0000008c, 0x000100fd, 0x00010038, +}; diff --git a/runtime/host.h b/runtime/host.h index b0eb23e4..6f8398f0 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -247,6 +247,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.c b/runtime/input.c index 108b967b..4980dac1 100644 --- a/runtime/input.c +++ b/runtime/input.c @@ -282,7 +282,10 @@ static void walk_get(void) { } } -// 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, t0; static int32_t held[2]; @@ -305,8 +308,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 float stick_dead = -1; // TOTK_STICK_DEADZONE as a fraction of full deflection; live (cfg_version) diff --git a/runtime/input_map.c b/runtime/input_map.c index 49220eac..5bce90ef 100644 --- a/runtime/input_map.c +++ b/runtime/input_map.c @@ -288,6 +288,18 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) { return east_labelled_a ? PAD_LAYOUT_NINTENDO : PAD_LAYOUT_XBOX; } +int input_prompts_pick(const char *prompts, const char *pad_layout) { + if (prompts && *prompts) return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : PROMPTS_NINTENDO; + return pad_layout && !strcasecmp(pad_layout, "xbox_prompts") ? PROMPTS_XBOX : PROMPTS_NINTENDO; +} + +const char *input_prompts_folder(int prompts, const char *pad_layout) { + if (prompts != PROMPTS_XBOX) return NULL; + // The folders are read at start, before a pad is open: auto counts as Xbox, as for a pad without Nintendo labels. + // A Nintendo-labelled pad under auto plays by label too (its A is on the button labelled A), so it matches as well. + return input_pad_layout_pick(pad_layout, 0) == PAD_LAYOUT_NINTENDO ? "romfs-patches-xbox" : "romfs-patches-xbox-label"; +} + uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout) { const PadBinding *t = input_map.pads[layout]; uint64_t b = 0; diff --git a/runtime/input_map.h b/runtime/input_map.h index 6e66b4ab..545eae89 100644 --- a/runtime/input_map.h +++ b/runtime/input_map.h @@ -80,11 +80,23 @@ int input_map_bind(const char *button, const char *list); // Applies the TOTK_BIND_ settings (cfg_get) over the defaults: at start, and again when one of them changes. void input_map_configure(void); -// The layout for a TOTK_PAD_LAYOUT value: "nintendo" or "xbox" (any case); "xbox_prompts" is the Nintendo layout with -// the A/B and X/Y prompts swapped (runtime/romfs.c overlay_init), so the buttons map as "nintendo". Anything else -// ("auto", NULL) picks Nintendo when the pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox -// otherwise. +// The layout for a TOTK_PAD_LAYOUT value: "nintendo" or "xbox" (any case); "xbox_prompts", 0.1.9's name for the Nintendo +// layout with the Xbox prompts, maps the buttons as "nintendo". Anything else ("auto", NULL) picks Nintendo when the +// pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox otherwise. int input_pad_layout_pick(const char *setting, int east_labelled_a); + +// Button prompts (TOTK_PROMPTS): the controller whose buttons the game's prompts show. Nintendo: the game's own. Xbox: +// LB RB LT RT, Menu, View and a d-pad cross for the other buttons, and the face buttons named by the label of the +// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). +enum { PROMPTS_NINTENDO, PROMPTS_XBOX }; +// The prompts for a TOTK_PROMPTS value ("nintendo" or "xbox", any case). Unset or empty: Xbox while the pad layout +// setting is "xbox_prompts", else Nintendo. +int input_prompts_pick(const char *prompts, const char *pad_layout); +// The folder next to romfs-index.bin that holds those prompts for a TOTK_PAD_LAYOUT value, NULL for the game's own. The +// Nintendo layout plays an Xbox pad by position, so its folder names the face buttons the other way round +// (romfs-patches-xbox: the right button does A and is labelled B); xbox and auto put every Switch button on the button +// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. +const char *input_prompts_folder(int prompts, const char *pad_layout); // down[pad] != 0 for the gamepad inputs held. Returns the Switch button bits (0..15) the layout's pad table presses. uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout); diff --git a/runtime/main.c b/runtime/main.c index dd4eabb0..9bd1009a 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -260,11 +260,22 @@ static double now_s(void) { return (double)plat_now_ns() / 1e9; } static volatile int host_probe_hits; static void host_probe(Cpu *c) { host_probe_hits++; c->x[0] = 42; } +// The instruction set build_game.py --cpu compiled for: v3 (AVX2/FMA/BMI2, the default) or v2 (SSE4.2/POPCNT). +#ifndef RT_CPU_LEVEL +#define RT_CPU_LEVEL 3 +#endif + static void check_cpu(void) { __builtin_cpu_init(); +#if RT_CPU_LEVEL >= 3 int ok = __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && __builtin_cpu_supports("bmi2"); printf("cpu: x86-64-v3 (AVX2, FMA, BMI2) %s\n", ok ? "present" : "MISSING"); CHECK(ok, "the lifted code is built for x86-64-v3"); +#else + int ok = __builtin_cpu_supports("sse4.2") && __builtin_cpu_supports("popcnt"); + printf("cpu: x86-64-v2 (SSE4.2, POPCNT) %s\n", ok ? "present" : "MISSING"); + CHECK(ok, "the lifted code is built for x86-64-v2"); +#endif } // Layout: ascending, no overlap, below 2^39, and inside the window mem_init reserved. @@ -469,6 +480,9 @@ static void portable_paths(RtConfig *c) { int main(int argc, char **argv) { mem_init(); // first: claim the guest address space before anything else can land there; reads totk.ini + // A restart from the settings menu (gfx_present.c gfx_window_closed) starts this process while the one it replaces + // is still exiting: its log, RomFS and saves are free once it is gone. + if (plat_restart_wait(30000) < 0) rt_log("restart: the previous process still runs after 30 s; starting anyway"); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); plat_crash_hook(crash_handler); diff --git a/runtime/ov_probe.c b/runtime/ov_probe.c index 9a08a3e5..844b3e01 100644 --- a/runtime/ov_probe.c +++ b/runtime/ov_probe.c @@ -811,17 +811,23 @@ 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, Brazilian Portuguese and Simplified +// Chinese 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); // the description pane keeps the whole text and a note after it (option_rows.cpp desc_set) CHECK(strlen(ui_text_in("en", (UiTextId)id)) + 256 < UI_DESC_BYTES && - strlen(ui_text_in("ru", (UiTextId)id)) + 256 < UI_DESC_BYTES, "menu text id %d is too long for the " - "description pane", id); + strlen(ui_text_in("ru", (UiTextId)id)) + 256 < UI_DESC_BYTES && + strlen(ui_text_in("pt-BR", (UiTextId)id)) + 256 < UI_DESC_BYTES && + strlen(ui_text_in("zh-Hans", (UiTextId)id)) + 256 < UI_DESC_BYTES, + "menu text id %d is too long for the description pane", id); + CHECK(ui_text_defined("zh-Hans", (UiTextId)id), "menu text id %d lacks Simplified Chinese", 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 @@ -829,22 +835,31 @@ 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", "zh-Hans"); + CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("zh-Hans", UI_MENU_TITLE), "menu_text ignores MENU_LANG=zh-Hans"); 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 *sys_lang = ui_text_lang(plat_ui_language()); + const char *auto_lang = ui_text_defined(sys_lang, UI_MENU_TITLE) ? sys_lang : "en"; + 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/platform/linux.c b/runtime/platform/linux.c index 136b43c4..690ecb44 100644 --- a/runtime/platform/linux.c +++ b/runtime/platform/linux.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1650,3 +1651,85 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) { while (k < 0 && errno == EINTR); return (long)k; } + +// ---- restart +// TOTK_RESTART_WAIT names the process that called plat_restart, as its id and start time (field 22 of /proc//stat, +// clock ticks after boot): a process that has only reused the id is not waited for. Waiting keeps the new process off +// the old one's files (the log it moves at start, the saves) until the old one is gone. The new process gets no +// descriptor past stderr (glibc 2.34's closefrom file action), and the default signal mask and dispositions, whatever +// the calling thread had. +#define RESTART_WAIT "TOTK_RESTART_WAIT" + +// The start time of process pid (field 22 of its /proc stat line), 0 when it is gone. +static unsigned long long process_start(int pid) { + char path[64], buf[1024]; + snprintf(path, sizeof path, "/proc/%d/stat", pid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + size_t n = fread(buf, 1, sizeof buf - 1, f); + fclose(f); + buf[n] = 0; + char *p = strrchr(buf, ')'); // the command name may hold spaces + unsigned long long start = 0; + if (!p || sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %*d %*d %llu", + &start) != 1) + return 0; + return start; +} + +int plat_restart(void) { + // the arguments, NUL-separated, from /proc/self/cmdline + static char args[16384]; + char *argv[256]; + int argc = 0; + FILE *f = fopen("/proc/self/cmdline", "rb"); + size_t n = f ? fread(args, 1, sizeof args - 1, f) : 0; + if (f) fclose(f); + args[n] = 0; + for (size_t i = 0; i < n && argc < 255; i += strlen(args + i) + 1) argv[argc++] = args + i; + argv[argc] = NULL; + char exe[PATH_MAX], wait[64]; + if (!argc || !plat_exe_path(exe, sizeof exe)) return 0; + snprintf(wait, sizeof wait, "%d.%llu", (int)getpid(), process_start((int)getpid())); + posix_spawn_file_actions_t fa; + posix_spawn_file_actions_init(&fa); + posix_spawn_file_actions_addclosefrom_np(&fa, 3); + posix_spawnattr_t at; + posix_spawnattr_init(&at); + sigset_t none, all; + sigemptyset(&none); + sigfillset(&all); + posix_spawnattr_setsigmask(&at, &none); + posix_spawnattr_setsigdefault(&at, &all); + posix_spawnattr_setflags(&at, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF); + setenv(RESTART_WAIT, wait, 1); + pid_t pid; + int e = posix_spawn(&pid, exe, &fa, &at, argv, environ); + unsetenv(RESTART_WAIT); + posix_spawnattr_destroy(&at); + posix_spawn_file_actions_destroy(&fa); + return e == 0; +} + +int plat_restart_wait(uint32_t timeout_ms) { + const char *v = getenv(RESTART_WAIT); + if (!v) return 0; + int pid = 0; + unsigned long long start = 0; + int ok = sscanf(v, "%d.%llu", &pid, &start) == 2 && pid > 0 && start; + unsetenv(RESTART_WAIT); // the processes this one starts do not wait again + if (!ok) return 0; + // The descriptor is taken first: a start time that still matches then proves it is that process, not a new one with + // the id. It reads as ready once the process has exited, reaped or not. + int fd = (int)syscall(SYS_pidfd_open, pid, 0); + if (fd < 0) return 0; // already gone + int r = 0; + if (process_start(pid) == start) { + struct pollfd p = {fd, POLLIN, 0}; + do r = poll(&p, 1, (int)timeout_ms); + while (r < 0 && errno == EINTR); + r = r > 0 ? 1 : -1; + } + close(fd); + return r; +} diff --git a/runtime/platform/platform.h b/runtime/platform/platform.h index 66ac1870..70249095 100644 --- a/runtime/platform/platform.h +++ b/runtime/platform/platform.h @@ -411,3 +411,11 @@ PlatChild *plat_child_start(const char *exe, const char *arg, uint32_t *err); void plat_child_stop(PlatChild *c); // kills the child and frees c int plat_child_write(PlatChild *c, const void *data, size_t n); // 1 when all n bytes were written long plat_child_read(PlatChild *c, void *buf, size_t cap); // bytes read (at least 1); 0 or negative: pipe broke + +// ---- restart: this program again, in a new process that starts once this one is gone +// Starts this executable again with the same command line, environment and working folder, and no handle of this +// process. 1 when it started; the caller then exits. +int plat_restart(void); +// In a process plat_restart started: waits, at most timeout_ms, until the process that started it has exited. 1 after +// the wait, -1 on timeout, 0 when there is nothing to wait for (not started by plat_restart, or that process is gone). +int plat_restart_wait(uint32_t timeout_ms); diff --git a/runtime/platform/win32.c b/runtime/platform/win32.c index b32c644d..096ef9ec 100644 --- a/runtime/platform/win32.c +++ b/runtime/platform/win32.c @@ -1526,3 +1526,44 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) { if (!ReadFile(c->out, buf, (DWORD)cap, &got, NULL)) return -1; return (long)got; } + +// ---- restart +// TOTK_RESTART_WAIT names the process that called plat_restart, as its id and creation time: a process that has only +// reused the id is not waited for. Waiting keeps the new process off the old one's files (the log it moves at start, +// the saves) until the old one is gone; no handle is inherited, so none of them stays open in the new one either. +#define RESTART_WAIT "TOTK_RESTART_WAIT" + +static uint64_t process_created(HANDLE h) { + FILETIME c, e, k, u; + return GetProcessTimes(h, &c, &e, &k, &u) ? ft64(c) : 0; +} + +int plat_restart(void) { + char wait[48]; + snprintf(wait, sizeof wait, "%lu.%llu", GetCurrentProcessId(), (unsigned long long)process_created(GetCurrentProcess())); + plat_setenv(RESTART_WAIT, wait); + STARTUPINFOW si = {.cb = sizeof si}; + PROCESS_INFORMATION pi; + wchar_t *cmd = _wcsdup(GetCommandLineW()); // CreateProcessW may write its command line + BOOL ok = cmd && CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); + free(cmd); + plat_setenv(RESTART_WAIT, NULL); + if (!ok) return 0; + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return 1; +} + +int plat_restart_wait(uint32_t timeout_ms) { + char v[48]; + if (!plat_getenv(RESTART_WAIT, v, sizeof v)) return 0; + plat_setenv(RESTART_WAIT, NULL); // the processes this one starts do not wait again + unsigned long pid = 0; + unsigned long long created = 0; + if (sscanf(v, "%lu.%llu", &pid, &created) != 2) return 0; + HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!h) return 0; // already gone + int r = process_created(h) != created ? 0 : WaitForSingleObject(h, timeout_ms) == WAIT_OBJECT_0 ? 1 : -1; + CloseHandle(h); + return r; +} diff --git a/runtime/romfs.c b/runtime/romfs.c index 64129b0d..a389593f 100644 --- a/runtime/romfs.c +++ b/runtime/romfs.c @@ -24,6 +24,7 @@ #include "cfg.h" #include "fs.h" #include "host.h" +#include "input_map.h" #include "romfs_config.h" #include "romfs_path.h" #include "platform/platform.h" @@ -315,40 +316,46 @@ 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]; - PlatFile *f = base ? open_read(base->path) : image; - uint64_t off = base ? 0 : entry(i).offset, n = base ? base->size : entry(i).size; - void *in = n && n < (16u << 20) && f ? malloc((size_t)n) : NULL; - int ok = in && read_at(f, in, (uint32_t)n, off) == (int64_t)n; - if (base && f) plat_file_close(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]; + PlatFile *f = *base ? open_read((*base)->path) : image; + uint64_t off = *base ? 0 : entry(i).offset, size = *base ? (*base)->size : entry(i).size; + void *in = size && size < (16u << 20) && f ? malloc((size_t)size) : NULL; + int ok = in && read_at(f, in, (uint32_t)size, off) == (int64_t)size; + if (*base && f) plat_file_close(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"); plat_file_mkdir_p(dir); - ok = plat_file_write(file, out, out_n); + int ok = plat_file_write(file, out, out_n); free(out); PlatFile *r = ok ? open_read(file) : NULL; if (!r) { - rt_log("RomFS: cannot write %s; the game keeps its own resolution", file); - return; + rt_log("RomFS: cannot write %s; %s", file, keeps); + return 0; } Identity id = identity_of(r); plat_file_close(r); @@ -365,31 +372,97 @@ 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; } -static int xbox_prompts_ready; // romfs-patches-xbox/manifest.tsv was next to romfs-index.bin at start -static int xbox_prompts_active; // and overlay_init loaded it +// 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(); +} -int romfs_xbox_prompts_ready(void) { return xbox_prompts_ready; } -int romfs_xbox_prompts_active(void) { return xbox_prompts_active; } +// 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(); +} + +// The button prompts' folders (input_prompts_folder) and whether each had a manifest next to romfs-index.bin at start; +// the one the settings asked for at start, the one overlay_init loaded (NULL: the game's own prompts) and why the first +// did not load (ROMFS_PROMPTS_*). The menu compares them with the settings in effect (ui/menu.cpp prompts_note). +static struct { const char *name; int ready; } prompts_folders[2]; +static const char *prompts_wanted, *prompts_loaded; +static int prompts_off; + +const char *romfs_prompts(void) { return prompts_loaded; } + +int romfs_prompts_ready(const char *folder) { + for (int i = 0; i < 2; i++) + if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready; + return 0; +} + +int romfs_prompts_off(const char *folder) { + return folder && prompts_wanted && !strcmp(folder, prompts_wanted) ? prompts_off : ROMFS_PROMPTS_OK; +} + +// The first RomFS file that the overlays [a, b) and [c, d) both replace, or NULL. +static const char *overlay_clash(size_t a, size_t b, size_t c, size_t d) { + for (size_t i = a; i < b; i++) + for (size_t j = c; j < d; j++) + if (overlays[i].index != ADDED && overlays[i].index == overlays[j].index) return overlays[i].name; + return NULL; +} + +// Drops the overlays [a, b), the ones after them moving down. +static void overlay_drop(size_t a, size_t b) { + for (size_t k = a; k < b; k++) { + free((void *)overlays[k].path); + free((void *)overlays[k].name); + } + memmove(overlays + a, overlays + b, (noverlay - b) * sizeof *overlays); + noverlay -= b - a; +} static void overlay_init(void) { // TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py). // A game resolution that is not 16:9 takes romfs-patches-x instead when it is there: the same overlay with // the UI laid out for that shape (make_romfs_patches.py --aspect), when the game version has the camera aspect patch // the layout goes with (res_wants_wide_overlay). - // With pad_layout = xbox_prompts, romfs-patches-xbox in its place: the same patches with the A/B and X/Y prompts - // swapped (make_romfs_patches.py --xbox-prompts). The game reads the archives once at boot, so the prompts stay - // until restart even though the layout itself changes live. Each folder replaces romfs-patches as a whole and the - // setup builds no wide folder with Xbox prompts, so a wide game resolution keeps the Switch prompts. - char def[2100], xbox[2100]; - const char *patches = cfg_get("TOTK_ROMFS_PATCHES"); + // With prompts = xbox, the Xbox prompts' folder for the pad layout in its place (input_prompts_folder): the same + // patches with Xbox button icons (make_romfs_patches.py --prompts). The game reads the archives once at boot, so + // the prompts stay until restart even though the layout itself changes live. Each folder replaces romfs-patches as + // a whole and the setup builds no folder of another shape with Xbox prompts, so a game resolution that is not 16:9 + // keeps the Switch prompts. So does a RomFS mod that replaces one of the prompts' files (the fonts, the resource + // size table): romfs-patches loads in their place, where two overlays replacing one file would stop the game. + char def[2100], path[2100]; + const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS"); int wide = 0; unsigned out[2]; res_wanted(out); @@ -403,30 +476,56 @@ static void overlay_init(void) { "(tools/make_romfs_patches.py --aspect %ux%u)", out[0], out[1], out[0], out[1]); } } - xbox_prompts_ready = - snprintf(xbox, sizeof xbox, "%s/romfs-patches-xbox/manifest.tsv", index_dir) < (int)sizeof xbox && - plat_file_exists(xbox); - int want_xbox = !strcasecmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts"); - if (!patches && want_xbox && xbox_prompts_ready) { - xbox[strlen(xbox) - strlen("/manifest.tsv")] = 0; - xbox_prompts_active = overlay_load(xbox, 1); - if (xbox_prompts_active) rt_log("RomFS overlay: Xbox button prompts (%s)", xbox); - else rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", xbox); - } else if (want_xbox) { - rt_log("RomFS overlay: pad_layout = xbox_prompts, but %s; Switch prompts stay", - wide ? "the game resolution takes the wide UI layout" - : patches ? "TOTK_ROMFS_PATCHES is set" - : "romfs-patches-xbox has no manifest.tsv (run the setup again)"); + static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each folder + for (int i = 0; i < 2; i++) { + prompts_folders[i].name = input_prompts_folder(PROMPTS_XBOX, layouts[i]); + prompts_folders[i].ready = + snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, prompts_folders[i].name) < (int)sizeof path && + plat_file_exists(path); } - if (!patches && !xbox_prompts_active && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def && - plat_file_exists(def)) { - def[strlen(def) - strlen("/manifest.tsv")] = 0; - patches = def; + const char *layout = cfg_value("TOTK_PAD_LAYOUT"); + prompts_wanted = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout); + prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK + : wide ? ROMFS_PROMPTS_SHAPE + : patches ? ROMFS_PROMPTS_PATCHES + : !romfs_prompts_ready(prompts_wanted) ? ROMFS_PROMPTS_MISSING + : ROMFS_PROMPTS_OK; + size_t first = noverlay; + if (prompts_wanted && prompts_off == ROMFS_PROMPTS_OK) { + snprintf(path, sizeof path, "%s/%s", index_dir, prompts_wanted); // fits: its manifest path did + if (overlay_load(path, 1)) { + prompts_loaded = prompts_wanted; + rt_log("RomFS overlay: Xbox button prompts (%s)", path); + } else { + prompts_off = ROMFS_PROMPTS_FAILED; + rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", path); + } + } else if (prompts_wanted) { + rt_log("RomFS overlay: prompts = xbox, but %s; Switch prompts stay", + prompts_off == ROMFS_PROMPTS_SHAPE ? "the game resolution takes its own UI layout" + : prompts_off == ROMFS_PROMPTS_PATCHES ? "TOTK_ROMFS_PATCHES is set" + : "their folder has no manifest.tsv (run the setup again)"); + } + size_t prompts_end = noverlay; + char plain[2100]; // romfs-patches, when it has a manifest + int plain_ok = snprintf(plain, sizeof plain, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof plain && + plat_file_exists(plain); + if (plain_ok) plain[strlen(plain) - strlen("/manifest.tsv")] = 0; + if (!patches && !prompts_loaded && plain_ok) patches = plain; + if (patches && *patches && strcmp(patches, "0")) overlay_load(patches, 0); + size_t mods_first = noverlay; + if (mods && *mods && strcmp(mods, "0")) overlay_load(mods, 0); + const char *clash = prompts_loaded ? overlay_clash(first, prompts_end, mods_first, noverlay) : NULL; + if (clash) { + rt_log("RomFS overlay: the RomFS mods folder replaces %s, which the Xbox prompts change too; Switch prompts stay", + clash); + overlay_drop(first, prompts_end); + prompts_loaded = NULL; + prompts_off = ROMFS_PROMPTS_MODS; + if (plain_ok) overlay_load(plain, 0); } - const char *dirs[2] = {patches, cfg_get("TOTK_ROMFS_MODS")}; - for (int i = 0; i < 2; i++) - if (dirs[i] && *dirs[i] && strcmp(dirs[i], "0")) overlay_load(dirs[i], 0); 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/shaders/hdr_encode.comp b/runtime/shaders/hdr_encode.comp new file mode 100644 index 00000000..c6fb04da --- /dev/null +++ b/runtime/shaders/hdr_encode.comp @@ -0,0 +1,34 @@ +#version 450 +// HDR10 encode on the present (runtime/vk_hdr.c vk_hdr_encode): the game's picture, crop rectangle at offset, linear +// Rec. 709 with the HUD's white at 1.0 (an sRGB view decodes the 8-bit window texture), into an RGBA16F image of PQ +// code values in Rec. 2020 that FSR 1 or the blit then scale into the HDR10 swapchain. p.x: nits of 1.0, p.y: the +// display's peak in nits, p.z: 1 when the source holds sRGB-encoded values in a UNORM format. +// PQ: SMPTE ST 2084; the Rec. 709 to Rec. 2020 matrix: ITU-R BT.2087. +layout(local_size_x = 8, local_size_y = 8) in; +layout(binding = 0) uniform sampler2D src; +layout(binding = 1, rgba16f) uniform writeonly image2D dst; +layout(push_constant) uniform P { + ivec2 offset; + ivec2 size; + vec4 p; +} pc; + +vec3 srgb_decode(vec3 c) { + return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), greaterThan(c, vec3(0.04045))); +} + +vec3 pq(vec3 nits) { + const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875; + vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1)); + return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2)); +} + +void main() { + ivec2 at = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(at, pc.size))) return; + vec3 c = max(texelFetch(src, at + pc.offset, 0).rgb, vec3(0.0)); + if (pc.p.z > 0.5) c = srgb_decode(clamp(c, 0.0, 1.0)); + const mat3 to2020 = mat3(0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.0880, 0.0433, 0.0114, 0.8956); + vec3 nits = min(max(to2020 * c, vec3(0.0)) * pc.p.x, vec3(pc.p.y)); + imageStore(dst, at, vec4(pq(nits), 1.0)); +} diff --git a/runtime/shaders/hdr_fullscreen.vert b/runtime/shaders/hdr_fullscreen.vert new file mode 100644 index 00000000..ff645324 --- /dev/null +++ b/runtime/shaders/hdr_fullscreen.vert @@ -0,0 +1,8 @@ +#version 450 +// One triangle over the whole target, for hdr_ui.frag (runtime/vk_hdr.c vk_hdr_ui_compose). +layout(location = 0) out vec2 uv; + +void main() { + uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(uv * 2.0 - 1.0, 0.0, 1.0); +} diff --git a/runtime/shaders/hdr_tonemap.frag b/runtime/shaders/hdr_tonemap.frag new file mode 100644 index 00000000..5afe98f8 --- /dev/null +++ b/runtime/shaders/hdr_tonemap.frag @@ -0,0 +1,61 @@ +#version 450 +// The game's tonemap pass for HDR output (runtime/vk_hdr.c vk_hdr_shader_swap puts it in place of the translated +// shader when TOTK_HDR=1). Same inputs as the game's: fp_t_tcb_8 (bloom, clamped to 10000 as the game does) plus +// fp_t_tcb_A (the scene), weights in c1[0] and the saturation grade in c3[0]. The game maps luminance and each channel +// with 1 - e^-x, blends the two by the luminance curve squared, clamps to 0..1 and grades saturation. Here the curve is +// the game's up to PIVOT and a straight line with its slope above, so mid-greys look as in SDR and highlights keep +// going; the grade works on the colour divided by its largest channel above 1; a roll-off on the largest channel stops +// at the display's peak. The output is relative to the HUD's white (1.0), which the present maps to TOTK_HDR_UI_NITS. +// Approach after RenoDX's TotK mod by souperman9 and Musa (github.com/clshortfuse/renodx, src/games/totk, MIT): its +// "extended vanilla" curve. +// Bindings are those of the game's translated shader: vk_hdr.c rewrites them from the original's names. +layout(location = 0) in vec4 uv; +layout(location = 0) out vec4 color; + +layout(set = 0, binding = 0, std140) uniform SupportBuffer { + vec4 pad[88]; + vec4 hdr; // byte 1408 (vk_exec_draw.c support_fill): game white / HUD white, peak / game white +} support_buffer; +layout(set = 0, binding = 1) uniform sampler2D fp_t_tcb_8; +layout(set = 0, binding = 2) uniform sampler2D fp_t_tcb_A; +layout(set = 0, binding = 3, std140) uniform C1 { vec4 v[4096]; } fp_c1; +layout(set = 0, binding = 4, std140) uniform C3 { vec4 v[4096]; } fp_c3; + +const float PIVOT = 0.18; + +float curve(float x) { // the game's 1 - e^-x below PIVOT, its tangent there above + float y0 = 1.0 - exp(-PIVOT); + return x <= PIVOT ? 1.0 - exp(-x) : y0 + exp(-PIVOT) * (x - PIVOT); +} + +vec3 curve3(vec3 x) { return vec3(curve(x.r), curve(x.g), curve(x.b)); } + +float maxc(vec3 c) { return max(c.r, max(c.g, c.b)); } + +void main() { + vec3 x = min(texture(fp_t_tcb_8, uv.xy).rgb, vec3(10000.0)) + texture(fp_t_tcb_A, uv.xy).rgb; + vec4 w = fp_c1.v[0], g = fp_c3.v[0]; + float game = support_buffer.hdr.x > 0.0 ? support_buffer.hdr.x : 1.0; + float peak = support_buffer.hdr.y > 1.0 ? support_buffer.hdr.y : 1.0; + + float lum = max(x.r * 0.2989 + x.g * w.x + x.b * w.y, 0.0); + float sdr = 1.0 - exp(-lum); + vec3 by_lum = lum > 0.0 ? x * (curve(lum) / lum) : x; + vec3 c = max(mix(by_lum, curve3(x), sdr * sdr), vec3(0.0)); + + // the game's saturation grade, on the colour scaled into 0..1 by its largest channel + float s = max(maxc(c), 1.0); + vec3 n = c / s; + float m = maxc(n); + float d = n.r * 0.6666667 + (n.g + n.b) * w.z - 1.0; + float grade = g.y * (1.0 - d * d) + g.x; + c = s * ((n - m) * grade + m); + + // roll-off of the largest channel from half the peak to the peak + float top = maxc(c), knee = 0.5 * peak; + if (top > knee) { + float r = peak - knee; + c *= (knee + r * (1.0 - exp(-(top - knee) / r))) / top; + } + color = vec4(max(c, vec3(0.0)) * game, 0.0); +} diff --git a/runtime/shaders/hdr_ui.frag b/runtime/shaders/hdr_ui.frag new file mode 100644 index 00000000..30299d03 --- /dev/null +++ b/runtime/shaders/hdr_ui.frag @@ -0,0 +1,27 @@ +#version 450 +// The in-game menu on an HDR10 swapchain (runtime/vk_hdr.c vk_hdr_ui_compose): ImGui drew it into an RGBA8 image, +// premultiplied sRGB colour over a clear 0; this turns each pixel back into its colour, puts its white at p.x nits and +// writes the PQ code with its coverage, which the pipeline blends over the picture (in PQ code values, as the menu +// blends in sRGB code values on an SDR swapchain). PQ: SMPTE ST 2084; Rec. 709 to Rec. 2020: ITU-R BT.2087. +layout(location = 0) in vec2 uv; +layout(location = 0) out vec4 color; +layout(binding = 0) uniform sampler2D ui; +layout(push_constant) uniform P { vec4 p; } pc; + +vec3 srgb_decode(vec3 c) { + return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), greaterThan(c, vec3(0.04045))); +} + +vec3 pq(vec3 nits) { + const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875; + vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1)); + return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2)); +} + +void main() { + vec4 u = texture(ui, uv); + if (u.a <= 0.0) discard; + vec3 c = srgb_decode(clamp(u.rgb / u.a, 0.0, 1.0)); + const mat3 to2020 = mat3(0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.0880, 0.0433, 0.0114, 0.8956); + color = vec4(pq(max(to2020 * c, vec3(0.0)) * pc.p.x), u.a); +} diff --git a/runtime/simd.h b/runtime/simd.h index 535cb106..d8fb45c8 100644 --- a/runtime/simd.h +++ b/runtime/simd.h @@ -7,7 +7,7 @@ // tables. Not modelled: FPSR cumulative exception bits and QC, FPCR trap enables, FP16 arithmetic (ARMv8.2). // FPCR.AHP is honoured by the half-precision conversions. Host assumptions: IEEE binary32/64, MXCSR in // round-to-nearest outside the slow paths, with FTZ|DAZ equal to FPCR.FZ (cpu.h rt_fpcr_sync keeps it so); fma must be -// correctly rounded (build x86 with -mfma). +// correctly rounded: -march=x86-64-v3 has the FMA instruction, and the v2 build links runtime/fma.c for it. #pragma once #include #include diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 77f9d4b6..ef806392 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -35,6 +35,7 @@ static int g_font_bad; extern "C" { #include "cfg.h" +#include "fs.h" #include "input.h" #include "input_map.h" #include "perfmon.h" @@ -49,9 +50,6 @@ void vk_queue_unlock(void); void res_sizes(unsigned out[2], unsigned scene[2]); double frame_step_limit_hz(void); extern const int rt_game_version; -// fs.h (romfs.c): romfs-patches-xbox was next to romfs-index.bin at start, and was loaded. -int romfs_xbox_prompts_ready(void); -int romfs_xbox_prompts_active(void); extern const char rt_port_version[]; } @@ -266,7 +264,9 @@ static int vk_up(const MenuTarget *t) { // 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). +// A catalog row also holds menu text (Simplified Chinese), so every string of the row goes into the builder: the merged +// font must cover the whole menu of that language, not only its name. 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}; 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}, @@ -310,6 +310,11 @@ extern "C" int menu_font_check(void) { return ok; } +// The glyphs of every string of a catalog row (ui_text_visit), for the font that draws that language. +static void add_row_glyphs(void *ctx, const char *text) { + static_cast(ctx)->AddText(text); +} + static int fonts_up(float scale) { enum { N = sizeof kCjk / sizeof *kCjk }; ImFontAtlas *fa = ImGui::GetIO().Fonts; @@ -334,6 +339,7 @@ static int fonts_up(float scale) { merged++; ImFontGlyphRangesBuilder b; b.AddText(ui_text_in("en", kCjk[i].name)); + ui_text_visit(kCjk[i].lang, add_row_glyphs, &b); b.BuildRanges(&ranges[i]); ImFontConfig mc; mc.MergeMode = true; @@ -639,7 +645,15 @@ 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_slider("TOTK_FOV", UI_MENU_FOV, 70, 140, UI_MENU_FOV_DESC, 5, "%.0f %%"); + static const char *const aniso[] = {"game", "2", "4", "8", "16"}; + const char *aniso_names[] = {menu_text(UI_MENU_ANISO_GAME), "2x", "4x", "8x", "16x"}; + opt_choice_list("TOTK_ANISO", UI_MENU_ANISO, aniso, aniso_names, 5, UI_MENU_ANISO_DESC); rows_color(); + opt_group(UI_MENU_HDR_GROUP); + opt_toggle("TOTK_HDR", UI_MENU_HDR, UI_MENU_HDR_DESC); + opt_slider("TOTK_HDR_PEAK_NITS", UI_MENU_HDR_PEAK, 400, 10000, UI_MENU_HDR_PEAK_DESC, 50, "%.0f"); + opt_slider("TOTK_HDR_GAME_NITS", UI_MENU_HDR_GAME, 80, 500, UI_MENU_HDR_GAME_DESC, 5, "%.0f"); + opt_slider("TOTK_HDR_UI_NITS", UI_MENU_HDR_UI, 80, 500, UI_MENU_HDR_UI_DESC, 5, "%.0f"); opt_end(); } @@ -662,14 +676,11 @@ static void tab_sound(float scale) { opt_end(); } -// The note under the layout. Xbox prompts (the Nintendo layout with the A/B and X/Y prompts swapped, romfs.c -// overlay_init) change the buttons at once but the prompts only at the next start: "files missing" without -// romfs-patches-xbox, "prompts change after restart" while the prompts in use differ from the choice. Automatic with a -// gamepad connected: "in use: Xbox". NULL otherwise. +// A confirmation is open (Controls: restart, Advanced: reset): B and Esc close it, not the menu; L / R stay on the page. +static bool g_modal; + +// The note under the layout: Automatic with a gamepad connected, the layout it picked ("in use: Xbox"). NULL otherwise. static const char *pad_layout_note(void) { - bool want = !strcasecmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts"); - if (want && !romfs_xbox_prompts_ready()) return menu_text(UI_MENU_PAD_LAYOUT_PROMPTS_MISSING); - if (want != (romfs_xbox_prompts_active() != 0)) return menu_text(UI_MENU_PAD_LAYOUT_PROMPTS_RESTART); int got = input_pad_layout(); if (got < 0 || strcmp(cfg_value("TOTK_PAD_LAYOUT"), "auto")) return nullptr; static char note[96]; @@ -713,33 +724,95 @@ static void row_walk_key(void) { -1, n); } +// The note under the prompts. The settings name a folder of prompts (input_prompts_folder: the prompts and the pad +// layout, as a layout that puts A on the right button needs the face buttons named the other way round), but the game +// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: "files +// missing" when the setup did not write the one asked for, why it was left out at start (damaged, a game resolution +// that is not 16:9, a RomFS mod with the same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then +// *restart is set: a restart would bring the prompts asked for. NULL when they match. +static const char *prompts_note(bool *restart) { + *restart = false; + const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts(); + const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout); + if (want == used || (want && used && !strcmp(want, used))) return nullptr; + if (want && !romfs_prompts_ready(want)) return menu_text(UI_MENU_PROMPTS_MISSING); + switch (romfs_prompts_off(want)) { + case ROMFS_PROMPTS_FAILED: return menu_text(UI_MENU_PROMPTS_FAILED); + case ROMFS_PROMPTS_SHAPE: return menu_text(UI_MENU_PROMPTS_OFF_SHAPE); + case ROMFS_PROMPTS_MODS: return menu_text(UI_MENU_PROMPTS_OFF_MODS); + case ROMFS_PROMPTS_PATCHES: return menu_text(UI_MENU_PROMPTS_OFF_PATCHES); + default: *restart = true; return menu_text(UI_MENU_PROMPTS_RESTART); + } +} + +// The confirmation of "Restart now", over the menu; Cancel has the cursor first. Restart writes totk.ini, then closes +// the game as Quit does and starts it again (gfx_window_request_restart). It waits while the game writes a save, and +// the game stays when totk.ini cannot be written, as the new prompts would not come back. +static void restart_confirm(void) { + g_modal = false; + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + if (!ImGui::BeginPopupModal("##restart_confirm", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize)) + return; + g_modal = true; + ImGui::TextUnformatted(menu_text(UI_MENU_RESTART_CONFIRM)); + bool saving = fs_save_busy() != 0; + if (saving || !cfg_last_save_ok()) + ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", + menu_text(saving ? UI_MENU_RESTART_SAVING : UI_MENU_SAVE_FAILED)); + ImGui::Spacing(); + const char *yes = menu_text(UI_MENU_RESTART_YES), *no = menu_text(UI_MENU_RESET_NO); + const ImGuiStyle &st = ImGui::GetStyle(); + float bw = fmaxf(ImGui::CalcTextSize(yes).x, ImGui::CalcTextSize(no).x) + st.FramePadding.x * 4; + bool close = ImGui::Button(no, ImVec2(bw, 0)); + if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + ImGui::BeginDisabled(saving); + if (ImGui::Button(yes, ImVec2(bw, 0)) && cfg_save()) gfx_window_request_restart(); + ImGui::EndDisabled(); + if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) + close = true; + if (close) { + ImGui::CloseCurrentPopup(); + opt_focus_key("##restart"); // back on the row it came from + } + ImGui::EndPopup(); +} + static void tab_controls(float scale) { opt_begin("##controls", scale); - static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX, - UI_MENU_PAD_LAYOUT_XBOX_PROMPTS}; - opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 4, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note()); + static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX}; + opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 3, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note()); + static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX}; + bool restart; + const char *note = prompts_note(&restart); + opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 2, UI_MENU_PROMPTS_DESC, note); + bool ask = restart && opt_button("##restart", UI_MENU_RESTART, UI_MENU_RESTART_DESC); opt_toggle("TOTK_MOTION", UI_MENU_MOTION, UI_MENU_MOTION_DESC); opt_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 %%"); + 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"); row_walk_key(); opt_slider("TOTK_WALK_SCALE", UI_MENU_WALK_SCALE, 0.2f, 0.9f, UI_MENU_WALK_SCALE_DESC, 0.01f, "%.2f"); binds_rows(scale); opt_end(); binds_after_page(); + if (ask) ImGui::OpenPopup("##restart_confirm"); // at the level BeginPopupModal looks it up + restart_confirm(); } 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, UI_MENU_LANGNAME_ZH_HANS}; + opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, sizeof langs / sizeof *langs, UI_MENU_MENU_LANG_DESC); 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 // A thread count with no fixed default: Automatic (unset), then the common counts. static void row_threads(const char *key, UiTextId label, UiTextId desc) { @@ -971,7 +1044,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { ImGui::SameLine(); if (ImGui::Button(quit, ImVec2(bw, 0))) gfx_window_request_close(); bool was_modal = g_modal || binds_modal(); - if (g_tab != TAB_ADVANCED) g_modal = false; + if (g_tab != TAB_ADVANCED && g_tab != TAB_CONTROLS) g_modal = false; if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))) set_open(0); ImGui::End(); diff --git a/runtime/ui/menu.h b/runtime/ui/menu.h index ae24384b..a1d5202b 100644 --- a/runtime/ui/menu.h +++ b/runtime/ui/menu.h @@ -60,6 +60,7 @@ int menu_font_check(void); // ---- what the menu asks of the platform side (gfx_window_win.c, gfx_window_sdl.c) void gfx_window_apply_settings(void); // TOTK_FULLSCREEN or TOTK_WINDOW_SIZE changed: the window follows void gfx_window_request_close(void); // as the window's close button: the process ends +void gfx_window_request_restart(void); // the same, then totk.exe starts again with the same command line int gfx_window_monitor_size(int *w, int *h); // pixels of the monitor the window is on; 0 when unknown double gfx_window_refresh_hz(void); // its refresh rate (TOTK_FPS_LIMIT=display); 0 when unknown unsigned gfx_window_dpi(void); // the window's DPI (96 at 100% display scale); any thread diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 2ca5a1e9..cfdfc8bd 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -1,6 +1,7 @@ // 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, Brazilian Portuguese and Simplified +// Chinese. #include #include @@ -16,7 +17,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) \ @@ -74,6 +76,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { "near the ground, so leaf shadows look blocky and jump; a fixed size keeps them still and " "sharper. Above 1024 the shadows cost more GPU time and video memory.", [UI_MENU_SHADOW_RES_GAME] = "Game (changes)", + [UI_MENU_ANISO] = "Texture filtering", + [UI_MENU_ANISO_DESC] = "Anisotropic filtering of surface textures: ground, roads and walls seen at a shallow angle stay sharp into the distance instead of blurring. Game: the level the game asks for, as on the Switch.", + [UI_MENU_ANISO_GAME] = "Game", [UI_MENU_SHARPNESS] = "FSR sharpness", [UI_MENU_SHARPNESS_DESC] = "Sharpening after FSR scaling; 0 turns it off.", [UI_MENU_COLOR] = "Colour", @@ -91,6 +96,18 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_COLOR_SATURATION_DESC] = "Colour strength against grey; 100 % leaves it.", [UI_MENU_COLOR_GAMMA] = "Gamma", [UI_MENU_COLOR_GAMMA_DESC] = "Below 1 brightens dark and middle tones, above 1 darkens them; 1 leaves them.", + [UI_MENU_HDR_GROUP] = "HDR", + [UI_MENU_HDR] = "HDR output", + [UI_MENU_HDR_DESC] = "Bright highlights on an HDR display. Needs HDR turned on in Windows (\"Use HDR\") or in a " + "Wayland compositor with colour management; without it the picture stays SDR. Applies after a " + "restart. The colour profile above is for SDR and is not used in HDR.", + [UI_MENU_HDR_PEAK] = "Peak brightness", + [UI_MENU_HDR_PEAK_DESC] = "Your display's peak in nits; the brightest highlights stop there.", + [UI_MENU_HDR_GAME] = "Game brightness", + [UI_MENU_HDR_GAME_DESC] = "Nits of the picture's white (paper white). 203 is the HDR reference; raise it in a " + "bright room.", + [UI_MENU_HDR_UI] = "HUD and menu brightness", + [UI_MENU_HDR_UI_DESC] = "Nits of the HUD's and this menu's white.", [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 " @@ -128,15 +145,31 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT] = "Button layout", [UI_MENU_PAD_LAYOUT_DESC] = "Which button is A. Nintendo: the right one, as on a Switch. Xbox: the bottom one, as " "labelled on an Xbox controller (cross on a PlayStation controller). Automatic picks " - "Nintendo for controllers with Nintendo labels and Xbox for the others. Xbox prompts: " - "A is the right one as with Nintendo, and the game shows the Xbox labels (B for A, A " - "for B, Y for X, X for Y); the prompts change after a restart. The letters are part of the " - "game's files, so a button you remap in Controls keeps the old letter on screen.", + "Nintendo for controllers with Nintendo labels and Xbox for the others. Which " + "controller the game's prompts show is set under Button prompts.", [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_XBOX_PROMPTS] = "Xbox prompts (A right)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A bottom)", [UI_MENU_PAD_LAYOUT_IN_USE] = "in use: %s", - [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "prompt files missing: run the setup again", - [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "prompts change after restart", + [UI_MENU_PROMPTS] = "Button prompts", + [UI_MENU_PROMPTS_DESC] = "Which controller's buttons the game's prompts show. Nintendo: the game's own. Xbox: LB, " + "RB, LT, RT, Menu, View and a d-pad cross, and A, B, X and Y as labelled on the button " + "the layout above presses (with Nintendo (A right) the right button is labelled B, so the " + "prompts for A show B). The game reads its prompts at start, so they change after a " + "restart. They are part of the game's files, so a button you remap in Controls keeps its " + "old prompt on screen.", + [UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", + [UI_MENU_PROMPTS_MISSING] = "prompt files missing: run the setup again", + [UI_MENU_PROMPTS_FAILED] = "prompt files damaged: run the setup again", + [UI_MENU_PROMPTS_RESTART] = "prompts change after restart", + [UI_MENU_PROMPTS_OFF_SHAPE] = "off at a game resolution not 16:9", + [UI_MENU_PROMPTS_OFF_MODS] = "off: a RomFS mod replaces their files", + [UI_MENU_PROMPTS_OFF_PATCHES] = "off while TOTK_ROMFS_PATCHES is set", + [UI_MENU_RESTART] = "Restart now", + [UI_MENU_RESTART_DESC] = "Closes the game and starts it again with the new prompts. Progress since your last save " + "is lost.", + [UI_MENU_RESTART_CONFIRM] = "Restart the game now? Progress since your last save is lost.", + [UI_MENU_RESTART_YES] = "Restart", + [UI_MENU_RESTART_SAVING] = "The game is saving: Restart is possible in a moment.", [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_MOUSE_SENS] = "Mouse camera sensitivity", @@ -148,6 +181,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_WALK_SCALE] = "Walk scale", [UI_MENU_WALK_SCALE_DESC] = "The tilt the keyboard's sticks get while the walk key is held. Half is a walk, the " "full tilt a run.", + [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.", @@ -347,6 +383,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { "примерно 400, поэтому тени листвы выглядят квадратными и дёргаются; постоянный размер делает " "их ровными и чётче. Выше 1024 тени требуют больше времени GPU и видеопамяти.", [UI_MENU_SHADOW_RES_GAME] = "Как в игре (меняется)", + [UI_MENU_ANISO] = "Фильтрация текстур", + [UI_MENU_ANISO_DESC] = "Анизотропная фильтрация текстур поверхностей: земля, дороги и стены под острым углом остаются чёткими вдали, а не размываются. Игра: уровень, который запрашивает игра, как на Switch.", + [UI_MENU_ANISO_GAME] = "Игра", [UI_MENU_SHARPNESS] = "Резкость FSR", [UI_MENU_SHARPNESS_DESC] = "Повышение резкости после масштабирования FSR; 0 выключает его.", [UI_MENU_COLOR] = "Цвет", @@ -365,6 +404,18 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_COLOR_SATURATION_DESC] = "Сила цвета относительно серого; 100 % — без изменений.", [UI_MENU_COLOR_GAMMA] = "Гамма", [UI_MENU_COLOR_GAMMA_DESC] = "Ниже 1 осветляет тёмные и средние тона, выше 1 затемняет их; 1 — без изменений.", + [UI_MENU_HDR_GROUP] = "HDR", + [UI_MENU_HDR] = "Вывод HDR", + [UI_MENU_HDR_DESC] = "Яркие блики на HDR-дисплее. Нужен включённый HDR в Windows («Использовать HDR») или " + "Wayland-композитор с управлением цветом; без него картинка остаётся SDR. Применяется после " + "перезапуска. Цветовой профиль выше — для SDR и в HDR не используется.", + [UI_MENU_HDR_PEAK] = "Пиковая яркость", + [UI_MENU_HDR_PEAK_DESC] = "Пик вашего дисплея в нитах; самые яркие блики останавливаются на нём.", + [UI_MENU_HDR_GAME] = "Яркость игры", + [UI_MENU_HDR_GAME_DESC] = "Ниты белого цвета картинки (paper white). 203 — эталон HDR; в светлой комнате " + "поднимите.", + [UI_MENU_HDR_UI] = "Яркость интерфейса и меню", + [UI_MENU_HDR_UI_DESC] = "Ниты белого цвета интерфейса игры и этого меню.", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " @@ -401,16 +452,31 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_PAD_LAYOUT] = "Раскладка кнопок", [UI_MENU_PAD_LAYOUT_DESC] = "Какая кнопка работает как A. Nintendo: правая, как на Switch. Xbox: нижняя, как " "подписано на контроллере Xbox (крест на контроллере PlayStation). Автоматически: " - "Nintendo для контроллеров с подписями Nintendo, Xbox для остальных. Подсказки Xbox: " - "A справа, как в Nintendo, а игра показывает надписи Xbox (B вместо A, A вместо B, Y " - "вместо X, X вместо Y); подсказки меняются после перезапуска. Буквы записаны в файлах " - "игры, поэтому у кнопки, переназначенной на вкладке управления, на экране остаётся " - "прежняя буква.", + "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_XBOX_PROMPTS] = "Подсказки Xbox (A справа)", + [UI_MENU_PAD_LAYOUT_XBOX] = "Xbox (A снизу)", [UI_MENU_PAD_LAYOUT_IN_USE] = "сейчас: %s", - [UI_MENU_PAD_LAYOUT_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова", - [UI_MENU_PAD_LAYOUT_PROMPTS_RESTART] = "подсказки сменятся после перезапуска", + [UI_MENU_PROMPTS] = "Подсказки кнопок", + [UI_MENU_PROMPTS_DESC] = "Кнопки какого контроллера показывают подсказки игры. Nintendo: как в самой игре. Xbox: " + "LB, RB, LT, RT, Menu, View и крестовина, а A, B, X и Y подписаны так же, как кнопка, " + "которую нажимает раскладка выше (в Nintendo (A справа) правая кнопка подписана B, и " + "подсказки A показывают B). Игра читает подсказки при запуске, так что они меняются после " + "перезапуска. Подсказки записаны в файлах игры, поэтому у кнопки, переназначенной на " + "вкладке управления, на экране остаётся прежняя подсказка.", + [UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", + [UI_MENU_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова", + [UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова", + [UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска", + [UI_MENU_PROMPTS_OFF_SHAPE] = "выкл. при разрешении игры не 16:9", + [UI_MENU_PROMPTS_OFF_MODS] = "выкл.: мод RomFS заменяет их файлы", + [UI_MENU_PROMPTS_OFF_PATCHES] = "выкл., пока задан TOTK_ROMFS_PATCHES", + [UI_MENU_RESTART] = "Перезапустить сейчас", + [UI_MENU_RESTART_DESC] = "Закрывает игру и запускает её снова с новыми подсказками. Прогресс после последнего " + "сохранения будет потерян.", + [UI_MENU_RESTART_CONFIRM] = "Перезапустить игру сейчас? Прогресс после последнего сохранения будет потерян.", + [UI_MENU_RESTART_YES] = "Перезапустить", + [UI_MENU_RESTART_SAVING] = "Игра сохраняется: перезапуск будет доступен через мгновение.", [UI_MENU_STICK_DEADZONE] = "Мёртвая зона стиков", [UI_MENU_STICK_DEADZONE_DESC] = "Насколько нужно отклонить стик геймпада, чтобы игра это заметила. Увеличьте, если персонаж или камера двигаются сами.", [UI_MENU_MOUSE_SENS] = "Чувствительность мыши", @@ -422,6 +488,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_WALK_SCALE] = "Сила шага", [UI_MENU_WALK_SCALE_DESC] = "Отклонение стиков клавиатуры при удержании клавиши шага. Половина — шаг, полное " "отклонение — бег.", + [UI_MENU_STICK_SENS] = "Скорость камеры (стик)", + [UI_MENU_STICK_SENS_DESC] = "Умножает скорость поворота камеры правым стиком, включая наибольшую, при каждой из пяти " + "чувствительностей камеры в игре. На мышь не влияет.", [UI_BINDS_HELP] = "Выберите ячейку и нажмите A или Enter, затем клавишу, кнопку мыши или кнопку контроллера. " "Delete или X очищает ячейку. Занятая клавиша переходит сюда; кнопка контроллера меняется " @@ -574,6 +643,788 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_OV_SCALE_DOWN] = "билинейное (FSR только увеличивает)", }; +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; um mais alto (16:10, Steam Deck) " + "leva-o para as bordas de cima e de baixo.", + [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_40] = "40 FPS", [UI_MENU_FPS_45] = "45 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_ASSUME_FOCUS] = "Continuar rodando fora de foco", + [UI_MENU_ASSUME_FOCUS_DESC] = "Ligado (o padrão), o jogo continua rodando enquanto você está em outra janela, e o " + "teclado fica sem efeito até a janela voltar para a frente. Desligado, ele pausa quando " + "a janela perde o foco, como no Switch ao apertar Home; um carregamento interrompido " + "assim pode parar de vez.", + [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_IN_USE] = "em uso: %s", + [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_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 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", + [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_DYN_A2C] = "Alpha to coverage dinâmico", + [UI_MENU_VK_DYN_A2C_DESC] = "Força o alpha to coverage dinâmico ligado ou desligado. Padrão: desligado no driver da AMD " + "para RDNA 2 e anteriores, que com ele desenha os personagens pretos, ligado nos demais.", + [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", + [UI_MENU_FOV] = "Campo de visão", + [UI_MENU_FOV_DESC] = "Quanto do mundo a câmera mostra, em porcentagem do original do jogo. Só na versão 1.4.3 do " + "jogo.", + [UI_MENU_SHADOW_RES] = "Tamanho do mapa de sombras", + [UI_MENU_SHADOW_RES_DESC] = "Tamanho do mapa de sombras do sol. O tamanho do jogo muda com a vista, até cerca de " + "400 perto do chão, então as sombras das folhas ficam quadriculadas e pulam; um " + "tamanho fixo as deixa paradas e mais nítidas. Acima de 1024 as sombras custam mais " + "tempo de GPU e memória de vídeo.", + [UI_MENU_SHADOW_RES_GAME] = "Do jogo (varia)", + [UI_MENU_ANISO] = "Filtragem de texturas", + [UI_MENU_ANISO_DESC] = "Filtragem anisotrópica das texturas de superfície: chão, estradas e paredes vistos em " + "ângulo raso continuam nítidos ao longe em vez de borrar. Jogo: o nível que o jogo pede, " + "como no Switch.", + [UI_MENU_ANISO_GAME] = "Jogo", + [UI_MENU_COLOR] = "Cor", + [UI_MENU_COLOR_PRESET] = "Perfil de cor", + [UI_MENU_COLOR_PRESET_DESC] = "Define os quatro valores abaixo. Vívido: mais contraste e saturação, sombras um " + "pouco mais abertas (feito para telas OLED). Clareza: um pouco mais de contraste, " + "saturação e brilho. Mexer em um valor torna o perfil Personalizado. O HUD muda com " + "a imagem; este menu não.", + [UI_MENU_COLOR_DEFAULT] = "Do jogo", + [UI_MENU_COLOR_VIVID] = "Vívido (OLED)", + [UI_MENU_COLOR_CLARITY] = "Clareza", + [UI_MENU_COLOR_CUSTOM] = "Personalizado", + [UI_MENU_COLOR_BRIGHTNESS] = "Brilho", + [UI_MENU_COLOR_BRIGHTNESS_DESC] = "Somado a todas as cores; 0 não muda nada.", + [UI_MENU_COLOR_CONTRAST] = "Contraste", + [UI_MENU_COLOR_CONTRAST_DESC] = "Afasta as cores do cinza médio (acima de 100 %) ou as aproxima dele; 100 % não " + "muda nada.", + [UI_MENU_COLOR_SATURATION] = "Saturação", + [UI_MENU_COLOR_SATURATION_DESC] = "Força da cor em relação ao cinza; 100 % não muda nada.", + [UI_MENU_COLOR_GAMMA] = "Gama", + [UI_MENU_COLOR_GAMMA_DESC] = "Abaixo de 1 clareia os tons escuros e médios, acima de 1 os escurece; 1 não muda " + "nada.", + [UI_MENU_HDR_GROUP] = "HDR", + [UI_MENU_HDR] = "Saída HDR", + [UI_MENU_HDR_DESC] = "Realces brilhantes em uma tela HDR. Precisa do HDR ligado no Windows (\"Usar HDR\") ou num " + "compositor Wayland com gerenciamento de cor; sem isso a imagem continua SDR. Vale após " + "reiniciar. O perfil de cor acima é para SDR e não é usado em HDR.", + [UI_MENU_HDR_PEAK] = "Brilho máximo", + [UI_MENU_HDR_PEAK_DESC] = "O pico da sua tela em nits; os realces mais claros param aí.", + [UI_MENU_HDR_GAME] = "Brilho do jogo", + [UI_MENU_HDR_GAME_DESC] = "Nits do branco da imagem (branco de papel). 203 é a referência de HDR; aumente num " + "ambiente claro.", + [UI_MENU_HDR_UI] = "Brilho do HUD e do menu", + [UI_MENU_HDR_UI_DESC] = "Nits do branco do HUD e deste menu.", + [UI_MENU_PROMPTS] = "Ícones de botões", + [UI_MENU_PROMPTS_DESC] = "Os botões de qual controle os ícones do jogo mostram. Nintendo: os do próprio jogo. " + "Xbox: LB, RB, LT, RT, Menu, Exibir e uma cruz direcional, e A, B, X e Y com a letra do " + "botão que o layout acima aperta (com Nintendo (A à direita) o botão da direita tem a " + "letra B, então os ícones de A mostram B). O jogo lê os ícones ao iniciar, então eles " + "mudam depois de reiniciar. Eles fazem parte dos arquivos do jogo, então um botão " + "remapeado em Controles continua com o ícone antigo na tela.", + [UI_MENU_PROMPTS_NINTENDO] = "Nintendo", + [UI_MENU_PROMPTS_XBOX] = "Xbox", + [UI_MENU_PROMPTS_MISSING] = "faltam os arquivos dos ícones: execute a instalação de novo", + [UI_MENU_PROMPTS_FAILED] = "arquivos dos ícones danificados: execute a instalação de novo", + [UI_MENU_PROMPTS_RESTART] = "os ícones mudam após reiniciar", + [UI_MENU_PROMPTS_OFF_SHAPE] = "desligados numa resolução de jogo que não é 16:9", + [UI_MENU_PROMPTS_OFF_MODS] = "desligados: um mod de RomFS substitui os arquivos deles", + [UI_MENU_PROMPTS_OFF_PATCHES] = "desligados enquanto TOTK_ROMFS_PATCHES está definido", + [UI_MENU_RESTART] = "Reiniciar agora", + [UI_MENU_RESTART_DESC] = "Fecha o jogo e o abre de novo com os novos ícones. O progresso desde o último " + "salvamento é perdido.", + [UI_MENU_RESTART_CONFIRM] = "Reiniciar o jogo agora? O progresso desde o último salvamento é perdido.", + [UI_MENU_RESTART_YES] = "Reiniciar", + [UI_MENU_RESTART_SAVING] = "O jogo está salvando: dá para reiniciar em um instante.", + [UI_MENU_STICK_SENS] = "Velocidade da câmera (analógico)", + [UI_MENU_STICK_SENS_DESC] = "Multiplica a velocidade da câmera do analógico direito do jogo, incluindo a máxima, " + "em cada uma das cinco sensibilidades de câmera do jogo. O mouse mantém a própria " + "configuração.", + [UI_MENU_WALK_KEY] = "Tecla de andar", + [UI_MENU_WALK_KEY_DESC] = "Segure para inclinar os analógicos do teclado só em parte, assim o teclado anda em vez " + "de correr. A intensidade do andar define quanto. Controle e mouse não são afetados.", + [UI_MENU_WALK_KEY_TAKEN] = "também %s", + [UI_MENU_WALK_SCALE] = "Intensidade do andar", + [UI_MENU_WALK_SCALE_DESC] = "A inclinação dos analógicos do teclado enquanto a tecla de andar está segura. Metade " + "é andar, a inclinação total é correr.", + [UI_MENU_OV_SCALE_DOWN] = "bilinear (o FSR só amplia)", +}; + +// Simplified Chinese: this row covers the software keyboard and the whole menu, so the menu and the overlay read Chinese +// when the menu language is zh-Hans (ui_text.h menu_text). The rows are fixed width, so the strings stay close to the +// English length; an id without a Chinese entry falls back to English. +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] = "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)会扩大视野,并把界面移到屏幕四角;" + "更高的尺寸(16:10、Steam Deck)则移到上下边缘。", + [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_FOV] = "视野", + [UI_MENU_FOV_DESC] = "镜头能看到多大范围,以游戏自身视野的百分比表示。" + "仅限游戏版本 1.4.3。", + [UI_MENU_SHARPNESS] = "FSR 锐度", + [UI_MENU_SHARPNESS_DESC] = "FSR 缩放后的锐化强度;0 为关闭。", + [UI_MENU_COLOR] = "色彩", + [UI_MENU_COLOR_PRESET] = "色彩配置", + [UI_MENU_COLOR_PRESET_DESC] = "同时设置下面四项。鲜艳:对比度和饱和度更高,暗部略微提亮(为 OLED 屏幕调校)。" + "清晰:对比度、饱和度和亮度都略高。改动任一项后,配置变为自定义。" + "HUD 随画面一起变化,本菜单不随之变化。", + [UI_MENU_COLOR_DEFAULT] = "游戏原样", [UI_MENU_COLOR_VIVID] = "鲜艳(OLED)", + [UI_MENU_COLOR_CLARITY] = "清晰", [UI_MENU_COLOR_CUSTOM] = "自定义", + [UI_MENU_COLOR_BRIGHTNESS] = "亮度", + [UI_MENU_COLOR_BRIGHTNESS_DESC] = "叠加到每种颜色上;0 表示不调整。", + [UI_MENU_COLOR_CONTRAST] = "对比度", + [UI_MENU_COLOR_CONTRAST_DESC] = "把颜色从中灰向外拉开(高于 100%)或向中灰收拢;" + "100% 表示不调整。", + [UI_MENU_COLOR_SATURATION] = "饱和度", + [UI_MENU_COLOR_SATURATION_DESC] = "颜色相对灰色的强度;100% 表示不调整。", + [UI_MENU_COLOR_GAMMA] = "伽马", + [UI_MENU_COLOR_GAMMA_DESC] = "小于 1 提亮暗部与中间调,大于 1 压暗;1 表示不调整。", + [UI_MENU_FPS_LIMIT] = "帧率上限", + [UI_MENU_FPS_LIMIT_DESC] = "游戏每秒绘制的最高帧数。高于 60 帧为实验性功能," + "需要开启“游戏速度跟随时钟”。", + [UI_MENU_FPS_30] = "30 FPS", + [UI_MENU_FPS_40] = "40 FPS", + [UI_MENU_FPS_45] = "45 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] = "游戏认为自己处于底座模式还是掌机模式。", + [UI_MENU_MODE_DOCKED] = "底座模式", + [UI_MENU_MODE_HANDHELD] = "掌机模式", + [UI_MENU_ASSUME_FOCUS] = "后台保持运行", + [UI_MENU_ASSUME_FOCUS_DESC] = "开启(默认)时,切到其他窗口游戏仍会继续运行," + "但键盘要等窗口回到前台才会响应。关闭时," + "窗口失去焦点即暂停,如同在 Switch 上按 Home 键;" + "这样被打断的读取可能会永久卡住。", + [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 手柄上的标注一致(PlayStation 手柄上为叉键)。自动:" + "带 Nintendo 标注的手柄使用 Nintendo 布局,其他手柄使用 Xbox 布局。" + "Xbox 按键提示:A 仍是右侧键,但游戏显示 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_IN_USE] = "使用中:%s", + [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] = "回车", + [UI_KEY_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_TIMER_1MS] = "1 ms Windows 计时器", + [UI_MENU_TIMER_1MS_DESC] = "将系统计时器精度提高到 1 ms,使帧间隔更平稳。", + [UI_MENU_PIPE_WAIT] = "等待中绘制的处理", + [UI_MENU_PIPE_WAIT_DESC] = "默认保留当前调度,并为等待中的绘制预留一个工作线程;" + "旧版(绘制)沿用先前的调度。", + [UI_MENU_PIPE_WAIT_DEFAULT] = "默认", + [UI_MENU_PIPE_WAIT_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] = "等待游戏改写完细节层次数据后再让 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] = "强制开关动态顶点输入;默认值取决于显卡。", + [UI_MENU_VK_DYN_A2C] = "动态 Alpha 覆盖", + [UI_MENU_VK_DYN_A2C_DESC] = "强制开关动态 Alpha 覆盖。默认:AMD RDNA 2 及更早的驱动上为关闭," + "开启会导致人物变黑;其他显卡上为开启。", + [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] = "卡顿阈值(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] = "把显卡、驱动、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] = "双线性", + [UI_MENU_SHADOW_RES] = "阴影贴图尺寸", + [UI_MENU_SHADOW_RES_DESC] = "太阳阴影贴图的尺寸。游戏自身的尺寸随视角变化,靠近地面时降到约 400,因此树叶阴影显得块状并且跳动;固定尺寸能让阴影稳定、更清晰。高于 1024 时阴影会占用更多 " + "GPU 时间和显存。", + [UI_MENU_SHADOW_RES_GAME] = "游戏默认(会变化)", + [UI_MENU_ANISO] = "纹理过滤", + [UI_MENU_ANISO_DESC] = "表面纹理的各向异性过滤:以小角度看到的地面、道路和墙壁在远处依然清晰,而不会模糊。游戏:使用游戏请求的级别,与 Switch 上相同。", + [UI_MENU_ANISO_GAME] = "游戏", + [UI_MENU_HDR_GROUP] = "HDR", + [UI_MENU_HDR] = "HDR 输出", + [UI_MENU_HDR_DESC] = "在 HDR 显示器上呈现明亮的高光。需要在 Windows 中开启 HDR(“使用 HDR”),或使用带色彩管理的 Wayland 合成器;否则画面保持 " + "SDR。重启后生效。上方的色彩配置用于 SDR,在 HDR 下不使用。", + [UI_MENU_HDR_PEAK] = "峰值亮度", + [UI_MENU_HDR_PEAK_DESC] = "显示器的峰值亮度(尼特);最亮的高光止于此。", + [UI_MENU_HDR_GAME] = "游戏亮度", + [UI_MENU_HDR_GAME_DESC] = "画面白色(纸白)的尼特值。203 为 HDR 参考值;在明亮的房间里可调高。", + [UI_MENU_HDR_UI] = "HUD 和菜单亮度", + [UI_MENU_HDR_UI_DESC] = "HUD 和本菜单白色的尼特值。", + [UI_MENU_PROMPTS] = "按键提示", + [UI_MENU_PROMPTS_DESC] = "游戏的按键提示显示哪种手柄的按键。Nintendo:游戏原有的提示。Xbox:LB、RB、LT、RT、Menu、View 和十字键,以及上方布局所按下的按键上标注的 " + "A、B、X、Y(使用 Nintendo(A 在右)时右侧按键标为 B,因此 A 的提示显示 " + "B)。游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。", + [UI_MENU_PROMPTS_NINTENDO] = "Nintendo", + [UI_MENU_PROMPTS_XBOX] = "Xbox", + [UI_MENU_PROMPTS_MISSING] = "缺少按键提示文件:请重新运行安装程序", + [UI_MENU_PROMPTS_FAILED] = "按键提示文件已损坏:请重新运行安装程序", + [UI_MENU_PROMPTS_RESTART] = "按键提示重启后生效", + [UI_MENU_PROMPTS_OFF_SHAPE] = "游戏分辨率不是 16:9 时关闭", + [UI_MENU_PROMPTS_OFF_MODS] = "已关闭:RomFS 模组替换了它们的文件", + [UI_MENU_PROMPTS_OFF_PATCHES] = "设置了 TOTK_ROMFS_PATCHES 时关闭", + [UI_MENU_RESTART] = "立即重启", + [UI_MENU_RESTART_DESC] = "关闭游戏并以新的按键提示重新启动。上次存档之后的进度将会丢失。", + [UI_MENU_RESTART_CONFIRM] = "现在重启游戏?上次存档之后的进度将会丢失。", + [UI_MENU_RESTART_YES] = "重启", + [UI_MENU_RESTART_SAVING] = "游戏正在存档:稍后即可重启。", + [UI_MENU_STICK_SENS] = "摇杆镜头速度", + [UI_MENU_STICK_SENS_DESC] = "在游戏的五档镜头灵敏度下,按倍数调整右摇杆的镜头转动速度(包括最高速度)。鼠标使用自己的设置。", + [UI_MENU_WALK_KEY] = "步行键", + [UI_MENU_WALK_KEY_DESC] = "按住时键盘模拟的摇杆只推到一部分,使键盘操作走路而不是奔跑。推动幅度由步行幅度决定。手柄和鼠标不受影响。", + [UI_MENU_WALK_KEY_TAKEN] = "同时为 %s", + [UI_MENU_WALK_SCALE] = "步行幅度", + [UI_MENU_WALK_SCALE_DESC] = "按住步行键时键盘摇杆的推动幅度。一半为走路,推满为奔跑。", + [UI_MENU_OV_SCALE_DOWN] = "双线性(FSR 只能放大)", +}; + #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"); @@ -583,19 +1434,18 @@ 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 취소"); 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++) @@ -621,14 +1471,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. +// A language's own strings, for the font that draws them: the merged system font must cover the whole menu of the +// language, not only its name (ui/menu.cpp fonts_up). +void ui_text_visit(const char *lang, void (*visit)(void *ctx, const char *text), void *ctx) { + const Row *r = find_row(lang); + if (!r) return; + for (int id = 0; id < (int)UI_TEXT_COUNT; id++) + if (r->text[id] && *r->text[id]) visit(ctx, r->text[id]); +} + +// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG names a catalog language ("en", "ru", "pt-BR", +// "zh-Hans"); unset, it follows the system UI language, through the same code map the game language uses ("zh-CN" -> +// "zh-Hans"). Windows names a region with it ("ru-RU"), so a tag without menu text tries its language alone ("ru"). A +// language whose row has no menu text (only the software keyboard does) shows English, so other Windows locales keep the +// English menu. 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"; + const char *lang = v && *v ? ui_text_lang(v) : sys && *sys ? ui_text_lang(sys) : "en"; + if (ui_text_defined(lang, UI_MENU_TITLE)) return lang; + static char base[16]; // menu_text calls this on one thread at a time, on a cfg_version change + size_t n = strcspn(lang, "-"); + if (n < sizeof base && lang[n]) { + memcpy(base, lang, n), base[n] = 0; + if (ui_text_defined(base, UI_MENU_TITLE)) return find_row(base)->lang; + } + return "en"; } const char *menu_text(UiTextId id) { diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 41502d88..76b9cfd3 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, Brazilian Portuguese 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, @@ -38,12 +39,16 @@ typedef enum { UI_MENU_ASPECT, UI_MENU_ASPECT_DESC, UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH, UI_MENU_FOV, UI_MENU_FOV_DESC, UI_MENU_SHADOW_RES, UI_MENU_SHADOW_RES_DESC, UI_MENU_SHADOW_RES_GAME, + UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME, UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC, UI_MENU_COLOR, // group heading over the colour rows UI_MENU_COLOR_PRESET, UI_MENU_COLOR_PRESET_DESC, UI_MENU_COLOR_DEFAULT, UI_MENU_COLOR_VIVID, UI_MENU_COLOR_CLARITY, UI_MENU_COLOR_CUSTOM, UI_MENU_COLOR_BRIGHTNESS, UI_MENU_COLOR_BRIGHTNESS_DESC, UI_MENU_COLOR_CONTRAST, UI_MENU_COLOR_CONTRAST_DESC, UI_MENU_COLOR_SATURATION, UI_MENU_COLOR_SATURATION_DESC, UI_MENU_COLOR_GAMMA, UI_MENU_COLOR_GAMMA_DESC, + UI_MENU_HDR_GROUP, // group heading over the HDR rows + UI_MENU_HDR, UI_MENU_HDR_DESC, UI_MENU_HDR_PEAK, UI_MENU_HDR_PEAK_DESC, UI_MENU_HDR_GAME, UI_MENU_HDR_GAME_DESC, + UI_MENU_HDR_UI, UI_MENU_HDR_UI_DESC, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_40, UI_MENU_FPS_45, UI_MENU_FPS_60, UI_MENU_FPS_90, @@ -65,9 +70,14 @@ typedef enum { UI_MENU_RUMBLE_CURVE, UI_MENU_RUMBLE_CURVE_DESC, 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_XBOX_PROMPTS, UI_MENU_PAD_LAYOUT_IN_USE, - UI_MENU_PAD_LAYOUT_PROMPTS_MISSING, UI_MENU_PAD_LAYOUT_PROMPTS_RESTART, - UI_MENU_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, + UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_IN_USE, + UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, + // the notes under the prompts: their files are missing or damaged, they change after restart, or why they are off + UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE, + UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES, + // "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO) + UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING, + UI_MENU_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC, UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC, UI_MENU_WALK_KEY, UI_MENU_WALK_KEY_DESC, UI_MENU_WALK_KEY_TAKEN, UI_MENU_WALK_SCALE, UI_MENU_WALK_SCALE_DESC, @@ -107,7 +117,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, @@ -180,13 +190,17 @@ enum { UI_DESC_BYTES = 2048 }; // 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); +// Calls visit(ctx, text) for every string the row of lang has its own text for (an id that falls back to English is not +// visited): the font builder covers the glyphs of the text a language shows (ui/menu.cpp). +void ui_text_visit(const char *lang, void (*visit)(void *ctx, const char *text), void *ctx); // 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", "zh-Hans"); +// unset, the system UI language when the catalog has menu text for it (English, Russian, Brazilian Portuguese, +// Simplified Chinese), else English. Follows a live change of the setting. const char *menu_text(UiTextId id); diff --git a/runtime/vk.h b/runtime/vk.h index b45692d8..0817dd2a 100644 --- a/runtime/vk.h +++ b/runtime/vk.h @@ -34,7 +34,8 @@ typedef struct VkCtx { has_conditional_rendering, has_transform_feedback, has_provoking_vertex, has_device_fault, has_memory_budget, has_robustness2, has_buffer_device_address, has_fragment_shader_interlock, has_buffer_marker, has_astc_ldr, // textureCompressionASTC_LDR (enabled when reported) - has_calibrated; // VK_KHR/EXT_calibrated_timestamps (GPU idle split in the perf line) + has_calibrated, // VK_KHR/EXT_calibrated_timestamps (GPU idle split in the perf line) + has_hdr_metadata; // VK_EXT_hdr_metadata (vk_hdr.c vk_hdr_metadata) // Feedback loops (maxwell.md 1.9, vk_exec_draw.c feedback_prepare): a draw samples a target of its open pass that // an earlier draw of the pass wrote. TOTK_FEEDBACK=0: VK_FEEDBACK_OFF (sampled in GENERAL without a barrier, the // old behaviour); VK_FEEDBACK_LAYOUT with VK_EXT_attachment_feedback_loop_layout and dynamicRenderingLocalRead @@ -108,6 +109,23 @@ void vk_fsr_release(void); // before the device goes away // scales that one instead, crop {0, 0, w, h}); VK_NULL_HANDLE = nothing recorded. src is in GENERAL, fmt its format. VkImage vk_color_record(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, const int crop[4]); void vk_color_release(void); // before the device goes away +// HDR output (vk_hdr.c). vk_hdr_wanted: TOTK_HDR, read once. vk_hdr_surface_format: the HDR10 surface format when wanted +// and offered (1). vk_hdr_set_active: gfx_present.c says whether the swapchain is HDR10 (vk_hdr_active). vk_hdr_encode: +// like vk_color_record, src's crop as PQ code values (RGBA16F, crop {0, 0, w, h}). vk_hdr_ui_target / vk_hdr_ui_compose: +// the in-game menu's RGBA8 target, then blended onto the swapchain image. vk_hdr_to_srgb8: 10-bit PQ pixels to sRGB bytes. +int vk_hdr_wanted(void); +void vk_hdr_off(void); // probes that read back 8-bit swapchain pixels: SDR whatever the setting +int vk_hdr_surface_format(const VkSurfaceFormatKHR *f, uint32_t n, VkSurfaceFormatKHR *out); +void vk_hdr_metadata(VkSwapchainKHR sc, int new_sc); +void vk_hdr_set_active(int on); +int vk_hdr_active(void); +VkImage vk_hdr_encode(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, const int crop[4]); +VkImageView vk_hdr_ui_target(VkCommandBuffer cb, uint32_t w, uint32_t h); +void vk_hdr_ui_compose(VkCommandBuffer cb, VkImageView dst_view, VkFormat fmt, uint32_t w, uint32_t h); +void vk_hdr_to_srgb8(const uint8_t *in, uint8_t *out, size_t px, int a2r); +void vk_hdr_release(void); // before the device goes away +// The support buffer's HDR parameters (vk_exec_draw.c support_fill, read by shaders/hdr_tonemap.frag). +void vk_hdr_support(float out[4]); 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. @@ -304,6 +322,10 @@ typedef struct { 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) } VkTexImage; +// The window texture the backend presents (vk_backend.c): *image and *format become the float picture the game copied +// into it, when the last draw into it was that copy and the swapchain is HDR10. +void vk_hdr_present_source(const VkTexImage *win, VkImage *image, VkFormat *format); +void vk_hdr_image_gone(VkImage image); 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). const VkTexImage *vk_texture_by_id(int id, view_t *view, int *has_view); diff --git a/runtime/vk_backend.c b/runtime/vk_backend.c index 37566c5d..9bf4a1db 100644 --- a/runtime/vk_backend.c +++ b/runtime/vk_backend.c @@ -116,6 +116,7 @@ static void present_image(const tex_t *t, const int crop[4], uint64_t at_ns, uin } PresentJob j = {.image = img->image, .format = img->format, .w = (int)img->width, .h = (int)img->height, .frame = frame, .at = at_ns, .queued = queued, .value = value}; + vk_hdr_present_source(img, &j.image, &j.format); // TOTK_HDR: the float picture the game copied into it, same size if (crop) { j.has_crop = 1; for (int i = 0; i < 4; i++) j.crop[i] = crop[i]; diff --git a/runtime/vk_device.c b/runtime/vk_device.c index e523f033..21bae4b7 100644 --- a/runtime/vk_device.c +++ b/runtime/vk_device.c @@ -41,6 +41,17 @@ static int layer_present(const char *name) { return found; } +static int instance_ext_present(const char *name) { + uint32_t n = 0; + vkEnumerateInstanceExtensionProperties(NULL, &n, NULL); + VkExtensionProperties *e = calloc(n ? n : 1, sizeof *e); + vkEnumerateInstanceExtensionProperties(NULL, &n, e); + int found = 0; + for (uint32_t i = 0; i < n; i++) if (!strcmp(e[i].extensionName, name)) found = 1; + free(e); + return found; +} + // Mesa's drivers (RADV on Linux and the Steam Deck) keep a shader cache of their own beside our pipeline cache, by // default in ~/.cache and up to 1 GB: about 35 MB in a minute of the title screen. A Deck's /home is small and the game // usually sits on the SD card, so unless MESA_SHADER_CACHE_DIR names a folder, it goes to mesa-cache beside the exe. @@ -57,7 +68,7 @@ static void mesa_cache_beside_exe(void) { static int create_instance(void) { mesa_cache_beside_exe(); const char *ext[8]; - uint32_t n_ext = (uint32_t)gfx_window_vk_extensions(ext, 7); + uint32_t n_ext = (uint32_t)gfx_window_vk_extensions(ext, 6); const char *layers[] = {"VK_LAYER_KHRONOS_validation"}; int validate = cfg_bool("TOTK_VK_VALIDATION"); if (validate && !layer_present(layers[0])) { @@ -65,6 +76,8 @@ static int create_instance(void) { validate = 0; } if (validate) ext[n_ext++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + if (vk_hdr_wanted() && instance_ext_present(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) // HDR10 surface formats + ext[n_ext++] = VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME; 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, @@ -209,7 +222,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[32]; 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]; @@ -250,6 +263,10 @@ static int create_device(void) { // GPU timestamps on the CPU clock (vk_sync.c): the perf line splits GPU idle time into waiting for a submission or not. if (has_ext(ep, ne, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 2; ext[n_ext++] = VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; } else if (has_ext(ep, ne, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 1; ext[n_ext++] = VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; } + if (vk_hdr_wanted() && has_ext(ep, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME)) { // the display's peak (vk_hdr_metadata) + g_vk.has_hdr_metadata = 1; + ext[n_ext++] = VK_EXT_HDR_METADATA_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; } // Graphics pipeline library: chained last so it can be dropped again when vk_caps_gpl declines it. diff --git a/runtime/vk_exec.h b/runtime/vk_exec.h index 6236929e..36c07d75 100644 --- a/runtime/vk_exec.h +++ b/runtime/vk_exec.h @@ -126,6 +126,9 @@ void vk_exec_draw_new_cb(void); VkBuffer vk_exec_inline_buffer(VkDeviceSize size); // vk_exec.c: the stand-in a 3D BC render target is drawn through goes with its image (vk_exec_image_gone). void vk_exec_bc_gone(VkImage image); +// vk_hdr.c: with TOTK_HDR=1, notes a draw into a presented window texture (vk_hdr_track: set by the first present). +extern int vk_hdr_track; +void vk_hdr_draw(VkExec *ex, const VkPipeInfo *info); // Scissor 0 clipped to the render area of the open pass; extent 0: nothing to draw. VkRect2D vk_exec_scissor(const VkExec *ex); void vk_exec_noatt_dims(const VkExec *ex, uint32_t *w, uint32_t *h); // pass size when no attachment is set diff --git a/runtime/vk_exec_draw.c b/runtime/vk_exec_draw.c index 976d3285..2655f181 100644 --- a/runtime/vk_exec_draw.c +++ b/runtime/vk_exec_draw.c @@ -33,7 +33,8 @@ #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, ...; + // 1408: HDR parameters (support_fill) #define NVN_STAGE_VS 0 #define NVN_STAGE_FS 1 #define NVN_STAGE_CS 5 @@ -567,6 +568,7 @@ VkImageView vk_exec_target_view(const VkTexImage *img, VkFormat format, VkImageV void vk_exec_image_gone(VkImage image) { vk_exec_bc_gone(image); + vk_hdr_image_gone(image); if (!views_by_image.klen) return; for (ViewNode *n = nvn_hm_del(&views_by_image, &image), *next; n; n = next) { next = n->next; @@ -1432,6 +1434,11 @@ 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 for (int i = 0; i < 73; i++) memcpy(b + 192 + 16 * i, &one, 4); // render scale 1: the host renders at guest size + if (vk_hdr_wanted()) { // read by the HDR tonemap only (shaders/hdr_tonemap.frag), which declares it past the translator's + float hdr[4]; + vk_hdr_support(hdr); + memcpy(b + 1408, hdr, 16); + } } // TOTK_BIND_STATS=1: bindings and descriptors per draw of each stage (Task 2.2's choice of the pushed stage), and how @@ -2118,6 +2125,7 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) { feedback_written(ex, &s); bind_vertex_buffers(ex); if (vk_dump_armed) vk_dump_draw(ex, &s, p, info); + if (vk_hdr_track) vk_hdr_draw(ex, info); vk_exec_oq_draw(ex); return 1; } diff --git a/runtime/vk_exec_probe.c b/runtime/vk_exec_probe.c index 504ce3d5..3663e556 100644 --- a/runtime/vk_exec_probe.c +++ b/runtime/vk_exec_probe.c @@ -846,6 +846,7 @@ static int test_mirror(const GfxBackend *b, uint8_t *guest, int *bytes) { } int probe_vkexec(void) { + vk_hdr_off(); // the present checks read 8-bit swapchain pixels layouts_equal = 0; main_tid = plat_thread_id(); const GfxBackend *b = &gfx_vulkan_backend; diff --git a/runtime/vk_hdr.c b/runtime/vk_hdr.c new file mode 100644 index 00000000..7d591b87 --- /dev/null +++ b/runtime/vk_hdr.c @@ -0,0 +1,584 @@ +// HDR output (TOTK_HDR=1): an HDR10 swapchain (Rec. 2020 primaries, PQ) and a game picture with highlights above the +// SDR white. Settings: TOTK_HDR (read at start), TOTK_HDR_PEAK_NITS (the display's peak), TOTK_HDR_GAME_NITS (the +// picture's white, "paper white") and TOTK_HDR_UI_NITS (the HUD's and this menu's white), the three read when the +// settings change. With TOTK_HDR=0 nothing here runs and the present is what it was. +// +// The game's picture (docs/architecture.md, "HDR"). The game tonemaps its scene into an r11g11b10f target, upscales it +// and draws the HUD into a second one (float, nothing in these passes clamps), and one last draw copies that into the +// 8-bit sRGB window texture it presents. So: +// 1. vk_hdr_shader_swap: the tonemap's fragment shader becomes shaders/hdr_tonemap.frag, which keeps values above 1 +// (relative to the HUD's white) and rolls off at the peak. It is recognised by its constants and resources, not by +// a hash, so another game version or translator still finds it; its SPIR-V is replaced in memory only. +// 2. vk_hdr_draw / vk_hdr_present_source: a draw into a presented window texture that samples one float texture of +// its size is that copy; the present then reads the float texture instead of the window texture. Any other last +// draw into it leaves the window texture, decoded from sRGB: menus and movies stay SDR at the HUD's white. +// The present is queued before the next frame's work (vk_backend.c), so the float target is read before the game +// draws into it again. +// 3. vk_hdr_encode: on the present, the crop rectangle goes to PQ code values in an RGBA16F image (shaders/hdr_encode.comp) +// that FSR 1 or the blit scale into the swapchain. vk_hdr_ui_*: the in-game menu draws into an RGBA8 image and +// shaders/hdr_ui.frag blends it onto the swapchain at the HUD's white. +// The tonemap's approach is RenoDX's TotK mod by souperman9 and Musa on ShortFuse's RenoDX (github.com/clshortfuse/renodx, +// src/games/totk, MIT); the code is ours. +#include "vk.h" + +#include +#include + +#include "cfg.h" +#include "gfx.h" +#include "hdr_encode_spv.h" +#include "hdr_fullscreen_spv.h" +#include "hdr_tonemap_spv.h" +#include "hdr_ui_spv.h" +#include "host.h" +#include "nvn_api.h" +#include "vk_exec.h" +#include "platform/platform.h" + +#define SLOTS 8 + +// ---- settings + +static int g_wanted = -1; + +int vk_hdr_wanted(void) { + if (g_wanted < 0) g_wanted = cfg_bool("TOTK_HDR"); + return g_wanted; +} + +void vk_hdr_off(void) { g_wanted = 0; } + +// The three nits, read again when the settings change. The replay (every draw's support buffer) and the present +// thread read them: an update fills the snapshot not in use and then publishes it. +typedef struct { float peak, game, ui; } Nits; +static struct { unsigned seen; int cur; Nits snap[2]; PlatMutex lock; } N = {.seen = ~0u, .lock = PLAT_MUTEX_INIT}; + +static Nits nits(void) { + unsigned v = cfg_version(); + if (__atomic_load_n(&N.seen, __ATOMIC_ACQUIRE) != v) { + plat_mutex_lock(&N.lock); + if (N.seen != v) { + Nits *n = &N.snap[!N.cur]; + n->peak = fmaxf((float)cfg_double("TOTK_HDR_PEAK_NITS"), 80.0f); + n->game = fmaxf((float)cfg_double("TOTK_HDR_GAME_NITS"), 80.0f); + n->ui = fmaxf((float)cfg_double("TOTK_HDR_UI_NITS"), 80.0f); + __atomic_store_n(&N.cur, !N.cur, __ATOMIC_RELEASE); + __atomic_store_n(&N.seen, v, __ATOMIC_RELEASE); + } + plat_mutex_unlock(&N.lock); + } + return N.snap[__atomic_load_n(&N.cur, __ATOMIC_ACQUIRE)]; +} + +void vk_hdr_support(float out[4]) { + Nits n = nits(); + out[0] = n.game / n.ui; // the picture's white against the HUD's + out[1] = n.peak > n.game ? n.peak / n.game : 1.0f; // the peak against the picture's white + out[2] = out[3] = 0; +} + +// ---- 1. the tonemap shader + +enum { SPV_OP_NAME = 5, SPV_OP_TYPE_FLOAT = 22, SPV_OP_CONSTANT = 43, SPV_OP_DECORATE = 71, SPV_DEC_BINDING = 33, + SPV_DEC_SET = 34 }; + +// The variables of the game's shader, in the order of hdr_tonemap.frag's bindings 0..4. +static const char *const tm_names[5] = {"support_buffer", "fp_t_tcb_8", "fp_t_tcb_A", "fp_c1", "fp_c3"}; + +static int name_is(const uint32_t *a, uint32_t len, const char *s) { // OpName operands after the id + size_t n = strlen(s); + return (len - 2) * 4 >= n + 1 && !memcmp(a + 1, s, n + 1); +} + +void vk_hdr_shader_swap(uint32_t **spirv, uint64_t *words) { + if (!vk_hdr_wanted() || !*spirv || *words < 5) return; + const uint32_t *w = *spirv; + uint64_t n = *words; + // the game's constants: the BT.601 red weight, -1/ln 2 (e^-x as exp2), 2/3 (the grade's red weight), the bloom clamp + static const float want[4] = {0.298900008f, -1.44269502f, 0.666666687f, 10000.0f}; + uint32_t float_type = 0, found = 0, ids[5] = {0}, bind[5], set[5]; + int has_bind[5] = {0}; + for (uint64_t i = 5; i < n;) { + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + if (!len || i + len > n) return; + const uint32_t *a = w + i + 1; + if (op == SPV_OP_TYPE_FLOAT && len == 3 && a[1] == 32) float_type = a[0]; + else if (op == SPV_OP_CONSTANT && len == 4 && a[0] == float_type && float_type) + for (int k = 0; k < 4; k++) { + float f; + memcpy(&f, &a[2], 4); + if (f == want[k]) found |= 1u << k; + } + else if (op == SPV_OP_NAME && len >= 3) + for (int k = 0; k < 5; k++) + if (name_is(a, len, tm_names[k])) ids[k] = a[0]; + i += len; + } + if (found != 15) return; + for (int k = 0; k < 5; k++) + if (!ids[k]) return; + for (uint64_t i = 5; i < n;) { // the bindings and sets of those variables + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + const uint32_t *a = w + i + 1; + if (op == SPV_OP_DECORATE && len == 4) + for (int k = 0; k < 5; k++) + if (a[0] == ids[k]) { + if (a[1] == SPV_DEC_BINDING) bind[k] = a[2], has_bind[k] |= 1; + else if (a[1] == SPV_DEC_SET) set[k] = a[2], has_bind[k] |= 2; + } + i += len; + } + for (int k = 0; k < 5; k++) + if (has_bind[k] != 3) return; + uint64_t m = sizeof hdr_tonemap_spv / 4; + uint32_t *out = malloc(sizeof hdr_tonemap_spv); + if (!out) return; + memcpy(out, hdr_tonemap_spv, sizeof hdr_tonemap_spv); + // ours declares binding k for tm_names[k] in set 0: each gets the game's binding and set + uint32_t bound = out[3], *ours = calloc(bound ? bound : 1, sizeof *ours); // id -> our binding + 1 + if (!ours) { + free(out); + return; + } + for (uint64_t i = 5; i < m;) { + uint32_t op = out[i] & 0xffff, len = out[i] >> 16; + uint32_t *a = out + i + 1; + if (op == SPV_OP_DECORATE && len == 4 && a[1] == SPV_DEC_BINDING && a[2] < 5) { + if (a[0] < bound) ours[a[0]] = a[2] + 1; + a[2] = bind[a[2]]; + } + i += len; + } + for (uint64_t i = 5; i < m;) { + uint32_t op = out[i] & 0xffff, len = out[i] >> 16; + uint32_t *a = out + i + 1; + if (op == SPV_OP_DECORATE && len == 4 && a[1] == SPV_DEC_SET && a[0] < bound && ours[a[0]]) a[2] = set[ours[a[0]] - 1]; + i += len; + } + free(ours); + free(*spirv); + *spirv = out; + *words = m; + static volatile int32_t swaps; + rt_log("hdr: the game's tonemap shader runs as shaders/hdr_tonemap.frag (%d so far)", plat_inc32(&swaps)); +} + +// ---- 2. the picture the window texture is copied from + +int vk_hdr_track; // vk_exec_draw.c calls vk_hdr_draw: set at the first present with TOTK_HDR=1 +static volatile int32_t g_active; // the swapchain is HDR10 (gfx_present.c vk_hdr_set_active) +static PlatMutex rec_lock = PLAT_MUTEX_INIT; +static struct { VkImage win, src; VkFormat fmt; } recs[4]; // per presented window image: what the last draw copied +static int nrecs; + +void vk_hdr_set_active(int on) { plat_xchg32(&g_active, on); } +int vk_hdr_active(void) { return plat_cas32(&g_active, 0, 0); } + +static int is_float(VkFormat f) { + return f == VK_FORMAT_B10G11R11_UFLOAT_PACK32 || f == VK_FORMAT_R16G16B16A16_SFLOAT || + f == VK_FORMAT_R32G32B32A32_SFLOAT; +} + +void vk_hdr_draw(VkExec *ex, const VkPipeInfo *info) { + const VkExecTarget *t = &ex->color[0]; + if (!t->image) return; + int known = 0; + for (int i = 0; i < 4; i++) // unlocked first look: most draws go elsewhere (a stale slot only costs the lock below) + known |= __atomic_load_n(&recs[i].win, __ATOMIC_RELAXED) == t->image; + if (!known) return; + VkImage src = VK_NULL_HANDLE; + VkFormat fmt = VK_FORMAT_UNDEFINED; + int ntex = 0, slot = -1; + for (uint32_t i = 0; i < info->n_bindings; i++) { + const VkPipeBinding *bd = &info->bindings[i]; + if (bd->kind != GFX_RES_TEX || bd->stage != GFX_STAGE_FS || !bd->res) continue; + ntex += bd->count ? bd->count : 1; + if ((bd->res->type & 0x7ff) == 3 && !bd->res->separate) slot = bd->res->slot; // a plain 2D texture + } + if (ntex == 1 && slot >= 0 && slot < 128 && ex->tex[1][slot]) { + const VkTexImage *s = vk_texture_by_id(NVN_HANDLE_TEX(ex->tex[1][slot]), NULL, NULL); + if (s && is_float(s->format) && s->width == t->width && s->height == t->height && s->samples == 1) + src = s->image, fmt = s->format; + } + plat_mutex_lock(&rec_lock); + for (int i = 0; i < nrecs; i++) + if (recs[i].win == t->image) recs[i].src = src, recs[i].fmt = fmt; + plat_mutex_unlock(&rec_lock); +} + +void vk_hdr_present_source(const VkTexImage *win, VkImage *image, VkFormat *format) { + if (!vk_hdr_wanted()) return; + vk_hdr_track = 1; + plat_mutex_lock(&rec_lock); + int r = -1; + for (int i = 0; i < nrecs; i++) + if (recs[i].win == win->image) r = i; + if (r < 0 && nrecs < 4) r = nrecs++, recs[r].win = win->image, recs[r].src = VK_NULL_HANDLE; + // kept until the next draw into the window texture: a present again without a new copy shows the same picture + if (r >= 0 && recs[r].src && vk_hdr_active()) *image = recs[r].src, *format = recs[r].fmt; + plat_mutex_unlock(&rec_lock); + static int logged; + if (!logged && *image != win->image) logged = 1, rt_log("hdr: the present reads the game's float picture"); +} + +void vk_hdr_image_gone(VkImage image) { // a texture image went away: forget it as window or source + if (!vk_hdr_track) return; // no records before the first HDR present (vk_hdr_present_source): no lock per image + plat_mutex_lock(&rec_lock); + for (int i = 0; i < nrecs; i++) { + if (recs[i].src == image) recs[i].src = VK_NULL_HANDLE; + if (recs[i].win == image) recs[i] = recs[--nrecs], recs[nrecs] = (typeof(recs[0])){0}, i--; + } + plat_mutex_unlock(&rec_lock); +} + +// ---- swapchain + +// With TOTK_HDR=1, the HDR10 format among the surface's (10-bit UNORM, ST 2084): 1 with *out set, else 0 and the +// reason logged once. +int vk_hdr_surface_format(const VkSurfaceFormatKHR *f, uint32_t n, VkSurfaceFormatKHR *out) { + if (!vk_hdr_wanted()) return 0; + static int logged; + if (!logged) { + char b[1024]; + int o = 0; + for (uint32_t i = 0; i < n && o < (int)sizeof b - 32; i++) + o += snprintf(b + o, sizeof b - (size_t)o, " %d/%d", (int)f[i].format, (int)f[i].colorSpace); + rt_log("hdr: surface formats (VkFormat/VkColorSpaceKHR):%s", b); + } + for (int pass = 0; pass < 2; pass++) + for (uint32_t i = 0; i < n; i++) + if (f[i].colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT && + f[i].format == (pass ? VK_FORMAT_A2R10G10B10_UNORM_PACK32 : VK_FORMAT_A2B10G10R10_UNORM_PACK32)) { + *out = f[i]; + if (!logged) rt_log("hdr: HDR10 swapchain (format %d)", (int)f[i].format); + logged = 1; + return 1; + } + if (!logged) + rt_log("hdr: the display offers no HDR10 format, so the picture stays SDR (Windows: turn on \"Use HDR\" in the " + "display settings; Linux: a Wayland compositor with colour management and HDR on)"); + logged = 1; + return 0; +} + +// The display's peak and the picture's white for sc; again when the settings change (gfx_present.c calls it on every +// present to an HDR10 swapchain, with new = 1 for a new swapchain). +void vk_hdr_metadata(VkSwapchainKHR sc, int new_sc) { + static unsigned sent = ~0u; + VkCtx *c = vk_ctx(); + if (!c->has_hdr_metadata || (!new_sc && cfg_version() == sent)) return; + sent = cfg_version(); + PFN_vkSetHdrMetadataEXT set = (PFN_vkSetHdrMetadataEXT)vkGetDeviceProcAddr(c->device, "vkSetHdrMetadataEXT"); + if (!set) return; + Nits n = nits(); + VkHdrMetadataEXT m = {.sType = VK_STRUCTURE_TYPE_HDR_METADATA_EXT, + .displayPrimaryRed = {0.708f, 0.292f}, .displayPrimaryGreen = {0.170f, 0.797f}, + .displayPrimaryBlue = {0.131f, 0.046f}, .whitePoint = {0.3127f, 0.3290f}, + .maxLuminance = n.peak, .minLuminance = 0.0f, .maxContentLightLevel = n.peak, + .maxFrameAverageLightLevel = n.game}; + set(c->device, 1, &sc, &m); +} + +// ---- 3. present passes + +static void barrier(VkCommandBuffer cb, VkImage img, VkImageLayout from, VkImageLayout to, VkPipelineStageFlags2 ss, + VkAccessFlags2 sa, VkPipelineStageFlags2 ds, VkAccessFlags2 da) { + VkImageMemoryBarrier2 b = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, .srcStageMask = ss, .srcAccessMask = sa, + .dstStageMask = ds, .dstAccessMask = da, .oldLayout = from, .newLayout = to, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + VkDependencyInfo d = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .imageMemoryBarrierCount = 1, + .pImageMemoryBarriers = &b}; + vkCmdPipelineBarrier2(cb, &d); +} + +typedef struct { VkImage img; VmaAllocation alloc; VkImageView view; uint32_t w, h; } Img; + +static void img_free(VkCtx *c, Img *m) { + if (m->view) vkDestroyImageView(c->device, m->view, NULL); + if (m->img) vmaDestroyImage(c->vma, m->img, m->alloc); + *m = (Img){0}; +} + +// m at w x h in fmt; another size waits for the device first (earlier presents may still read the old image). +static int img_ensure(VkCtx *c, Img *m, uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage) { + if (m->img && m->w == w && m->h == h) return 1; + if (m->img) { + vk_queue_lock(); + vkDeviceWaitIdle(c->device); + vk_queue_unlock(); + img_free(c, m); + } + VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = fmt, + .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = usage}; + VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}; + if (vmaCreateImage(c->vma, &ii, &ai, &m->img, &m->alloc, NULL) != VK_SUCCESS) { + m->img = VK_NULL_HANDLE; + return 0; + } + VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = m->img, + .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + if (vkCreateImageView(c->device, &vi, NULL, &m->view) != VK_SUCCESS) { + m->view = VK_NULL_HANDLE; + img_free(c, m); + return 0; + } + m->w = w, m->h = h; + return 1; +} + +static struct { + int tried, ok; + PFN_vkCmdPushDescriptorSetKHR push; + VkSampler sampler; + VkDescriptorSetLayout dsl_enc, dsl_ui; + VkPipelineLayout enc_layout, ui_layout; + VkPipeline enc; + VkPipeline ui; // for ui_fmt + VkFormat ui_fmt; + Img out; // PQ code values of the crop, RGBA16F + Img menu; // the in-game menu, RGBA8 + VkImageView src_view[SLOTS]; +} H; + +static VkShaderModule module(VkCtx *c, const uint32_t *code, size_t size) { + VkShaderModuleCreateInfo mi = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code}; + VkShaderModule m = VK_NULL_HANDLE; + return vkCreateShaderModule(c->device, &mi, NULL, &m) == VK_SUCCESS ? m : VK_NULL_HANDLE; +} + +static VkDescriptorSetLayout set_layout(VkCtx *c, const VkDescriptorSetLayoutBinding *b, uint32_t n) { + VkDescriptorSetLayoutCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, + .bindingCount = n, .pBindings = b}; + VkDescriptorSetLayout l = VK_NULL_HANDLE; + return vkCreateDescriptorSetLayout(c->device, &ci, NULL, &l) == VK_SUCCESS ? l : VK_NULL_HANDLE; +} + +static VkPipelineLayout pipe_layout(VkCtx *c, VkDescriptorSetLayout *dsl, VkShaderStageFlags st, uint32_t pc) { + VkPushConstantRange pr = {st, 0, pc}; + VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, + .pSetLayouts = dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr}; + VkPipelineLayout l = VK_NULL_HANDLE; + return vkCreatePipelineLayout(c->device, &li, NULL, &l) == VK_SUCCESS ? l : VK_NULL_HANDLE; +} + +static int init(VkCtx *c) { + H.tried = 1; + H.push = (PFN_vkCmdPushDescriptorSetKHR)vkGetDeviceProcAddr(c->device, "vkCmdPushDescriptorSetKHR"); + VkDescriptorSetLayoutBinding enc[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}}; + VkDescriptorSetLayoutBinding ui = {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT}; + 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, .maxLod = 0}; + if (!H.push || vkCreateSampler(c->device, &si, NULL, &H.sampler) != VK_SUCCESS || + !(H.dsl_enc = set_layout(c, enc, 2)) || !(H.dsl_ui = set_layout(c, &ui, 1)) || + !(H.enc_layout = pipe_layout(c, &H.dsl_enc, VK_SHADER_STAGE_COMPUTE_BIT, 32)) || + !(H.ui_layout = pipe_layout(c, &H.dsl_ui, VK_SHADER_STAGE_FRAGMENT_BIT, 16))) { + rt_log("hdr: the present passes could not be created; the picture goes out unconverted"); + return 0; + } + VkShaderModule m = module(c, hdr_encode_spv, sizeof hdr_encode_spv); + 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 = H.enc_layout}; + VkResult r = m ? vkCreateComputePipelines(c->device, VK_NULL_HANDLE, 1, &ci, NULL, &H.enc) : VK_ERROR_UNKNOWN; + if (m) vkDestroyShaderModule(c->device, m, NULL); + if (r != VK_SUCCESS) { + rt_log("hdr: the present passes could not be created; the picture goes out unconverted"); + return 0; + } + return H.ok = 1; +} + +VkImage vk_hdr_encode(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, const int crop[4]) { + VkCtx *c = vk_ctx(); + if (!H.tried) init(c); + if (!H.ok || !img_ensure(c, &H.out, (uint32_t)crop[2], (uint32_t)crop[3], VK_FORMAT_R16G16B16A16_SFLOAT, + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) + return VK_NULL_HANDLE; + slot %= SLOTS; + if (H.src_view[slot]) vkDestroyImageView(c->device, H.src_view[slot], NULL); + VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = src, + .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + if (vkCreateImageView(c->device, &vi, NULL, &H.src_view[slot]) != VK_SUCCESS) { + H.src_view[slot] = VK_NULL_HANDLE; + return VK_NULL_HANDLE; + } + Nits n = nits(); + // an sRGB format decodes itself through the view; 8-bit UNORM holds sRGB codes the shader decodes + int decode = fmt == VK_FORMAT_R8G8B8A8_UNORM || fmt == VK_FORMAT_B8G8R8A8_UNORM; + const VkPipelineStageFlags2 CS = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, ALL = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; + barrier(cb, src, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, ALL, VK_ACCESS_2_MEMORY_WRITE_BIT, CS, + VK_ACCESS_2_SHADER_SAMPLED_READ_BIT); + barrier(cb, H.out.img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, ALL, 0, CS, + VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + VkDescriptorImageInfo ii = {H.sampler, H.src_view[slot], VK_IMAGE_LAYOUT_GENERAL}, + oi = {VK_NULL_HANDLE, H.out.view, 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, H.enc); + rec_push(H.push, cb, VK_PIPELINE_BIND_POINT_COMPUTE, H.enc_layout, 0, 2, w); + struct { int32_t offset[2], size[2]; float p[4]; } pc = {{crop[0], crop[1]}, {crop[2], crop[3]}, + {n.ui, n.peak, decode ? 1.0f : 0.0f, 0}}; + vkCmdPushConstants(cb, H.enc_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, &pc); + vkCmdDispatch(cb, ((uint32_t)crop[2] + 7) / 8, ((uint32_t)crop[3] + 7) / 8, 1); + barrier(cb, src, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, CS, 0, ALL, 0); + barrier(cb, H.out.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, CS, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, ALL, + VK_ACCESS_2_MEMORY_READ_BIT); + return H.out.img; +} + +// The in-game menu's target: an RGBA8 image of the swapchain's size in COLOR_ATTACHMENT_OPTIMAL (its old content +// dropped); the caller renders the menu into the view with a clear to 0. +VkImageView vk_hdr_ui_target(VkCommandBuffer cb, uint32_t w, uint32_t h) { + VkCtx *c = vk_ctx(); + if (!H.tried) init(c); + if (!H.ok || !img_ensure(c, &H.menu, w, h, VK_FORMAT_R8G8B8A8_UNORM, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)) + return VK_NULL_HANDLE; + barrier(cb, H.menu.img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, 0, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT); + return H.menu.view; +} + +static int ui_pipeline(VkCtx *c, VkFormat fmt) { + if (H.ui && H.ui_fmt == fmt) return 1; + if (H.ui) { // another swapchain format: earlier presents may still use the old pipeline + vk_queue_lock(); + vkDeviceWaitIdle(c->device); + vk_queue_unlock(); + vkDestroyPipeline(c->device, H.ui, NULL); + H.ui = VK_NULL_HANDLE; + } + VkShaderModule vs = module(c, hdr_fullscreen_spv, sizeof hdr_fullscreen_spv), + fs = module(c, hdr_ui_spv, sizeof hdr_ui_spv); + VkPipelineShaderStageCreateInfo st[2] = { + {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vs, + .pName = "main"}, + {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fs, + .pName = "main"}}; + VkPipelineVertexInputStateCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo ia = {.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST}; + VkPipelineViewportStateCreateInfo vp = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, + .viewportCount = 1, .scissorCount = 1}; + VkPipelineRasterizationStateCreateInfo rs = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE, + .lineWidth = 1.0f}; + VkPipelineMultisampleStateCreateInfo ms = {.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; + VkPipelineColorBlendAttachmentState ba = { + .blendEnable = VK_TRUE, .srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA, + .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, .colorBlendOp = VK_BLEND_OP_ADD, + .srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, .dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + .alphaBlendOp = VK_BLEND_OP_ADD, .colorWriteMask = 0xf}; + VkPipelineColorBlendStateCreateInfo cb = {.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, + .attachmentCount = 1, .pAttachments = &ba}; + VkDynamicState dyn[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo ds = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .dynamicStateCount = 2, .pDynamicStates = dyn}; + VkPipelineRenderingCreateInfo ri = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO, + .colorAttachmentCount = 1, .pColorAttachmentFormats = &fmt}; + VkGraphicsPipelineCreateInfo gi = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .pNext = &ri, + .stageCount = 2, .pStages = st, .pVertexInputState = &vi, + .pInputAssemblyState = &ia, .pViewportState = &vp, .pRasterizationState = &rs, + .pMultisampleState = &ms, .pColorBlendState = &cb, .pDynamicState = &ds, + .layout = H.ui_layout}; + VkResult r = vs && fs ? vkCreateGraphicsPipelines(c->device, VK_NULL_HANDLE, 1, &gi, NULL, &H.ui) : VK_ERROR_UNKNOWN; + if (vs) vkDestroyShaderModule(c->device, vs, NULL); + if (fs) vkDestroyShaderModule(c->device, fs, NULL); + if (r != VK_SUCCESS) { + H.ui = VK_NULL_HANDLE; + rt_log("hdr: the menu pass could not be created; the menu is not shown"); + return 0; + } + H.ui_fmt = fmt; + return 1; +} + +// The menu image onto dst (a swapchain image in COLOR_ATTACHMENT_OPTIMAL, view dst_view of format fmt). +void vk_hdr_ui_compose(VkCommandBuffer cb, VkImageView dst_view, VkFormat fmt, uint32_t w, uint32_t h) { + VkCtx *c = vk_ctx(); + if (!H.ok || !H.menu.img || !ui_pipeline(c, fmt)) return; + barrier(cb, H.menu.img, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, VK_ACCESS_2_SHADER_SAMPLED_READ_BIT); + VkRenderingAttachmentInfo ca = {.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, .imageView = dst_view, + .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp = VK_ATTACHMENT_STORE_OP_STORE}; + VkRenderingInfo ri = {.sType = VK_STRUCTURE_TYPE_RENDERING_INFO, .renderArea = {{0, 0}, {w, h}}, .layerCount = 1, + .colorAttachmentCount = 1, .pColorAttachments = &ca}; + vkCmdBeginRendering(cb, &ri); + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, H.ui); + VkViewport v = {0, 0, (float)w, (float)h, 0, 1}; + VkRect2D s = {{0, 0}, {w, h}}; + vkCmdSetViewport(cb, 0, 1, &v); + vkCmdSetScissor(cb, 0, 1, &s); + VkDescriptorImageInfo ii = {H.sampler, H.menu.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; + VkWriteDescriptorSet wr = {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ii}; + rec_push(H.push, cb, VK_PIPELINE_BIND_POINT_GRAPHICS, H.ui_layout, 0, 1, &wr); + float pc[4] = {nits().ui, 0, 0, 0}; + vkCmdPushConstants(cb, H.ui_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof pc, pc); + vkCmdDraw(cb, 3, 1, 0, 0); + vkCmdEndRendering(cb); +} + +void vk_hdr_release(void) { + VkCtx *c = vk_ctx(); + for (int i = 0; i < SLOTS; i++) + if (H.src_view[i]) vkDestroyImageView(c->device, H.src_view[i], NULL), H.src_view[i] = VK_NULL_HANDLE; + img_free(c, &H.out); + img_free(c, &H.menu); + if (H.enc) vkDestroyPipeline(c->device, H.enc, NULL); + if (H.ui) vkDestroyPipeline(c->device, H.ui, NULL); + if (H.enc_layout) vkDestroyPipelineLayout(c->device, H.enc_layout, NULL); + if (H.ui_layout) vkDestroyPipelineLayout(c->device, H.ui_layout, NULL); + if (H.dsl_enc) vkDestroyDescriptorSetLayout(c->device, H.dsl_enc, NULL); + if (H.dsl_ui) vkDestroyDescriptorSetLayout(c->device, H.dsl_ui, NULL); + if (H.sampler) vkDestroySampler(c->device, H.sampler, NULL); + memset(&H, 0, sizeof H); +} + +// PQ code (0..1023) of a 10-bit channel to the sRGB byte of the same colour at the HUD's white (menu test shots and +// flight thumbnails of an HDR10 swapchain). +static float pq_nits(float e) { + const float m1 = 0.1593017578125f, m2 = 78.84375f, c1 = 0.8359375f, c2 = 18.8515625f, c3 = 18.6875f; + float p = powf(e, 1.0f / m2); + return 10000.0f * powf(fmaxf(p - c1, 0.0f) / (c2 - c3 * p), 1.0f / m1); +} + +void vk_hdr_to_srgb8(const uint8_t *in, uint8_t *out, size_t px, int a2r) { + float ui = nits().ui; + // Rec. 2020 to Rec. 709 (the inverse of ITU-R BT.2087's matrix) + static const float m[9] = {1.6605f, -0.5876f, -0.0728f, -0.1246f, 1.1329f, -0.0083f, -0.0182f, -0.1006f, 1.1187f}; + for (size_t i = 0; i < px; i++) { + uint32_t v; + memcpy(&v, in + 4 * i, 4); + float c[3] = {(float)(v & 1023), (float)(v >> 10 & 1023), (float)(v >> 20 & 1023)}; // A2B10G10R10: R low + if (a2r) { float t = c[0]; c[0] = c[2]; c[2] = t; } + for (int k = 0; k < 3; k++) c[k] = pq_nits(c[k] / 1023.0f) / ui; + for (int k = 0; k < 3; k++) { + float l = fminf(fmaxf(m[3 * k] * c[0] + m[3 * k + 1] * c[1] + m[3 * k + 2] * c[2], 0.0f), 1.0f); + float s = l <= 0.0031308f ? 12.92f * l : 1.055f * powf(l, 1.0f / 2.4f) - 0.055f; + out[4 * i + k] = (uint8_t)(s * 255.0f + 0.5f); + } + out[4 * i + 3] = 255; + } +} diff --git a/runtime/vk_texture.c b/runtime/vk_texture.c index 34080da9..a51adee7 100644 --- a/runtime/vk_texture.c +++ b/runtime/vk_texture.c @@ -1576,7 +1576,7 @@ static VkCompareOp compare_op(uint32_t f) { } } -static struct { int init, mirror_clamp_edge, minmax, border_no_format; } sf; +static struct { int init, mirror_clamp_edge, minmax, border_no_format; float aniso; } sf; // aniso: TOTK_ANISO, 0 = the game's static void sampler_features(VkCtx *c) { if (sf.init) return; @@ -1588,6 +1588,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"); + sf.aniso = strcmp(an, "game") ? (float)atoi(an) : 0; + rt_log("vk: anisotropic filtering: %s", sf.aniso > 1 ? an : "the game's"); sf.init = 1; } @@ -1622,9 +1625,21 @@ 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) { + // TOTK_ANISO raises the level for filtered, mipmapped colour samplers that repeat on U and V: the surface textures, + // which tile, so ground and walls seen at a shallow angle stay sharp into the distance. Depth-compare (shadow) + // samplers, nearest or unmipmapped ones (data maps, LUTs) and clamped ones keep the game's level: clamped samplers + // read screen-sized buffers, whose coordinates can stretch steeply at an object's edge, where anisotropic taps reach + // across it and leave a speckled fringe (the inventory's character preview). + float aniso = d->aniso; + // The game's own wrap modes: a mirror-clamp one maps to MIRRORED_REPEAT where the device lacks mirror-clamp-to-edge. + int tiled = (d->ws == NVN_WRAP_MODE_REPEAT || d->ws == NVN_WRAP_MODE_MIRRORED_REPEAT) && + (d->wt == NVN_WRAP_MODE_REPEAT || d->wt == NVN_WRAP_MODE_MIRRORED_REPEAT); + if (sf.aniso > aniso && 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 = sf.aniso; + 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; diff --git a/tests/diff/common.py b/tests/diff/common.py index 648e280c..c2f796df 100644 --- a/tests/diff/common.py +++ b/tests/diff/common.py @@ -213,7 +213,8 @@ def build_harness(work, bodies, jobs, cflags): f.write(''.join(f'void t{k}(Cpu *c);\n' for k in range(len(bodies)))) f.write('GuestFn tests[] = {' + ','.join(f't{k}' for k in range(len(bodies))) + '};\n') f.write(f'int ntests = {len(bodies)};\n') - srcs += [work / 'table.c', ROOT / 'tests' / 'diff' / 'harness.c'] + # fma.c: a --cflags=-march=x86-64-v2 run must exercise the software fma the v2 build links, not the C runtime's. + srcs += [work / 'table.c', ROOT / 'tests' / 'diff' / 'harness.c', ROOT / 'runtime' / 'fma.c'] objs, procs = [], [] for s in srcs: o = work / (s.stem + '.o') diff --git a/tests/diff/func.py b/tests/diff/func.py index 25a5d0bc..62c34068 100644 --- a/tests/diff/func.py +++ b/tests/diff/func.py @@ -204,7 +204,8 @@ def build(work, emitted, jobs, cflags): f'int ntests = {len(emitted)};\n' + 'void rt_stub_call(Cpu *c, uint64_t target);\n' + ''.join(f'void {gen.fname(t)}(Cpu *c) {{ rt_stub_call(c, {hex(t)}ull); }}\n' for t in sorted(called))) - srcs += [table, ROOT / 'tests' / 'diff' / 'harness.c'] + # fma.c: a --cflags=-march=x86-64-v2 run must exercise the software fma the v2 build links, not the C runtime's. + srcs += [table, ROOT / 'tests' / 'diff' / 'harness.c', ROOT / 'runtime' / 'fma.c'] objs, procs = [], [] for s in srcs: o = work / (s.stem + '.o') diff --git a/tests/romfs_prompts_test.py b/tests/romfs_prompts_test.py new file mode 100644 index 00000000..dca0d054 --- /dev/null +++ b/tests/romfs_prompts_test.py @@ -0,0 +1,539 @@ +"""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)}} + +# restbl: the resource size table's name after its version, in both forms the tool takes. +VERSIONS = {'v121': dict(common='110', size=72, newest=121, restbl='Nin_NX_NVN.rsizetable.zs'), + 'v143': dict(common='140', size=108, newest=143, restbl='rsizetable.zs')} +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"]}.{v["restbl"]}' + self.old_restbl = f'System/Resource/ResourceSizeTable.Product.100.{v["restbl"]}' # an older version's: left alone + 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/build_game.py b/tools/build_game.py index 99df700a..ef55110c 100644 --- a/tools/build_game.py +++ b/tools/build_game.py @@ -94,9 +94,20 @@ NINJA = UCRT / 'ninja.exe' if WIN else on_path('ninja') SDL3_DLLS = [UCRT / 'SDL3.dll', UCRT / 'libiconv-2.dll', UCRT / 'libopus-0.dll'] if WIN else [] # Flags for generated code as LAS Recomp builds it (Makefile GENFLAGS, Windows), plus -march for the FP/SIMD lowering. +# --cpu v2 replaces the level for CPUs without AVX2/FMA; runtime/fma.c then supplies the correctly rounded fma the +# lowering needs (runtime/simd.h). GEN_FLAGS = ['-O1', '-fno-strict-aliasing', '-Wno-return-type', '-Wno-unused-label', '-fvisibility=hidden', '-march=x86-64-v3'] RT_FLAGS = ['-O2', '-g', '-Wall', '-fno-strict-aliasing', '-march=x86-64-v3'] + + +def set_cpu(cpu): + """Target x86-64-v3 (the default) or x86-64-v2. RT_CPU_LEVEL lets runtime/main.c's self-test check the same + instruction set the build was compiled for.""" + march = f'-march=x86-64-{cpu}' + GEN_FLAGS[GEN_FLAGS.index('-march=x86-64-v3')] = march + RT_FLAGS[RT_FLAGS.index('-march=x86-64-v3')] = march + RT_FLAGS.append(f'-DRT_CPU_LEVEL={3 if cpu == "v3" else 2}') if WIN: # _WIN32_WINNT: Windows 10, the port's minimum. MSYS2's headers default to it, llvm-mingw's (the release toolchain) # to Windows 7, which hides the per-monitor DPI functions gfx_window_win.c and dpi_probe_win.c call. @@ -229,9 +240,10 @@ def write_if_changed(path, text): def copy_romfs_patches(version, out): """totk.exe loads romfs-patches beside romfs-index.bin (runtime/romfs.c overlay_init). tools/make_romfs_patches.py writes them into build/ only, so a build in another directory ran without the 60 fps overlay (the quick - menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox (the same with - the A/B and X/Y prompts swapped, pad_layout = xbox_prompts) the same way when it was made.""" - for name in ('romfs-patches', 'romfs-patches-xbox'): + menus' captured background turned black). Copies them when their manifest differs; romfs-patches-xbox and + romfs-patches-xbox-label (the same with Xbox button prompts, make_romfs_patches.py --prompts) the same way when they + were made.""" + for name in ('romfs-patches', 'romfs-patches-xbox', 'romfs-patches-xbox-label'): src = ROOT / 'build' / version / name dst = out / name if src.resolve() == dst.resolve() or not (src / 'manifest.tsv').is_file(): @@ -710,6 +722,8 @@ def mib(n): def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument('--version', default='v121', help='game version (default v121)') + ap.add_argument('--cpu', choices=('v2', 'v3'), default='v3', + help='target CPU level: v3 (AVX2/FMA, default) or v2 (SSE4.2, for older CPUs; slower)') ap.add_argument('--gen', type=Path, help='generated C directory (default generated/)') ap.add_argument('--out', type=Path, help='build directory (default build/)') ap.add_argument('--modules', help='comma-separated subset of the layout modules (default all)') @@ -747,6 +761,7 @@ def main(): ap.add_argument('--expected', type=Path, help='expected hashes (default tools/data/expected-.json)') args = ap.parse_args() + set_cpu(args.cpu) gen = (args.gen or ROOT / 'generated' / args.version).resolve() out = (args.out or ROOT / 'build' / args.version).resolve() diff --git a/tools/build_shaders.py b/tools/build_shaders.py index 3ce6300e..c64afb94 100644 --- a/tools/build_shaders.py +++ b/tools/build_shaders.py @@ -1,6 +1,6 @@ -"""Compile the runtime's own GLSL shaders (runtime/shaders/*.comp) into C headers of SPIR-V words. +"""Compile the runtime's own GLSL shaders (runtime/shaders/*.comp, *.vert, *.frag) into C headers of SPIR-V words. -Each runtime/shaders/.comp becomes runtime/_spv.h, which declares `static const uint32_t _spv[]` +Each runtime/shaders/.comp (or .vert, .frag: one name per shader) becomes runtime/_spv.h, which declares `static const uint32_t _spv[]` and records the SHA-256 of the source it came from. The headers are committed, so building totk.exe needs no shader compiler; tools/build_game.py refuses to build when a header no longer matches its source. Run this after editing a shader. Needs glslc and spirv-val from MSYS2 UCRT64 (package mingw-w64-ucrt-x86_64-shaderc, spirv-tools). @@ -20,6 +20,7 @@ ROOT = Path(__file__).resolve().parent.parent BIN = Path(r'C:\msys64\ucrt64\bin') # Windows; elsewhere glslc and spirv-val come from PATH WIN = os.name == 'nt' TARGET = 'vulkan1.1' +STAGES = {'.comp': 'compute', '.vert': 'vertex', '.frag': 'fragment'} def source_hash(src): @@ -43,10 +44,14 @@ def header_path(src): return src.parent.parent / f'{src.stem}_spv.h' +def sources(runtime): + return sorted(p for p in (runtime / 'shaders').iterdir() if p.suffix in STAGES) + + def stale(runtime): """Shader sources under runtime/shaders whose header is missing or records another source hash.""" out = [] - for src in sorted((runtime / 'shaders').glob('*.comp')): + for src in sources(runtime): h = header_path(src) if not h.exists() or f'// source sha256 {source_hash(src)}' not in h.read_text(encoding='utf-8'): out.append(src) @@ -56,7 +61,7 @@ def stale(runtime): def compile_one(src): with tempfile.TemporaryDirectory() as tmp: spv = Path(tmp) / 'out.spv' - subprocess.run([str(BIN / 'glslc.exe') if WIN else 'glslc', '-O', f'--target-env={TARGET}', '-fshader-stage=compute', + subprocess.run([str(BIN / 'glslc.exe') if WIN else 'glslc', '-O', f'--target-env={TARGET}', f'-fshader-stage={STAGES[src.suffix]}', '-o', str(spv), str(src)], check=True) subprocess.run([str(BIN / 'spirv-val.exe') if WIN else 'spirv-val', f'--target-env', TARGET, str(spv)], check=True) data = spv.read_bytes() @@ -75,7 +80,7 @@ def main(): for s in bad: print(f'{header_path(s)}: stale, run tools/build_shaders.py') return 1 if bad else 0 - for src in sorted((args.runtime / 'shaders').glob('*.comp')): + for src in sources(args.runtime): compile_one(src) return 0 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-v121.txt, 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-