mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-20 04:35:57 +00:00
Merge the in-game settings menu: Screen, Game, Sound, Controls and Menu tabs over the cfg table, English and Russian text, settings saved to totk.ini; the overlay, the Advanced tab and the rest wait in the backlog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
12e234f2c0
59 files changed
+56442
-233
No files matched your search
@@ -6,7 +6,7 @@ Code copied or adapted from another project is listed here with its source, the
|
||||
|---|---|---|---|
|
||||
| MacNativeGames extraction scripts and verification hashes | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11`, Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/vendor/macnativegames/` (unmodified), `tools/data/expected-v*.json` |
|
||||
| LAS Recomp lifter, code generator, FP/SIMD lowering, CPU headers and differential tests | https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f`, Copyright (c) 2026 Peiikai | MIT | `recomp/lifter.py`, `recomp/simd_c.py`, `recomp/nso.py`, `recomp/gen.py`, `recomp/module.py`, `tests/jumptables_check.py`, `runtime/cpu.h`, `runtime/simd.h`, `runtime/simd_fp.h`, `tests/diff/` |
|
||||
| LAS Recomp host runtime: NSO loader, host-function table, guest-space reservation and re-execution, guest thread start | https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f`, Copyright (c) 2026 Peiikai | MIT | `runtime/loader.c`, `runtime/hostfn.c`, `runtime/memory.c`; `runtime/kernel.c`, `runtime/boot.c`; `runtime/vk_device.c`, `runtime/gfx_window.c`, `runtime/tex_astc.c` (`runtime/nvn/astc.c`; its decode ported to GLSL in `runtime/shaders/astc_decode.comp`, compiled into `runtime/astc_decode_spv.h`, and its tables copied into `runtime/vk_astc.c`), `runtime/vk_formats.c` (format table of `runtime/nvn/vulkan/textures.c`), `runtime/vk_memory.c` (page write generations of `runtime/nvn/vulkan/exec.c`, deferred destruction of `textures.c`), `runtime/vk_texture.c` (image creation, uploads and samplers of `runtime/nvn/vulkan/textures.c`), `runtime/vk_sync.c` (timeline submissions and waits of `runtime/nvn/vulkan/exec.c`), `runtime/vk_pipeline.c` (blend, compare and stencil mappings, vertex format table with its 3-component fallback and pipeline cache file of `runtime/nvn/vulkan/exec.c` and `device.c`), `runtime/vk_exec.c` (pass begin and end, scissor clip and attachment clears of `runtime/nvn/vulkan/exec.c`), `runtime/vk_exec_xfer.c` (copies of `runtime/nvn/vulkan/exec.c`), `runtime/vk_exec_draw.c` (uniform buffer spans, texture and sampler descriptors and dispatch flow of `runtime/nvn/vulkan/exec.c`) |
|
||||
| LAS Recomp host runtime: NSO loader, host-function table, guest-space reservation and re-execution, guest thread start | https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f`, Copyright (c) 2026 Peiikai | MIT | `runtime/loader.c`, `runtime/hostfn.c`, `runtime/memory.c`; `runtime/kernel.c`, `runtime/boot.c`; `runtime/vk_device.c`, `runtime/gfx_window.c`, `runtime/tex_astc.c` (`runtime/nvn/astc.c`; its decode ported to GLSL in `runtime/shaders/astc_decode.comp`, compiled into `runtime/astc_decode_spv.h`, and its tables copied into `runtime/vk_astc.c`), `runtime/vk_formats.c` (format table of `runtime/nvn/vulkan/textures.c`), `runtime/vk_memory.c` (page write generations of `runtime/nvn/vulkan/exec.c`, deferred destruction of `textures.c`), `runtime/vk_texture.c` (image creation, uploads and samplers of `runtime/nvn/vulkan/textures.c`), `runtime/vk_sync.c` (timeline submissions and waits of `runtime/nvn/vulkan/exec.c`), `runtime/vk_pipeline.c` (blend, compare and stencil mappings, vertex format table with its 3-component fallback and pipeline cache file of `runtime/nvn/vulkan/exec.c` and `device.c`), `runtime/vk_exec.c` (pass begin and end, scissor clip and attachment clears of `runtime/nvn/vulkan/exec.c`), `runtime/vk_exec_xfer.c` (copies of `runtime/nvn/vulkan/exec.c`), `runtime/vk_exec_draw.c` (uniform buffer spans, texture and sampler descriptors and dispatch flow of `runtime/nvn/vulkan/exec.c`); in-game menu: `runtime/ui/menu.cpp` (Dear ImGui Vulkan set-up of `runtime/nvn/vulkan/imgui_glue.cpp`) |
|
||||
| MacNativeGames TotK host runtime: dynamic linking, identity check, module permissions, guest memory and SVCs, threads, IPC, audio renderer, system services, RomFS and save storage, boot sequence | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/`, `games/totk/scripts/prepare_runtime.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/loader.c`, `runtime/memory.c`; `runtime/kernel.c`, `runtime/svc.c`, `runtime/ipc.c`, `runtime/ipc.h`, `runtime/audren.c`, `runtime/audren.h`, `runtime/audio_mixer.c`, `runtime/audio_effects.c`, `runtime/audio_effects.h`, `runtime/audio_reverb.c`, `runtime/audio_reverb.h` (SDL3 output replaces CoreAudio), `runtime/ov_system.c` (also `shared_font.c`: the BFTTF layout behind nn::pl), `runtime/ov_input.c` (also `hid_feedback.c`: vibration and six-axis handles and calls), `runtime/motion_fusion.c` (six-axis fusion of `motion_fusion.c`), `runtime/ov_media.c` (hardware Opus decoder over libopus), `runtime/swkbd_win.c` (`swkbd_host.c`: ShowKeyboardArg offsets, UTF-8/UTF-16 conversion, disabled-key filter, result codes; Win32 window replaces the macOS text bar), `runtime/ov_gfx.c`, `runtime/romfs.c`, `runtime/romfs_path.h`, `runtime/fs_host.c`, `runtime/fs.h`, `runtime/boot.c`; `runtime/gfx_window.c` |
|
||||
| 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 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) |
|
||||
@@ -22,6 +22,9 @@ Code copied or adapted from another project is listed here with its source, the
|
||||
| MacNativeGames block-linear deswizzler (address function; copy loop split out as `tex_bl_copy`) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/third_party/d2r_gfx/gfx/tex/nvn_deswizzle.c`), Copyright (c) 2026 jhaizhou | MIT | `runtime/tex_deswizzle.c`, `runtime/tex.h` |
|
||||
| SDL 3.4.18, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.18-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) |
|
||||
| libopus (MSYS2 `mingw-w64-ucrt-x86_64-opus`), dynamic link, `libopus-0.dll` copied next to `totk.exe` | https://opus-codec.org, Copyright (c) 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon | BSD-3-Clause | `runtime/ov_media.c` (nn::codec hardware Opus decoder) |
|
||||
| Dear ImGui 1.91.9 (core and Vulkan back end, unmodified), as vendored by LAS Recomp | https://github.com/ocornut/imgui, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/`), Copyright (c) 2014-2025 Omar Cornut | MIT | `runtime/third_party/imgui/` (compiled into `totk.exe` for the in-game menu, `runtime/ui/`) |
|
||||
| SavageWindRecomp settings menu: two-pane option rows (row look, left / right stepping, hold speed-up, description pane), the menu style and tab bar | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/ui/option_rows.mm`, `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/ui/option_rows.cpp`, `runtime/ui/option_rows.h`, `runtime/ui/menu.cpp` |
|
||||
| Roboto Medium font (Dear ImGui's `misc/fonts/Roboto-Medium.ttf`, unmodified) | https://fonts.google.com/specimen/Roboto, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/misc/fonts/`), Copyright 2011 Google Inc. | Apache-2.0 | `runtime/ui/fonts/Roboto-Medium.ttf` (licence text in `runtime/ui/fonts/LICENSE-Roboto.txt`), embedded by `runtime/ui/menu.cpp` |
|
||||
| Vulkan Memory Allocator 3.4.0 (MSYS2 `mingw-w64-ucrt-x86_64-vulkan-memory-allocator`), header-only, compiled into `totk.exe` | https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator, Copyright (c) 2017-2026 Advanced Micro Devices, Inc. | MIT | `runtime/vk_vma.cpp` (the allocator behind `runtime/vk_memory.c`) |
|
||||
| MacNativeGames host movie decoder (`movie::Decoder` for VP9 over libvpx: entry list, buffer and event semantics, NV12 output format, PTS pacing) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/movie_host.c`, `movie_host.h`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/ov_movie.c`, `runtime/movie.h` |
|
||||
| libvpx 1.17.0 (MSYS2 `mingw-w64-ucrt-x86_64-libvpx`), static link (`libvpx.a`), no DLL shipped; the release notices must carry its BSD licence text and the WebM Project's `PATENTS` grant | https://chromium.googlesource.com/webm/libvpx, Copyright (c) 2010, The WebM Project authors | BSD-3-Clause | `runtime/ov_movie.c` (VP9 decoding of the `Event/Movie` WebM files) |
|
||||
|
||||
+18
-22
@@ -150,33 +150,29 @@ Each platform item gets a written design first, agreed with the maintainer.
|
||||
|
||||
## Later
|
||||
|
||||
38. **In-game menu** (branch `task/menu`, in progress). Base: LAS Recomp's menu (MIT, same Vulkan base as ours):
|
||||
`refs/LASRecomp/runtime/nvn/vulkan/imgui_glue.cpp` (Dear ImGui on our device and dynamic rendering),
|
||||
`runtime/ui/menu.mm`, `option_rows.mm`, `controls_ui.mm`; SavageWindRecomp has the same menu. It opens with F1/Esc
|
||||
or Minus+Plus; while it is open the game gets no input and keeps running. Every setting is saved to `totk.ini`.
|
||||
It is drawn after the blit of the game image into the swapchain image (`gfx_window.c`). The menu and settings code
|
||||
stays free of Win32; a thin adapter feeds window and input events to ImGui. Menu text goes through a translation
|
||||
catalog (SavageWindRecomp `runtime/ui/i18n.mm`), English and Russian. Stages, one branch each:
|
||||
1. Frame: ImGui, open and close, input, live settings with `cfg_save`, the catalog; pages for video (fullscreen
|
||||
and window size, FPS counter, frame limit 30 or 60), controls (rumble strength and curve, gyro on or off),
|
||||
sound (volume) and quit.
|
||||
2. The remapping page (`controls_ui.mm`; the bindings of `input_map.c` and [controls.md](controls.md) are the
|
||||
defaults) and mouse sensitivity.
|
||||
38. **In-game menu**: the first stage is in. F1, Esc or Minus+Plus opens it; the game gets no input while it is open.
|
||||
Tabs Screen, Game, Sound, Controls and Menu show option rows over the `cfg` table (`runtime/cfg.c`), with the
|
||||
description of the selected row beside them, English and Russian text from `runtime/ui_text.c`. Every change goes
|
||||
to `totk.ini`, keeping the user's comments; a key set in the environment shows greyed out, a key read only at start
|
||||
says "after restart". Dear ImGui is drawn after the blit into the swapchain image (`runtime/ui/menu.cpp`).
|
||||
|
||||
Later pages: AMD FSR 1 or bilinear scaling of the 900p image to the window (LAS Recomp's Windows upscaler); a
|
||||
frame-time graph with the wait breakdown of `TOTK_TRACE=perf`; VSync (FIFO) for 60 Hz displays without VRR, if
|
||||
testers report double frames under back-edge pacing; gyro sensitivity.
|
||||
|
||||
Live settings: today each module reads its `cfg_get` string once and keeps the value (`rumble_cfg` in
|
||||
`ov_input.c`). The menu needs `cfg_set` and a version counter that consumers check (per-frame readers re-read only
|
||||
when it changes), and a `cfg_save` that rewrites only the changed lines of `totk.ini`, keeps the user's comments and
|
||||
adds a missing key under its section (LAS Recomp's `settings_save` rewrites the whole file). A key set in the
|
||||
environment shows greyed out. Settings read only at start (RomFS mods, shader preparation, operation mode) are
|
||||
marked "after restart".
|
||||
Left to do, in this order (unfinished work on branch `task/menu-advanced`):
|
||||
1. Performance overlay (`TOTK_PERF_OVERLAY`, off, fps or full, F10 cycles; SavageWindRecomp `runtime/perfmon.c`):
|
||||
frame rate, frame time, CPU and GPU load through PDH and NVML. Its menu row is greyed out until then.
|
||||
2. Advanced tab: the remaining `cfg` keys (scheduling, replay thread, pipeline and shader switches), reset of all
|
||||
settings, and a system information block (`sysinfo.c`) with copy to clipboard and open the log folder.
|
||||
3. Game language list without Portuguese (TotK ships ja, en, fr, de, it, es, nl, ru, zh-CN, zh-TW, ko).
|
||||
4. The Presentation row notes the mode the swapchain got when it differs from the setting (mailbox falls back to
|
||||
fifo).
|
||||
5. Not yet checked by hand: keyboard and gamepad navigation, Quit, input right after closing, `totk.ini` locked by
|
||||
another program.
|
||||
6. Later pages: button remapping (LAS Recomp `runtime/ui/controls_ui.mm`), AMD FSR 1 or bilinear scaling of the
|
||||
900p image, a frame-time graph with the wait breakdown of `TOTK_TRACE=perf`, gyro sensitivity.
|
||||
|
||||
Rendering above the game's 900p is a separate study (a game-side resolution patch, as Switch mods do, or scaling
|
||||
every render target ourselves); MacNativeGames has neither. The software keyboard could move onto
|
||||
SavageWindRecomp's `osk.mm`.
|
||||
|
||||
39. **Game version 1.4.3** (branch `task/v143`, paused). The 1.4.3 files extract and verify, and the generator runs on
|
||||
them unchanged. Estimate: one day to the title screen, two to three to play at 60 fps. Steps:
|
||||
1. `stg` no-op lift, DT_RELR in `recomp/nso.py` and `runtime/loader.c`, symbol count from DT_GNU_HASH for `sdk`
|
||||
|
||||
+14
-1
@@ -55,6 +55,19 @@ typedef struct Mixer {
|
||||
} Mixer;
|
||||
|
||||
static _Atomic float device_volume = 1.0f;
|
||||
|
||||
// TOTK_VOLUME: the player's volume in percent (0..100) on top of the game's own; a live setting (the
|
||||
// menu), parsed again when cfg_version changes. Render thread only.
|
||||
static float host_volume(void) {
|
||||
static float v = 1.0f;
|
||||
static unsigned seen = ~0u;
|
||||
unsigned ver = cfg_version();
|
||||
if (ver == seen) return v;
|
||||
seen = ver;
|
||||
double pct = cfg_double("TOTK_VOLUME");
|
||||
v = (float)((pct < 0 ? 0 : pct > 100 ? 100 : pct) / 100);
|
||||
return v;
|
||||
}
|
||||
static unsigned audio_revision(const AudioRenderer *r) { unsigned byte = r->revision >> 24; return byte >= '0' ? byte - '0' : 0; }
|
||||
static void report_once(Mixer *m, unsigned bit, const char *msg, int value) {
|
||||
if (m->reported & (1u << bit)) return;
|
||||
@@ -741,7 +754,7 @@ void audio_mixer_render(AudioRenderer *r, double seconds) {
|
||||
float *lr=m->output_scratch;
|
||||
memset(lr, 0, sizeof(float) * 2 * (size_t)frames);
|
||||
if (sink && sink->input_count >= 1 && sink->input_count <= 6) {
|
||||
const float gain = atomic_load(&device_volume) * (r->mixes[0].in_use ? r->mixes[0].volume : 1.0f);
|
||||
const float gain = host_volume() * atomic_load(&device_volume) * (r->mixes[0].in_use ? r->mixes[0].volume : 1.0f);
|
||||
const float *ch[6] = {0};
|
||||
for (uint32_t c = 0; c < sink->input_count; c++) if (sink->inputs[c] >= 0 && sink->inputs[c] < m->nbuf) ch[c] = mixbuf(m, sink->inputs[c]);
|
||||
for (int k = 0; k < frames; k++) {
|
||||
|
||||
+436
-29
@@ -2,6 +2,10 @@
|
||||
// Format: "key = value" lines, '#' or ';' at the start of a line begins a comment, [sections] only group. A key is a
|
||||
// variable name without "TOTK_" (an optional TOTK_ prefix is accepted), case-insensitive. A value is the rest of the
|
||||
// line, trimmed, optionally in double quotes; an empty value counts as unset. The environment wins over the file.
|
||||
//
|
||||
// Live settings: cfg_set changes a value in memory (readers see the new pointer; the old string is kept, so a pointer
|
||||
// cfg_get handed out stays valid) and cfg_save writes only the changed keys back, keeping the rest of the file.
|
||||
// Readers take no lock: an entry is complete before n_entries counts it, and value pointers are swapped atomically.
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -15,31 +19,98 @@
|
||||
#define PREFIX_LEN 5
|
||||
#define CFG_MAX_KEYS 512
|
||||
|
||||
typedef struct { char *key, *value; } CfgEntry; // key upper-case, without the prefix
|
||||
typedef struct { char *key, *value; int dirty, removed; } CfgEntry; // key upper-case, without the prefix; value NULL after cfg_reset
|
||||
|
||||
static CfgEntry entries[CFG_MAX_KEYS];
|
||||
static int n_entries;
|
||||
static unsigned version;
|
||||
static PlatMutex set_lock = PLAT_MUTEX_INIT; // cfg_set, cfg_reset, cfg_save
|
||||
static int save_ok = 1; // the last cfg_save_to wrote (or had nothing to write)
|
||||
|
||||
// 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[] = {
|
||||
"APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT",
|
||||
"BIND_MINUS", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_ZL",
|
||||
"BIND_ZR",
|
||||
"CLOTH_REALTIME", "CORE_DIAG", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT",
|
||||
"FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FPS60", "FREE_CORES", "FREEZE_IDLE", "GPL",
|
||||
"GPL_DRAW_BUILD",
|
||||
"GPU", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
|
||||
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST",
|
||||
"MOVIE_PACE", "OPERATION_MODE", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
|
||||
"PREWARM_XLATE",
|
||||
"PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC",
|
||||
"RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC", "REPLAY_ASYNC", "REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
|
||||
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS",
|
||||
"SHADER_CACHE", "SHADER_MEMO", "SHARED_FONTS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL",
|
||||
"SPEED_PROBE", "SPLIT_DRAWS", "SWKBD_ANSWER", "SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TIMER_1MS",
|
||||
"TRACE", "VK_NO_FLOAT64", "VK_DYN_VERTEX", "VK_PRESENT", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION",
|
||||
"VS_OUTS", "XLATE", "XLATE_ID", "XLATE_PROCS",
|
||||
"APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS",
|
||||
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_MINUS",
|
||||
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
|
||||
"BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG",
|
||||
"EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS",
|
||||
"FLIGHT_THUMBS", "FPS60", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU",
|
||||
"GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
|
||||
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST",
|
||||
"MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
|
||||
"OPERATION_MODE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
|
||||
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
|
||||
"PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REEXEC", "REPLAY_ASYNC",
|
||||
"REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
|
||||
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE",
|
||||
"SHADER_MEMO", "SHARED_FONTS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPLIT_DRAWS", "SWKBD_ANSWER",
|
||||
"SWKBD_TEST", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TIMER_1MS", "TRACE", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
|
||||
"VK_PRESENT", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VS_OUTS",
|
||||
"WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS",
|
||||
};
|
||||
|
||||
// The totk.ini section a key cfg_set may write goes to when the file lacks it (totk.ini.example's sections).
|
||||
static const struct { const char *key, *section; } sections[] = {
|
||||
{"FPS60", "frame rate"},
|
||||
{"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"},
|
||||
{"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"},
|
||||
{"VOLUME", "audio"},
|
||||
{"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
|
||||
{"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"},
|
||||
{"ASYNC_PREEMPT", "performance"}, {"REPLAY_ASYNC", "performance"}, {"FREE_CORES", "performance"},
|
||||
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"},
|
||||
{"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"},
|
||||
{"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"},
|
||||
{"TEX_ALIAS", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"},
|
||||
{"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"DESC_TEMPLATE", "performance"},
|
||||
{"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"VK_VALIDATION", "performance"},
|
||||
{"VK_DYN_VERTEX", "performance"}, {"VK_SUBGROUP_PIN", "performance"},
|
||||
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
|
||||
};
|
||||
|
||||
// The settings the menu shows: the value in effect when the key is unset, and what the key accepts. The only place a
|
||||
// default lives: consumers read cfg_value / cfg_int / cfg_double / cfg_bool. A row with an empty default has no fixed
|
||||
// value (it depends on the machine); its consumer reads cfg_get and keeps an "unset" branch.
|
||||
#define LIVE 1
|
||||
#define RESTART 0
|
||||
static const CfgMeta metas[] = {
|
||||
// Screen
|
||||
{"FULLSCREEN", "0", "0|1", LIVE}, {"WINDOW_SIZE", "1920x1080", NULL, LIVE},
|
||||
{"VK_PRESENT", "mailbox", "mailbox|fifo|immediate", LIVE}, {"GPU_INDEX", "", NULL, RESTART},
|
||||
{"PERF_OVERLAY", "off", "off|fps|full", LIVE},
|
||||
// Game
|
||||
{"FPS60", "1", "0|1", LIVE}, {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART},
|
||||
{"HIGHFPS_FIX", "1", "0|1", RESTART},
|
||||
{"LANG", "", "ja|en-US|fr|de|it|es|zh-CN|ko|nl|pt|ru|zh-TW|en-GB|fr-CA|es-419|zh-Hans|zh-Hant|pt-BR", RESTART},
|
||||
{"OPERATION_MODE", "docked", "docked|handheld", RESTART},
|
||||
// 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}, {"MOUSE_SENS", "1", "0..10", LIVE},
|
||||
{"MENU_LANG", "", "en|ru", LIVE},
|
||||
// Advanced: scheduling
|
||||
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART},
|
||||
{"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART},
|
||||
// shaders and pipelines
|
||||
{"PIPE_WAIT", "default", "default|draw", RESTART}, {"PIPE_SKIP", "any", "strict|any|fullscreen", RESTART},
|
||||
{"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
|
||||
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART},
|
||||
// textures and memory
|
||||
{"ASTC", "auto", "auto|gpu|native|cpu", RESTART}, {"MEMORY", "auto", "auto|import|mirror|verify", RESTART},
|
||||
{"TEX_ALIAS", "1", "0|1", RESTART},
|
||||
// render fixes
|
||||
{"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART},
|
||||
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"DESC_TEMPLATE", "1", "0|1", RESTART},
|
||||
{"PUSH_SKIP", "1", "0|1", RESTART}, {"SPLIT_DRAWS", "64", "0..1000", RESTART},
|
||||
// Vulkan
|
||||
{"VK_VALIDATION", "0", "0|1", RESTART}, {"VK_DYN_VERTEX", "", "0|1", RESTART},
|
||||
{"VK_SUBGROUP_PIN", "1", "0|1", RESTART},
|
||||
// diagnostics
|
||||
{"TRACE", "", NULL, RESTART}, {"FLIGHT", "0", "0|1", RESTART}, {"FLIGHT_SPIKE_MS", "100", "0..60000", RESTART},
|
||||
{"INPUT_RECORD", "", NULL, RESTART},
|
||||
};
|
||||
|
||||
static int is_known(const char *key) {
|
||||
@@ -60,9 +131,14 @@ static char *trim(char *s) {
|
||||
return s;
|
||||
}
|
||||
|
||||
static void add(char *key, char *value, int line) {
|
||||
// The upper-case key without the prefix, in place.
|
||||
static char *norm_key(char *key) {
|
||||
for (char *p = key; *p; p++) *p = (char)toupper((unsigned char)*p);
|
||||
if (!strncmp(key, PREFIX, PREFIX_LEN)) key += PREFIX_LEN;
|
||||
return strncmp(key, PREFIX, PREFIX_LEN) ? key : key + PREFIX_LEN;
|
||||
}
|
||||
|
||||
static void add(char *key, char *value, int line) {
|
||||
key = norm_key(key);
|
||||
size_t vl = strlen(value);
|
||||
if (vl >= 2 && value[0] == '"' && value[vl - 1] == '"') value[vl - 1] = 0, value++;
|
||||
if (!*key) return;
|
||||
@@ -75,7 +151,7 @@ static void add(char *key, char *value, int line) {
|
||||
return;
|
||||
}
|
||||
if (n_entries == CFG_MAX_KEYS) return;
|
||||
entries[n_entries++] = (CfgEntry){_strdup(key), _strdup(value)};
|
||||
entries[n_entries++] = (CfgEntry){_strdup(key), _strdup(value), 0, 0};
|
||||
}
|
||||
|
||||
int cfg_load(const char *path) {
|
||||
@@ -107,23 +183,354 @@ int cfg_load(const char *path) {
|
||||
const char *cfg_get(const char *name) {
|
||||
const char *e = getenv(name);
|
||||
if (e || strncmp(name, PREFIX, PREFIX_LEN)) return e;
|
||||
for (int i = 0; i < n_entries; i++)
|
||||
if (!_stricmp(entries[i].key, name + PREFIX_LEN)) return entries[i].value;
|
||||
int n = __atomic_load_n(&n_entries, __ATOMIC_ACQUIRE);
|
||||
for (int i = 0; i < n; i++)
|
||||
if (!_stricmp(entries[i].key, name + PREFIX_LEN)) return __atomic_load_n(&entries[i].value, __ATOMIC_ACQUIRE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void cfg_init(void) {
|
||||
unsigned cfg_version(void) { return __atomic_load_n(&version, __ATOMIC_ACQUIRE); }
|
||||
|
||||
int cfg_from_env(const char *name) { return getenv(name) != NULL; }
|
||||
|
||||
void cfg_set(const char *name, const char *value) {
|
||||
if (strncmp(name, PREFIX, PREFIX_LEN) || !value) return;
|
||||
char key[64];
|
||||
snprintf(key, sizeof key, "%s", name + PREFIX_LEN);
|
||||
for (char *p = key; *p; p++) *p = (char)toupper((unsigned char)*p);
|
||||
plat_mutex_lock(&set_lock);
|
||||
int i = 0, n = n_entries;
|
||||
while (i < n && strcmp(entries[i].key, key)) i++;
|
||||
if (i < n) {
|
||||
if (!entries[i].value || strcmp(entries[i].value, value)) {
|
||||
__atomic_store_n(&entries[i].value, _strdup(value), __ATOMIC_RELEASE); // the old string stays for readers
|
||||
entries[i].dirty = 1;
|
||||
}
|
||||
entries[i].removed = 0; // a value set after cfg_reset replaces the line instead of deleting it
|
||||
} else if (n < CFG_MAX_KEYS) {
|
||||
entries[n] = (CfgEntry){_strdup(key), _strdup(value), 1, 0};
|
||||
__atomic_store_n(&n_entries, n + 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
__atomic_add_fetch(&version, 1, __ATOMIC_RELEASE);
|
||||
plat_mutex_unlock(&set_lock);
|
||||
}
|
||||
|
||||
int cfg_reset(const char *const *keys, int n) {
|
||||
int done = 0;
|
||||
plat_mutex_lock(&set_lock);
|
||||
for (int k = 0; k < n; k++) {
|
||||
char key[64], var[80];
|
||||
snprintf(key, sizeof key, "%s", keys[k]);
|
||||
const char *name = norm_key(key);
|
||||
snprintf(var, sizeof var, PREFIX "%s", name);
|
||||
if (getenv(var)) continue; // the environment wins; the file line stays
|
||||
int i = 0;
|
||||
while (i < n_entries && strcmp(entries[i].key, name)) i++;
|
||||
if (i == n_entries) { // no value in memory ("key =" in the file): the line still has to go
|
||||
if (i == CFG_MAX_KEYS) continue;
|
||||
entries[i] = (CfgEntry){_strdup(name), NULL, 0, 1};
|
||||
__atomic_store_n(&n_entries, i + 1, __ATOMIC_RELEASE);
|
||||
} else if (entries[i].value) {
|
||||
__atomic_store_n(&entries[i].value, NULL, __ATOMIC_RELEASE); // the old string stays for readers
|
||||
entries[i].dirty = 0;
|
||||
entries[i].removed = 1; // cfg_save_to deletes the key's lines
|
||||
done++;
|
||||
} else {
|
||||
entries[i].removed = 1;
|
||||
}
|
||||
}
|
||||
if (done) __atomic_add_fetch(&version, 1, __ATOMIC_RELEASE);
|
||||
plat_mutex_unlock(&set_lock);
|
||||
return done;
|
||||
}
|
||||
|
||||
int cfg_last_save_ok(void) { return __atomic_load_n(&save_ok, __ATOMIC_ACQUIRE); }
|
||||
|
||||
const CfgMeta *cfg_meta(const char *key) {
|
||||
char k[64];
|
||||
snprintf(k, sizeof k, "%s", key);
|
||||
const char *name = norm_key(k);
|
||||
for (size_t i = 0; i < sizeof metas / sizeof *metas; i++)
|
||||
if (!strcmp(metas[i].key, name)) return &metas[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const CfgMeta *cfg_meta_at(int i) { return i >= 0 && (size_t)i < sizeof metas / sizeof *metas ? &metas[i] : NULL; }
|
||||
|
||||
const char *cfg_value(const char *name) {
|
||||
const char *e = cfg_get(name);
|
||||
if (e && *e) return e;
|
||||
const CfgMeta *m = cfg_meta(name);
|
||||
if (!m) rt_fatal("cfg: %s has no row in the settings table", name);
|
||||
return m->def;
|
||||
}
|
||||
|
||||
// The row's default as a number, for a set value that does not parse.
|
||||
static double default_number(const char *name) {
|
||||
return strtod(cfg_meta(name)->def, NULL);
|
||||
}
|
||||
|
||||
double cfg_double(const char *name) {
|
||||
const char *v = cfg_value(name);
|
||||
char *end;
|
||||
double d = strtod(v, &end);
|
||||
return end == v || *end || d != d ? default_number(name) : d;
|
||||
}
|
||||
|
||||
int cfg_int(const char *name) {
|
||||
const char *v = cfg_value(name);
|
||||
char *end;
|
||||
long l = strtol(v, &end, 10);
|
||||
return end == v || *end ? (int)default_number(name) : (int)l;
|
||||
}
|
||||
|
||||
int cfg_bool(const char *name) { return strcmp(cfg_value(name), "0") != 0; }
|
||||
|
||||
// ---- cfg_save: the file as lines, each with its line ending
|
||||
typedef struct { const char *s; size_t n; } Line; // n includes the '\n' (and '\r') when present
|
||||
|
||||
static int line_count(const char *p, size_t size) {
|
||||
int n = 0;
|
||||
for (size_t i = 0; i < size; i++) n += p[i] == '\n';
|
||||
return n + 1;
|
||||
}
|
||||
|
||||
// The line's text without its ending, BOM and surrounding blanks, into out.
|
||||
static void line_text(const Line *l, int first, char *out, size_t cap) {
|
||||
size_t n = l->n;
|
||||
const char *s = l->s;
|
||||
if (first && n >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) s += 3, n -= 3;
|
||||
while (n && (s[n - 1] == '\n' || s[n - 1] == '\r')) n--;
|
||||
if (n >= cap) n = cap - 1;
|
||||
memcpy(out, s, n);
|
||||
out[n] = 0;
|
||||
char *t = trim(out);
|
||||
memmove(out, t, strlen(t) + 1);
|
||||
}
|
||||
|
||||
// The key of a "key = value" line (comment = 0) or of a commented "# key = value" line (comment = 1), normalised,
|
||||
// into key; 0 when the line is not one.
|
||||
static int line_key(const char *text, int comment, char *key, size_t cap) {
|
||||
if (comment) {
|
||||
if (*text != '#' && *text != ';') return 0;
|
||||
text++;
|
||||
while (*text == ' ' || *text == '\t') text++;
|
||||
}
|
||||
if (!*text || *text == '#' || *text == ';' || *text == '[') return 0;
|
||||
const char *eq = strchr(text, '=');
|
||||
if (!eq) return 0;
|
||||
size_t n = (size_t)(eq - text);
|
||||
while (n && (text[n - 1] == ' ' || text[n - 1] == '\t')) n--;
|
||||
if (!n || n >= cap) return 0;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (!isalnum((unsigned char)text[i]) && text[i] != '_') return 0;
|
||||
char tmp[128];
|
||||
memcpy(tmp, text, n);
|
||||
tmp[n] = 0;
|
||||
snprintf(key, cap, "%s", norm_key(tmp));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The section name of a "[name]" line, lower-case, into out; 0 when the line is not one.
|
||||
static int line_section(const char *text, char *out, size_t cap) {
|
||||
if (*text != '[') return 0;
|
||||
const char *e = strchr(text, ']');
|
||||
if (!e) return 0;
|
||||
char tmp[128];
|
||||
size_t n = (size_t)(e - text - 1);
|
||||
if (n >= sizeof tmp) n = sizeof tmp - 1;
|
||||
memcpy(tmp, text + 1, n);
|
||||
tmp[n] = 0;
|
||||
snprintf(out, cap, "%s", trim(tmp));
|
||||
for (char *p = out; *p; p++) *p = (char)tolower((unsigned char)*p);
|
||||
return 1;
|
||||
}
|
||||
|
||||
typedef struct { char *buf; size_t n, cap; } Out;
|
||||
static void put(Out *o, const char *s, size_t n) {
|
||||
if (o->n + n + 1 > o->cap) {
|
||||
o->cap = (o->n + n + 1) * 2;
|
||||
o->buf = realloc(o->buf, o->cap);
|
||||
if (!o->buf) rt_fatal("cfg: out of memory writing totk.ini");
|
||||
}
|
||||
memcpy(o->buf + o->n, s, n);
|
||||
o->n += n;
|
||||
}
|
||||
static void puts_(Out *o, const char *s) { put(o, s, strlen(s)); }
|
||||
|
||||
static const char *section_of(const char *key) {
|
||||
for (size_t i = 0; i < sizeof sections / sizeof *sections; i++)
|
||||
if (!strcmp(sections[i].key, key)) return sections[i].section;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// "key = value" + eol for entry e (key lower-case)
|
||||
static void put_entry(Out *o, const CfgEntry *e, const char *eol) {
|
||||
char k[64];
|
||||
snprintf(k, sizeof k, "%s", e->key);
|
||||
for (char *p = k; *p; p++) *p = (char)tolower((unsigned char)*p);
|
||||
puts_(o, k);
|
||||
puts_(o, " = ");
|
||||
puts_(o, e->value);
|
||||
puts_(o, eol);
|
||||
}
|
||||
|
||||
int cfg_save_to(const char *path) {
|
||||
plat_mutex_lock(&set_lock);
|
||||
int n = n_entries, any = 0;
|
||||
for (int i = 0; i < n; i++) any |= entries[i].dirty | entries[i].removed;
|
||||
if (!any) {
|
||||
__atomic_store_n(&save_ok, 1, __ATOMIC_RELEASE);
|
||||
plat_mutex_unlock(&set_lock);
|
||||
return 1;
|
||||
}
|
||||
uint64_t size = 0;
|
||||
uint8_t *data = plat_file_read(path, &size);
|
||||
if (!data && plat_file_exists(path) && plat_file_size(path) != 0) {
|
||||
// the file is there but unreadable (locked, transient error): rebuilding it from nothing would lose its lines
|
||||
rt_log("cfg: cannot read %s, nothing written", path);
|
||||
__atomic_store_n(&save_ok, 0, __ATOMIC_RELEASE);
|
||||
plat_mutex_unlock(&set_lock);
|
||||
return 0;
|
||||
}
|
||||
const char *text = data ? (const char *)data : "";
|
||||
int nl = data ? line_count(text, size) : 0;
|
||||
Line *lines = calloc((size_t)nl + 1, sizeof *lines);
|
||||
// after[i]: entries to write after line i (-1 = none); replace[i]: the entry whose value line i now carries
|
||||
int *replace = malloc(sizeof(int) * ((size_t)nl + 1)), *after_key = malloc(sizeof(int) * (size_t)(n + 1));
|
||||
char *drop = calloc((size_t)nl + 1, 1); // lines of a reset key
|
||||
if (!lines || !replace || !after_key || !drop) rt_fatal("cfg: out of memory writing totk.ini");
|
||||
for (int i = 0, at = 0; i < nl; i++) {
|
||||
size_t start = (size_t)at;
|
||||
while ((uint64_t)at < size && text[at] != '\n') at++;
|
||||
if ((uint64_t)at < size) at++;
|
||||
lines[i] = (Line){text + start, (size_t)at - start};
|
||||
replace[i] = -1;
|
||||
}
|
||||
if (nl && !lines[nl - 1].n) nl--; // the text ended with a newline: no last empty line
|
||||
const char *eol = data && strstr(text, "\r\n") ? "\r\n" : "\n";
|
||||
char t[1024], k[128], sec[128];
|
||||
for (int e = 0; e < n; e++) {
|
||||
after_key[e] = -2; // -2 clean, -1 append in a new section at the end, >= 0 insert after that line
|
||||
if (entries[e].removed)
|
||||
for (int i = 0; i < nl; i++) {
|
||||
line_text(&lines[i], i == 0, t, sizeof t);
|
||||
if (line_key(t, 0, k, sizeof k) && !strcmp(k, entries[e].key)) drop[i] = 1;
|
||||
}
|
||||
if (!entries[e].dirty) continue;
|
||||
int last = -1;
|
||||
for (int i = 0; i < nl; i++) {
|
||||
line_text(&lines[i], i == 0, t, sizeof t);
|
||||
if (line_key(t, 0, k, sizeof k) && !strcmp(k, entries[e].key)) last = i;
|
||||
}
|
||||
if (last >= 0) {
|
||||
replace[last] = e;
|
||||
continue;
|
||||
}
|
||||
const char *want = section_of(entries[e].key);
|
||||
int in = 0, example = -1, tail = -1;
|
||||
for (int i = 0; i < nl && want; i++) {
|
||||
line_text(&lines[i], i == 0, t, sizeof t);
|
||||
if (line_section(t, sec, sizeof sec)) {
|
||||
in = !strcmp(sec, want);
|
||||
if (in) tail = i;
|
||||
continue;
|
||||
}
|
||||
if (!in) continue;
|
||||
if (*t) tail = i;
|
||||
if (line_key(t, 1, k, sizeof k) && !strcmp(k, entries[e].key)) example = i;
|
||||
}
|
||||
after_key[e] = example >= 0 ? example : tail;
|
||||
}
|
||||
Out o = {0};
|
||||
for (int i = 0; i < nl; i++) {
|
||||
if (drop[i]) {
|
||||
// the line leaves the file; keys inserted after it still need a line ending before them
|
||||
} else if (replace[i] >= 0) {
|
||||
// keep the line's indentation and key spelling, put the new value after " = "
|
||||
const char *s = lines[i].s;
|
||||
size_t len = lines[i].n;
|
||||
if (i == 0 && len >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) put(&o, s, 3), s += 3, len -= 3;
|
||||
const char *eq = memchr(s, '=', len);
|
||||
size_t kn = (size_t)(eq - s);
|
||||
while (kn && (s[kn - 1] == ' ' || s[kn - 1] == '\t')) kn--;
|
||||
put(&o, s, kn);
|
||||
puts_(&o, " = ");
|
||||
puts_(&o, entries[replace[i]].value);
|
||||
int had_eol = len && s[len - 1] == '\n';
|
||||
if (had_eol) puts_(&o, eol);
|
||||
} else {
|
||||
put(&o, lines[i].s, lines[i].n);
|
||||
}
|
||||
for (int e = 0; e < n; e++)
|
||||
if (after_key[e] == i) {
|
||||
if (o.n && o.buf[o.n - 1] != '\n') puts_(&o, eol);
|
||||
put_entry(&o, &entries[e], eol);
|
||||
}
|
||||
}
|
||||
// keys whose section the file lacks: one new section each, at the end
|
||||
for (int e = 0; e < n; e++) {
|
||||
if (after_key[e] != -1) continue;
|
||||
const char *want = section_of(entries[e].key);
|
||||
if (o.n && o.buf[o.n - 1] != '\n') puts_(&o, eol);
|
||||
if (want) {
|
||||
if (o.n) puts_(&o, eol);
|
||||
puts_(&o, "[");
|
||||
puts_(&o, want);
|
||||
puts_(&o, "]");
|
||||
puts_(&o, eol);
|
||||
}
|
||||
put_entry(&o, &entries[e], eol);
|
||||
// the following keys of the same new section go right after this one
|
||||
for (int f = e + 1; f < n && want; f++)
|
||||
if (after_key[f] == -1 && section_of(entries[f].key) && !strcmp(section_of(entries[f].key), want)) {
|
||||
put_entry(&o, &entries[f], eol);
|
||||
after_key[f] = -3;
|
||||
}
|
||||
}
|
||||
int ok = plat_file_write_atomic(path, o.buf ? o.buf : "", o.n);
|
||||
if (ok)
|
||||
for (int e = 0; e < n; e++) entries[e].dirty = entries[e].removed = 0;
|
||||
else
|
||||
rt_log("cfg: cannot write %s", path);
|
||||
__atomic_store_n(&save_ok, ok ? 1 : 0, __ATOMIC_RELEASE);
|
||||
free(o.buf);
|
||||
free(drop);
|
||||
free(after_key);
|
||||
free(replace);
|
||||
free(lines);
|
||||
free(data);
|
||||
plat_mutex_unlock(&set_lock);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static char ini_path[1024];
|
||||
|
||||
static int find_ini(void) {
|
||||
if (ini_path[0]) return 1;
|
||||
char path[1024];
|
||||
if (!plat_exe_path(path, sizeof path)) return;
|
||||
if (!plat_exe_path(path, sizeof path)) return 0;
|
||||
char *cut = strrchr(path, '\\');
|
||||
if (!cut) cut = strrchr(path, '/');
|
||||
if (!cut || cut + 10 >= path + sizeof path) return;
|
||||
if (!cut || cut + 10 >= path + sizeof path) return 0;
|
||||
strcpy(cut + 1, "totk.ini");
|
||||
if (!cfg_load(path)) {
|
||||
rt_log("cfg: no settings file at %s", path);
|
||||
snprintf(ini_path, sizeof ini_path, "%s", path);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int cfg_save(void) {
|
||||
if (find_ini()) return cfg_save_to(ini_path);
|
||||
__atomic_store_n(&save_ok, 0, __ATOMIC_RELEASE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void cfg_init(void) {
|
||||
if (!find_ini()) return;
|
||||
if (!cfg_load(ini_path)) {
|
||||
rt_log("cfg: no settings file at %s", ini_path);
|
||||
return;
|
||||
}
|
||||
rt_log("cfg: read %s: %d keys", path, n_entries);
|
||||
rt_log("cfg: read %s: %d keys", ini_path, n_entries);
|
||||
for (int i = 0; i < n_entries; i++) {
|
||||
char var[128];
|
||||
snprintf(var, sizeof var, PREFIX "%s", entries[i].key);
|
||||
|
||||
+42
-2
@@ -2,8 +2,8 @@
|
||||
#pragma once
|
||||
|
||||
// getenv for a setting: the environment variable when set, else the totk.ini key (the name without "TOTK_", any
|
||||
// case), else NULL. Same string semantics as getenv; the pointer stays valid for the process. A name without the
|
||||
// TOTK_ prefix goes to getenv unchanged. Safe from any thread once cfg_init has returned.
|
||||
// case), else NULL. Same string semantics as getenv; the pointer stays valid for the process (a value cfg_set replaces
|
||||
// is kept). A name without the TOTK_ prefix goes to getenv unchanged. Safe from any thread once cfg_init has returned.
|
||||
const char *cfg_get(const char *name);
|
||||
|
||||
// Reads totk.ini once, first thing in main. Logs the file, its key count, unknown keys and environment overrides.
|
||||
@@ -13,3 +13,43 @@ void cfg_init(void);
|
||||
// Not thread-safe: nothing else may call cfg_get meanwhile.
|
||||
int cfg_load(const char *path);
|
||||
|
||||
// Live settings (the in-game menu). cfg_set stores value as the totk.ini value of name (TOTK_ prefixed), marks it for
|
||||
// cfg_save and bumps cfg_version. cfg_get returns it unless the environment sets name. Any thread.
|
||||
void cfg_set(const char *name, const char *value);
|
||||
// Bumped by every cfg_set. A consumer that keeps a parsed value compares this with the number it last saw (one atomic
|
||||
// load) and parses again when it changed.
|
||||
unsigned cfg_version(void);
|
||||
// 1 when the environment sets name: cfg_set cannot change what cfg_get returns (the menu greys the setting out).
|
||||
int cfg_from_env(const char *name);
|
||||
// Writes the keys cfg_set changed since the last save into totk.ini next to totk.exe (cfg_save_to: the file at path).
|
||||
// Only those lines change: the last line of a changed key gets the new value, a missing key goes under its section
|
||||
// (after the commented example line of the key when the section has one; the section is added at the end of the file
|
||||
// when missing), comments and every other line stay byte for byte. 1 on success or with nothing to write.
|
||||
int cfg_save(void);
|
||||
int cfg_save_to(const char *path);
|
||||
|
||||
// Reset (the menu's "Reset all settings to defaults"). Removes the active line of each key (names without TOTK_, any
|
||||
// case) from totk.ini at the next cfg_save and its value from memory, so the consumer's own default applies again; the
|
||||
// commented example lines stay. Keys the environment sets are skipped. Bumps cfg_version. Returns how many it reset.
|
||||
int cfg_reset(const char *const *keys, int n);
|
||||
// 0 when the last cfg_save / cfg_save_to failed to write (the values stay set in memory, the next save tries again).
|
||||
int cfg_last_save_ok(void);
|
||||
|
||||
// What the menu knows about a setting. key: without TOTK_, upper case. def: what the consumer uses when the key is
|
||||
// unset ("" = no fixed default, the consumer picks per machine). values: "0|1", "mailbox|fifo|immediate", a range
|
||||
// "0..300", or NULL for free text. live: applies at once; the others are read at start.
|
||||
typedef struct { const char *key, *def, *values; int live; } CfgMeta;
|
||||
// The row of key (prefix and case ignored); NULL for a key the menu does not show.
|
||||
const CfgMeta *cfg_meta(const char *key);
|
||||
// The i-th row (0-based, table order); NULL past the last.
|
||||
const CfgMeta *cfg_meta_at(int i);
|
||||
|
||||
// The setting's value for consumers: the environment or totk.ini value, else the CfgMeta default. name has the TOTK_
|
||||
// prefix, like cfg_get; a name without a row is a bug (rt_fatal). A row with an empty default has no fixed value: its
|
||||
// consumer reads cfg_get and keeps its own "unset" branch. An empty value counts as unset.
|
||||
const char *cfg_value(const char *name);
|
||||
// cfg_value parsed. A set value that does not parse (int: whole string; double: strtod) gives the default's number.
|
||||
// cfg_bool: "0" is false, anything else true.
|
||||
int cfg_int(const char *name);
|
||||
double cfg_double(const char *name);
|
||||
int cfg_bool(const char *name);
|
||||
@@ -55,6 +55,166 @@ int probe_cfg(void) {
|
||||
plat_file_delete(path);
|
||||
CHECK(cfg_load(path) == 0, "missing file is not an error");
|
||||
CHECK(cfg_get("TOTK_FPS60") == NULL, "missing file leaves no keys");
|
||||
|
||||
// cfg_set / cfg_save: only changed lines move, comments stay, a missing key goes under its section
|
||||
static const char before[] =
|
||||
"\xEF\xBB\xBF# my settings\r\n"
|
||||
"[frame rate]\r\n"
|
||||
" FPS60 = 1\r\n"
|
||||
"; keep this\r\n"
|
||||
"\r\n"
|
||||
"[input]\r\n"
|
||||
"# Gamepad motion controls (0 = off) and vibration (0 = off).\r\n"
|
||||
"# motion = 1\r\n"
|
||||
"# rumble = 1\r\n"
|
||||
"rumble_curve = 0.6\r\n"
|
||||
"\r\n"
|
||||
"[files]\r\n"
|
||||
"romfs_mods = C:\\mods";
|
||||
static const char after[] =
|
||||
"\xEF\xBB\xBF# my settings\r\n"
|
||||
"[frame rate]\r\n"
|
||||
" FPS60 = 0\r\n"
|
||||
"; keep this\r\n"
|
||||
"\r\n"
|
||||
"[input]\r\n"
|
||||
"# Gamepad motion controls (0 = off) and vibration (0 = off).\r\n"
|
||||
"# motion = 1\r\n"
|
||||
"motion = 0\r\n"
|
||||
"# rumble = 1\r\n"
|
||||
"rumble_curve = 0.6\r\n"
|
||||
"rumble_strength = 80\r\n"
|
||||
"\r\n"
|
||||
"[files]\r\n"
|
||||
"romfs_mods = C:\\mods\r\n"
|
||||
"\r\n"
|
||||
"[audio]\r\n"
|
||||
"volume = 40\r\n";
|
||||
_putenv_s("TOTK_MOTION", "");
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
_putenv_s("TOTK_RUMBLE_STRENGTH", "");
|
||||
CHECK(plat_file_write(path, before, sizeof before - 1), "write the save ini");
|
||||
CHECK(cfg_load(path) == 1, "load the save ini");
|
||||
unsigned v0 = cfg_version();
|
||||
cfg_set("TOTK_FPS60", "0");
|
||||
cfg_set("TOTK_MOTION", "0");
|
||||
cfg_set("TOTK_RUMBLE_STRENGTH", "80");
|
||||
cfg_set("TOTK_VOLUME", "40");
|
||||
CHECK(cfg_version() == v0 + 4, "cfg_set bumps the version");
|
||||
CHECK(EQ(cfg_get("TOTK_FPS60"), "0") && EQ(cfg_get("TOTK_VOLUME"), "40"), "cfg_set values are read back at once");
|
||||
CHECK(cfg_save_to(path) == 1, "cfg_save_to writes");
|
||||
uint64_t got_n = 0;
|
||||
uint8_t *got = plat_file_read(path, &got_n);
|
||||
CHECK(got && got_n == sizeof after - 1 && !memcmp(got, after, got_n),
|
||||
"saved file: changed line replaced, comments kept, missing keys under their sections");
|
||||
if (got && (got_n != sizeof after - 1 || memcmp(got, after, got_n))) fprintf(stderr, "---- saved:\n%s\n----\n", got);
|
||||
free(got);
|
||||
CHECK(cfg_save_to(path) == 1, "a save with nothing changed");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && got_n == sizeof after - 1 && !memcmp(got, after, got_n), "a save with nothing changed keeps the file");
|
||||
free(got);
|
||||
CHECK(cfg_load(path) == 1 && EQ(cfg_get("TOTK_FPS60"), "0") && EQ(cfg_get("TOTK_MOTION"), "0") &&
|
||||
EQ(cfg_get("TOTK_RUMBLE_STRENGTH"), "80") && EQ(cfg_get("TOTK_VOLUME"), "40") &&
|
||||
EQ(cfg_get("TOTK_ROMFS_MODS"), "C:\\mods"), "the saved file reads back");
|
||||
const char *held = cfg_get("TOTK_VOLUME");
|
||||
_putenv_s("TOTK_VOLUME", "70");
|
||||
cfg_set("TOTK_VOLUME", "90");
|
||||
CHECK(cfg_from_env("TOTK_VOLUME") && EQ(cfg_get("TOTK_VOLUME"), "70"), "environment wins over cfg_set");
|
||||
CHECK(EQ(held, "40"), "a pointer cfg_get handed out stays valid after cfg_set");
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
CHECK(!cfg_from_env("TOTK_VOLUME") && EQ(cfg_get("TOTK_VOLUME"), "90"), "cfg_set value returns without the variable");
|
||||
plat_file_delete(path);
|
||||
CHECK(cfg_save_to(path) == 1, "cfg_save_to creates a missing file");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && !strcmp((const char *)got, "[audio]\nvolume = 90\n"), "new file: the section and the key");
|
||||
free(got);
|
||||
|
||||
// Defaults table: the menu's "default" marks and Reset
|
||||
const CfgMeta *m = cfg_meta("FPS60");
|
||||
CHECK(m && EQ(m->def, "1") && m->live, "meta: fps60 defaults to 1 and is live");
|
||||
m = cfg_meta("ASYNC_PREEMPT");
|
||||
CHECK(m && EQ(m->values, "0|1|2") && !m->live, "meta: async_preempt takes 0|1|2 and needs a restart");
|
||||
m = cfg_meta("totk_vk_present");
|
||||
CHECK(m && EQ(m->key, "VK_PRESENT") && EQ(m->values, "mailbox|fifo|immediate") && m->live,
|
||||
"meta: prefix and case are accepted");
|
||||
m = cfg_meta("RUMBLE_STRENGTH");
|
||||
CHECK(m && EQ(m->def, "130") && EQ(m->values, "0..300"), "meta: rumble strength 130 in 0..300");
|
||||
m = cfg_meta("PERF_OVERLAY");
|
||||
CHECK(m && EQ(m->def, "off") && EQ(m->values, "off|fps|full") && m->live, "meta: perf_overlay is live, off by default");
|
||||
CHECK(cfg_meta("BIND_A") == NULL && cfg_meta("FPS_COUNTER") == NULL && cfg_meta("NO_SUCH") == NULL,
|
||||
"meta: keys the menu does not show are NULL");
|
||||
|
||||
// cfg_reset: the key's active lines leave totk.ini, the commented example stays
|
||||
static const char rbase[] = "[audio]\n# volume = 100\n[input]\nmotion = 0\n";
|
||||
static const char *const vol[] = {"VOLUME"};
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
CHECK(plat_file_write(path, rbase, sizeof rbase - 1), "write the reset ini");
|
||||
CHECK(cfg_load(path) == 1, "load the reset ini");
|
||||
cfg_set("TOTK_VOLUME", "40");
|
||||
CHECK(cfg_save_to(path) == 1 && cfg_last_save_ok(), "reset: volume saved");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && strstr((const char *)got, "\nvolume = 40\n"), "reset: the active line is in the file");
|
||||
free(got);
|
||||
unsigned v1 = cfg_version();
|
||||
CHECK(cfg_reset(vol, 1) == 1, "reset: one key reset");
|
||||
CHECK(cfg_version() > v1 && cfg_get("TOTK_VOLUME") == NULL, "reset: the value is gone in memory, the version moved");
|
||||
CHECK(cfg_reset(vol, 1) == 0, "reset: a key already reset counts 0");
|
||||
CHECK(cfg_save_to(path) == 1, "reset: save");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && got_n == sizeof rbase - 1 && !memcmp(got, rbase, got_n) && strstr((const char *)got, "# volume = 100"),
|
||||
"reset: no active volume line, the commented example and the other keys stay");
|
||||
if (got && (got_n != sizeof rbase - 1 || memcmp(got, rbase, got_n))) fprintf(stderr, "---- saved:\n%s\n----\n", got);
|
||||
free(got);
|
||||
cfg_set("TOTK_VOLUME", "55");
|
||||
CHECK(cfg_reset(vol, 1) == 1 && cfg_get("TOTK_VOLUME") == NULL, "reset: a value set after a save resets too");
|
||||
cfg_set("TOTK_VOLUME", "60");
|
||||
CHECK(cfg_save_to(path) == 1 && EQ(cfg_get("TOTK_VOLUME"), "60"), "reset then set before the save: the set wins");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && strstr((const char *)got, "\nvolume = 60\n"), "reset then set: the new line is written");
|
||||
free(got);
|
||||
|
||||
// an active line with an empty value has no entry in memory; Reset still removes it from the file
|
||||
static const char rempty[] = "[audio]\n# volume = 100\nvolume =\n[input]\nmotion = 0\n";
|
||||
CHECK(plat_file_write(path, rempty, sizeof rempty - 1) && cfg_load(path) == 1 && cfg_get("TOTK_VOLUME") == NULL,
|
||||
"reset: load an ini with an empty value");
|
||||
CHECK(cfg_reset(vol, 1) == 0 && cfg_save_to(path) == 1, "reset: an empty-valued key saves");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && got_n == sizeof rbase - 1 && !memcmp(got, rbase, got_n), "reset: the empty-valued line is gone");
|
||||
free(got);
|
||||
cfg_set("TOTK_VOLUME", "60");
|
||||
CHECK(cfg_save_to(path) == 1, "reset: volume 60 again for the environment case");
|
||||
|
||||
// a key the environment sets is skipped and keeps its file line
|
||||
CHECK(cfg_load(path) == 1 && EQ(cfg_get("TOTK_VOLUME"), "60"), "reset: reload");
|
||||
_putenv_s("TOTK_VOLUME", "70");
|
||||
CHECK(cfg_reset(vol, 1) == 0, "reset: an environment-set key is skipped");
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
CHECK(EQ(cfg_get("TOTK_VOLUME"), "60"), "reset: the skipped key keeps its value");
|
||||
CHECK(cfg_save_to(path) == 1, "reset: save after a skip");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && strstr((const char *)got, "\nvolume = 60\n"), "reset: the skipped key keeps its file line");
|
||||
free(got);
|
||||
|
||||
// a failed save: the call fails, cfg_last_save_ok says so, the value stays set and a later save works
|
||||
CHECK(cfg_last_save_ok() == 1, "save status: ok after a good save");
|
||||
cfg_set("TOTK_VOLUME", "20");
|
||||
char bad[1100];
|
||||
snprintf(bad, sizeof bad, "%s", path);
|
||||
strcpy(strrchr(bad, '\\') + 1, "no-such-dir\\cfg-probe.ini");
|
||||
CHECK(cfg_save_to(bad) == 0 && cfg_last_save_ok() == 0 && EQ(cfg_get("TOTK_VOLUME"), "20"),
|
||||
"save status: an unwritable path fails, the value stays");
|
||||
cfg_set("TOTK_VOLUME", "21");
|
||||
CHECK(plat_file_write(path, rbase, sizeof rbase - 1), "write the read-only ini");
|
||||
CHECK(plat_file_set_readonly(path, 1), "set the file read-only");
|
||||
CHECK(cfg_save_to(path) == 0 && cfg_last_save_ok() == 0 && EQ(cfg_get("TOTK_VOLUME"), "21"),
|
||||
"save status: a read-only file fails, cfg_get returns the new value");
|
||||
plat_file_set_readonly(path, 0);
|
||||
CHECK(cfg_save_to(path) == 1 && cfg_last_save_ok() == 1, "save status: the retry after the failure works");
|
||||
got = plat_file_read(path, &got_n);
|
||||
CHECK(got && strstr((const char *)got, "\nvolume = 21\n"), "save status: the retried save wrote the value");
|
||||
free(got);
|
||||
plat_file_delete(path);
|
||||
cfg_load(path);
|
||||
CHECK(rumble_motor(0, 0.6f, 1.3f) == 0 && rumble_motor(0.5f, 0.6f, 0) == 0, "rumble: zero amplitude or strength is silent");
|
||||
CHECK(rumble_motor(1, 0.6f, 3) == 65535 && rumble_motor(5, 1, 1) == 65535, "rumble: saturates at 65535");
|
||||
CHECK(rumble_motor(0.25f, 1, 1) > 16000 && rumble_motor(0.25f, 1, 1) < 16800, "rumble: curve 1, strength 100% is linear");
|
||||
@@ -101,6 +261,53 @@ int probe_cfg(void) {
|
||||
CHECK((int64_t)st[0] * st[0] + (int64_t)st[1] * st[1] <= 32768ll * 32768, "mouse: clamped to the unit circle");
|
||||
input_mouse_stick(30, 0, 1.0 / 60, 0, st);
|
||||
CHECK(st[0] == 0 && st[1] == 0, "mouse: sensitivity 0 is off");
|
||||
// defaults live in the CfgMeta table: cfg_value and the typed accessors fall back to it
|
||||
cfg_load("cfg-probe-missing.ini");
|
||||
_putenv_s("TOTK_FPS60", "");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "");
|
||||
_putenv_s("TOTK_FREE_CORES", "");
|
||||
CHECK(cfg_bool("TOTK_FPS60") == 1, "default: unset FPS60 is on");
|
||||
CHECK(EQ(cfg_value("TOTK_VK_PRESENT"), "mailbox") && cfg_int("TOTK_SPLIT_DRAWS") == 64, "default: text and integer");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "2.5");
|
||||
CHECK(cfg_double("TOTK_MOUSE_SENS") == 2.5, "double: the environment value");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "fast");
|
||||
CHECK(cfg_double("TOTK_MOUSE_SENS") == 1.0, "double: a value that does not parse gives the default");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "");
|
||||
cfg_set("TOTK_MOUSE_SENS", "3");
|
||||
CHECK(cfg_double("TOTK_MOUSE_SENS") == 3.0 && cfg_int("TOTK_MOUSE_SENS") == 3, "a cfg_set value beats the default");
|
||||
CHECK(cfg_bool("TOTK_FREE_CORES") == 0, "free_cores unset: off");
|
||||
_putenv_s("TOTK_FREE_CORES", "0");
|
||||
CHECK(cfg_bool("TOTK_FREE_CORES") == 0, "free_cores 0 gives the same as unset");
|
||||
_putenv_s("TOTK_FREE_CORES", "1");
|
||||
CHECK(cfg_bool("TOTK_FREE_CORES") == 1, "free_cores 1: on");
|
||||
_putenv_s("TOTK_FREE_CORES", "");
|
||||
cfg_load("cfg-probe-missing.ini");
|
||||
int listed = 0;
|
||||
for (int i = 0; cfg_meta_at(i); i++) {
|
||||
const CfgMeta *m = cfg_meta_at(i);
|
||||
if (!*m->def) continue;
|
||||
listed++;
|
||||
char name[96];
|
||||
snprintf(name, sizeof name, "TOTK_%s", m->key);
|
||||
_putenv_s(name, "");
|
||||
CHECK(EQ(cfg_value(name), m->def), "cfg_value returns the table default");
|
||||
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);
|
||||
double d = strtod(m->def, NULL);
|
||||
ok = d >= (double)lo && d <= (double)hi;
|
||||
} else {
|
||||
size_t dl = strlen(m->def);
|
||||
for (const char *v = m->values; *v;) {
|
||||
size_t n = strcspn(v, "|");
|
||||
ok |= n == dl && !strncmp(v, m->def, n);
|
||||
v += n + (v[n] == '|');
|
||||
}
|
||||
}
|
||||
if (!ok) fprintf(stderr, "FAIL cfg: default '%s' of %s is not one of its values '%s'\n", m->def, m->key, m->values), fails++;
|
||||
}
|
||||
CHECK(listed >= 30, "the defaults table was walked");
|
||||
printf("probe-cfg: %s\n", fails ? "FAIL" : "ok");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
+2
-3
@@ -65,13 +65,12 @@ static unsigned env_u(const char *name, unsigned def) {
|
||||
}
|
||||
|
||||
void flight_init(void) {
|
||||
const char *e = cfg_get("TOTK_FLIGHT");
|
||||
if (!e || strcmp(e, "1")) return;
|
||||
if (strcmp(cfg_value("TOTK_FLIGHT"), "1")) return;
|
||||
ring_n = (int)env_u("TOTK_FLIGHT_FRAMES", 600);
|
||||
if (ring_n < 64) ring_n = 64;
|
||||
if (ring_n > 7200) ring_n = 7200;
|
||||
if (!(ring = calloc((size_t)ring_n, sizeof *ring))) { rt_log("flight: no memory for %d records, off", ring_n); return; }
|
||||
spike_ns = (uint64_t)env_u("TOTK_FLIGHT_SPIKE_MS", 100) * 1000000ull;
|
||||
spike_ns = (uint64_t)cfg_int("TOTK_FLIGHT_SPIKE_MS") * 1000000ull;
|
||||
for (const char *p = cfg_get("TOTK_FLIGHT_AT"); p && *p && n_at < 16;) {
|
||||
char *end;
|
||||
unsigned long long f = strtoull(p, &end, 10);
|
||||
|
||||
@@ -72,6 +72,28 @@ void frame_step_init(void) {
|
||||
|
||||
int frame_step_realtime(void) { return step_word != NULL; }
|
||||
|
||||
// The frame limit (menu: 30 or 60): TOTK_FPS60 switches the set fps60 while the game runs; the controller reads its
|
||||
// minimum interval from the patched sites each frame. With the real-time step the pacer holds frames to the cap.
|
||||
static int fps60_set = -2;
|
||||
static unsigned fps60_seen;
|
||||
|
||||
static void frame_limit_live(void) {
|
||||
unsigned v = cfg_version();
|
||||
if (v == fps60_seen) return;
|
||||
fps60_seen = v;
|
||||
if (fps60_set == -2) fps60_set = rt_patch_set("fps60");
|
||||
if (fps60_set < 0) return;
|
||||
int on = cfg_bool("TOTK_FPS60");
|
||||
if (on == rt_patch_enabled(fps60_set)) return;
|
||||
rt_patch_switch(fps60_set, on);
|
||||
rt_log("frame rate: limit %d fps (TOTK_FPS60=%d)", on ? 60 : 30, on);
|
||||
}
|
||||
|
||||
int frame_step_cap_ticks(void) {
|
||||
if (fps60_set == -2) fps60_set = rt_patch_set("fps60");
|
||||
return fps60_set < 0 || rt_patch_enabled(fps60_set) ? 1 : 2;
|
||||
}
|
||||
|
||||
// ---- TOTK_TRACE=perf speed lines
|
||||
static uint64_t win_t0, win_frames, win_hist[4]; // win_hist: frames by present interval 1, 2, 3+ ([0] unused)
|
||||
static double win_game;
|
||||
@@ -142,6 +164,7 @@ static void speed_report(uint64_t now, double step, int interval) {
|
||||
}
|
||||
|
||||
void frame_step_present(uint64_t display_ns, int interval) {
|
||||
frame_limit_live();
|
||||
double step = 0;
|
||||
if (step_word && last_ns) {
|
||||
double dt = (double)(display_ns - last_ns) * 1e-9;
|
||||
|
||||
+214
-26
@@ -8,6 +8,10 @@
|
||||
// bound system events. Presents come from any host thread (the back end's present worker) and take g_pl; every queue
|
||||
// submission takes the recursive queue lock (vk_queue_lock). The swapchain is rebuilt lazily: WM_SIZE only marks it
|
||||
// dirty, the next present (or gfx_window_resize) rebuilds it.
|
||||
//
|
||||
// The in-game menu (ui/menu.h) draws over the game image in the present's command buffer, after the blit; its keyboard
|
||||
// and mouse come from the window procedure (ui/menu_win.cpp). The window's size and fullscreen state are the settings
|
||||
// TOTK_WINDOW_SIZE and TOTK_FULLSCREEN, applied at start and whenever a cfg_set changes them (window_settings_live).
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -17,6 +21,8 @@
|
||||
#include "flight.h"
|
||||
#include "gfx.h"
|
||||
#include "input.h"
|
||||
#include "nvn_api.h"
|
||||
#include "ui/menu.h"
|
||||
#include "vk.h"
|
||||
|
||||
#define FRAMES 2
|
||||
@@ -39,6 +45,7 @@ static volatile LONG g_focused = 1;
|
||||
static volatile LONG g_focus_msgs;
|
||||
static CRITICAL_SECTION g_start_lock; // gfx_window_start / vsync start
|
||||
static int g_started, g_wnd_failed;
|
||||
static int g_background; // TOTK_BACKGROUND_WINDOW: the window stays behind the user's windows
|
||||
|
||||
// ---- swapchain and present state (g_pl)
|
||||
static CRITICAL_SECTION g_pl;
|
||||
@@ -47,6 +54,7 @@ static VkFormat g_sc_fmt;
|
||||
static VkExtent2D g_sc_ext;
|
||||
static uint32_t g_sc_n;
|
||||
static VkImage g_sc_img[MAX_IMAGES];
|
||||
static VkImageView g_sc_view[MAX_IMAGES]; // colour attachment views for the menu overlay
|
||||
static VkSemaphore g_render_done[MAX_IMAGES];
|
||||
static VkCommandPool g_pool;
|
||||
static VkCommandBuffer g_cb[FRAMES];
|
||||
@@ -171,37 +179,141 @@ HWND gfx_window_handle(void) { return g_hwnd; }
|
||||
|
||||
// ---- window thread
|
||||
#define WND_STYLE WS_OVERLAPPEDWINDOW
|
||||
#define WM_APP_SETTINGS (WM_APP + 1)
|
||||
|
||||
static WINDOWPLACEMENT g_saved_place = {sizeof g_saved_place}; // the window behind fullscreen (window thread)
|
||||
|
||||
static int is_fullscreen(HWND h) { return !(GetWindowLongW(h, GWL_STYLE) & WS_OVERLAPPEDWINDOW); }
|
||||
|
||||
// TOTK_FULLSCREEN=1: borderless window over the monitor. TOTK_WINDOW_SIZE=<w>x<h>: client area of the window (the
|
||||
// swapchain follows the window; the game image is scaled to it).
|
||||
static int cfg_fullscreen(void) {
|
||||
return cfg_bool("TOTK_FULLSCREEN");
|
||||
}
|
||||
|
||||
static void cfg_window_size(int *w, int *h) {
|
||||
int x = 0, y = 0;
|
||||
if (sscanf(cfg_value("TOTK_WINDOW_SIZE"), "%dx%d", &x, &y) != 2 || x < 640 || y < 360 || x > 7680 || y > 4320)
|
||||
sscanf(cfg_meta("WINDOW_SIZE")->def, "%dx%d", &x, &y); // unparsable or out of range: the default
|
||||
*w = x;
|
||||
*h = y;
|
||||
}
|
||||
|
||||
// F11: borderless window over the whole monitor, and back to the saved window. The swapchain follows through WM_SIZE.
|
||||
// Not Alt+Enter: Enter is the Plus button (input_win.c).
|
||||
// Not Alt+Enter: Enter is the Plus button (input_win.c). A background window (test runs) keeps its place behind the
|
||||
// user's windows and takes no focus.
|
||||
static void toggle_fullscreen(HWND h) {
|
||||
static WINDOWPLACEMENT saved = {sizeof saved};
|
||||
LONG style = GetWindowLongW(h, GWL_STYLE);
|
||||
if (style & WS_OVERLAPPEDWINDOW) {
|
||||
MONITORINFO mi = {sizeof mi};
|
||||
if (!GetWindowPlacement(h, &saved) || !GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTOPRIMARY), &mi))
|
||||
if (!GetWindowPlacement(h, &g_saved_place) || !GetMonitorInfoW(MonitorFromWindow(h, MONITOR_DEFAULTTOPRIMARY), &mi))
|
||||
return;
|
||||
SetWindowLongW(h, GWL_STYLE, (style & ~WS_OVERLAPPEDWINDOW) | WS_POPUP);
|
||||
SetWindowPos(h, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left,
|
||||
mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
|
||||
mi.rcMonitor.bottom - mi.rcMonitor.top,
|
||||
SWP_NOOWNERZORDER | SWP_FRAMECHANGED | (g_background ? SWP_NOZORDER | SWP_NOACTIVATE : 0));
|
||||
} else {
|
||||
SetWindowLongW(h, GWL_STYLE, (style & ~WS_POPUP) | WND_STYLE);
|
||||
SetWindowPlacement(h, &saved);
|
||||
SetWindowPos(h, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
|
||||
if (g_background) g_saved_place.showCmd = SW_SHOWNOACTIVATE;
|
||||
SetWindowPlacement(h, &g_saved_place);
|
||||
SetWindowPos(h, NULL, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED |
|
||||
(g_background ? SWP_NOACTIVATE : 0));
|
||||
}
|
||||
}
|
||||
|
||||
// The window size and fullscreen state last taken from the settings (window thread). apply_settings acts on a change of
|
||||
// either value only, so a window resized by hand keeps its size when another setting changes.
|
||||
static char g_applied_size[32];
|
||||
static int g_applied_fs;
|
||||
|
||||
static void note_applied(void) {
|
||||
snprintf(g_applied_size, sizeof g_applied_size, "%s", cfg_value("TOTK_WINDOW_SIZE"));
|
||||
g_applied_fs = cfg_fullscreen();
|
||||
}
|
||||
|
||||
// Window thread: the window takes the size and fullscreen state of the settings when they changed. In fullscreen the
|
||||
// size goes into the placement restored when fullscreen ends.
|
||||
static void apply_settings(HWND h) {
|
||||
int size_changed = strcmp(cfg_value("TOTK_WINDOW_SIZE"), g_applied_size) != 0, fs = cfg_fullscreen(), fs_changed = fs != g_applied_fs;
|
||||
note_applied();
|
||||
if (size_changed) {
|
||||
int cw, ch;
|
||||
cfg_window_size(&cw, &ch);
|
||||
RECT r = {0, 0, cw, ch};
|
||||
AdjustWindowRect(&r, WND_STYLE, FALSE);
|
||||
if (is_fullscreen(h)) {
|
||||
RECT *n = &g_saved_place.rcNormalPosition;
|
||||
n->right = n->left + (r.right - r.left);
|
||||
n->bottom = n->top + (r.bottom - r.top);
|
||||
} else {
|
||||
RECT have;
|
||||
if (GetClientRect(h, &have) && (have.right != cw || have.bottom != ch)) {
|
||||
if (IsZoomed(h)) ShowWindow(h, SW_RESTORE);
|
||||
SetWindowPos(h, NULL, 0, 0, r.right - r.left, r.bottom - r.top,
|
||||
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fs_changed && fs != is_fullscreen(h)) {
|
||||
input_cursor_suspend(1);
|
||||
toggle_fullscreen(h);
|
||||
input_cursor_suspend(0);
|
||||
}
|
||||
}
|
||||
|
||||
void gfx_window_apply_settings(void) {
|
||||
if (g_hwnd) PostMessageW(g_hwnd, WM_APP_SETTINGS, 0, 0);
|
||||
}
|
||||
|
||||
// Present path (g_pl held): a settings change (cfg_version) reaches the window thread, which applies a changed size or
|
||||
// fullscreen; a changed TOTK_VK_PRESENT rebuilds the swapchain at this present.
|
||||
static void window_settings_live(void) {
|
||||
static unsigned seen;
|
||||
static int started;
|
||||
static char present[16]; // the TOTK_VK_PRESENT the swapchain was made with
|
||||
unsigned v = cfg_version();
|
||||
if (started && v == seen) return;
|
||||
seen = v;
|
||||
const char *e = cfg_value("TOTK_VK_PRESENT");
|
||||
if (!started || strncmp(e, present, sizeof present - 1)) {
|
||||
snprintf(present, sizeof present, "%s", e);
|
||||
if (started) InterlockedExchange(&g_dirty, 1);
|
||||
}
|
||||
if (started) gfx_window_apply_settings();
|
||||
started = 1;
|
||||
}
|
||||
|
||||
void gfx_window_request_close(void) {
|
||||
if (g_hwnd) PostMessageW(g_hwnd, WM_CLOSE, 0, 0);
|
||||
}
|
||||
|
||||
int gfx_window_monitor_size(int *w, int *h) {
|
||||
MONITORINFO mi = {sizeof mi};
|
||||
if (!g_hwnd || !GetMonitorInfoW(MonitorFromWindow(g_hwnd, MONITOR_DEFAULTTOPRIMARY), &mi)) return 0;
|
||||
*w = mi.rcMonitor.right - mi.rcMonitor.left;
|
||||
*h = mi.rcMonitor.bottom - mi.rcMonitor.top;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK wnd_proc(HWND h, UINT m, WPARAM w, LPARAM l) {
|
||||
LRESULT input_res;
|
||||
if (input_window_msg(h, m, w, l, &input_res)) return input_res;
|
||||
if (menu_window_msg(h, m, w, l, &input_res)) return input_res;
|
||||
switch (m) {
|
||||
case WM_KEYDOWN:
|
||||
if (w == VK_F11 && !(l & (1 << 30))) { // bit 30: auto-repeat
|
||||
input_cursor_suspend(1);
|
||||
toggle_fullscreen(h);
|
||||
input_cursor_suspend(0);
|
||||
cfg_set("TOTK_FULLSCREEN", is_fullscreen(h) ? "1" : "0"); // the menu shows it; the next start keeps it
|
||||
cfg_save();
|
||||
note_applied(); // what cfg_get reads now (the environment may still override it)
|
||||
}
|
||||
break;
|
||||
case WM_APP_SETTINGS:
|
||||
apply_settings(h);
|
||||
return 0;
|
||||
case WM_SIZE:
|
||||
if (w != SIZE_MINIMIZED) InterlockedExchange(&g_dirty, 1);
|
||||
return 0;
|
||||
@@ -231,11 +343,13 @@ static DWORD WINAPI window_main(void *arg) {
|
||||
WNDCLASSEXW wc = {.cbSize = sizeof wc, .lpfnWndProc = wnd_proc, .hInstance = inst,
|
||||
.hCursor = LoadCursorW(NULL, (LPCWSTR)IDC_ARROW), .lpszClassName = L"TotKRecompWindow"};
|
||||
RegisterClassExW(&wc);
|
||||
RECT r = {0, 0, 1920, 1080};
|
||||
int cw, ch;
|
||||
cfg_window_size(&cw, &ch);
|
||||
RECT r = {0, 0, cw, ch};
|
||||
AdjustWindowRect(&r, WND_STYLE, FALSE);
|
||||
// TOTK_BACKGROUND_WINDOW=1 (test runs): the window opens behind the user's windows without taking focus; it keeps its
|
||||
// taskbar button and can be brought up by hand.
|
||||
int background = cfg_get("TOTK_BACKGROUND_WINDOW") && atoi(cfg_get("TOTK_BACKGROUND_WINDOW"));
|
||||
// taskbar button and can be brought up by hand. It never goes fullscreen at start.
|
||||
int background = g_background = cfg_get("TOTK_BACKGROUND_WINDOW") && atoi(cfg_get("TOTK_BACKGROUND_WINDOW"));
|
||||
g_hwnd = CreateWindowExW(0, wc.lpszClassName, L"TotK Recomp", WND_STYLE, CW_USEDEFAULT, CW_USEDEFAULT,
|
||||
r.right - r.left, r.bottom - r.top, NULL, NULL, inst, NULL);
|
||||
if (!g_hwnd) {
|
||||
@@ -246,6 +360,8 @@ static DWORD WINAPI window_main(void *arg) {
|
||||
SetWindowPos(g_hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
|
||||
else
|
||||
ShowWindow(g_hwnd, cfg_get("TOTK_ASSUME_FOCUS") ? SW_SHOWNOACTIVATE : SW_SHOW); // scripted runs leave focus alone
|
||||
if (!background && cfg_fullscreen()) toggle_fullscreen(g_hwnd);
|
||||
note_applied();
|
||||
}
|
||||
SetEvent(g_wnd_ready);
|
||||
if (g_wnd_failed) return 1;
|
||||
@@ -259,16 +375,23 @@ static DWORD WINAPI window_main(void *arg) {
|
||||
|
||||
// ---- swapchain
|
||||
static VkPresentModeKHR pick_present_mode(VkPhysicalDevice pd) {
|
||||
const char *e = cfg_get("TOTK_VK_PRESENT");
|
||||
VkPresentModeKHR want = !e || !strcmp(e, "mailbox") ? VK_PRESENT_MODE_MAILBOX_KHR
|
||||
const char *e = cfg_value("TOTK_VK_PRESENT");
|
||||
VkPresentModeKHR want = !strcmp(e, "mailbox") ? VK_PRESENT_MODE_MAILBOX_KHR
|
||||
: !strcmp(e, "immediate") ? VK_PRESENT_MODE_IMMEDIATE_KHR : VK_PRESENT_MODE_FIFO_KHR;
|
||||
uint32_t n = 0;
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(pd, g_surface, &n, NULL);
|
||||
VkPresentModeKHR m[16];
|
||||
if (n > 16) n = 16;
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(pd, g_surface, &n, m);
|
||||
for (uint32_t i = 0; i < n; i++) if (m[i] == want) return want;
|
||||
return VK_PRESENT_MODE_FIFO_KHR;
|
||||
VkPresentModeKHR got = VK_PRESENT_MODE_FIFO_KHR;
|
||||
for (uint32_t i = 0; i < n; i++) if (m[i] == want) got = want;
|
||||
static int logged = -1; // the mode last logged: a change from the menu shows in the log
|
||||
if ((int)got != logged) {
|
||||
logged = (int)got;
|
||||
rt_log("gfx: present mode %s (TOTK_VK_PRESENT=%s)",
|
||||
got == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : got == VK_PRESENT_MODE_IMMEDIATE_KHR ? "immediate" : "fifo", e);
|
||||
}
|
||||
return got;
|
||||
}
|
||||
|
||||
// Queues the present of a blit vk_present_blit left waiting (g_pl held). A swapchain rebuild and the next blit flush it
|
||||
@@ -329,7 +452,8 @@ static int create_swapchain(void) {
|
||||
VkSwapchainCreateInfoKHR ci = {
|
||||
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .surface = g_surface, .minImageCount = count,
|
||||
.imageFormat = sf.format, .imageColorSpace = sf.colorSpace, .imageExtent = ext, .imageArrayLayers = 1,
|
||||
.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
|
||||
.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
|
||||
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, // every surface supports it (the menu overlay draws into it)
|
||||
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, .preTransform = caps.currentTransform,
|
||||
.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, .presentMode = pick_present_mode(c->phys), .clipped = VK_TRUE,
|
||||
.oldSwapchain = old};
|
||||
@@ -340,14 +464,24 @@ static int create_swapchain(void) {
|
||||
vk_queue_unlock();
|
||||
return 0;
|
||||
}
|
||||
for (uint32_t i = 0; i < g_sc_n; i++) vkDestroySemaphore(c->device, g_render_done[i], NULL);
|
||||
for (uint32_t i = 0; i < g_sc_n; i++) {
|
||||
vkDestroySemaphore(c->device, g_render_done[i], NULL);
|
||||
if (g_sc_view[i]) vkDestroyImageView(c->device, g_sc_view[i], NULL);
|
||||
g_sc_view[i] = VK_NULL_HANDLE;
|
||||
}
|
||||
if (old) vkDestroySwapchainKHR(c->device, old, NULL);
|
||||
g_sc_fmt = sf.format;
|
||||
g_sc_ext = ext;
|
||||
g_sc_n = MAX_IMAGES;
|
||||
vkGetSwapchainImagesKHR(c->device, g_sc, &g_sc_n, g_sc_img);
|
||||
VkSemaphoreCreateInfo semi = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
||||
for (uint32_t i = 0; i < g_sc_n; i++) vkCreateSemaphore(c->device, &semi, NULL, &g_render_done[i]);
|
||||
for (uint32_t i = 0; i < g_sc_n; i++) {
|
||||
vkCreateSemaphore(c->device, &semi, NULL, &g_render_done[i]);
|
||||
VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = g_sc_img[i],
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D, .format = sf.format,
|
||||
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
|
||||
if (vkCreateImageView(c->device, &vi, NULL, &g_sc_view[i]) != VK_SUCCESS) g_sc_view[i] = VK_NULL_HANDLE;
|
||||
}
|
||||
free_capture();
|
||||
vk_queue_unlock();
|
||||
InterlockedExchange(&g_dirty, 0);
|
||||
@@ -505,6 +639,23 @@ int vk_present_captured(const uint8_t **px, int *w, int *h, VkFormat *fmt) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
// The captured swapchain image as a PNG (the menu's test hook), RGBA with opaque alpha.
|
||||
static void save_capture(const char *path) {
|
||||
size_t n = (size_t)g_cap_w * (size_t)g_cap_h * 4;
|
||||
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) {
|
||||
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)];
|
||||
px[i + 3] = 255;
|
||||
}
|
||||
rt_write_png(path, px, (uint32_t)g_cap_w, (uint32_t)g_cap_h);
|
||||
free(px);
|
||||
rt_log("gfx: menu test shot %s (%dx%d)", path, g_cap_w, g_cap_h);
|
||||
}
|
||||
|
||||
static void present_image(VkImage src, VkImageLayout layout, int w, int h, const int crop[4], int defer) {
|
||||
int general = layout == VK_IMAGE_LAYOUT_GENERAL;
|
||||
gfx_window_start();
|
||||
@@ -542,7 +693,14 @@ static void present_image(VkImage src, VkImageLayout layout, int w, int h, const
|
||||
if (cy < 0) cy = 0;
|
||||
if (cx + cw > w) cw = w - cx;
|
||||
if (cy + ch > h) ch = h - cy;
|
||||
int cap = g_capture && ensure_capture_buffer();
|
||||
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,
|
||||
g_sc_ext.height};
|
||||
int overlay = g_sc_view[idx] &&
|
||||
menu_overlay_frame(__atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED), &mt, &menu_shot);
|
||||
int cap = (g_capture || menu_shot) && ensure_capture_buffer();
|
||||
int thumb = g_th_n && ensure_thumbs();
|
||||
|
||||
VkCommandBuffer cb = g_cb[slot];
|
||||
@@ -564,25 +722,46 @@ static void present_image(VkImage src, VkImageLayout layout, int w, int h, const
|
||||
if (general) // later submissions that write the source wait for the blit's read
|
||||
sync_barrier(cb, src, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, VK_PIPELINE_STAGE_2_TRANSFER_BIT, 0,
|
||||
VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, 0);
|
||||
// last: the image's layout, and the stage and access of its last write, as each step leaves it
|
||||
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;
|
||||
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],
|
||||
.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}, g_sc_ext}, .layerCount = 1,
|
||||
.colorAttachmentCount = 1, .pColorAttachments = &ca};
|
||||
vkCmdBeginRendering(cb, &ri);
|
||||
menu_overlay_draw(cb);
|
||||
vkCmdEndRendering(cb);
|
||||
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;
|
||||
}
|
||||
if (cap) {
|
||||
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_2_TRANSFER_BIT,
|
||||
VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_READ_BIT);
|
||||
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, last_stage, last_write,
|
||||
VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_READ_BIT);
|
||||
VkBufferImageCopy bc = {.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.imageExtent = {g_sc_ext.width, g_sc_ext.height, 1}};
|
||||
vkCmdCopyImageToBuffer(cb, dst, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, g_cap_buf, 1, &bc);
|
||||
last = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
last_stage = VK_PIPELINE_STAGE_2_TRANSFER_BIT;
|
||||
last_write = 0;
|
||||
}
|
||||
if (thumb) {
|
||||
if (last != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL)
|
||||
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_2_TRANSFER_BIT,
|
||||
VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_READ_BIT);
|
||||
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, last_stage, last_write,
|
||||
VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_READ_BIT);
|
||||
last = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
last_stage = VK_PIPELINE_STAGE_2_TRANSFER_BIT;
|
||||
last_write = 0;
|
||||
record_thumb(cb, dst, slot);
|
||||
}
|
||||
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_PIPELINE_STAGE_2_TRANSFER_BIT,
|
||||
last == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ? VK_ACCESS_2_TRANSFER_WRITE_BIT : 0,
|
||||
VK_PIPELINE_STAGE_2_NONE, 0);
|
||||
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, last_stage, last_write, VK_PIPELINE_STAGE_2_NONE, 0);
|
||||
vkEndCommandBuffer(cb);
|
||||
|
||||
VkSemaphoreSubmitInfo wait = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO, .semaphore = g_acquire[slot],
|
||||
@@ -610,6 +789,7 @@ static void present_image(VkImage src, VkImageLayout layout, int w, int h, const
|
||||
g_cap_w = (int)g_sc_ext.width;
|
||||
g_cap_h = (int)g_sc_ext.height;
|
||||
g_cap_valid = 1;
|
||||
if (menu_shot) save_capture(menu_shot);
|
||||
}
|
||||
out:
|
||||
LeaveCriticalSection(&g_pl);
|
||||
@@ -649,13 +829,18 @@ void gfx_window_release_vk(void) {
|
||||
vkDeviceWaitIdle(c->device);
|
||||
vk_queue_unlock();
|
||||
g_flip_on = 0; // its blit is done (device idle); the swapchain goes away unpresented
|
||||
menu_vk_release();
|
||||
free_capture();
|
||||
free_thumbs();
|
||||
for (int i = 0; i < FRAMES; i++) {
|
||||
vkDestroySemaphore(c->device, g_acquire[i], NULL);
|
||||
vkDestroyFence(c->device, g_fence[i], NULL);
|
||||
}
|
||||
for (uint32_t i = 0; i < g_sc_n; i++) vkDestroySemaphore(c->device, g_render_done[i], NULL);
|
||||
for (uint32_t i = 0; i < g_sc_n; i++) {
|
||||
vkDestroySemaphore(c->device, g_render_done[i], NULL);
|
||||
if (g_sc_view[i]) vkDestroyImageView(c->device, g_sc_view[i], NULL);
|
||||
g_sc_view[i] = VK_NULL_HANDLE;
|
||||
}
|
||||
if (g_pool) vkDestroyCommandPool(c->device, g_pool, NULL);
|
||||
if (g_sc) vkDestroySwapchainKHR(c->device, g_sc, NULL);
|
||||
if (g_surface) vkDestroySurfaceKHR(c->instance, g_surface, NULL);
|
||||
@@ -702,7 +887,10 @@ void gfx_window_start(void) {
|
||||
EnterCriticalSection(&g_pl);
|
||||
create_swapchain();
|
||||
LeaveCriticalSection(&g_pl);
|
||||
rt_log("gfx: window %dx%d, swapchain %ux%u format %d", 1920, 1080, g_sc_ext.width, g_sc_ext.height, (int)g_sc_fmt);
|
||||
RECT rc = {0};
|
||||
GetClientRect(g_hwnd, &rc);
|
||||
rt_log("gfx: window %ldx%ld, swapchain %ux%u format %d", rc.right, rc.bottom, g_sc_ext.width, g_sc_ext.height,
|
||||
(int)g_sc_fmt);
|
||||
}
|
||||
LeaveCriticalSection(&g_start_lock);
|
||||
vsync_ensure();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include "gfx.h"
|
||||
#include "input.h"
|
||||
#include "ui/menu.h"
|
||||
#include "vk.h"
|
||||
|
||||
#define SRC_W 640
|
||||
@@ -162,6 +163,7 @@ int probe_window(void) {
|
||||
SendMessageW(hw, WM_ACTIVATEAPP, FALSE, 0);
|
||||
SendMessageW(hw, WM_ACTIVATEAPP, TRUE, 0);
|
||||
int back = input_cursor_released();
|
||||
if (menu_is_open()) menu_toggle(); // Esc opened the menu: the presents below compare the bare game image
|
||||
if (!esc || click || client || !caption || back) {
|
||||
printf("probe-window: released esc=%d click=%d client=%d caption=%d reactivated=%d\n", esc, click, client, caption, back);
|
||||
return fail("cursor release");
|
||||
|
||||
@@ -222,9 +222,13 @@ void rt_patches_init(void); // after ldr_load: sw
|
||||
int rt_patch_set(const char *name); // index of a set of generated patches.h, -1 if absent
|
||||
int rt_patch_enabled(int set); // the set is on (0 for -1)
|
||||
void rt_patch_disable(int set); // before the guest starts: a set needs another that is off
|
||||
void rt_patch_switch(int set, int on); // at run time (live settings): each site takes the new code
|
||||
// the next time it runs
|
||||
void *rt_patch_page(void); // the page the patched code reads (NULL without the table)
|
||||
void frame_step_init(void); // after rt_patches_init: the real-time step's first value
|
||||
int frame_step_realtime(void); // the real-time step is on: presents ignore the interval
|
||||
int frame_step_cap_ticks(void); // with the real-time step: 60 Hz ticks per frame at most
|
||||
// (1 = 60 fps, 2 = 30 fps; TOTK_FPS60, live)
|
||||
void frame_step_present(uint64_t display_ns, int interval); // nvnQueuePresentTexture: the frame's display time and
|
||||
// present interval (60 Hz ticks)
|
||||
// ---- boot (boot.c T6, main.c T1)
|
||||
|
||||
+14
-1
@@ -13,6 +13,14 @@ void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_
|
||||
// reports nothing; input_block(0) when it closes: nothing until all buttons and stick directions are released.
|
||||
void input_poll_ui(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
|
||||
void input_block(int on);
|
||||
// The in-game menu (ui/menu.h): input_menu(1) when it opens (input_poll reports nothing, the cursor is released), (0) when
|
||||
// it closes (nothing until every button and stick direction is released). Independent of input_block.
|
||||
void input_menu(int open);
|
||||
// The gamepad alone, for the menu: Switch button bits and the left stick (up +y). 0 without a connected gamepad.
|
||||
// Minus+Plus combo and the neutral pad while the menu is open (input_map.c, window-system free): *held is the caller's memory
|
||||
// of the combo, sticks are lx, ly, rx, ry. Returns 1 in the poll where the combo goes down (toggle the menu once).
|
||||
int input_menu_gate(int *held, int menu_open, uint64_t *buttons, int32_t sticks[4]);
|
||||
int input_pad_read(uint64_t *buttons, int32_t *lx, int32_t *ly);
|
||||
|
||||
// Mouse camera and cursor (input_win.c, Win32 window thread). The window procedure calls input_window_msg first for raw
|
||||
// mouse input, cursor hiding and confinement; it returns 1 with *res set when the message is handled. input_cursor_suspend(1)
|
||||
@@ -20,6 +28,9 @@ void input_block(int on);
|
||||
#ifdef _WIN32
|
||||
int input_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res);
|
||||
int input_cursor_released(void); // Esc or a non-client activation released the cursor (probe)
|
||||
// The menu's Win32 adapter (ui/menu_win.cpp), called next: F1 / Esc open or close the menu; while it is open, keys,
|
||||
// mouse and focus go to it. Returns 1 with *res set when the message is fully handled.
|
||||
int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res);
|
||||
#endif
|
||||
void input_cursor_suspend(int on);
|
||||
|
||||
@@ -31,9 +42,11 @@ uint16_t rumble_motor(float a, float curve, float strength);
|
||||
// TOTK_RUMBLE_TRIGGERS=1: input_rumble also drives the impulse triggers (Xbox) with the high motor's value.
|
||||
int input_rumble_triggers_enabled(void);
|
||||
|
||||
// Motion (TOTK_MOTION=0 turns it off). input_motion_start starts the sensor thread once: every 4 ms it reads the
|
||||
// Motion (TOTK_MOTION=0 turns it off, live). input_motion_start starts the sensor thread once: every 4 ms it reads the
|
||||
// gamepad's gyro and accelerometer (when it has them) and feeds motion_global(). Callable from any thread.
|
||||
void input_motion_start(void);
|
||||
// TOTK_MOTION is not "0" (a live setting: read again when cfg_version changes). Off: the sensor reads at rest.
|
||||
int input_motion_enabled(void);
|
||||
// SDL sensor values (accelerometer m/s^2, gyro rad/s, SDL gamepad axes) to the Switch controller frame motion_feed
|
||||
// takes (acceleration in G as gravity reads, rotation rad/s). The mapping is documented in input_win.c.
|
||||
void input_motion_axes(const float sdl_acc[3], const float sdl_gyro[3], double acc_g[3], double gyro[3]);
|
||||
|
||||
@@ -159,3 +159,25 @@ void input_mouse_stick(int32_t dx, int32_t dy, double dt_s, float sens, int32_t
|
||||
out[0] = (int32_t)lrint(x);
|
||||
out[1] = (int32_t)lrint(y);
|
||||
}
|
||||
|
||||
// Minus and Plus held together open or close the menu. *held: latched from the poll where both go down until neither is
|
||||
// down (the caller keeps it). Every poll of the latch reports neither to the game, so releasing one button first does not
|
||||
// leak the other; Minus alone before Plus reaches the game unchanged. With the menu open the game sees a neutral pad.
|
||||
// Returns 1 in the poll where both go down: the caller toggles the menu once.
|
||||
int input_menu_gate(int *held, int menu_open, uint64_t *buttons, int32_t sticks[4]) {
|
||||
const uint64_t combo = 1ull << B_MINUS | 1ull << B_PLUS;
|
||||
uint64_t raw = *buttons & combo;
|
||||
int edge = 0;
|
||||
if (*held) {
|
||||
*held = raw != 0;
|
||||
} else if (raw == combo) {
|
||||
*held = 1;
|
||||
edge = 1;
|
||||
}
|
||||
if (*held) *buttons &= ~combo;
|
||||
if (menu_open) {
|
||||
*buttons = 0;
|
||||
sticks[0] = sticks[1] = sticks[2] = sticks[3] = 0;
|
||||
}
|
||||
return edge;
|
||||
}
|
||||
+102
-42
@@ -16,6 +16,7 @@
|
||||
#include "input.h"
|
||||
#include "input_map.h"
|
||||
#include "nvn_api.h"
|
||||
#include "ui/menu.h"
|
||||
#include "vk.h"
|
||||
|
||||
enum { STICK_MAX = 32767, STICK_DEAD = 2500, STICK_DIR = 16384, TRIGGER_ON = 16384, RESCAN_MS = 1000 };
|
||||
@@ -133,7 +134,7 @@ static void rec_flush_all(void) {
|
||||
|
||||
static void rec_apply(uint64_t b, const int32_t sl[2], const int32_t sr[2]) {
|
||||
if (!rec_state) {
|
||||
const char *path = cfg_get("TOTK_INPUT_RECORD");
|
||||
const char *path = cfg_get("TOTK_INPUT_RECORD"); // no default: not recording when unset
|
||||
rec = path && *path ? fopen(path, "w") : NULL;
|
||||
rec_state = rec ? 1 : -1;
|
||||
if (path && *path && !rec) rt_log("input: cannot open TOTK_INPUT_RECORD %s", path);
|
||||
@@ -190,29 +191,41 @@ static int key_vk(int key) {
|
||||
static volatile LONG mouse_dx, mouse_dy; // raw counts since the last frame sample
|
||||
static volatile LONG cur_captured; // cursor hidden and confined to the client area
|
||||
static volatile LONG cur_active; // WM_ACTIVATEAPP: the window's application is active
|
||||
static volatile LONG cur_released; // Esc, or activation by a click on the title bar or border: until a client click
|
||||
// Bits: CUR_REL, Esc or activation by a click on the title bar or border: until a client click; CUR_ESC, set with CUR_REL
|
||||
// by Esc (not when it was already set): closing the menu gives the capture back. One word, changed by one CAS.
|
||||
enum { CUR_REL = 1, CUR_ESC = 2 };
|
||||
static volatile LONG cur_rel;
|
||||
static void cur_rel_update(LONG (*f)(LONG)) {
|
||||
LONG o, n;
|
||||
do { o = cur_rel; n = f(o); } while (n != o && InterlockedCompareExchange(&cur_rel, n, o) != o);
|
||||
}
|
||||
static LONG rel_esc(LONG o) { return o & CUR_REL ? o : CUR_REL | CUR_ESC; }
|
||||
static LONG rel_title(LONG o) { (void)o; return CUR_REL; }
|
||||
static LONG rel_clear(LONG o) { (void)o; return 0; }
|
||||
static LONG rel_menu_closed(LONG o) { return o & CUR_ESC ? 0 : o; }
|
||||
static volatile LONG cur_suspend; // F11 or a modal size or move loop under way
|
||||
static SRWLOCK cur_lock = SRWLOCK_INIT; // serialises cursor_update (window thread, input_block callers)
|
||||
static volatile LONG g_block; // text entry state, see input_block
|
||||
static float mouse_sens = -1; // TOTK_MOUSE_SENS, 0 = mouse camera off, read once
|
||||
static volatile LONG g_menu; // in-game menu state, see input_menu
|
||||
static float mouse_sens = -1; // TOTK_MOUSE_SENS, 0 = mouse camera off; live (cfg_version)
|
||||
static unsigned mouse_sens_seen;
|
||||
|
||||
static float mouse_sens_get(void) {
|
||||
if (mouse_sens >= 0) return mouse_sens;
|
||||
const char *e = cfg_get("TOTK_MOUSE_SENS");
|
||||
char *end;
|
||||
double v = e ? strtod(e, &end) : 1;
|
||||
if (!e || end == e || *end || v != v) v = 1;
|
||||
unsigned ver = cfg_version();
|
||||
if (mouse_sens >= 0 && ver == mouse_sens_seen) return mouse_sens;
|
||||
mouse_sens_seen = ver;
|
||||
double v = cfg_double("TOTK_MOUSE_SENS");
|
||||
mouse_sens = (float)(v < 0 ? 0 : v > 10 ? 10 : v);
|
||||
return mouse_sens;
|
||||
}
|
||||
|
||||
// Hide the cursor and confine it to the client area while the window is focused, not suspended, not behind a text entry
|
||||
// and the mouse camera is on; release it otherwise. Safe from any thread.
|
||||
// or the menu, and the mouse camera is on; release it otherwise. Safe from any thread.
|
||||
static void cursor_update(HWND h) {
|
||||
const char *in = cfg_get("TOTK_INPUT");
|
||||
AcquireSRWLockExclusive(&cur_lock);
|
||||
int want = h && cur_active && !cur_released && !cur_suspend && g_block != 1 && mouse_sens_get() > 0 && !(in && !strcmp(in, "none")) &&
|
||||
GetForegroundWindow() == h && !IsIconic(h);
|
||||
int want = h && cur_active && !(cur_rel & CUR_REL) && !cur_suspend && g_block != 1 && g_menu != 1 && mouse_sens_get() > 0 &&
|
||||
!(in && !strcmp(in, "none")) && GetForegroundWindow() == h && !IsIconic(h);
|
||||
RECT r;
|
||||
POINT tl = {0, 0};
|
||||
if (want && GetClientRect(h, &r) && ClientToScreen(h, &tl)) {
|
||||
@@ -227,7 +240,7 @@ static void cursor_update(HWND h) {
|
||||
ReleaseSRWLockExclusive(&cur_lock);
|
||||
}
|
||||
|
||||
int input_cursor_released(void) { return cur_released != 0; }
|
||||
int input_cursor_released(void) { return (cur_rel & CUR_REL) != 0; }
|
||||
|
||||
void input_cursor_suspend(int on) {
|
||||
InterlockedExchange(&cur_suspend, on != 0);
|
||||
@@ -255,17 +268,17 @@ int input_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) {
|
||||
case WM_SETCURSOR:
|
||||
if (cur_captured && LOWORD(l) == HTCLIENT) { SetCursor(NULL); *res = TRUE; return 1; }
|
||||
break;
|
||||
case WM_KEYDOWN: // Esc is unbound in the game layout, so it only releases the cursor
|
||||
if (w == VK_ESCAPE) { InterlockedExchange(&cur_released, 1); cursor_update(h); }
|
||||
case WM_KEYDOWN: // Esc is unbound in the game layout: it releases the cursor and opens the menu (menu_window_msg)
|
||||
if (w == VK_ESCAPE && !(cur_rel & CUR_REL)) { cur_rel_update(rel_esc); cursor_update(h); }
|
||||
break;
|
||||
case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: // client area only; poll_merged drops the click
|
||||
if (cur_released) { InterlockedExchange(&cur_released, 0); cursor_update(h); }
|
||||
if (cur_rel & CUR_REL) { cur_rel_update(rel_clear); cursor_update(h); }
|
||||
break;
|
||||
case WM_MOUSEACTIVATE: // sent before WM_ACTIVATEAPP: a title bar or border click must not capture
|
||||
if (LOWORD(l) != HTCLIENT) InterlockedExchange(&cur_released, 1);
|
||||
if (LOWORD(l) != HTCLIENT) cur_rel_update(rel_title);
|
||||
break;
|
||||
case WM_ACTIVATEAPP:
|
||||
if (!w) InterlockedExchange(&cur_released, 0); // Alt+Tab back in captures again
|
||||
if (!w) cur_rel_update(rel_clear); // Alt+Tab back in captures again
|
||||
InterlockedExchange(&cur_active, w != 0);
|
||||
cursor_update(h);
|
||||
break;
|
||||
@@ -362,27 +375,30 @@ static void pick(int32_t *x, int32_t *y, int32_t kx, int32_t ky) {
|
||||
if (b > a) { *x = kx; *y = ky; }
|
||||
}
|
||||
|
||||
// Under lock, state 1: the open gamepad's buttons (Switch bits after the TOTK_BIND_* layout) and sticks; 0 without a
|
||||
// connected gamepad.
|
||||
static int pad_read(uint64_t *b, int32_t sl[2], int32_t sr[2]) {
|
||||
if ((!pad || !SDL_GamepadConnected(pad)) && GetTickCount64() >= next_scan) { next_scan = GetTickCount64() + RESCAN_MS; scan_pads(); }
|
||||
SDL_UpdateGamepads();
|
||||
if (!pad || !SDL_GamepadConnected(pad)) return 0;
|
||||
uint8_t pd[PAD_COUNT] = {0};
|
||||
for (int p = PAD_SOUTH; p < PAD_ZL; p++) pd[p] = SDL_GetGamepadButton(pad, pad_sdl[p]);
|
||||
pd[PAD_ZL] = SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER) > TRIGGER_ON;
|
||||
pd[PAD_ZR] = SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) > TRIGGER_ON;
|
||||
*b |= input_map_pad_buttons(pd);
|
||||
sl[0] = axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX));
|
||||
sl[1] = -axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY));
|
||||
sr[0] = axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX));
|
||||
sr[1] = -axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY));
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
|
||||
uint64_t b = 0;
|
||||
int32_t sl[2] = {0, 0}, sr[2] = {0, 0};
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
if (!state) start();
|
||||
if (state > 0) {
|
||||
if (state == 1) {
|
||||
if ((!pad || !SDL_GamepadConnected(pad)) && GetTickCount64() >= next_scan) { next_scan = GetTickCount64() + RESCAN_MS; scan_pads(); }
|
||||
SDL_UpdateGamepads();
|
||||
if (pad && SDL_GamepadConnected(pad)) {
|
||||
uint8_t pd[PAD_COUNT] = {0};
|
||||
for (int p = PAD_SOUTH; p < PAD_ZL; p++) pd[p] = SDL_GetGamepadButton(pad, pad_sdl[p]);
|
||||
pd[PAD_ZL] = SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER) > TRIGGER_ON;
|
||||
pd[PAD_ZR] = SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) > TRIGGER_ON;
|
||||
b |= input_map_pad_buttons(pd);
|
||||
sl[0] = axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX));
|
||||
sl[1] = -axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY));
|
||||
sr[0] = axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX));
|
||||
sr[1] = -axis(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY));
|
||||
}
|
||||
}
|
||||
HWND w = gfx_window_handle();
|
||||
if (w && w == GetForegroundWindow()) {
|
||||
uint8_t down[KEY_COUNT] = {0};
|
||||
@@ -412,7 +428,13 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
|
||||
}
|
||||
script_apply(&b, sl, sr);
|
||||
rec_apply(b, sl, sr);
|
||||
// Minus and Plus held together (gamepad or keys) open or close the menu and never reach the game
|
||||
static int combo_held;
|
||||
int32_t st[4] = {sl[0], sl[1], sr[0], sr[1]};
|
||||
int toggle = input_menu_gate(&combo_held, menu_is_open(), &b, st);
|
||||
sl[0] = st[0], sl[1] = st[1], sr[0] = st[2], sr[1] = st[3];
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
if (toggle) menu_toggle();
|
||||
stick_bits(&b, sl[0], sl[1], B_SL_LEFT);
|
||||
stick_bits(&b, sr[0], sr[1], B_SR_LEFT);
|
||||
*buttons = b; *lx = sl[0]; *ly = sl[1]; *rx = sr[0]; *ry = sr[1];
|
||||
@@ -426,10 +448,24 @@ void input_block(int on) {
|
||||
cursor_update(gfx_window_handle());
|
||||
}
|
||||
|
||||
// The in-game menu (ui/menu.cpp) blocks the game's input the same way: g_menu 0 closed, 1 open, 2 closed, waiting for
|
||||
// the release. The cursor is released while it is open, for the menu's mouse.
|
||||
void input_menu(int open) {
|
||||
InterlockedExchange(&g_menu, open ? 1 : 2);
|
||||
if (!open) cur_rel_update(rel_menu_closed); // the capture before Esc comes back
|
||||
cursor_update(gfx_window_handle());
|
||||
}
|
||||
|
||||
// 1 while flag (g_block, g_menu) blocks the game's input; state 2 ends at the first poll with nothing held.
|
||||
static int blocked(volatile LONG *flag, uint64_t buttons) {
|
||||
LONG k = *flag;
|
||||
return k && !(k == 2 && !buttons && InterlockedCompareExchange(flag, 0, 2) == 2);
|
||||
}
|
||||
|
||||
void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
|
||||
poll_merged(buttons, lx, ly, rx, ry);
|
||||
LONG k = g_block;
|
||||
if (!k || (k == 2 && !*buttons && InterlockedCompareExchange(&g_block, 0, 2) == 2)) return;
|
||||
int text = blocked(&g_block, *buttons), menu = blocked(&g_menu, *buttons);
|
||||
if (!text && !menu) return;
|
||||
*buttons = 0; *lx = *ly = *rx = *ry = 0;
|
||||
}
|
||||
|
||||
@@ -437,6 +473,19 @@ void input_poll_ui(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int
|
||||
poll_merged(buttons, lx, ly, rx, ry);
|
||||
}
|
||||
|
||||
int input_pad_read(uint64_t *buttons, int32_t *lx, int32_t *ly) {
|
||||
uint64_t b = 0;
|
||||
int32_t sl[2] = {0, 0}, sr[2] = {0, 0};
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
if (!state) start();
|
||||
int ok = state == 1 && pad_read(&b, sl, sr);
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
*buttons = b;
|
||||
*lx = sl[0];
|
||||
*ly = sl[1];
|
||||
return ok;
|
||||
}
|
||||
|
||||
uint16_t rumble_motor(float a, float curve, float strength) {
|
||||
if (!(a > 0) || !(strength > 0)) return 0;
|
||||
float v = powf(a > 1 ? 1 : a, curve) * strength * 65535.0f + 0.5f;
|
||||
@@ -444,14 +493,14 @@ uint16_t rumble_motor(float a, float curve, float strength) {
|
||||
}
|
||||
|
||||
int input_rumble_triggers_enabled(void) {
|
||||
const char *e = cfg_get("TOTK_RUMBLE_TRIGGERS");
|
||||
return e && !strcmp(e, "1");
|
||||
return cfg_bool("TOTK_RUMBLE_TRIGGERS");
|
||||
}
|
||||
|
||||
int input_rumble(uint16_t low, uint16_t high, uint32_t ms) {
|
||||
int ok = 0;
|
||||
static int triggers = -1;
|
||||
if (triggers < 0) triggers = input_rumble_triggers_enabled();
|
||||
static unsigned seen;
|
||||
if (triggers < 0 || seen != cfg_version()) seen = cfg_version(), triggers = input_rumble_triggers_enabled();
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
if (state == 1 && pad && pad_rumble) {
|
||||
ok = SDL_RumbleGamepad(pad, low, high, ms);
|
||||
@@ -495,8 +544,20 @@ static int sensors_ready(void) {
|
||||
return sensor_ok;
|
||||
}
|
||||
|
||||
int input_motion_enabled(void) {
|
||||
static int on = -1;
|
||||
static unsigned seen;
|
||||
unsigned v = cfg_version();
|
||||
if (on < 0 || v != seen) {
|
||||
seen = v;
|
||||
on = cfg_bool("TOTK_MOTION");
|
||||
}
|
||||
return on;
|
||||
}
|
||||
|
||||
// 250 Hz: the gamepads update (reports read, rumble expiry) and the newest gyro and accelerometer sample goes into the
|
||||
// fusion. Without a gamepad with sensors nothing is fed and the six-axis sensor reads at rest.
|
||||
// fusion. Without a gamepad with sensors, or with motion off (TOTK_MOTION=0, live), nothing is fed and the six-axis
|
||||
// sensor reads at rest.
|
||||
static DWORD WINAPI motion_main(void *arg) {
|
||||
(void)arg;
|
||||
HANDLE timer = CreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
|
||||
@@ -515,7 +576,7 @@ static DWORD WINAPI motion_main(void *arg) {
|
||||
SDL_GetGamepadSensorData(pad, SDL_SENSOR_GYRO, g, 3);
|
||||
}
|
||||
ReleaseSRWLockExclusive(&lock);
|
||||
if (!have) continue;
|
||||
if (!have || !input_motion_enabled()) continue;
|
||||
double acc[3], gyro[3];
|
||||
input_motion_axes(a, g, acc, gyro);
|
||||
motion_feed(motion_global(), acc, gyro, kern_now_ns());
|
||||
@@ -527,9 +588,8 @@ void input_motion_start(void) {
|
||||
AcquireSRWLockExclusive(&lock);
|
||||
if (!state) start();
|
||||
if (!motion_thread) {
|
||||
const char *e = cfg_get("TOTK_MOTION");
|
||||
if (e && !strcmp(e, "0")) { motion_thread = -1; rt_log("input: motion off (TOTK_MOTION=0)"); }
|
||||
else if (state != 1) motion_thread = -1;
|
||||
if (!input_motion_enabled()) rt_log("input: motion off (TOTK_MOTION=0); it can be turned on while the game runs");
|
||||
if (state != 1) motion_thread = -1;
|
||||
else {
|
||||
HANDLE h = CreateThread(NULL, 0, motion_main, NULL, 0, NULL);
|
||||
if (!h) rt_fatal("input: motion thread CreateThread failed (error %lu)", GetLastError());
|
||||
|
||||
+4
-4
@@ -266,7 +266,7 @@ static void ap_init(void);
|
||||
|
||||
static int cores_enabled(void) {
|
||||
if (g_cores_on < 0) {
|
||||
g_cores_on = cfg_get("TOTK_FREE_CORES") ? 0 : 1;
|
||||
g_cores_on = !cfg_bool("TOTK_FREE_CORES"); // "0" keeps the gate, like unset
|
||||
diag_init();
|
||||
ap_init();
|
||||
}
|
||||
@@ -307,9 +307,9 @@ void kern_ap_stub(void);
|
||||
|
||||
static void ap_init(void) {
|
||||
if (g_ap >= 0) return;
|
||||
const char *e = cfg_get("TOTK_ASYNC_PREEMPT");
|
||||
g_ap = !(e && !strcmp(e, "0"));
|
||||
g_ap_int = g_ap && !(e && !strcmp(e, "2"));
|
||||
const char *e = cfg_value("TOTK_ASYNC_PREEMPT");
|
||||
g_ap = strcmp(e, "0") != 0;
|
||||
g_ap_int = g_ap && strcmp(e, "2") != 0;
|
||||
if (g_ap) {
|
||||
RtModule m[16];
|
||||
int n = rt_linked_modules(m, 16);
|
||||
|
||||
@@ -417,7 +417,7 @@ static void test_cores(Cpu *c) {
|
||||
int now, held_max;
|
||||
kern_core_stats(&now, &held_max);
|
||||
DWORD cpus = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
|
||||
int gate = cfg_get("TOTK_FREE_CORES") == NULL; // the kernel's own switch
|
||||
int gate = !cfg_bool("TOTK_FREE_CORES"); // the kernel's own switch
|
||||
int ok = g_run_max <= 3 && held_max <= 3 && !g_core_clash && (cpus < 4 || g_run_max == 3);
|
||||
printf("virtual cores: %d threads x %d runs on %lu host CPUs: at most %ld running guest code at once, at most %d "
|
||||
"core holders (kernel count), %ld core-number clashes: %s\n", CORE_WORKERS, CORE_RUNS, cpus, g_run_max,
|
||||
|
||||
+2
-3
@@ -47,7 +47,7 @@ void rt_log(const char *fmt, ...) {
|
||||
}
|
||||
|
||||
static void parse_trace(void) {
|
||||
const char *e = cfg_get("TOTK_TRACE");
|
||||
const char *e = cfg_get("TOTK_TRACE"); // no default: nothing is traced when unset
|
||||
if (!e) return;
|
||||
static const struct { const char *name; unsigned bit; } names[] = {
|
||||
{"svc", RT_TRACE_SVC}, {"host", RT_TRACE_HOSTCALL}, {"ipc", RT_TRACE_IPC}, {"fs", RT_TRACE_FS},
|
||||
@@ -433,8 +433,7 @@ int main(int argc, char **argv) {
|
||||
prof_start();
|
||||
// Timed guest waits (kernel.c block_inner) sleep in whole milliseconds; at the default 15.6 ms tick a 1 ms wait
|
||||
// costs a full tick. TOTK_TIMER_1MS=0 keeps the default for comparison.
|
||||
const char *tick = cfg_get("TOTK_TIMER_1MS");
|
||||
if (!tick || strcmp(tick, "0")) timeBeginPeriod(1);
|
||||
if (cfg_bool("TOTK_TIMER_1MS")) timeBeginPeriod(1);
|
||||
cfg = (RtConfig){.exefs = rt_default_exefs, .romfs = rt_default_romfs, .profile = rt_default_profile,
|
||||
.gpu = cfg_get("TOTK_GPU")};
|
||||
portable_paths(&cfg); // command-line paths below still win
|
||||
|
||||
@@ -605,8 +605,7 @@ static void obs_release_read(Cpu *c) {
|
||||
if (lr != 0x70008c70c8ull) return;
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *e = cfg_get("TOTK_LOD_GUARD");
|
||||
on = !(e && !strcmp(e, "0"));
|
||||
on = cfg_bool("TOTK_LOD_GUARD");
|
||||
}
|
||||
if (!on || *(volatile uint8_t *)(uintptr_t)(obj + 0x528) != *(volatile uint8_t *)(uintptr_t)(obj + 0x529)) return;
|
||||
uint64_t e = __atomic_load_n(&lod_entered, __ATOMIC_SEQ_CST);
|
||||
|
||||
@@ -633,10 +633,12 @@ NVN_API(nvnWindowSetCrop) {
|
||||
// ---------- Present pacing
|
||||
// The vsync thread ticks at a fixed 60 Hz whatever the monitor does, so one game frame lasts `interval` ticks. With
|
||||
// the real-time frame step (frame_rate.c) game speed does not depend on the interval, so a frame is shown when it is
|
||||
// ready, at most VSYNC_HZ per second: holding it to the 2nd or 3rd tick would only add latency and 50 ms frames.
|
||||
// ready, at most at the frame limit (60 or 30 per second): holding it to the 2nd or 3rd tick would only add latency
|
||||
// and 50 ms frames.
|
||||
#define VSYNC_HZ 60ull
|
||||
static uint64_t present_period(const win_t *o) {
|
||||
uint64_t ticks = o->interval > 0 && !frame_step_realtime() ? (uint64_t)o->interval : 1ull;
|
||||
uint64_t ticks = frame_step_realtime() ? (uint64_t)frame_step_cap_ticks()
|
||||
: o->interval > 0 ? (uint64_t)o->interval : 1ull;
|
||||
return ticks * 1000000000ull / VSYNC_HZ;
|
||||
}
|
||||
|
||||
|
||||
+18
-15
@@ -5,7 +5,7 @@
|
||||
// TOTK_OPERATION_MODE=handheld it is the handheld controller (id 0x20, style bit 1) and player 1 is not connected,
|
||||
// which is the controller the game reads in that mode. Mouse and keyboard report no input. The controller has two
|
||||
// vibration devices (left, right) played on the gamepad's motors (TOTK_RUMBLE=0: none) and a six-axis sensor fed by
|
||||
// the gamepad's gyro and accelerometer (TOTK_MOTION=0: none). State layouts follow libnx HID.
|
||||
// the gamepad's gyro and accelerometer (TOTK_MOTION=0, live: reads at rest). State layouts follow libnx HID.
|
||||
#include <windows.h>
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
@@ -189,21 +189,22 @@ static void once(volatile long *flag, const char *fmt, uint32_t v) {
|
||||
// TOTK_RUMBLE_STRENGTH (percent, 0..300, default 130; 0 = off) and TOTK_RUMBLE_CURVE (exponent on the amplitude, 0.2..1.5,
|
||||
// default 0.6). HD rumble is strong at low amplitude, an ERM motor hardly turns there, so weak values are lifted by the
|
||||
// curve (0.1 -> 0.25) and the strength scales the result (saturating at 65535; 0.66 and up reach full drive at 130 %).
|
||||
// Both are live settings (the menu): read again whenever cfg_version changes.
|
||||
static float rumble_strength = 1.3f, rumble_curve = 0.6f;
|
||||
static volatile long rumble_cfg_done;
|
||||
static float cfg_float(const char *name, float def, float lo, float hi) {
|
||||
const char *e = cfg_get(name);
|
||||
char *end;
|
||||
double v = e ? strtod(e, &end) : 0;
|
||||
if (!e || end == e || *end || v != v) return def;
|
||||
static volatile long rumble_cfg_logged;
|
||||
static unsigned rumble_cfg_seen = ~0u;
|
||||
static float cfg_float(const char *name, float lo, float hi) {
|
||||
double v = cfg_double(name);
|
||||
return (float)(v < lo ? lo : v > hi ? hi : v);
|
||||
}
|
||||
static void rumble_cfg(void) {
|
||||
if (rumble_cfg_done) return;
|
||||
rumble_strength = cfg_float("TOTK_RUMBLE_STRENGTH", 130, 0, 300) / 100;
|
||||
rumble_curve = cfg_float("TOTK_RUMBLE_CURVE", 0.6f, 0.2f, 1.5f);
|
||||
unsigned v = cfg_version();
|
||||
if (v == rumble_cfg_seen) return;
|
||||
rumble_cfg_seen = v;
|
||||
rumble_strength = cfg_float("TOTK_RUMBLE_STRENGTH", 0, 300) / 100;
|
||||
rumble_curve = cfg_float("TOTK_RUMBLE_CURVE", 0.2f, 1.5f);
|
||||
int trig = input_rumble_triggers_enabled();
|
||||
if (!InterlockedExchange(&rumble_cfg_done, 1))
|
||||
if (!InterlockedExchange(&rumble_cfg_logged, 1))
|
||||
rt_log("hid: rumble strength %.0f%%, curve %.2f, triggers %s", rumble_strength * 100, rumble_curve, trig ? "on" : "off");
|
||||
}
|
||||
static uint16_t motor(float a) { return rumble_motor(a, rumble_curve, rumble_strength); }
|
||||
@@ -228,7 +229,8 @@ static void ov_vibration_handles(Cpu *c) {
|
||||
rt_fatal("nn::hid::GetVibrationDeviceHandles: invalid arguments (count %d, styles %#x)", max, style);
|
||||
static volatile long asked;
|
||||
rumble_cfg();
|
||||
if (env_zero("TOTK_RUMBLE") || rumble_strength == 0) { once(&asked, "hid: no vibration devices (TOTK_RUMBLE=%u)", 0); ret_x(c, 0); return; }
|
||||
// strength 0 keeps the devices (silent), so the menu can turn rumble up again
|
||||
if (env_zero("TOTK_RUMBLE")) { once(&asked, "hid: no vibration devices (TOTK_RUMBLE=%u)", 0); ret_x(c, 0); return; }
|
||||
static const struct { uint8_t bit, n; uint32_t base; } t[] = {
|
||||
{0, 2, 0x3}, {1, 2, 0x4}, {2, 2, 0x5}, {3, 1, 0x6}, {4, 1, 0x10007}, {5, 1, 0x8}, {10, 1, 0xd}, {8, 2, 0x4},
|
||||
{30, 2, 0x21}, {29, 2, 0x20}};
|
||||
@@ -243,14 +245,14 @@ static void ov_vibration_handles(Cpu *c) {
|
||||
}
|
||||
|
||||
// int GetSixAxisSensorHandles(SixAxisSensorHandle *out, int count, const NpadIdType &id, NpadStyleSet style):
|
||||
// utility::GetSixAxisSensorHandle's order (one sensor per style, two for the Joy-Con pair); none with TOTK_MOTION=0.
|
||||
// utility::GetSixAxisSensorHandle's order (one sensor per style, two for the Joy-Con pair). Also with TOTK_MOTION=0: the
|
||||
// sensor then reads at rest (six_fill), so the menu can turn motion on while the game runs.
|
||||
static void ov_six_axis_handles(Cpu *c) {
|
||||
uint32_t *out = arg_p(c, 0), style = (uint32_t)arg_x(c, 3);
|
||||
int max = (int)arg_x(c, 1);
|
||||
uint32_t id = handle_id(c, "GetSixAxisSensorHandles");
|
||||
if (!out || max <= 0) rt_fatal("nn::hid::GetSixAxisSensorHandles: invalid arguments (count %d)", max);
|
||||
static volatile long asked;
|
||||
if (env_zero("TOTK_MOTION")) { once(&asked, "hid: no six-axis sensor (TOTK_MOTION=%u)", 0); ret_x(c, 0); return; }
|
||||
uint32_t base = 0, n = 1;
|
||||
if (style & 1) base = 0x20003;
|
||||
else if (style & 2) base = 0x20004;
|
||||
@@ -446,7 +448,8 @@ static void ov_six_stop(Cpu *c) {
|
||||
static int six_fill(MotionState *s, int max, const uint32_t *h, const char *fn) {
|
||||
if (max <= 0) return 0;
|
||||
if (!s) rt_fatal("nn::hid::detail::%s: null output", fn);
|
||||
int n = six_axis_ours(h, fn) && six_running ? motion_read(motion_global(), s, max, kern_now_ns()) : 0;
|
||||
int live = six_axis_ours(h, fn) && six_running && input_motion_enabled();
|
||||
int n = live ? motion_read(motion_global(), s, max, kern_now_ns()) : 0;
|
||||
if (!n) {
|
||||
static const MotionState rest = {.acc = {0, 0, -1}, .dir = {1, 0, 0, 0, 1, 0, 0, 0, 1}};
|
||||
for (int i = 0; i < max; i++) s[i] = rest;
|
||||
|
||||
+79
-4
@@ -20,6 +20,7 @@
|
||||
#include "input.h"
|
||||
#include "kernel.h"
|
||||
#include "ov.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui_text.h"
|
||||
|
||||
#define CHILD_ENV "TOTK_PROBE_SERVICES_CHILD"
|
||||
@@ -484,10 +485,12 @@ static void probe_feedback(uint32_t pid, uint32_t style) {
|
||||
char *keep_m = cfg_get("TOTK_MOTION") ? _strdup(cfg_get("TOTK_MOTION")) : NULL;
|
||||
set_env("TOTK_RUMBLE", "0");
|
||||
set_env("TOTK_MOTION", "0");
|
||||
uint32_t none[2] = {0xdead, 0xdead};
|
||||
CHECK((int32_t)CALL("hid.GetVibrationDeviceHandles", U(none), 2, U(&pid), style) == 0 &&
|
||||
(int32_t)CALL("hid.GetSixAxisSensorHandles", U(none), 2, U(&pid), style) == 0 && none[0] == 0xdead,
|
||||
"TOTK_RUMBLE=0 / TOTK_MOTION=0 still report handles");
|
||||
uint32_t none[2] = {0xdead, 0xdead}, six_off[2] = {0};
|
||||
CHECK((int32_t)CALL("hid.GetVibrationDeviceHandles", U(none), 2, U(&pid), style) == 0 && none[0] == 0xdead,
|
||||
"TOTK_RUMBLE=0 still reports vibration handles");
|
||||
// TOTK_MOTION is live: the handle stays (the sensor reads at rest while it is 0)
|
||||
CHECK((int32_t)CALL("hid.GetSixAxisSensorHandles", U(six_off), 2, U(&pid), style) == 1 && six_off[0] == sh[0],
|
||||
"TOTK_MOTION=0 drops the six-axis handle %#x", six_off[0]);
|
||||
set_env("TOTK_RUMBLE", keep_r);
|
||||
set_env("TOTK_MOTION", keep_m);
|
||||
free(keep_r);
|
||||
@@ -730,6 +733,44 @@ static void probe_swkbd(void) {
|
||||
"minimum length, the Win32 window with OK and Cancel)\n", n - bad, n, def);
|
||||
}
|
||||
|
||||
// ---- the menu's input gate: Minus+Plus is consumed, a menu that is open leaves the game a neutral pad
|
||||
static void probe_menu_gate(void) {
|
||||
const uint64_t minus = 1ull << 11, plus = 1ull << 10, a = 1ull;
|
||||
int held = 0;
|
||||
int32_t st[4] = {100, -200, 300, -400};
|
||||
uint64_t b = minus | a; // Minus alone, a frame before Plus: reaches the guest unchanged
|
||||
int t1 = input_menu_gate(&held, 0, &b, st);
|
||||
CHECK(!t1 && b == (minus | a) && st[0] == 100 && st[3] == -400 && !held, "Minus alone changed: toggle %d buttons %#llx", t1,
|
||||
(unsigned long long)b);
|
||||
b = minus | plus | a; // both down: the guest sees neither, the menu toggles once
|
||||
int t2 = input_menu_gate(&held, 0, &b, st);
|
||||
CHECK(t2 == 1 && b == a && held, "Minus+Plus: toggle %d buttons %#llx", t2, (unsigned long long)b);
|
||||
b = minus | plus; // still held with the menu open: no second toggle, a neutral pad
|
||||
int t3 = input_menu_gate(&held, 1, &b, st);
|
||||
CHECK(!t3 && b == 0 && st[0] == 0 && st[1] == 0 && st[2] == 0 && st[3] == 0, "menu open: toggle %d buttons %#llx", t3,
|
||||
(unsigned long long)b);
|
||||
b = a | plus; st[0] = 5; // the menu is open and the pad is neutral whatever is pressed
|
||||
input_menu_gate(&held, 1, &b, st);
|
||||
CHECK(b == 0 && st[0] == 0, "an open menu left buttons %#llx", (unsigned long long)b);
|
||||
b = 0; // released, then pressed again toggles again
|
||||
input_menu_gate(&held, 0, &b, st);
|
||||
b = minus | plus;
|
||||
CHECK(input_menu_gate(&held, 0, &b, st) == 1, "the second hold did not toggle");
|
||||
// Plus released first while Minus is still down: Minus must not leak; a new Minus press after both are up passes
|
||||
held = 0;
|
||||
b = minus | plus;
|
||||
input_menu_gate(&held, 0, &b, st);
|
||||
b = minus;
|
||||
int t4 = input_menu_gate(&held, 0, &b, st);
|
||||
CHECK(!t4 && b == 0 && held, "Minus left down after Plus leaked: buttons %#llx", (unsigned long long)b);
|
||||
b = 0;
|
||||
input_menu_gate(&held, 0, &b, st);
|
||||
b = minus | a;
|
||||
int t5 = input_menu_gate(&held, 0, &b, st);
|
||||
CHECK(!t5 && b == (minus | a) && !held, "Minus after the release did not pass: buttons %#llx", (unsigned long long)b);
|
||||
printf("menu gate: Minus alone passes, Minus+Plus is consumed and toggles once per hold, an open menu gives a neutral pad\n");
|
||||
}
|
||||
|
||||
// ---- shared fonts: the extracted files when present (the missing case is a fatal child)
|
||||
static void probe_fonts(void) {
|
||||
char dir[MAX_PATH], path[MAX_PATH + 32];
|
||||
@@ -755,6 +796,38 @@ 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.
|
||||
static void probe_menu_text(void) {
|
||||
static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko"};
|
||||
for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) {
|
||||
CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id), "menu text id %d lacks en or ru", id);
|
||||
CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id), "menu text id %d is empty", id);
|
||||
}
|
||||
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
|
||||
CHECK(!strcmp(ui_text_in("ja", UI_MENU_CONTINUE), ui_text_in("en", UI_MENU_CONTINUE)), "ja menu text is not English");
|
||||
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 (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");
|
||||
// menu_text follows the setting live
|
||||
cfg_set("TOTK_MENU_LANG", "ru");
|
||||
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("ru", UI_MENU_CONTINUE), "menu_text ignores MENU_LANG=ru");
|
||||
cfg_set("TOTK_MENU_LANG", "en");
|
||||
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en");
|
||||
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");
|
||||
}
|
||||
|
||||
static void probe_main(Cpu *c) {
|
||||
gc = c;
|
||||
probe_oe();
|
||||
@@ -766,6 +839,8 @@ static void probe_main(Cpu *c) {
|
||||
probe_input();
|
||||
probe_media_gfx();
|
||||
probe_swkbd();
|
||||
probe_menu_text();
|
||||
probe_menu_gate();
|
||||
probe_fonts();
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -43,8 +43,8 @@ int ov_handheld(void) {
|
||||
static volatile LONG v = -1;
|
||||
LONG h = v;
|
||||
if (h < 0) {
|
||||
const char *e = cfg_get("TOTK_OPERATION_MODE");
|
||||
if (!e || !strcmp(e, "docked")) h = 0;
|
||||
const char *e = cfg_value("TOTK_OPERATION_MODE");
|
||||
if (!strcmp(e, "docked")) h = 0;
|
||||
else if (!strcmp(e, "handheld")) h = 1;
|
||||
else rt_fatal("TOTK_OPERATION_MODE must be docked or handheld, not '%s'", e);
|
||||
if (InterlockedCompareExchange(&v, h, -1) == -1)
|
||||
@@ -92,7 +92,7 @@ static const char *switch_language(const char *tag) {
|
||||
const char *ov_language(void) {
|
||||
static const char *const codes[] = {"ja", "en-US", "fr", "de", "it", "es", "zh-CN", "ko", "nl", "pt", "ru",
|
||||
"zh-TW", "en-GB", "fr-CA", "es-419", "zh-Hans", "zh-Hant", "pt-BR"};
|
||||
const char *code = cfg_get("TOTK_LANG");
|
||||
const char *code = cfg_get("TOTK_LANG"); // no fixed default: TOTK_LOCALE or the Windows user locale decides when unset
|
||||
if (code && *code) {
|
||||
for (size_t i = 0; i < sizeof codes / sizeof *codes; i++)
|
||||
if (!strcmp(code, codes[i])) return codes[i];
|
||||
|
||||
+9
-3
@@ -1,7 +1,8 @@
|
||||
// Code patch sets (recomp/patches.py, gen.py --patches). The generator lifts both the original and the replacement
|
||||
// instructions of every patched site, and rt_patch_on[set] picks one when the site runs, so a set is switched at start
|
||||
// without touching code. The sets, their environment switches and defaults, and the patch page come from the generated
|
||||
// patches.h; without it (C generated without --patches) there are no sets and every site runs the original.
|
||||
// without touching code, and also while the game runs (rt_patch_switch: the frame-limit setting of the menu). The sets,
|
||||
// their environment switches and defaults, and the patch page come from the generated patches.h; without it (C
|
||||
// generated without --patches) there are no sets and every site runs the original.
|
||||
//
|
||||
// The patch page is the first 4 KiB page after main's image, inside the module window memory.c reserved: replacement
|
||||
// code reaches it with one adrp, as MacNativeGames' data page after main (games/totk/runtime/game_patches.c). Its
|
||||
@@ -44,7 +45,8 @@ void rt_patches_init(void) {
|
||||
list[0] = 0;
|
||||
for (int i = 0; i < RT_PATCH_COUNT; i++) {
|
||||
const char *e = cfg_get(sets[i].env);
|
||||
rt_patch_on[i] = (uint8_t)(e && *e ? strcmp(e, "0") != 0 : sets[i].on);
|
||||
// a set with a row in the settings table takes its default from there; the generated default serves the rest
|
||||
rt_patch_on[i] = (uint8_t)(cfg_meta(sets[i].env) ? cfg_bool(sets[i].env) : e && *e ? strcmp(e, "0") != 0 : sets[i].on);
|
||||
n += (size_t)snprintf(list + n, sizeof list - n, "%s%s %s", i ? ", " : "", sets[i].name,
|
||||
rt_patch_on[i] ? "on" : "off");
|
||||
if (n >= sizeof list) n = sizeof list - 1;
|
||||
@@ -68,6 +70,10 @@ void rt_patch_disable(int set) {
|
||||
if (set >= 0 && set < RT_PATCH_COUNT) rt_patch_on[set] = 0;
|
||||
}
|
||||
|
||||
void rt_patch_switch(int set, int on) {
|
||||
if (set >= 0 && set < RT_PATCH_COUNT) __atomic_store_n(&rt_patch_on[set], (uint8_t)(on != 0), __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
void *rt_patch_page(void) {
|
||||
#if RT_PATCH_COUNT
|
||||
return page;
|
||||
|
||||
@@ -58,13 +58,20 @@ int plat_file_write_atomic(const char *path, const void *data, size_t n);
|
||||
int plat_file_flush(const char *path); // flushes a written file's data to the disk; 1 on success
|
||||
void plat_file_delete(const char *path);
|
||||
int plat_file_truncate(const char *path, uint64_t size); // 1 on success
|
||||
int64_t plat_file_size(const char *path); // bytes of a file, -1 when missing or unreadable
|
||||
int plat_file_set_readonly(const char *path, int on); // sets or clears the read-only attribute; 1 on success
|
||||
// Calls cb(name, ctx) for each file in dir whose name ends in ext (".in"); name has no directory part. cb returns 0 to
|
||||
// stop. Returns 0 when dir cannot be listed.
|
||||
int plat_file_list(const char *dir, const char *ext, int (*cb)(const char *name, void *ctx), void *ctx);
|
||||
int plat_exe_path(char *out, size_t cap); // path of the running executable; 0 on failure
|
||||
// Environment variable as UTF-8 into out; its length, or 0 when unset, empty or too long for cap.
|
||||
size_t plat_getenv(const char *name, char *out, size_t cap);
|
||||
// The user's UI language as a BCP-47 tag ("ru-RU", "en-US"); "" when the system gives none. Valid for the process.
|
||||
const char *plat_ui_language(void);
|
||||
uint32_t plat_thread_id(void); // id of the calling thread, for unique file names
|
||||
// A system font file with the glyphs of a catalog language ("ja", "ko", "zh-Hans", "zh-Hant"): the menu shows each
|
||||
// language's name in its own script. Copies the UTF-8 path into out; 0 when the system has none.
|
||||
int plat_font_path(const char *lang, char *out, size_t cap);
|
||||
|
||||
// ---- child processes: a program with stdin and stdout piped to us (stderr discarded), no console window.
|
||||
typedef struct PlatChild PlatChild;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#include "platform.h"
|
||||
@@ -236,6 +237,21 @@ int plat_file_truncate(const char *path, uint64_t size) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
int64_t plat_file_size(const char *path) {
|
||||
wchar_t w[WPATH];
|
||||
WIN32_FILE_ATTRIBUTE_DATA d;
|
||||
if (!widen(path, w, WPATH) || !GetFileAttributesExW(w, GetFileExInfoStandard, &d)) return -1;
|
||||
return (int64_t)(((uint64_t)d.nFileSizeHigh << 32) | d.nFileSizeLow);
|
||||
}
|
||||
|
||||
int plat_file_set_readonly(const char *path, int on) {
|
||||
wchar_t w[WPATH];
|
||||
if (!widen(path, w, WPATH)) return 0;
|
||||
DWORD a = GetFileAttributesW(w);
|
||||
if (a == INVALID_FILE_ATTRIBUTES) return 0;
|
||||
return SetFileAttributesW(w, on ? a | FILE_ATTRIBUTE_READONLY : a & ~(DWORD)FILE_ATTRIBUTE_READONLY) != 0;
|
||||
}
|
||||
|
||||
int plat_file_list(const char *dir, const char *ext, int (*cb)(const char *name, void *ctx), void *ctx) {
|
||||
wchar_t wd[WPATH], we[64], pat[WPATH + 64];
|
||||
if (!widen(dir, wd, WPATH) || !widen(ext, we, 64)) return 0;
|
||||
@@ -279,6 +295,41 @@ size_t plat_getenv(const char *name, char *out, size_t cap) {
|
||||
|
||||
uint32_t plat_thread_id(void) { return GetCurrentThreadId(); }
|
||||
|
||||
const char *plat_ui_language(void) {
|
||||
static char tag[LOCALE_NAME_MAX_LENGTH];
|
||||
static int done;
|
||||
if (!done) {
|
||||
wchar_t w[LOCALE_NAME_MAX_LENGTH];
|
||||
LCID lcid = GetUserDefaultUILanguage();
|
||||
int n = LCIDToLocaleName(lcid, w, LOCALE_NAME_MAX_LENGTH, 0);
|
||||
if (n <= 0 || !WideCharToMultiByte(CP_UTF8, 0, w, -1, tag, sizeof tag, NULL, NULL)) tag[0] = 0;
|
||||
done = 1;
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
int plat_font_path(const char *lang, char *out, size_t cap) {
|
||||
static const struct { const char *lang; const wchar_t *files[3]; } fonts[] = {
|
||||
{"ja", {L"YuGothM.ttc", L"meiryo.ttc", L"msgothic.ttc"}},
|
||||
{"ko", {L"malgun.ttf", L"gulim.ttc", NULL}},
|
||||
{"zh-Hans", {L"msyh.ttc", L"simsun.ttc", NULL}},
|
||||
{"zh-Hant", {L"msjh.ttc", L"mingliu.ttc", NULL}},
|
||||
};
|
||||
wchar_t dir[MAX_PATH], w[WPATH];
|
||||
UINT n = GetWindowsDirectoryW(dir, MAX_PATH);
|
||||
if (!n || n >= MAX_PATH) return 0;
|
||||
for (size_t i = 0; i < sizeof fonts / sizeof *fonts; i++) {
|
||||
if (strcmp(fonts[i].lang, lang)) continue;
|
||||
for (int k = 0; k < 3 && fonts[i].files[k]; k++) {
|
||||
swprintf(w, WPATH, L"%ls\\Fonts\\%ls", dir, fonts[i].files[k]);
|
||||
DWORD a = GetFileAttributesW(w);
|
||||
if (a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY))
|
||||
return WideCharToMultiByte(CP_UTF8, 0, w, -1, out, (int)cap, NULL, NULL) != 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- child processes
|
||||
|
||||
struct PlatChild {
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2025 Omar Cornut
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,222 @@
|
||||
// dear imgui: Renderer Backend for Vulkan
|
||||
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
|
||||
|
||||
// Implemented features:
|
||||
// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
|
||||
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
|
||||
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
|
||||
|
||||
// The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
|
||||
// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// Learn about Dear ImGui:
|
||||
// - FAQ https://dearimgui.com/faq
|
||||
// - Getting Started https://dearimgui.com/getting-started
|
||||
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
|
||||
// - Introduction, links and more at the top of imgui.cpp
|
||||
|
||||
// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
|
||||
// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
|
||||
// You will use those if you want to use this rendering backend in your engine/app.
|
||||
// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by
|
||||
// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
|
||||
// Read comments in imgui_impl_vulkan.h.
|
||||
|
||||
#pragma once
|
||||
#ifndef IMGUI_DISABLE
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
|
||||
// [Configuration] in order to use a custom Vulkan function loader:
|
||||
// (1) You'll need to disable default Vulkan function prototypes.
|
||||
// We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag.
|
||||
// In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit:
|
||||
// - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file
|
||||
// - Or as a compilation flag in your build system
|
||||
// - Or uncomment here (not recommended because you'd be modifying imgui sources!)
|
||||
// - Do not simply add it in a .cpp file!
|
||||
// (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function.
|
||||
// If you have no idea what this is, leave it alone!
|
||||
//#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES
|
||||
|
||||
// Convenience support for Volk
|
||||
// (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
|
||||
//#define IMGUI_IMPL_VULKAN_USE_VOLK
|
||||
|
||||
#if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES)
|
||||
#define VK_NO_PROTOTYPES
|
||||
#endif
|
||||
#if defined(VK_USE_PLATFORM_WIN32_KHR) && !defined(NOMINMAX)
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
|
||||
// Vulkan includes
|
||||
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
|
||||
#include <volk.h>
|
||||
#else
|
||||
#include <vulkan/vulkan.h>
|
||||
#endif
|
||||
#if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering)
|
||||
#define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
|
||||
#endif
|
||||
|
||||
// Current version of the backend use 1 descriptor for the font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture().
|
||||
// It is expected that as early as Q1 2025 the backend will use a few more descriptors. Use this value + number of desired calls to ImGui_ImplVulkan_AddTexture().
|
||||
#define IMGUI_IMPL_VULKAN_MINIMUM_IMAGE_SAMPLER_POOL_SIZE (1) // Minimum per atlas
|
||||
|
||||
// Initialization data, for ImGui_ImplVulkan_Init()
|
||||
// [Please zero-clear before use!]
|
||||
// - About descriptor pool:
|
||||
// - A VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
|
||||
// and must contain a pool size large enough to hold a small number of VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptors.
|
||||
// - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you.
|
||||
// - About dynamic rendering:
|
||||
// - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure.
|
||||
struct ImGui_ImplVulkan_InitInfo
|
||||
{
|
||||
uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3 or your value of VkApplicationInfo::apiVersion. May be lower than header version (VK_HEADER_VERSION_COMPLETE)
|
||||
VkInstance Instance;
|
||||
VkPhysicalDevice PhysicalDevice;
|
||||
VkDevice Device;
|
||||
uint32_t QueueFamily;
|
||||
VkQueue Queue;
|
||||
VkDescriptorPool DescriptorPool; // See requirements in note above; ignored if using DescriptorPoolSize > 0
|
||||
VkRenderPass RenderPass; // Ignored if using dynamic rendering
|
||||
uint32_t MinImageCount; // >= 2
|
||||
uint32_t ImageCount; // >= MinImageCount
|
||||
VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT
|
||||
|
||||
// (Optional)
|
||||
VkPipelineCache PipelineCache;
|
||||
uint32_t Subpass;
|
||||
|
||||
// (Optional) Set to create internal descriptor pool instead of using DescriptorPool
|
||||
uint32_t DescriptorPoolSize;
|
||||
|
||||
// (Optional) Dynamic Rendering
|
||||
// Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3.
|
||||
bool UseDynamicRendering;
|
||||
#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
|
||||
VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo;
|
||||
#endif
|
||||
|
||||
// (Optional) Allocation, Debugging
|
||||
const VkAllocationCallbacks* Allocator;
|
||||
void (*CheckVkResultFn)(VkResult err);
|
||||
VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory.
|
||||
};
|
||||
|
||||
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
|
||||
IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info);
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE);
|
||||
IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture();
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture();
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated)
|
||||
|
||||
// Register a texture (VkDescriptorSet == ImTextureID)
|
||||
// FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem
|
||||
// Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions.
|
||||
IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout);
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set);
|
||||
|
||||
// Optional: load Vulkan functions with a custom function loader
|
||||
// This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES
|
||||
IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(uint32_t api_version, PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr);
|
||||
|
||||
// [BETA] Selected render state data shared with callbacks.
|
||||
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplVulkan_RenderDrawData() call.
|
||||
// (Please open an issue if you feel you need access to more data)
|
||||
struct ImGui_ImplVulkan_RenderState
|
||||
{
|
||||
VkCommandBuffer CommandBuffer;
|
||||
VkPipeline Pipeline;
|
||||
VkPipelineLayout PipelineLayout;
|
||||
};
|
||||
|
||||
//-------------------------------------------------------------------------
|
||||
// Internal / Miscellaneous Vulkan Helpers
|
||||
//-------------------------------------------------------------------------
|
||||
// Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.
|
||||
//
|
||||
// You probably do NOT need to use or care about those functions.
|
||||
// Those functions only exist because:
|
||||
// 1) they facilitate the readability and maintenance of the multiple main.cpp examples files.
|
||||
// 2) the multi-viewport / platform window implementation needs them internally.
|
||||
// Generally we avoid exposing any kind of superfluous high-level helpers in the backends,
|
||||
// but it is too much code to duplicate everywhere so we exceptionally expose them.
|
||||
//
|
||||
// Your engine/app will likely _already_ have code to setup all that stuff (swap chain,
|
||||
// render pass, frame buffers, etc.). You may read this code if you are curious, but
|
||||
// it is recommended you use you own custom tailored code to do equivalent work.
|
||||
//
|
||||
// We don't provide a strong guarantee that we won't change those functions API.
|
||||
//
|
||||
// The ImGui_ImplVulkanH_XXX functions should NOT interact with any of the state used
|
||||
// by the regular ImGui_ImplVulkan_XXX functions).
|
||||
//-------------------------------------------------------------------------
|
||||
|
||||
struct ImGui_ImplVulkanH_Frame;
|
||||
struct ImGui_ImplVulkanH_Window;
|
||||
|
||||
// Helpers
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count);
|
||||
IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator);
|
||||
IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space);
|
||||
IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count);
|
||||
IMGUI_IMPL_API VkPhysicalDevice ImGui_ImplVulkanH_SelectPhysicalDevice(VkInstance instance);
|
||||
IMGUI_IMPL_API uint32_t ImGui_ImplVulkanH_SelectQueueFamilyIndex(VkPhysicalDevice physical_device);
|
||||
IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode);
|
||||
|
||||
// Helper structure to hold the data needed by one rendering frame
|
||||
// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.)
|
||||
// [Please zero-clear before use!]
|
||||
struct ImGui_ImplVulkanH_Frame
|
||||
{
|
||||
VkCommandPool CommandPool;
|
||||
VkCommandBuffer CommandBuffer;
|
||||
VkFence Fence;
|
||||
VkImage Backbuffer;
|
||||
VkImageView BackbufferView;
|
||||
VkFramebuffer Framebuffer;
|
||||
};
|
||||
|
||||
struct ImGui_ImplVulkanH_FrameSemaphores
|
||||
{
|
||||
VkSemaphore ImageAcquiredSemaphore;
|
||||
VkSemaphore RenderCompleteSemaphore;
|
||||
};
|
||||
|
||||
// Helper structure to hold the data needed by one rendering context into one OS window
|
||||
// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.)
|
||||
struct ImGui_ImplVulkanH_Window
|
||||
{
|
||||
int Width;
|
||||
int Height;
|
||||
VkSwapchainKHR Swapchain;
|
||||
VkSurfaceKHR Surface;
|
||||
VkSurfaceFormatKHR SurfaceFormat;
|
||||
VkPresentModeKHR PresentMode;
|
||||
VkRenderPass RenderPass;
|
||||
VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo
|
||||
bool UseDynamicRendering;
|
||||
bool ClearEnable;
|
||||
VkClearValue ClearValue;
|
||||
uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount)
|
||||
uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count)
|
||||
uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR
|
||||
uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data)
|
||||
ImVector<ImGui_ImplVulkanH_Frame> Frames;
|
||||
ImVector<ImGui_ImplVulkanH_FrameSemaphores> FrameSemaphores;
|
||||
|
||||
ImGui_ImplVulkanH_Window()
|
||||
{
|
||||
memset((void*)this, 0, sizeof(*this));
|
||||
PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this.
|
||||
ClearEnable = true;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // #ifndef IMGUI_DISABLE
|
||||
Vendored
+141
@@ -0,0 +1,141 @@
|
||||
//-----------------------------------------------------------------------------
|
||||
// DEAR IMGUI COMPILE-TIME OPTIONS
|
||||
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
|
||||
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
|
||||
//-----------------------------------------------------------------------------
|
||||
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
|
||||
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
|
||||
//-----------------------------------------------------------------------------
|
||||
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
|
||||
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
|
||||
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
|
||||
// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using.
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#pragma once
|
||||
|
||||
//---- Define assertion handler. Defaults to calling assert().
|
||||
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
|
||||
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
|
||||
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
|
||||
|
||||
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
|
||||
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
|
||||
// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
|
||||
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
|
||||
//#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export
|
||||
//#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import
|
||||
//#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden
|
||||
|
||||
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
|
||||
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
|
||||
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
|
||||
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
|
||||
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
|
||||
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
|
||||
//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
|
||||
|
||||
//---- Don't implement some functions to reduce linkage requirements.
|
||||
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
|
||||
//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
|
||||
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
|
||||
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME).
|
||||
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
|
||||
//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")).
|
||||
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
|
||||
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
|
||||
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
|
||||
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
|
||||
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
|
||||
//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert.
|
||||
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
|
||||
|
||||
//---- Enable Test Engine / Automation features.
|
||||
//#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_config.h", see Test Engine for details.
|
||||
|
||||
//---- Include imgui_user.h at the end of imgui.h as a convenience
|
||||
// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included.
|
||||
//#define IMGUI_INCLUDE_IMGUI_USER_H
|
||||
//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h"
|
||||
|
||||
//---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support.
|
||||
//#define IMGUI_USE_BGRA_PACKED_COLOR
|
||||
|
||||
//---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate.
|
||||
//#define IMGUI_USE_LEGACY_CRC32_ADLER
|
||||
|
||||
//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
|
||||
//#define IMGUI_USE_WCHAR32
|
||||
|
||||
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
|
||||
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
|
||||
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
|
||||
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
|
||||
//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined.
|
||||
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
|
||||
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
|
||||
//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined.
|
||||
|
||||
//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
|
||||
// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
|
||||
//#define IMGUI_USE_STB_SPRINTF
|
||||
|
||||
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
|
||||
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
|
||||
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
|
||||
//#define IMGUI_ENABLE_FREETYPE
|
||||
|
||||
//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT)
|
||||
// Only works in combination with IMGUI_ENABLE_FREETYPE.
|
||||
// - plutosvg is currently easier to install, as e.g. it is part of vcpkg. It will support more fonts and may load them faster. See misc/freetype/README for instructions.
|
||||
// - Both require headers to be available in the include path + program to be linked with the library code (not provided).
|
||||
// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
|
||||
//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG
|
||||
//#define IMGUI_ENABLE_FREETYPE_LUNASVG
|
||||
|
||||
//---- Use stb_truetype to build and rasterize the font atlas (default)
|
||||
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
|
||||
//#define IMGUI_ENABLE_STB_TRUETYPE
|
||||
|
||||
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
|
||||
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
|
||||
/*
|
||||
#define IM_VEC2_CLASS_EXTRA \
|
||||
constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
|
||||
operator MyVec2() const { return MyVec2(x,y); }
|
||||
|
||||
#define IM_VEC4_CLASS_EXTRA \
|
||||
constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
|
||||
operator MyVec4() const { return MyVec4(x,y,z,w); }
|
||||
*/
|
||||
//---- ...Or use Dear ImGui's own very basic math operators.
|
||||
//#define IMGUI_DEFINE_MATH_OPERATORS
|
||||
|
||||
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
|
||||
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
|
||||
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
|
||||
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
|
||||
//#define ImDrawIdx unsigned int
|
||||
|
||||
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
|
||||
//struct ImDrawList;
|
||||
//struct ImDrawCmd;
|
||||
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
|
||||
//#define ImDrawCallback MyImDrawCallback
|
||||
|
||||
//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase)
|
||||
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
|
||||
//#define IM_DEBUG_BREAK IM_ASSERT(0)
|
||||
//#define IM_DEBUG_BREAK __debugbreak()
|
||||
|
||||
//---- Debug Tools: Enable slower asserts
|
||||
//#define IMGUI_DEBUG_PARANOID
|
||||
|
||||
//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files)
|
||||
/*
|
||||
namespace ImGui
|
||||
{
|
||||
void MyFunction(const char* name, MyMatrix44* mtx);
|
||||
}
|
||||
*/
|
||||
Vendored
+17060
File diff suppressed because it is too large.
Load diff
Vendored
+3765
File diff suppressed because it is too large.
Load diff
+4828
File diff suppressed because it is too large.
Load diff
+3636
File diff suppressed because it is too large.
Load diff
+4525
File diff suppressed because it is too large.
Load diff
+10451
File diff suppressed because it is too large.
Load diff
+627
@@ -0,0 +1,627 @@
|
||||
// [DEAR IMGUI]
|
||||
// This is a slightly modified version of stb_rect_pack.h 1.01.
|
||||
// Grep for [DEAR IMGUI] to find the changes.
|
||||
//
|
||||
// stb_rect_pack.h - v1.01 - public domain - rectangle packing
|
||||
// Sean Barrett 2014
|
||||
//
|
||||
// Useful for e.g. packing rectangular textures into an atlas.
|
||||
// Does not do rotation.
|
||||
//
|
||||
// Before #including,
|
||||
//
|
||||
// #define STB_RECT_PACK_IMPLEMENTATION
|
||||
//
|
||||
// in the file that you want to have the implementation.
|
||||
//
|
||||
// Not necessarily the awesomest packing method, but better than
|
||||
// the totally naive one in stb_truetype (which is primarily what
|
||||
// this is meant to replace).
|
||||
//
|
||||
// Has only had a few tests run, may have issues.
|
||||
//
|
||||
// More docs to come.
|
||||
//
|
||||
// No memory allocations; uses qsort() and assert() from stdlib.
|
||||
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
|
||||
//
|
||||
// This library currently uses the Skyline Bottom-Left algorithm.
|
||||
//
|
||||
// Please note: better rectangle packers are welcome! Please
|
||||
// implement them to the same API, but with a different init
|
||||
// function.
|
||||
//
|
||||
// Credits
|
||||
//
|
||||
// Library
|
||||
// Sean Barrett
|
||||
// Minor features
|
||||
// Martins Mozeiko
|
||||
// github:IntellectualKitty
|
||||
//
|
||||
// Bugfixes / warning fixes
|
||||
// Jeremy Jaussaud
|
||||
// Fabian Giesen
|
||||
//
|
||||
// Version history:
|
||||
//
|
||||
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
|
||||
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
|
||||
// 0.99 (2019-02-07) warning fixes
|
||||
// 0.11 (2017-03-03) return packing success/fail result
|
||||
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
|
||||
// 0.09 (2016-08-27) fix compiler warnings
|
||||
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
|
||||
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
|
||||
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
|
||||
// 0.05: added STBRP_ASSERT to allow replacing assert
|
||||
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
|
||||
// 0.01: initial release
|
||||
//
|
||||
// LICENSE
|
||||
//
|
||||
// See end of file for license information.
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// INCLUDE SECTION
|
||||
//
|
||||
|
||||
#ifndef STB_INCLUDE_STB_RECT_PACK_H
|
||||
#define STB_INCLUDE_STB_RECT_PACK_H
|
||||
|
||||
#define STB_RECT_PACK_VERSION 1
|
||||
|
||||
#ifdef STBRP_STATIC
|
||||
#define STBRP_DEF static
|
||||
#else
|
||||
#define STBRP_DEF extern
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct stbrp_context stbrp_context;
|
||||
typedef struct stbrp_node stbrp_node;
|
||||
typedef struct stbrp_rect stbrp_rect;
|
||||
|
||||
typedef int stbrp_coord;
|
||||
|
||||
#define STBRP__MAXVAL 0x7fffffff
|
||||
// Mostly for internal use, but this is the maximum supported coordinate value.
|
||||
|
||||
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
|
||||
// Assign packed locations to rectangles. The rectangles are of type
|
||||
// 'stbrp_rect' defined below, stored in the array 'rects', and there
|
||||
// are 'num_rects' many of them.
|
||||
//
|
||||
// Rectangles which are successfully packed have the 'was_packed' flag
|
||||
// set to a non-zero value and 'x' and 'y' store the minimum location
|
||||
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
|
||||
// if you imagine y increasing downwards). Rectangles which do not fit
|
||||
// have the 'was_packed' flag set to 0.
|
||||
//
|
||||
// You should not try to access the 'rects' array from another thread
|
||||
// while this function is running, as the function temporarily reorders
|
||||
// the array while it executes.
|
||||
//
|
||||
// To pack into another rectangle, you need to call stbrp_init_target
|
||||
// again. To continue packing into the same rectangle, you can call
|
||||
// this function again. Calling this multiple times with multiple rect
|
||||
// arrays will probably produce worse packing results than calling it
|
||||
// a single time with the full rectangle array, but the option is
|
||||
// available.
|
||||
//
|
||||
// The function returns 1 if all of the rectangles were successfully
|
||||
// packed and 0 otherwise.
|
||||
|
||||
struct stbrp_rect
|
||||
{
|
||||
// reserved for your use:
|
||||
int id;
|
||||
|
||||
// input:
|
||||
stbrp_coord w, h;
|
||||
|
||||
// output:
|
||||
stbrp_coord x, y;
|
||||
int was_packed; // non-zero if valid packing
|
||||
|
||||
}; // 16 bytes, nominally
|
||||
|
||||
|
||||
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
|
||||
// Initialize a rectangle packer to:
|
||||
// pack a rectangle that is 'width' by 'height' in dimensions
|
||||
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
|
||||
//
|
||||
// You must call this function every time you start packing into a new target.
|
||||
//
|
||||
// There is no "shutdown" function. The 'nodes' memory must stay valid for
|
||||
// the following stbrp_pack_rects() call (or calls), but can be freed after
|
||||
// the call (or calls) finish.
|
||||
//
|
||||
// Note: to guarantee best results, either:
|
||||
// 1. make sure 'num_nodes' >= 'width'
|
||||
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
|
||||
//
|
||||
// If you don't do either of the above things, widths will be quantized to multiples
|
||||
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
|
||||
//
|
||||
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
|
||||
// may run out of temporary storage and be unable to pack some rectangles.
|
||||
|
||||
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
|
||||
// Optionally call this function after init but before doing any packing to
|
||||
// change the handling of the out-of-temp-memory scenario, described above.
|
||||
// If you call init again, this will be reset to the default (false).
|
||||
|
||||
|
||||
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
|
||||
// Optionally select which packing heuristic the library should use. Different
|
||||
// heuristics will produce better/worse results for different data sets.
|
||||
// If you call init again, this will be reset to the default.
|
||||
|
||||
enum
|
||||
{
|
||||
STBRP_HEURISTIC_Skyline_default=0,
|
||||
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
|
||||
STBRP_HEURISTIC_Skyline_BF_sortHeight
|
||||
};
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// the details of the following structures don't matter to you, but they must
|
||||
// be visible so you can handle the memory allocations for them
|
||||
|
||||
struct stbrp_node
|
||||
{
|
||||
stbrp_coord x,y;
|
||||
stbrp_node *next;
|
||||
};
|
||||
|
||||
struct stbrp_context
|
||||
{
|
||||
int width;
|
||||
int height;
|
||||
int align;
|
||||
int init_mode;
|
||||
int heuristic;
|
||||
int num_nodes;
|
||||
stbrp_node *active_head;
|
||||
stbrp_node *free_head;
|
||||
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// IMPLEMENTATION SECTION
|
||||
//
|
||||
|
||||
#ifdef STB_RECT_PACK_IMPLEMENTATION
|
||||
#ifndef STBRP_SORT
|
||||
#include <stdlib.h>
|
||||
#define STBRP_SORT qsort
|
||||
#endif
|
||||
|
||||
#ifndef STBRP_ASSERT
|
||||
#include <assert.h>
|
||||
#define STBRP_ASSERT assert
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define STBRP__NOTUSED(v) (void)(v)
|
||||
#define STBRP__CDECL __cdecl
|
||||
#else
|
||||
#define STBRP__NOTUSED(v) (void)sizeof(v)
|
||||
#define STBRP__CDECL
|
||||
#endif
|
||||
|
||||
enum
|
||||
{
|
||||
STBRP__INIT_skyline = 1
|
||||
};
|
||||
|
||||
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
|
||||
{
|
||||
switch (context->init_mode) {
|
||||
case STBRP__INIT_skyline:
|
||||
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
|
||||
context->heuristic = heuristic;
|
||||
break;
|
||||
default:
|
||||
STBRP_ASSERT(0);
|
||||
}
|
||||
}
|
||||
|
||||
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
|
||||
{
|
||||
if (allow_out_of_mem)
|
||||
// if it's ok to run out of memory, then don't bother aligning them;
|
||||
// this gives better packing, but may fail due to OOM (even though
|
||||
// the rectangles easily fit). @TODO a smarter approach would be to only
|
||||
// quantize once we've hit OOM, then we could get rid of this parameter.
|
||||
context->align = 1;
|
||||
else {
|
||||
// if it's not ok to run out of memory, then quantize the widths
|
||||
// so that num_nodes is always enough nodes.
|
||||
//
|
||||
// I.e. num_nodes * align >= width
|
||||
// align >= width / num_nodes
|
||||
// align = ceil(width/num_nodes)
|
||||
|
||||
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
|
||||
}
|
||||
}
|
||||
|
||||
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i=0; i < num_nodes-1; ++i)
|
||||
nodes[i].next = &nodes[i+1];
|
||||
nodes[i].next = NULL;
|
||||
context->init_mode = STBRP__INIT_skyline;
|
||||
context->heuristic = STBRP_HEURISTIC_Skyline_default;
|
||||
context->free_head = &nodes[0];
|
||||
context->active_head = &context->extra[0];
|
||||
context->width = width;
|
||||
context->height = height;
|
||||
context->num_nodes = num_nodes;
|
||||
stbrp_setup_allow_out_of_mem(context, 0);
|
||||
|
||||
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
|
||||
context->extra[0].x = 0;
|
||||
context->extra[0].y = 0;
|
||||
context->extra[0].next = &context->extra[1];
|
||||
context->extra[1].x = (stbrp_coord) width;
|
||||
context->extra[1].y = (1<<30);
|
||||
context->extra[1].next = NULL;
|
||||
}
|
||||
|
||||
// find minimum y position if it starts at x1
|
||||
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
|
||||
{
|
||||
stbrp_node *node = first;
|
||||
int x1 = x0 + width;
|
||||
int min_y, visited_width, waste_area;
|
||||
|
||||
STBRP__NOTUSED(c);
|
||||
|
||||
STBRP_ASSERT(first->x <= x0);
|
||||
|
||||
#if 0
|
||||
// skip in case we're past the node
|
||||
while (node->next->x <= x0)
|
||||
++node;
|
||||
#else
|
||||
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
|
||||
#endif
|
||||
|
||||
STBRP_ASSERT(node->x <= x0);
|
||||
|
||||
min_y = 0;
|
||||
waste_area = 0;
|
||||
visited_width = 0;
|
||||
while (node->x < x1) {
|
||||
if (node->y > min_y) {
|
||||
// raise min_y higher.
|
||||
// we've accounted for all waste up to min_y,
|
||||
// but we'll now add more waste for everything we've visted
|
||||
waste_area += visited_width * (node->y - min_y);
|
||||
min_y = node->y;
|
||||
// the first time through, visited_width might be reduced
|
||||
if (node->x < x0)
|
||||
visited_width += node->next->x - x0;
|
||||
else
|
||||
visited_width += node->next->x - node->x;
|
||||
} else {
|
||||
// add waste area
|
||||
int under_width = node->next->x - node->x;
|
||||
if (under_width + visited_width > width)
|
||||
under_width = width - visited_width;
|
||||
waste_area += under_width * (min_y - node->y);
|
||||
visited_width += under_width;
|
||||
}
|
||||
node = node->next;
|
||||
}
|
||||
|
||||
*pwaste = waste_area;
|
||||
return min_y;
|
||||
}
|
||||
|
||||
typedef struct
|
||||
{
|
||||
int x,y;
|
||||
stbrp_node **prev_link;
|
||||
} stbrp__findresult;
|
||||
|
||||
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
|
||||
{
|
||||
int best_waste = (1<<30), best_x, best_y = (1 << 30);
|
||||
stbrp__findresult fr;
|
||||
stbrp_node **prev, *node, *tail, **best = NULL;
|
||||
|
||||
// align to multiple of c->align
|
||||
width = (width + c->align - 1);
|
||||
width -= width % c->align;
|
||||
STBRP_ASSERT(width % c->align == 0);
|
||||
|
||||
// if it can't possibly fit, bail immediately
|
||||
if (width > c->width || height > c->height) {
|
||||
fr.prev_link = NULL;
|
||||
fr.x = fr.y = 0;
|
||||
return fr;
|
||||
}
|
||||
|
||||
node = c->active_head;
|
||||
prev = &c->active_head;
|
||||
while (node->x + width <= c->width) {
|
||||
int y,waste;
|
||||
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
|
||||
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
|
||||
// bottom left
|
||||
if (y < best_y) {
|
||||
best_y = y;
|
||||
best = prev;
|
||||
}
|
||||
} else {
|
||||
// best-fit
|
||||
if (y + height <= c->height) {
|
||||
// can only use it if it first vertically
|
||||
if (y < best_y || (y == best_y && waste < best_waste)) {
|
||||
best_y = y;
|
||||
best_waste = waste;
|
||||
best = prev;
|
||||
}
|
||||
}
|
||||
}
|
||||
prev = &node->next;
|
||||
node = node->next;
|
||||
}
|
||||
|
||||
best_x = (best == NULL) ? 0 : (*best)->x;
|
||||
|
||||
// if doing best-fit (BF), we also have to try aligning right edge to each node position
|
||||
//
|
||||
// e.g, if fitting
|
||||
//
|
||||
// ____________________
|
||||
// |____________________|
|
||||
//
|
||||
// into
|
||||
//
|
||||
// | |
|
||||
// | ____________|
|
||||
// |____________|
|
||||
//
|
||||
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
|
||||
//
|
||||
// This makes BF take about 2x the time
|
||||
|
||||
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
|
||||
tail = c->active_head;
|
||||
node = c->active_head;
|
||||
prev = &c->active_head;
|
||||
// find first node that's admissible
|
||||
while (tail->x < width)
|
||||
tail = tail->next;
|
||||
while (tail) {
|
||||
int xpos = tail->x - width;
|
||||
int y,waste;
|
||||
STBRP_ASSERT(xpos >= 0);
|
||||
// find the left position that matches this
|
||||
while (node->next->x <= xpos) {
|
||||
prev = &node->next;
|
||||
node = node->next;
|
||||
}
|
||||
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
|
||||
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
|
||||
if (y + height <= c->height) {
|
||||
if (y <= best_y) {
|
||||
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
|
||||
best_x = xpos;
|
||||
//STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
|
||||
best_y = y;
|
||||
best_waste = waste;
|
||||
best = prev;
|
||||
}
|
||||
}
|
||||
}
|
||||
tail = tail->next;
|
||||
}
|
||||
}
|
||||
|
||||
fr.prev_link = best;
|
||||
fr.x = best_x;
|
||||
fr.y = best_y;
|
||||
return fr;
|
||||
}
|
||||
|
||||
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
|
||||
{
|
||||
// find best position according to heuristic
|
||||
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
|
||||
stbrp_node *node, *cur;
|
||||
|
||||
// bail if:
|
||||
// 1. it failed
|
||||
// 2. the best node doesn't fit (we don't always check this)
|
||||
// 3. we're out of memory
|
||||
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
|
||||
res.prev_link = NULL;
|
||||
return res;
|
||||
}
|
||||
|
||||
// on success, create new node
|
||||
node = context->free_head;
|
||||
node->x = (stbrp_coord) res.x;
|
||||
node->y = (stbrp_coord) (res.y + height);
|
||||
|
||||
context->free_head = node->next;
|
||||
|
||||
// insert the new node into the right starting point, and
|
||||
// let 'cur' point to the remaining nodes needing to be
|
||||
// stiched back in
|
||||
|
||||
cur = *res.prev_link;
|
||||
if (cur->x < res.x) {
|
||||
// preserve the existing one, so start testing with the next one
|
||||
stbrp_node *next = cur->next;
|
||||
cur->next = node;
|
||||
cur = next;
|
||||
} else {
|
||||
*res.prev_link = node;
|
||||
}
|
||||
|
||||
// from here, traverse cur and free the nodes, until we get to one
|
||||
// that shouldn't be freed
|
||||
while (cur->next && cur->next->x <= res.x + width) {
|
||||
stbrp_node *next = cur->next;
|
||||
// move the current node to the free list
|
||||
cur->next = context->free_head;
|
||||
context->free_head = cur;
|
||||
cur = next;
|
||||
}
|
||||
|
||||
// stitch the list back in
|
||||
node->next = cur;
|
||||
|
||||
if (cur->x < res.x + width)
|
||||
cur->x = (stbrp_coord) (res.x + width);
|
||||
|
||||
#ifdef _DEBUG
|
||||
cur = context->active_head;
|
||||
while (cur->x < context->width) {
|
||||
STBRP_ASSERT(cur->x < cur->next->x);
|
||||
cur = cur->next;
|
||||
}
|
||||
STBRP_ASSERT(cur->next == NULL);
|
||||
|
||||
{
|
||||
int count=0;
|
||||
cur = context->active_head;
|
||||
while (cur) {
|
||||
cur = cur->next;
|
||||
++count;
|
||||
}
|
||||
cur = context->free_head;
|
||||
while (cur) {
|
||||
cur = cur->next;
|
||||
++count;
|
||||
}
|
||||
STBRP_ASSERT(count == context->num_nodes+2);
|
||||
}
|
||||
#endif
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
|
||||
{
|
||||
const stbrp_rect *p = (const stbrp_rect *) a;
|
||||
const stbrp_rect *q = (const stbrp_rect *) b;
|
||||
if (p->h > q->h)
|
||||
return -1;
|
||||
if (p->h < q->h)
|
||||
return 1;
|
||||
return (p->w > q->w) ? -1 : (p->w < q->w);
|
||||
}
|
||||
|
||||
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
|
||||
{
|
||||
const stbrp_rect *p = (const stbrp_rect *) a;
|
||||
const stbrp_rect *q = (const stbrp_rect *) b;
|
||||
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
|
||||
}
|
||||
|
||||
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
|
||||
{
|
||||
int i, all_rects_packed = 1;
|
||||
|
||||
// we use the 'was_packed' field internally to allow sorting/unsorting
|
||||
for (i=0; i < num_rects; ++i) {
|
||||
rects[i].was_packed = i;
|
||||
}
|
||||
|
||||
// sort according to heuristic
|
||||
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
|
||||
|
||||
for (i=0; i < num_rects; ++i) {
|
||||
if (rects[i].w == 0 || rects[i].h == 0) {
|
||||
rects[i].x = rects[i].y = 0; // empty rect needs no space
|
||||
} else {
|
||||
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
|
||||
if (fr.prev_link) {
|
||||
rects[i].x = (stbrp_coord) fr.x;
|
||||
rects[i].y = (stbrp_coord) fr.y;
|
||||
} else {
|
||||
rects[i].x = rects[i].y = STBRP__MAXVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unsort
|
||||
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
|
||||
|
||||
// set was_packed flags and all_rects_packed status
|
||||
for (i=0; i < num_rects; ++i) {
|
||||
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
|
||||
if (!rects[i].was_packed)
|
||||
all_rects_packed = 0;
|
||||
}
|
||||
|
||||
// return the all_rects_packed status
|
||||
return all_rects_packed;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
------------------------------------------------------------------------------
|
||||
This software is available under 2 licenses -- choose whichever you prefer.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE A - MIT License
|
||||
Copyright (c) 2017 Sean Barrett
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
This is free and unencumbered software released into the public domain.
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
software, either in source code form or as a compiled binary, for any purpose,
|
||||
commercial or non-commercial, and by any means.
|
||||
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
software dedicate any and all copyright interest in the software to the public
|
||||
domain. We make this dedication for the benefit of the public at large and to
|
||||
the detriment of our heirs and successors. We intend this dedication to be an
|
||||
overt act of relinquishment in perpetuity of all present and future rights to
|
||||
this software under copyright law.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
*/
|
||||
+1469
File diff suppressed because it is too large.
Load diff
+5085
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,69 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
2. You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
APPENDIX: How to apply the Apache License to your work
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
------------
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
||||
Binary file not shown.
@@ -0,0 +1,639 @@
|
||||
// The in-game menu core: Dear ImGui state, the event queue the window adapter fills, gamepad navigation, the Vulkan back
|
||||
// end on our device and the menu's pages. Free of any window system (menu.h). ImGui runs on the present path only,
|
||||
// under gfx_window.c's present lock; the event functions only queue.
|
||||
//
|
||||
// The Vulkan set-up follows LAS Recomp's runtime/nvn/vulkan/imgui_glue.cpp (https://github.com/peiikai/LASRecomp @
|
||||
// da35b83a9611d046a9a681aae668d7085954d37f, MIT, Copyright (c) 2026 Peiikai): dynamic rendering into the swapchain
|
||||
// image, an internal descriptor pool, vertex buffers rotated over more frames than are in flight.
|
||||
//
|
||||
// The look (colours, rounding, the tab bar with L / R and Q / E, the window over a dimmed game) follows
|
||||
// SavageWindRecomp's runtime/ui/menu.mm (https://github.com/Revivedx/SavageWindRecomp @
|
||||
// 575ad88e02f9a89a9a885d90039d48af33c982f4, MIT, Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors,
|
||||
// Copyright (c) 2026 Peiikai); the pages are rows of option_rows.cpp.
|
||||
#include <atomic>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_internal.h" // SetFocusID, NavCursorVisible
|
||||
#include "backends/imgui_impl_vulkan.h"
|
||||
#include "ui/option_rows.h"
|
||||
|
||||
extern "C" {
|
||||
#include "cfg.h"
|
||||
#include "input.h"
|
||||
#include "input_map.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui/menu.h"
|
||||
#include "ui_text.h"
|
||||
// host.h and vk.h pull in cpu.h, which is C only: the three functions the menu needs from them, as declared there.
|
||||
void rt_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
void vk_queue_lock(void);
|
||||
void vk_queue_unlock(void);
|
||||
}
|
||||
|
||||
// Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs.
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wc23-extensions" // #embed in C++
|
||||
static const unsigned char roboto_ttf[] = {
|
||||
#embed "fonts/Roboto-Medium.ttf"
|
||||
};
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
// ---- open state, any thread
|
||||
static std::atomic<int> g_open; // the menu is open
|
||||
static std::atomic<int> g_reset; // opened or closed since the last laid-out frame: drop stale input
|
||||
|
||||
// g_open, the input block and the log line change together under open_lock, so they cannot disagree when the window thread
|
||||
// (F1, Esc), the polling thread (combo) and the present path (Continue, B) race.
|
||||
static PlatMutex open_lock = PLAT_MUTEX_INIT;
|
||||
|
||||
// want 0 or 1 sets the state; -1 flips it. Returns the new state.
|
||||
static int change_open(int want) {
|
||||
plat_mutex_lock(&open_lock);
|
||||
int open = want < 0 ? !g_open.load() : want;
|
||||
if (g_open.load() != open) {
|
||||
g_open.store(open);
|
||||
g_reset.store(1);
|
||||
input_menu(open);
|
||||
rt_log("menu: %s", open ? "open" : "closed");
|
||||
}
|
||||
plat_mutex_unlock(&open_lock);
|
||||
return open;
|
||||
}
|
||||
|
||||
static void set_open(int open) { change_open(open); }
|
||||
|
||||
static int g_failed_flag();
|
||||
extern "C" int menu_is_open(void) { return g_open.load(std::memory_order_relaxed); }
|
||||
extern "C" void menu_toggle(void) {
|
||||
if (!g_failed_flag()) change_open(-1);
|
||||
}
|
||||
|
||||
// ---- events from the window adapter, queued while the menu is open; the present path hands them to ImGui
|
||||
enum { EV_KEY, EV_POS, EV_BUTTON, EV_WHEEL, EV_FOCUS, EV_MAX = 256 };
|
||||
struct Ev { int type, a, b; float x, y; };
|
||||
static PlatMutex ev_lock = PLAT_MUTEX_INIT;
|
||||
static Ev ev_q[EV_MAX];
|
||||
static int ev_n;
|
||||
|
||||
static void push(Ev e) {
|
||||
if (!menu_is_open()) return;
|
||||
plat_mutex_lock(&ev_lock);
|
||||
if (e.type == EV_POS && ev_n && ev_q[ev_n - 1].type == EV_POS) ev_q[ev_n - 1] = e; // only the newest position
|
||||
else if (ev_n < EV_MAX) ev_q[ev_n++] = e;
|
||||
plat_mutex_unlock(&ev_lock);
|
||||
}
|
||||
|
||||
extern "C" void menu_event_key(int key, int down) { push({EV_KEY, key, down, 0, 0}); }
|
||||
extern "C" void menu_event_mouse_pos(float x, float y) { push({EV_POS, 0, 0, x, y}); }
|
||||
extern "C" void menu_event_mouse_button(int button, int down) { push({EV_BUTTON, button, down, 0, 0}); }
|
||||
extern "C" void menu_event_wheel(float dx, float dy) { push({EV_WHEEL, 0, 0, dx, dy}); }
|
||||
extern "C" void menu_event_focus(int focused) { push({EV_FOCUS, focused, 0, 0, 0}); }
|
||||
|
||||
static void drain_events(ImGuiIO &io) {
|
||||
Ev q[EV_MAX];
|
||||
plat_mutex_lock(&ev_lock);
|
||||
int n = ev_n;
|
||||
for (int i = 0; i < n; i++) q[i] = ev_q[i];
|
||||
ev_n = 0;
|
||||
plat_mutex_unlock(&ev_lock);
|
||||
for (int i = 0; i < n; i++) {
|
||||
const Ev &e = q[i];
|
||||
switch (e.type) {
|
||||
case EV_KEY: io.AddKeyEvent((ImGuiKey)e.a, e.b != 0); break;
|
||||
case EV_POS: io.AddMousePosEvent(e.x, e.y); break;
|
||||
case EV_BUTTON: io.AddMouseButtonEvent(e.a, e.b != 0); break;
|
||||
case EV_WHEEL: io.AddMouseWheelEvent(e.x, e.y); break;
|
||||
case EV_FOCUS: io.AddFocusEvent(e.a != 0); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- gamepad navigation: the Switch buttons of our SDL3 gamepad to ImGui's gamepad keys. Nintendo layout: A (east)
|
||||
// activates, B (south) cancels.
|
||||
static const struct { int bit; ImGuiKey key; } pad_keys[] = {
|
||||
{B_A, ImGuiKey_GamepadFaceDown}, {B_B, ImGuiKey_GamepadFaceRight}, {B_X, ImGuiKey_GamepadFaceUp},
|
||||
{B_Y, ImGuiKey_GamepadFaceLeft}, {B_L, ImGuiKey_GamepadL1}, {B_R, ImGuiKey_GamepadR1},
|
||||
{B_ZL, ImGuiKey_GamepadL2}, {B_ZR, ImGuiKey_GamepadR2}, {B_LEFT, ImGuiKey_GamepadDpadLeft},
|
||||
{B_UP, ImGuiKey_GamepadDpadUp}, {B_RIGHT, ImGuiKey_GamepadDpadRight}, {B_DOWN, ImGuiKey_GamepadDpadDown},
|
||||
};
|
||||
static uint64_t pad_prev; // buttons at the last frame; a button held when the menu opened counts once released
|
||||
static float stick_prev[4]; // left stick left, right, up, down as ImGui analog values
|
||||
|
||||
static void pad_events(ImGuiIO &io, int reset) {
|
||||
uint64_t b;
|
||||
int32_t lx, ly;
|
||||
int have = input_pad_read(&b, &lx, &ly);
|
||||
if (have) io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
|
||||
else io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
|
||||
if (reset) {
|
||||
pad_prev = b;
|
||||
for (float &s : stick_prev) s = 0;
|
||||
return;
|
||||
}
|
||||
for (const auto &k : pad_keys) {
|
||||
uint64_t m = 1ull << k.bit;
|
||||
if ((b ^ pad_prev) & m) io.AddKeyEvent(k.key, (b & m) != 0);
|
||||
}
|
||||
pad_prev = b;
|
||||
const float dead = 0.3f;
|
||||
float v[4] = {-lx / 32767.0f, lx / 32767.0f, ly / 32767.0f, -ly / 32767.0f};
|
||||
static const ImGuiKey sk[4] = {ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp,
|
||||
ImGuiKey_GamepadLStickDown};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float a = v[i] > dead ? (v[i] - dead) / (1 - dead) : 0;
|
||||
if (a != stick_prev[i]) io.AddKeyAnalogEvent(sk[i], a > 0.1f, a);
|
||||
stick_prev[i] = a;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ImGui and its Vulkan back end (present path)
|
||||
static int g_ctx_ok; // context made
|
||||
static std::atomic<int> g_failed; // set-up failed for good (the menu stays closed)
|
||||
static int g_failed_flag() { return g_failed.load(std::memory_order_relaxed); }
|
||||
static int g_vk_ok; // back end initialised for g_vk_fmt
|
||||
static VkFormat g_vk_fmt;
|
||||
static float g_font_scale; // the scale of the uploaded font atlas; 0 when none is uploaded
|
||||
static float g_style_scale; // the scale the style was last sized for
|
||||
static ImGuiStyle g_base_style; // the menu's style at 1080 lines
|
||||
static uint64_t g_last_ns;
|
||||
static uint64_t g_cost_ns, g_cost_frames; // CPU time of layout and recording while open, logged per 600 frames
|
||||
|
||||
// Sizes are tuned for 1080 lines and follow the window's height; under 720 lines they stay at the 720 size.
|
||||
static float menu_scale(uint32_t h) { return (h >= 720 ? h : 720) / 1080.0f; }
|
||||
|
||||
// SavageWindRecomp's colours: dark green panels, gold accents.
|
||||
static void style_init(ImGuiStyle &s) {
|
||||
ImGui::StyleColorsDark(&s);
|
||||
s.WindowRounding = 14; s.FrameRounding = 8; s.GrabRounding = 8; s.TabRounding = 8; s.ChildRounding = 10;
|
||||
s.WindowPadding = ImVec2(28, 22); s.FramePadding = ImVec2(14, 8); s.ItemSpacing = ImVec2(14, 12);
|
||||
s.WindowBorderSize = 0; s.ScrollbarSize = 18;
|
||||
ImVec4 *c = s.Colors;
|
||||
ImVec4 gold(0.93f, 0.76f, 0.33f, 1), green(0.15f, 0.36f, 0.25f, 1);
|
||||
c[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.09f, 0.08f, 0.94f);
|
||||
c[ImGuiCol_ChildBg] = ImVec4(0, 0, 0, 0);
|
||||
c[ImGuiCol_Text] = ImVec4(0.96f, 0.94f, 0.88f, 1);
|
||||
c[ImGuiCol_TextDisabled] = ImVec4(0.62f, 0.64f, 0.58f, 1);
|
||||
c[ImGuiCol_Button] = ImVec4(0.14f, 0.22f, 0.18f, 1);
|
||||
c[ImGuiCol_ButtonHovered] = green;
|
||||
c[ImGuiCol_ButtonActive] = ImVec4(0.21f, 0.50f, 0.34f, 1);
|
||||
c[ImGuiCol_Tab] = ImVec4(0.12f, 0.18f, 0.15f, 1);
|
||||
c[ImGuiCol_TabHovered] = green;
|
||||
c[ImGuiCol_TabSelected] = ImVec4(0.21f, 0.44f, 0.31f, 1);
|
||||
c[ImGuiCol_TabSelectedOverline] = gold;
|
||||
c[ImGuiCol_NavCursor] = gold;
|
||||
c[ImGuiCol_Separator] = ImVec4(0.30f, 0.36f, 0.30f, 1);
|
||||
}
|
||||
|
||||
static void make_context(void) {
|
||||
ImGui::CreateContext();
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
io.IniFilename = nullptr;
|
||||
io.LogFilename = nullptr;
|
||||
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_NavEnableGamepad;
|
||||
io.BackendPlatformName = "totk_menu";
|
||||
style_init(g_base_style);
|
||||
ImGui::GetStyle() = g_base_style;
|
||||
g_ctx_ok = 1;
|
||||
}
|
||||
|
||||
static void vk_down(void) {
|
||||
if (!g_vk_ok) return;
|
||||
ImGui_ImplVulkan_Shutdown();
|
||||
g_vk_ok = 0;
|
||||
g_font_scale = 0;
|
||||
}
|
||||
|
||||
static int vk_up(const MenuTarget *t) {
|
||||
if (g_vk_ok && g_vk_fmt == t->format) return 1;
|
||||
if (g_vk_ok) { // the swapchain changed format: pipelines for the new one
|
||||
vk_queue_lock();
|
||||
vkQueueWaitIdle(t->queue);
|
||||
vk_queue_unlock();
|
||||
vk_down();
|
||||
}
|
||||
ImGui_ImplVulkan_InitInfo ii = {};
|
||||
ii.ApiVersion = VK_API_VERSION_1_3;
|
||||
ii.Instance = t->instance;
|
||||
ii.PhysicalDevice = t->phys;
|
||||
ii.Device = t->device;
|
||||
ii.QueueFamily = t->queue_family;
|
||||
ii.Queue = t->queue;
|
||||
ii.DescriptorPoolSize = 16;
|
||||
ii.MinImageCount = 2;
|
||||
ii.ImageCount = 4; // vertex buffers rotate per recorded frame: more than gfx_window.c's 2 frames in flight
|
||||
ii.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
|
||||
ii.UseDynamicRendering = true;
|
||||
g_vk_fmt = t->format;
|
||||
ii.PipelineRenderingCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO;
|
||||
ii.PipelineRenderingCreateInfo.colorAttachmentCount = 1;
|
||||
ii.PipelineRenderingCreateInfo.pColorAttachmentFormats = &g_vk_fmt;
|
||||
if (!ImGui_ImplVulkan_Init(&ii)) return 0;
|
||||
g_vk_ok = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean
|
||||
// and Chinese language names merged in from a system font when there is one (each language is named in its own script).
|
||||
// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture).
|
||||
static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0};
|
||||
static const struct { const char *lang; UiTextId name; } kCjk[] = {
|
||||
{"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS},
|
||||
{"zh-Hant", UI_MENU_LANGNAME_ZH_HANT},
|
||||
};
|
||||
|
||||
static int fonts_up(float scale) {
|
||||
enum { N = sizeof kCjk / sizeof *kCjk };
|
||||
ImFontAtlas *fa = ImGui::GetIO().Fonts;
|
||||
fa->Clear();
|
||||
ImFontConfig fc;
|
||||
fc.FontDataOwnedByAtlas = false;
|
||||
fa->AddFontFromMemoryTTF((void *)roboto_ttf, (int)sizeof roboto_ttf, 26.0f * scale, &fc, kRanges);
|
||||
uint8_t *data[N] = {};
|
||||
ImVector<ImWchar> ranges[N];
|
||||
int merged = 0;
|
||||
for (int i = 0; i < N; i++) {
|
||||
char path[512];
|
||||
uint64_t size = 0;
|
||||
if (!plat_font_path(kCjk[i].lang, path, sizeof path) || !(data[i] = plat_file_read(path, &size))) continue;
|
||||
merged++;
|
||||
ImFontGlyphRangesBuilder b;
|
||||
b.AddText(ui_text_in("en", kCjk[i].name));
|
||||
b.BuildRanges(&ranges[i]);
|
||||
ImFontConfig mc;
|
||||
mc.MergeMode = true;
|
||||
mc.FontDataOwnedByAtlas = false;
|
||||
fa->AddFontFromMemoryTTF(data[i], (int)size, 26.0f * scale, &mc, ranges[i].Data);
|
||||
}
|
||||
vk_queue_lock(); // the upload submits on the queue and waits for it
|
||||
int ok = ImGui_ImplVulkan_CreateFontsTexture();
|
||||
vk_queue_unlock();
|
||||
fa->ClearInputData(); // the glyphs are in the texture: the font files and the pixels are not needed again
|
||||
fa->ClearTexData();
|
||||
for (uint8_t *d : data) free(d);
|
||||
rt_log("menu: font atlas at %.1f px, language names from %d of %d system fonts", 26.0f * scale, merged, (int)N);
|
||||
g_font_scale = ok ? scale : 0;
|
||||
return ok;
|
||||
}
|
||||
|
||||
extern "C" void menu_vk_release(void) {
|
||||
if (g_ctx_ok) vk_down();
|
||||
}
|
||||
|
||||
// ---- test hooks
|
||||
// TOTK_MENU_TEST=<frame>[:<frames per page>]: at that presented frame the menu opens on its first tab; each tab stays
|
||||
// <frames per page> frames (default 30) and its last frame's swapchain image goes to TOTK_MENU_TEST_DIR (default: the
|
||||
// working directory) as menu-test-<frame>-<page>.png; after the last tab the menu closes.
|
||||
// TOTK_MENU_TEST_SET=<frame>:<key>=<value>[,<key>=<value>...][;<frame>:...]: cfg_set of each key (TOTK_ prefix
|
||||
// optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by
|
||||
// the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note).
|
||||
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_COUNT };
|
||||
enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 };
|
||||
struct TestSet { uint64_t frame; char key[64], value[64]; };
|
||||
static struct {
|
||||
int parsed;
|
||||
uint64_t at; // TOTK_MENU_TEST frame; 0 none
|
||||
uint64_t per_page;
|
||||
uint64_t opened; // the frame the hook opened the menu; 0 not yet
|
||||
int page; // the tab being shot; -1 none
|
||||
TestSet sets[TEST_SETS];
|
||||
int n_sets, next_set; // TOTK_MENU_TEST_SET, in frame order
|
||||
} g_test = {0, 0, 0, 0, -1, {}, 0, 0};
|
||||
|
||||
static void test_parse(void) {
|
||||
g_test.parsed = 1;
|
||||
if (const char *e = cfg_get("TOTK_MENU_TEST")) {
|
||||
long long at = atoll(e), per = 0;
|
||||
if (const char *c = strchr(e, ':')) per = atoll(c + 1);
|
||||
g_test.at = at > 0 ? (uint64_t)at : 0;
|
||||
g_test.per_page = per > 0 ? (uint64_t)per : TEST_PAGE_FRAMES;
|
||||
}
|
||||
const char *s = cfg_get("TOTK_MENU_TEST_SET");
|
||||
while (s && *s) { // groups "<frame>:<key>=<value>,..." separated by ';'
|
||||
char *end;
|
||||
unsigned long long f = strtoull(s, &end, 10);
|
||||
if (*end != ':') break;
|
||||
s = end + 1;
|
||||
while (*s && *s != ';' && g_test.n_sets < TEST_SETS) {
|
||||
size_t n = strcspn(s, ",;");
|
||||
const char *eq = (const char *)memchr(s, '=', n);
|
||||
if (eq) {
|
||||
TestSet &t = g_test.sets[g_test.n_sets++];
|
||||
t.frame = f;
|
||||
int kn = (int)(eq - s), vn = (int)(s + n - eq - 1);
|
||||
snprintf(t.key, sizeof t.key, "%s%.*s", strncmp(s, "TOTK_", 5) ? "TOTK_" : "", kn, s);
|
||||
snprintf(t.value, sizeof t.value, "%.*s", vn, eq + 1);
|
||||
}
|
||||
s += n;
|
||||
if (*s == ',') s++;
|
||||
}
|
||||
while (*s && *s != ';') s++;
|
||||
if (*s == ';') s++;
|
||||
}
|
||||
if (g_test.at || g_test.n_sets)
|
||||
rt_log("menu: test hook: open at frame %llu, %llu frames per page, %d settings changes",
|
||||
(unsigned long long)g_test.at, (unsigned long long)g_test.per_page, g_test.n_sets);
|
||||
}
|
||||
|
||||
static void test_apply_sets(uint64_t frame) {
|
||||
for (; g_test.next_set < g_test.n_sets && g_test.sets[g_test.next_set].frame <= frame; g_test.next_set++) {
|
||||
const TestSet &t = g_test.sets[g_test.next_set];
|
||||
rt_log("menu: test hook: frame %llu: %s=%s", (unsigned long long)frame, t.key, t.value);
|
||||
if (!strcmp(t.key, "TOTK_SAVE")) rt_log("menu: test hook: cfg_save %s", cfg_save() ? "wrote" : "failed");
|
||||
else cfg_set(t.key, t.value);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the lists the Screen and Game tabs build
|
||||
enum { MAX_GPUS = 8 };
|
||||
static char g_gpu_names[MAX_GPUS][VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
|
||||
static int g_gpu_n = -1; // -1: not listed yet
|
||||
|
||||
// The Vulkan devices in vkEnumeratePhysicalDevices order, which TOTK_GPU_INDEX counts in (vk_device.c pick_device).
|
||||
static void list_gpus(VkInstance inst) {
|
||||
if (g_gpu_n >= 0) return;
|
||||
VkPhysicalDevice pd[MAX_GPUS];
|
||||
uint32_t n = MAX_GPUS;
|
||||
if (vkEnumeratePhysicalDevices(inst, &n, pd) < 0) n = 0; // VK_INCOMPLETE keeps the first MAX_GPUS
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkPhysicalDeviceProperties p;
|
||||
vkGetPhysicalDeviceProperties(pd[i], &p);
|
||||
snprintf(g_gpu_names[i], sizeof g_gpu_names[i], "%s", p.deviceName);
|
||||
}
|
||||
g_gpu_n = (int)n;
|
||||
}
|
||||
|
||||
// Window sizes: the common 16:9 sizes that fit the monitor, the 1920x1080 default and the current size.
|
||||
static const int kSizes[][2] = {{1280, 720}, {1366, 768}, {1600, 900}, {1920, 1080}, {2560, 1440}, {3200, 1800},
|
||||
{3840, 2160}};
|
||||
enum { MAX_SIZES = sizeof kSizes / sizeof *kSizes + 1 };
|
||||
|
||||
static void row_window_size(void) {
|
||||
int sz[MAX_SIZES][2], n = 0, mw = 0, mh = 0, cw = 0, ch = 0;
|
||||
int have = gfx_window_monitor_size(&mw, &mh);
|
||||
int cur_ok = sscanf(cfg_value("TOTK_WINDOW_SIZE"), "%dx%d", &cw, &ch) == 2;
|
||||
bool listed = false;
|
||||
for (size_t i = 0; i < sizeof kSizes / sizeof *kSizes; i++) {
|
||||
int w = kSizes[i][0], h = kSizes[i][1];
|
||||
bool cur = cur_ok && w == cw && h == ch;
|
||||
if (have && (w > mw || h > mh) && !cur && !(w == 1920 && h == 1080)) continue;
|
||||
listed |= cur;
|
||||
sz[n][0] = w, sz[n][1] = h, n++;
|
||||
}
|
||||
if (cur_ok && !listed) { // the current size where its area puts it
|
||||
int at = n;
|
||||
while (at > 0 && (long)sz[at - 1][0] * sz[at - 1][1] > (long)cw * ch) at--;
|
||||
memmove(sz[at + 1], sz[at], sizeof sz[0] * (n - at));
|
||||
sz[at][0] = cw, sz[at][1] = ch, n++;
|
||||
}
|
||||
char vals[MAX_SIZES][24], shown[MAX_SIZES][32];
|
||||
const char *pv[MAX_SIZES], *pn[MAX_SIZES];
|
||||
for (int i = 0; i < n; i++) {
|
||||
snprintf(vals[i], sizeof vals[i], "%dx%d", sz[i][0], sz[i][1]);
|
||||
snprintf(shown[i], sizeof shown[i], "%d × %d", sz[i][0], sz[i][1]); // U+00D7, the multiplication sign
|
||||
pv[i] = vals[i];
|
||||
pn[i] = shown[i];
|
||||
}
|
||||
opt_choice_list("TOTK_WINDOW_SIZE", UI_MENU_WINDOW_SIZE, pv, pn, n, UI_MENU_WINDOW_SIZE_DESC);
|
||||
}
|
||||
|
||||
static void row_gpu(void) {
|
||||
const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1];
|
||||
char idx[MAX_GPUS][4];
|
||||
vals[0] = "";
|
||||
names[0] = menu_text(UI_MENU_GPU_AUTO);
|
||||
for (int i = 0; i < g_gpu_n; i++) {
|
||||
snprintf(idx[i], sizeof idx[i], "%d", i);
|
||||
vals[i + 1] = idx[i];
|
||||
names[i + 1] = g_gpu_names[i];
|
||||
}
|
||||
opt_choice_list("TOTK_GPU_INDEX", UI_MENU_GPU, vals, names, g_gpu_n + 1, UI_MENU_GPU_DESC);
|
||||
}
|
||||
|
||||
// The game language: one entry per catalog language (a Switch code that names it), each language under its own name.
|
||||
static void row_game_lang(void) {
|
||||
static const struct { const char *code; UiTextId name; } langs[] = {
|
||||
{"en-US", UI_MENU_LANGNAME_EN}, {"ja", UI_MENU_LANGNAME_JA}, {"fr", UI_MENU_LANGNAME_FR},
|
||||
{"de", UI_MENU_LANGNAME_DE}, {"it", UI_MENU_LANGNAME_IT}, {"es", UI_MENU_LANGNAME_ES},
|
||||
{"nl", UI_MENU_LANGNAME_NL}, {"pt", UI_MENU_LANGNAME_PT}, {"ru", UI_MENU_LANGNAME_RU},
|
||||
{"zh-CN", UI_MENU_LANGNAME_ZH_HANS}, {"zh-TW", UI_MENU_LANGNAME_ZH_HANT}, {"ko", UI_MENU_LANGNAME_KO},
|
||||
};
|
||||
enum { N = sizeof langs / sizeof *langs + 1 };
|
||||
const char *vals[N], *names[N];
|
||||
vals[0] = "";
|
||||
names[0] = menu_text(UI_MENU_GAME_LANG_AUTO);
|
||||
const char *now = cfg_value("TOTK_LANG");
|
||||
int cur = *now ? -1 : 0;
|
||||
for (int i = 1; i < N; i++) {
|
||||
vals[i] = langs[i - 1].code;
|
||||
names[i] = menu_text(langs[i - 1].name);
|
||||
if (*now && !strcmp(ui_text_lang(now), ui_text_lang(vals[i]))) cur = i; // en-GB is English too
|
||||
}
|
||||
opt_choice_list("TOTK_LANG", UI_MENU_GAME_LANG, vals, names, N, UI_MENU_GAME_LANG_DESC, cur);
|
||||
}
|
||||
|
||||
// ---- the tabs
|
||||
static void tab_screen(float scale) {
|
||||
opt_begin("##screen", scale);
|
||||
opt_toggle("TOTK_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC);
|
||||
row_window_size();
|
||||
static const UiTextId present[] = {UI_MENU_PRESENT_MAILBOX, UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_IMMEDIATE};
|
||||
opt_choice("TOTK_VK_PRESENT", UI_MENU_PRESENT, present, 3, UI_MENU_PRESENT_DESC);
|
||||
row_gpu();
|
||||
static const UiTextId perf[] = {UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL};
|
||||
ImGui::BeginDisabled(); // no overlay draws yet (docs/backlog.md, in-game menu)
|
||||
opt_choice("TOTK_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC);
|
||||
ImGui::EndDisabled();
|
||||
opt_end();
|
||||
}
|
||||
|
||||
static void tab_game(float scale) {
|
||||
opt_begin("##game", scale);
|
||||
static const UiTextId fps[] = {UI_MENU_FPS_30, UI_MENU_FPS_60}; // values 0|1
|
||||
opt_choice("TOTK_FPS60", UI_MENU_FPS60, fps, 2, UI_MENU_FPS60_DESC);
|
||||
opt_toggle("TOTK_REALTIME", UI_MENU_REALTIME, UI_MENU_REALTIME_DESC);
|
||||
opt_toggle("TOTK_CLOTH_REALTIME", UI_MENU_CLOTH_REALTIME, UI_MENU_CLOTH_REALTIME_DESC);
|
||||
opt_toggle("TOTK_HIGHFPS_FIX", UI_MENU_HIGHFPS_FIX, UI_MENU_HIGHFPS_FIX_DESC);
|
||||
row_game_lang();
|
||||
static const UiTextId mode[] = {UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD};
|
||||
opt_choice("TOTK_OPERATION_MODE", UI_MENU_OPERATION_MODE, mode, 2, UI_MENU_OPERATION_MODE_DESC);
|
||||
opt_end();
|
||||
}
|
||||
|
||||
static void tab_sound(float scale) {
|
||||
opt_begin("##sound", scale);
|
||||
opt_slider("TOTK_VOLUME", UI_MENU_VOLUME, 0, 100, UI_MENU_VOLUME_DESC, 5, "%.0f %%");
|
||||
opt_end();
|
||||
}
|
||||
|
||||
static void tab_controls(float scale) {
|
||||
opt_begin("##controls", scale);
|
||||
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_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f");
|
||||
opt_end();
|
||||
}
|
||||
|
||||
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);
|
||||
opt_end();
|
||||
}
|
||||
|
||||
static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
|
||||
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU};
|
||||
static int g_tab; // the tab shown
|
||||
static int g_tab_request = -1; // select this tab at the next layout; -1 none
|
||||
static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none
|
||||
|
||||
// ---- the window: title, tabs (L / R or Q / E switch), the page, and the bottom row with "Continue" and "Quit game".
|
||||
// B on the gamepad and Esc close it.
|
||||
static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
||||
ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(0, 0), ImVec2((float)w, (float)h), IM_COL32(0, 0, 0, 120));
|
||||
float ww = fminf(w * 0.88f, 1400 * scale), wh = fminf(h * 0.86f, 820 * scale);
|
||||
ImGui::SetNextWindowPos(ImVec2(w * 0.5f, h * 0.5f), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
|
||||
ImGui::SetNextWindowSize(ImVec2(ww, wh), ImGuiCond_Always);
|
||||
ImGui::Begin("##menu", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove |
|
||||
ImGuiWindowFlags_NoSavedSettings);
|
||||
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(UI_MENU_TITLE));
|
||||
|
||||
int step = ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false) || ImGui::IsKeyPressed(ImGuiKey_E, false) ? 1
|
||||
: ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false) || ImGui::IsKeyPressed(ImGuiKey_Q, false) ? -1
|
||||
: 0;
|
||||
if (step) g_tab_request = (g_tab + step + TAB_COUNT) % TAB_COUNT;
|
||||
if (g_tab_request >= 0) g_focus_page = g_tab_request; // the new page's first row takes the cursor
|
||||
|
||||
const ImGuiStyle &st = ImGui::GetStyle();
|
||||
float bottom = ImGui::GetFrameHeight() + st.ItemSpacing.y * 2;
|
||||
if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_NoTabListScrollingButtons)) {
|
||||
for (int k = 0; k < TAB_COUNT; k++) {
|
||||
char label[128];
|
||||
snprintf(label, sizeof label, " %s ###tab%d", menu_text(kTabNames[k]), k); // the id stays per language
|
||||
if (!ImGui::BeginTabItem(label, nullptr, g_tab_request == k ? ImGuiTabItemFlags_SetSelected : 0)) continue;
|
||||
g_tab = k;
|
||||
if (g_focus_page == k) {
|
||||
opt_focus_first();
|
||||
g_focus_page = -1;
|
||||
}
|
||||
ImGui::Spacing();
|
||||
ImGui::BeginChild("##page", ImVec2(0, -bottom), ImGuiChildFlags_NavFlattened);
|
||||
switch (k) {
|
||||
case TAB_SCREEN: tab_screen(scale); break;
|
||||
case TAB_GAME: tab_game(scale); break;
|
||||
case TAB_SOUND: tab_sound(scale); break;
|
||||
case TAB_CONTROLS: tab_controls(scale); break;
|
||||
case TAB_MENU: tab_menu(scale); break;
|
||||
}
|
||||
ImGui::EndChild();
|
||||
ImGui::EndTabItem();
|
||||
}
|
||||
g_tab_request = -1;
|
||||
ImGui::EndTabBar();
|
||||
}
|
||||
|
||||
// bottom row: the save status on the left, the two buttons on the right
|
||||
ImGui::Spacing();
|
||||
float y = ImGui::GetCursorPosY();
|
||||
if (!cfg_last_save_ok()) { // stays until a save succeeds; the settings hold for the session
|
||||
ImGui::SetCursorPosY(y + st.FramePadding.y);
|
||||
ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", menu_text(UI_MENU_SAVE_FAILED));
|
||||
}
|
||||
const char *cont = menu_text(UI_MENU_CONTINUE), *quit = menu_text(UI_MENU_QUIT);
|
||||
float bw = fmaxf(ImGui::CalcTextSize(cont).x, ImGui::CalcTextSize(quit).x) + st.FramePadding.x * 4;
|
||||
ImGui::SetCursorPos(ImVec2(ImGui::GetWindowWidth() - st.WindowPadding.x - bw * 2 - st.ItemSpacing.x, y));
|
||||
if (ImGui::Button(cont, ImVec2(bw, 0))) set_open(0);
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Button(quit, ImVec2(bw, 0))) gfx_window_request_close();
|
||||
if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) set_open(0);
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
static int g_save_pending; // a changed setting still waits for its write to totk.ini (opt_save_tick)
|
||||
|
||||
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
|
||||
*shot = NULL;
|
||||
if (!g_test.parsed) test_parse();
|
||||
if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame);
|
||||
if (!g_open.load(std::memory_order_relaxed)) {
|
||||
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now
|
||||
if (!g_test.at || g_test.opened || frame < g_test.at) return 0;
|
||||
g_test.opened = frame;
|
||||
g_test.page = 0;
|
||||
g_tab_request = 0;
|
||||
set_open(1);
|
||||
}
|
||||
if (g_failed_flag()) {
|
||||
set_open(0);
|
||||
return 0;
|
||||
}
|
||||
uint64_t t0 = plat_now_ns();
|
||||
if (!g_ctx_ok) make_context();
|
||||
float scale = menu_scale(t->height);
|
||||
if (!vk_up(t) || (g_font_scale != scale && !fonts_up(scale))) {
|
||||
rt_log("menu: Dear ImGui Vulkan back end set-up failed; the menu stays closed");
|
||||
g_failed.store(1);
|
||||
set_open(0);
|
||||
return 0;
|
||||
}
|
||||
if (g_style_scale != scale) {
|
||||
ImGui::GetStyle() = g_base_style;
|
||||
ImGui::GetStyle().ScaleAllSizes(scale);
|
||||
g_style_scale = scale;
|
||||
}
|
||||
list_gpus(t->instance);
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
int reset = g_reset.exchange(0);
|
||||
if (reset) {
|
||||
io.ClearInputKeys();
|
||||
io.ClearInputMouse();
|
||||
g_last_ns = 0;
|
||||
g_focus_page = g_tab_request >= 0 ? g_tab_request : g_tab; // opening: the first row has the cursor
|
||||
}
|
||||
io.DisplaySize = ImVec2((float)t->width, (float)t->height);
|
||||
double dt = g_last_ns ? (t0 - g_last_ns) / 1e9 : 1 / 60.0;
|
||||
io.DeltaTime = (float)(dt < 1e-4 ? 1e-4 : dt > 0.1 ? 0.1 : dt);
|
||||
g_last_ns = t0;
|
||||
if (g_test.page < 0) {
|
||||
drain_events(io);
|
||||
pad_events(io, reset);
|
||||
} else { // the test hook's pages: the user's input in a background test window must not change settings
|
||||
plat_mutex_lock(&ev_lock);
|
||||
ev_n = 0;
|
||||
plat_mutex_unlock(&ev_lock);
|
||||
}
|
||||
ImGui_ImplVulkan_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
layout_menu(t->width, t->height, scale);
|
||||
ImGui::Render();
|
||||
g_save_pending = opt_save_tick(0);
|
||||
g_cost_ns += plat_now_ns() - t0;
|
||||
if (g_test.page >= 0 && frame >= g_test.opened + g_test.per_page * (uint64_t)(g_test.page + 1)) {
|
||||
static char path[512]; // this frame's image goes to a file; then the next tab, or the menu closes
|
||||
const char *dir = cfg_get("TOTK_MENU_TEST_DIR");
|
||||
snprintf(path, sizeof path, "%s/menu-test-%llu-%d.png", dir ? dir : ".", (unsigned long long)frame, g_test.page);
|
||||
*shot = path;
|
||||
if (++g_test.page == TAB_COUNT) {
|
||||
g_test.page = -1;
|
||||
set_open(0); // the next frame lays out nothing
|
||||
} else {
|
||||
g_tab_request = g_test.page;
|
||||
}
|
||||
}
|
||||
return ImGui::GetDrawData()->TotalVtxCount > 0;
|
||||
}
|
||||
|
||||
extern "C" void menu_overlay_draw(VkCommandBuffer cb) {
|
||||
uint64_t t0 = plat_now_ns();
|
||||
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cb);
|
||||
g_cost_ns += plat_now_ns() - t0;
|
||||
if (++g_cost_frames == 600) {
|
||||
rt_log("menu: %.3f ms CPU per open frame (layout and recording, mean of 600)", g_cost_ns / 600 / 1e6);
|
||||
g_cost_ns = g_cost_frames = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// The in-game menu (ui/menu.cpp, Dear ImGui) and its seams to the platform side: the window and its input (ui/menu_win.cpp
|
||||
// on Windows; an SDL3 window gets its own adapter later), the gamepad (input_pad_read, input.h) and the present path
|
||||
// (gfx_window.c). The menu core calls no window system: events come in through menu_event_*, the drawing happens in the
|
||||
// present path's command buffer.
|
||||
//
|
||||
// F1 or Esc on the keyboard and Minus and Plus held together (consumed in poll_merged, input_menu_gate in input.h) open it;
|
||||
// F1, Esc, B or "Continue" close it. While it is open the game gets no input (input_menu, input.h) and keeps running; the
|
||||
// cursor is released from the mouse camera. Tabs Screen, Game, Sound, Controls and Menu (L / R or Q / E switch them) hold
|
||||
// option rows (ui/option_rows.h) over the cfg settings; the bottom row has "Continue" and "Quit game".
|
||||
// Test hooks (ui/menu.cpp): TOTK_MENU_TEST=<frame>[:<frames per page>] opens the menu at that presented frame and saves
|
||||
// one swapchain shot per tab into TOTK_MENU_TEST_DIR; TOTK_MENU_TEST_SET=<frame>:<key>=<value>[,...][;...] sets settings
|
||||
// at given frames without input (SAVE=1 writes totk.ini).
|
||||
//
|
||||
// Threads: the event functions are called by the window thread, menu_toggle by whichever thread polls the pad, the
|
||||
// overlay functions by the present path under its lock. ImGui itself runs on the present path only.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// ---- state, any thread
|
||||
int menu_is_open(void);
|
||||
void menu_toggle(void); // F1 / Esc on the keyboard, Minus+Plus on the pad
|
||||
|
||||
// ---- events from the window adapter, used only while the menu is open. key: an ImGuiKey; coordinates in pixels of the
|
||||
// window's client area, which is the swapchain image.
|
||||
void menu_event_key(int key, int down);
|
||||
void menu_event_mouse_pos(float x, float y);
|
||||
void menu_event_mouse_button(int button, int down); // 0 left, 1 right, 2 middle
|
||||
void menu_event_wheel(float dx, float dy);
|
||||
void menu_event_focus(int focused);
|
||||
|
||||
// ---- the overlay, drawn into the swapchain image after the game image (gfx_window.c, present lock held)
|
||||
typedef struct {
|
||||
VkInstance instance;
|
||||
VkPhysicalDevice phys;
|
||||
VkDevice device;
|
||||
uint32_t queue_family;
|
||||
VkQueue queue; // submissions take vk_queue_lock
|
||||
VkFormat format; // of the swapchain image, a colour attachment
|
||||
uint32_t width, height;
|
||||
} MenuTarget;
|
||||
// Lays out this frame's overlay; 1 when there is something to draw. frame: the presented frame (0 unknown). *shot: a
|
||||
// path when the test hook wants this frame's swapchain image saved, else NULL. The first open starts ImGui's Vulkan
|
||||
// back end and uploads the font. With the menu closed it costs two loads and a compare.
|
||||
int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot);
|
||||
// Records the frame menu_overlay_frame laid out into cb, which is inside dynamic rendering on the image.
|
||||
void menu_overlay_draw(VkCommandBuffer cb);
|
||||
void menu_vk_release(void); // before the device goes away (gfx_window_release_vk)
|
||||
|
||||
// ---- what the menu asks of the platform side (gfx_window.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
|
||||
int gfx_window_monitor_size(int *w, int *h); // pixels of the monitor the window is on; 0 when unknown
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,81 @@
|
||||
// Win32 adapter of the in-game menu: window messages to menu events (menu.h). The only Win32 code of the menu; an SDL3
|
||||
// window gets its own adapter later. Window thread.
|
||||
//
|
||||
// F1 opens and closes the menu, Esc opens it (with the menu open, Esc goes to the menu, which closes). Esc also releases
|
||||
// the cursor (input_window_msg runs first; closing the menu gives the capture back). While the menu is open, its keys,
|
||||
// the mouse and focus changes go to it; the game polls the keyboard on its own (input_win.c) and gets nothing while the
|
||||
// menu is open (input_menu).
|
||||
#include <windows.h>
|
||||
#include <windowsx.h>
|
||||
|
||||
#include "imgui.h"
|
||||
|
||||
extern "C" {
|
||||
#include "input.h"
|
||||
#include "ui/menu.h"
|
||||
}
|
||||
|
||||
static ImGuiKey key_of(WPARAM vk) {
|
||||
switch (vk) {
|
||||
case VK_UP: return ImGuiKey_UpArrow;
|
||||
case VK_DOWN: return ImGuiKey_DownArrow;
|
||||
case VK_LEFT: return ImGuiKey_LeftArrow;
|
||||
case VK_RIGHT: return ImGuiKey_RightArrow;
|
||||
case VK_RETURN: return ImGuiKey_Enter;
|
||||
case VK_SPACE: return ImGuiKey_Space;
|
||||
case VK_ESCAPE: return ImGuiKey_Escape;
|
||||
case VK_TAB: return ImGuiKey_Tab;
|
||||
case VK_BACK: return ImGuiKey_Backspace;
|
||||
case VK_HOME: return ImGuiKey_Home;
|
||||
case VK_END: return ImGuiKey_End;
|
||||
case VK_PRIOR: return ImGuiKey_PageUp;
|
||||
case VK_NEXT: return ImGuiKey_PageDown;
|
||||
case VK_SHIFT: return ImGuiKey_LeftShift;
|
||||
case VK_CONTROL: return ImGuiKey_LeftCtrl;
|
||||
case 'Q': return ImGuiKey_Q; // previous tab
|
||||
case 'E': return ImGuiKey_E; // next tab
|
||||
default: return ImGuiKey_None;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int menu_window_msg(HWND h, UINT m, WPARAM w, LPARAM l, LRESULT *res) {
|
||||
(void)h;
|
||||
switch (m) {
|
||||
case WM_KEYDOWN:
|
||||
case WM_SYSKEYDOWN:
|
||||
// bit 30: auto-repeat
|
||||
// Esc with the menu open (opened by F1 too) is not a toggle here: it goes to the menu, which closes itself
|
||||
if (!(l & (1 << 30)) && (w == VK_F1 || (w == VK_ESCAPE && !menu_is_open()))) {
|
||||
menu_toggle();
|
||||
*res = 0;
|
||||
return 1;
|
||||
}
|
||||
[[fallthrough]];
|
||||
case WM_KEYUP:
|
||||
case WM_SYSKEYUP:
|
||||
if (!menu_is_open()) return 0;
|
||||
if (ImGuiKey k = key_of(w)) menu_event_key(k, m == WM_KEYDOWN || m == WM_SYSKEYDOWN);
|
||||
return 0; // F11 and the system keys keep working
|
||||
case WM_MOUSEMOVE:
|
||||
if (menu_is_open()) menu_event_mouse_pos((float)GET_X_LPARAM(l), (float)GET_Y_LPARAM(l));
|
||||
return 0;
|
||||
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
|
||||
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
|
||||
case WM_MBUTTONDOWN: case WM_MBUTTONUP: {
|
||||
if (!menu_is_open()) return 0;
|
||||
int b = m == WM_LBUTTONDOWN || m == WM_LBUTTONUP ? 0 : m == WM_RBUTTONDOWN || m == WM_RBUTTONUP ? 1 : 2;
|
||||
int down = m == WM_LBUTTONDOWN || m == WM_RBUTTONDOWN || m == WM_MBUTTONDOWN;
|
||||
menu_event_mouse_pos((float)GET_X_LPARAM(l), (float)GET_Y_LPARAM(l));
|
||||
menu_event_mouse_button(b, down);
|
||||
return 0;
|
||||
}
|
||||
case WM_MOUSEWHEEL:
|
||||
if (menu_is_open()) menu_event_wheel(0, (float)GET_WHEEL_DELTA_WPARAM(w) / WHEEL_DELTA);
|
||||
return 0;
|
||||
case WM_SETFOCUS:
|
||||
case WM_KILLFOCUS:
|
||||
menu_event_focus(m == WM_SETFOCUS);
|
||||
return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Two-pane settings pages (option_rows.h): rows on the left, the selected or hovered row's description on the right.
|
||||
//
|
||||
// Adapted from SavageWindRecomp's runtime/ui/option_rows.mm (https://github.com/Revivedx/SavageWindRecomp @
|
||||
// 575ad88e02f9a89a9a885d90039d48af33c982f4, MIT, Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors,
|
||||
// Copyright (c) 2026 Peiikai): the row look, the two panes, the left / right stepping and the hold speed-up. The rows
|
||||
// read and write cfg keys instead of a settings struct, take their text from the menu catalog (menu_text), and show
|
||||
// the default, "after restart" and environment notes; the text field, radio and on-screen keyboard rows are not ported.
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_internal.h" // SetKeyOwner, SetFocusID, NavCursorVisible
|
||||
|
||||
#include "ui/option_rows.h"
|
||||
|
||||
extern "C" {
|
||||
#include "cfg.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui_text.h"
|
||||
// host.h pulls in cpu.h, which is C only: the one function needed from it, as declared there.
|
||||
void rt_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
}
|
||||
|
||||
static const ImU32 kGold = IM_COL32(236, 194, 84, 255);
|
||||
static const ImU32 kDim = IM_COL32(150, 150, 140, 255);
|
||||
static const ImU32 kGrey = IM_COL32(110, 110, 102, 255);
|
||||
|
||||
static float g_scale = 1;
|
||||
static bool g_focus_req, g_take_first; // opt_focus_first: requested / this page's first row takes it
|
||||
static bool g_held; // the last row's left / right has been held a while (steppers go faster)
|
||||
|
||||
// The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown.
|
||||
struct Desc { char text[512]; };
|
||||
static Desc g_hover, g_focus, g_first, g_shown;
|
||||
|
||||
static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m) {
|
||||
int n = snprintf(d.text, sizeof d.text, "%s", menu_text(desc));
|
||||
if (n < 0 || n >= (int)sizeof d.text) return;
|
||||
if (cfg_from_env(key))
|
||||
snprintf(d.text + n, sizeof d.text - n, "\n\n%s %s", menu_text(UI_MENU_SET_BY_ENV), key);
|
||||
else if (m && !m->live)
|
||||
snprintf(d.text + n, sizeof d.text - n, "\n\n%s", menu_text(UI_MENU_AFTER_RESTART));
|
||||
}
|
||||
|
||||
void opt_focus_first(void) { g_focus_req = true; }
|
||||
|
||||
void opt_begin(const char *id, float scale) {
|
||||
g_scale = scale;
|
||||
g_take_first = g_focus_req;
|
||||
g_focus_req = false;
|
||||
if (g_take_first) ImGui::NavMoveRequestCancel(); // this frame's move goes to the first row instead
|
||||
g_hover.text[0] = g_focus.text[0] = g_first.text[0] = 0;
|
||||
ImVec2 avail = ImGui::GetContentRegionAvail();
|
||||
ImGui::PushID(id);
|
||||
ImGui::BeginChild("##rows", ImVec2(avail.x * 0.58f, avail.y), ImGuiChildFlags_NavFlattened);
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 5 * scale));
|
||||
}
|
||||
|
||||
void opt_end(void) {
|
||||
ImGui::PopStyleVar();
|
||||
ImGui::EndChild();
|
||||
// the hovered row (mouse) wins, else the selected one (controller), else the last shown, else the first row
|
||||
if (g_hover.text[0]) g_shown = g_hover;
|
||||
else if (g_focus.text[0]) g_shown = g_focus;
|
||||
else if (!g_shown.text[0]) g_shown = g_first;
|
||||
ImGui::SameLine(0, 0);
|
||||
ImVec2 p = ImGui::GetCursorScreenPos(), avail = ImGui::GetContentRegionAvail();
|
||||
float gap = 24 * g_scale;
|
||||
ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + gap * 0.5f, p.y), ImVec2(p.x + gap * 0.5f, p.y + avail.y),
|
||||
IM_COL32(236, 194, 84, 110), 1.0f);
|
||||
ImGui::SetCursorScreenPos(ImVec2(p.x + gap, p.y));
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(14 * g_scale, 6 * g_scale));
|
||||
ImGui::BeginChild("##desc", ImVec2(0, avail.y), ImGuiChildFlags_AlwaysUseWindowPadding, ImGuiWindowFlags_NoNav);
|
||||
ImGui::PopStyleVar();
|
||||
ImGui::PushTextWrapPos(0);
|
||||
ImGui::TextUnformatted(g_shown.text);
|
||||
ImGui::PopTextWrapPos();
|
||||
ImGui::EndChild();
|
||||
ImGui::PopID();
|
||||
}
|
||||
|
||||
// What a row shows besides its label.
|
||||
struct RowView {
|
||||
const char *value; // right side; "" for none
|
||||
bool is_default; // the value is the setting's default: the "default" mark, the value not highlighted
|
||||
bool arrows; // a stepper: < value >, the arrows click too
|
||||
};
|
||||
|
||||
// One row: draws it, handles A / click and left / right while selected. Returns 2 (A / click), -1 / +1 (left / right) or
|
||||
// 0; always 0 for a row the environment fixes (greyed out, still selectable so its description shows).
|
||||
static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) {
|
||||
const CfgMeta *m = cfg_meta(key);
|
||||
bool off = cfg_from_env(key) != 0;
|
||||
ImGui::PushID(key);
|
||||
ImVec2 p = ImGui::GetCursorScreenPos();
|
||||
float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x, h = fs * 2.2f;
|
||||
ImGui::PushStyleColor(ImGuiCol_NavCursor, ImVec4(0, 0, 0, 0)); // the row's own border shows the selection
|
||||
bool clicked = ImGui::InvisibleButton("##row", ImVec2(w, h), ImGuiButtonFlags_EnableNav);
|
||||
ImGui::PopStyleColor();
|
||||
if (g_take_first) {
|
||||
g_take_first = false;
|
||||
ImGui::SetFocusID(ImGui::GetItemID(), ImGui::GetCurrentWindow());
|
||||
ImGui::SetNavCursorVisible(true);
|
||||
ImGui::SetScrollHereY(0);
|
||||
}
|
||||
bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible;
|
||||
int step = clicked && !off ? 2 : 0;
|
||||
g_held = false;
|
||||
if (foc && !off) {
|
||||
if (ImGui::IsKeyPressed(ImGuiKey_GamepadDpadLeft) || ImGui::IsKeyPressed(ImGuiKey_GamepadLStickLeft) ||
|
||||
ImGui::IsKeyPressed(ImGuiKey_LeftArrow))
|
||||
step = -1;
|
||||
if (ImGui::IsKeyPressed(ImGuiKey_GamepadDpadRight) || ImGui::IsKeyPressed(ImGuiKey_GamepadLStickRight) ||
|
||||
ImGui::IsKeyPressed(ImGuiKey_RightArrow))
|
||||
step = 1;
|
||||
static const ImGuiKey steps[] = {ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_LeftArrow,
|
||||
ImGuiKey_RightArrow, ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight};
|
||||
for (ImGuiKey k : steps)
|
||||
if (ImGui::GetKeyData(k)->DownDuration > 1.0f) g_held = true;
|
||||
// left and right belong to the row (navigation would otherwise move sideways into the description pane); the
|
||||
// first four of steps, the stick stays with navigation
|
||||
for (int i = 0; i < 4; i++) ImGui::SetKeyOwner(steps[i], ImGui::GetItemID());
|
||||
}
|
||||
if (foc) desc_set(g_focus, desc, key, m);
|
||||
if (hov) desc_set(g_hover, desc, key, m);
|
||||
if (!g_first.text[0]) desc_set(g_first, desc, key, m);
|
||||
|
||||
ImDrawList *dl = ImGui::GetWindowDrawList();
|
||||
ImFont *font = ImGui::GetFont();
|
||||
float r = 9 * g_scale, pad = 16 * g_scale, small = fs * 0.72f;
|
||||
dl->AddRectFilled(p, ImVec2(p.x + w, p.y + h), hov || foc ? IM_COL32(255, 255, 255, 22) : IM_COL32(0, 0, 0, 40), r);
|
||||
dl->AddRect(p, ImVec2(p.x + w, p.y + h),
|
||||
hov || foc ? (off ? IM_COL32(236, 194, 84, 120) : kGold) : IM_COL32(255, 255, 255, off ? 18 : 38), r, 0,
|
||||
hov || foc ? 2.0f : 1.0f);
|
||||
float ty = p.y + fs * 0.25f, ny = p.y + fs * 1.3f; // the label line and the note line under it
|
||||
float right = p.x + w - pad; // the value's right edge
|
||||
float value_left = right;
|
||||
if (v.arrows && v.value[0]) { // < value >, drawn (the font has no arrow glyphs); a click on one steps
|
||||
float aw = fs * 0.42f, gap = fs * 0.55f, cy = ty + fs * 0.52f;
|
||||
float rx = right - aw, lx = rx - gap - ImGui::CalcTextSize(v.value).x - gap - aw;
|
||||
ImU32 ac = off ? kGrey : hov || foc ? kGold : IM_COL32(170, 170, 160, 255);
|
||||
dl->AddTriangleFilled(ImVec2(lx, cy), ImVec2(lx + aw, cy - aw * 0.75f), ImVec2(lx + aw, cy + aw * 0.75f), ac);
|
||||
dl->AddTriangleFilled(ImVec2(rx + aw, cy), ImVec2(rx, cy - aw * 0.75f), ImVec2(rx, cy + aw * 0.75f), ac);
|
||||
if (clicked && !off) {
|
||||
float mx = ImGui::GetIO().MousePos.x;
|
||||
if (mx >= lx - gap && mx <= lx + aw + gap) step = -1;
|
||||
else if (mx >= rx - gap && mx <= rx + aw + gap) step = 1;
|
||||
}
|
||||
right = rx - gap;
|
||||
value_left = lx;
|
||||
}
|
||||
if (v.value[0]) {
|
||||
float vx = right - ImGui::CalcTextSize(v.value).x;
|
||||
dl->AddText(ImVec2(vx, ty), off ? kGrey : v.is_default ? IM_COL32(205, 205, 195, 255) : IM_COL32(255, 255, 255, 255),
|
||||
v.value);
|
||||
if (!v.arrows) value_left = vx;
|
||||
}
|
||||
if (v.is_default) { // under the value, right-aligned with it
|
||||
const char *t = menu_text(UI_MENU_DEFAULT_MARK);
|
||||
float tw = font->CalcTextSizeA(small, FLT_MAX, 0, t).x;
|
||||
dl->AddText(font, small, ImVec2(right - tw, ny), kDim, t);
|
||||
}
|
||||
// the label and its note, clipped before the value
|
||||
ImVec4 clip(p.x, p.y, value_left - fs * 0.6f, p.y + h);
|
||||
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), menu_text(label), NULL, 0,
|
||||
&clip);
|
||||
const char *note = off ? menu_text(UI_MENU_SET_BY_ENV) : m && !m->live ? menu_text(UI_MENU_AFTER_RESTART) : NULL;
|
||||
if (note) dl->AddText(font, small, ImVec2(p.x + pad, ny), off ? IM_COL32(200, 150, 90, 255) : kDim, note);
|
||||
ImGui::PopID();
|
||||
return off ? 0 : step;
|
||||
}
|
||||
|
||||
// ---- writing a setting: at once in memory (live settings follow), to totk.ini a moment later (opt_save_tick)
|
||||
static uint64_t g_save_at; // plat_now_ns deadline of the pending write; 0 none
|
||||
static bool g_save_logged;
|
||||
|
||||
static void apply(const char *key, const char *value) {
|
||||
if (*value) {
|
||||
cfg_set(key, value);
|
||||
} else { // the automatic choice: the key unset, its line removed from totk.ini
|
||||
const char *k = key;
|
||||
cfg_reset(&k, 1);
|
||||
}
|
||||
g_save_at = plat_now_ns() + 400000000ull;
|
||||
}
|
||||
|
||||
int opt_save_tick(int force) {
|
||||
if (!g_save_at || (!force && plat_now_ns() < g_save_at)) return g_save_at != 0;
|
||||
g_save_at = 0;
|
||||
if (!cfg_save() && !g_save_logged) {
|
||||
g_save_logged = true;
|
||||
rt_log("menu: could not write totk.ini; the changed settings hold for this session");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- rows
|
||||
|
||||
bool opt_toggle(const char *key, UiTextId label, UiTextId desc) {
|
||||
const CfgMeta *m = cfg_meta(key);
|
||||
bool on = cfg_bool(key) != 0, def = m && strcmp(m->def, "0") != 0;
|
||||
RowView v = {menu_text(on ? UI_MENU_ON : UI_MENU_OFF), on == def, false};
|
||||
if (!row(key, label, desc, v)) return false; // any step flips it
|
||||
apply(key, on ? "0" : "1");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n,
|
||||
UiTextId desc, int cur) {
|
||||
const CfgMeta *m = cfg_meta(key);
|
||||
const char *now = cfg_value(key);
|
||||
if (cur < 0)
|
||||
for (int i = 0; i < n; i++)
|
||||
if (!strcmp(values[i], now)) cur = i;
|
||||
int def = -1;
|
||||
for (int i = 0; m && i < n; i++)
|
||||
if (!strcmp(values[i], m->def)) def = i;
|
||||
RowView v = {cur >= 0 ? names[cur] : now, cur == def, true};
|
||||
int step = row(key, label, desc, v);
|
||||
if (!step || n <= 0) return false;
|
||||
int nv;
|
||||
if (cur < 0) nv = 0;
|
||||
else if (step == 2) nv = (cur + 1) % n; // A / click: the next value, round to the first
|
||||
else nv = cur + step < 0 ? 0 : cur + step >= n ? n - 1 : cur + step; // left / right stop at the ends
|
||||
if (nv == cur) return false;
|
||||
apply(key, values[nv]);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc) {
|
||||
enum { MAX = 32 };
|
||||
const CfgMeta *m = cfg_meta(key);
|
||||
const char *values[MAX], *shown[MAX];
|
||||
char buf[256];
|
||||
int k = 0;
|
||||
if (m && !m->def[0]) values[k++] = ""; // the automatic choice
|
||||
snprintf(buf, sizeof buf, "%s", m && m->values ? m->values : "");
|
||||
for (char *s = buf, *e; *s && k < MAX; s = e) {
|
||||
e = strchr(s, '|');
|
||||
if (e) *e++ = 0;
|
||||
else e = s + strlen(s);
|
||||
values[k++] = s;
|
||||
}
|
||||
if (n > k) n = k;
|
||||
for (int i = 0; i < n; i++) shown[i] = menu_text(names[i]);
|
||||
return opt_choice_list(key, label, values, shown, n, desc);
|
||||
}
|
||||
|
||||
bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt) {
|
||||
const CfgMeta *m = cfg_meta(key);
|
||||
double v = cfg_double(key), def = m ? strtod(m->def, NULL) : lo;
|
||||
char shown[48];
|
||||
snprintf(shown, sizeof shown, fmt, v);
|
||||
RowView rv = {shown, fabs(v - def) < step * 0.01, true};
|
||||
int s = row(key, label, desc, rv);
|
||||
if (!s) return false;
|
||||
int steps = g_held && (hi - lo) > 40 * step ? 10 : 1; // held: ten steps at a time over a long range
|
||||
double n = round(v / step) * step + (s == 2 ? step : s * step * steps);
|
||||
if (s == 2 && n > hi + step * 0.01) n = lo; // A / click past the top goes round; left / right stop at the ends
|
||||
n = n < lo ? lo : n > hi ? hi : n;
|
||||
if (fabs(n - v) < step * 0.01) return false;
|
||||
char out[32];
|
||||
if (step >= 1) snprintf(out, sizeof out, "%d", (int)lround(n));
|
||||
else snprintf(out, sizeof out, "%g", round(n / step) * step);
|
||||
apply(key, out);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Settings pages in two panes (ui/option_rows.cpp): option rows on the left, the selected (controller) or hovered (mouse)
|
||||
// row's description on the right. Each row shows a setting of the cfg table (cfg.h) and changes it through cfg_set: A or
|
||||
// a click steps it (toggle, next value), left and right step it. A row marks the default value, says "after restart" when
|
||||
// the setting is read at start, and is greyed out with a note when an environment variable fixes it.
|
||||
//
|
||||
// opt_begin("##screen", scale);
|
||||
// opt_toggle("TOTK_FULLSCREEN", UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC);
|
||||
// opt_end();
|
||||
//
|
||||
// key: the setting's TOTK_ name, which must have a cfg_meta row. Present path only (ImGui).
|
||||
#pragma once
|
||||
#include "imgui.h"
|
||||
|
||||
extern "C" {
|
||||
#include "ui_text.h"
|
||||
}
|
||||
|
||||
void opt_begin(const char *id, float scale);
|
||||
void opt_end(void);
|
||||
// The next page's first row takes the controller's cursor (opening the menu, switching tabs).
|
||||
void opt_focus_first(void);
|
||||
|
||||
// The return value of every row: true when it changed the setting this frame.
|
||||
bool opt_toggle(const char *key, UiTextId label, UiTextId desc);
|
||||
// One name per value of the key's cfg_meta values list, in its order. When the key has no fixed default (an empty
|
||||
// def), names[0] is the automatic choice (the key unset) and names[1..] follow the values.
|
||||
bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc);
|
||||
// A choice over a list the caller builds (devices, window sizes): values[i] is written, names[i] shown; "" means the key
|
||||
// unset. cur: the index in effect, -1 to find cfg_value(key) in values (no match: the value shown as it is).
|
||||
bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n,
|
||||
UiTextId desc, int cur = -1);
|
||||
// lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%").
|
||||
bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1,
|
||||
const char *fmt = "%g");
|
||||
|
||||
// totk.ini is written a moment after the last change (a held slider would rewrite it every frame) and when the menu
|
||||
// closes. opt_save_tick: on every frame the menu lays out; force: write now if anything is pending. 1 while a write is
|
||||
// pending.
|
||||
int opt_save_tick(int force);
|
||||
+336
-20
@@ -1,27 +1,313 @@
|
||||
// Catalog of the text the host shows the player (ui_text.h). Rows follow the game's text languages; a new string gets
|
||||
// an id in ui_text.h and a column in every row (an empty entry falls back to English).
|
||||
// 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.
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "ov.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui_text.h"
|
||||
|
||||
typedef struct { const char *lang, *text[UI_TEXT_COUNT]; } Row;
|
||||
typedef struct { const char *lang; const char *const *text; } Row;
|
||||
|
||||
// The language names are the same in every row.
|
||||
#define LANG_NAMES \
|
||||
[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_PT] = "Português", [UI_MENU_LANGNAME_RU] = "Русский", \
|
||||
[UI_MENU_LANGNAME_ZH_HANS] = "简体中文", [UI_MENU_LANGNAME_ZH_HANT] = "繁體中文", [UI_MENU_LANGNAME_KO] = "한국어"
|
||||
|
||||
// SWKBD: TITLE, PROMPT, DEFAULT_NAME (at most 9 UTF-16 units, no '@' '%' '\'), OK, CANCEL, PAD_HINT.
|
||||
#define SWKBD(title, prompt, name, ok, cancel, hint) \
|
||||
[UI_SWKBD_TITLE] = title, [UI_SWKBD_PROMPT] = prompt, [UI_SWKBD_DEFAULT_NAME] = name, [UI_SWKBD_OK] = ok, \
|
||||
[UI_SWKBD_CANCEL] = cancel, [UI_SWKBD_PAD_HINT] = hint, LANG_NAMES
|
||||
|
||||
static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
SWKBD("Text entry", "Enter a name", "Horse", "OK", "Cancel", "Controller: A = OK, B = Cancel"),
|
||||
|
||||
[UI_MENU_TITLE] = "Settings",
|
||||
[UI_MENU_TAB_SCREEN] = "Screen", [UI_MENU_TAB_GAME] = "Game", [UI_MENU_TAB_SOUND] = "Sound",
|
||||
[UI_MENU_TAB_CONTROLS] = "Controls", [UI_MENU_TAB_MENU] = "Menu", [UI_MENU_TAB_ADVANCED] = "Advanced",
|
||||
[UI_MENU_CONTINUE] = "Continue", [UI_MENU_QUIT] = "Quit game",
|
||||
[UI_MENU_ON] = "On", [UI_MENU_OFF] = "Off", [UI_MENU_AUTO] = "Automatic", [UI_MENU_DEFAULT_MARK] = "default",
|
||||
[UI_MENU_AFTER_RESTART] = "after restart", [UI_MENU_SET_BY_ENV] = "set by environment variable",
|
||||
[UI_MENU_SAVE_FAILED] = "could not save settings",
|
||||
|
||||
[UI_MENU_FULLSCREEN] = "Fullscreen", [UI_MENU_FULLSCREEN_DESC] = "Fills the screen with the game; F11 toggles it.",
|
||||
[UI_MENU_WINDOW_SIZE] = "Window size", [UI_MENU_WINDOW_SIZE_DESC] = "Size of the game window when not fullscreen.",
|
||||
[UI_MENU_WINDOW_SIZE_CUSTOM] = "Custom",
|
||||
[UI_MENU_PRESENT] = "Presentation", [UI_MENU_PRESENT_DESC] = "How finished frames reach the screen.",
|
||||
[UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "VSync", [UI_MENU_PRESENT_IMMEDIATE] = "Immediate",
|
||||
[UI_MENU_GPU] = "Graphics card", [UI_MENU_GPU_DESC] = "The Vulkan device that draws the game.",
|
||||
[UI_MENU_GPU_AUTO] = "Automatic",
|
||||
[UI_MENU_PERF_OVERLAY] = "Performance overlay",
|
||||
[UI_MENU_PERF_OVERLAY_DESC] = "Frame rate and system numbers over the picture; F10 cycles the modes.",
|
||||
[UI_MENU_PERF_OFF] = "Off", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Full",
|
||||
|
||||
[UI_MENU_FPS60] = "Frame rate", [UI_MENU_FPS60_DESC] = "Runs the game at 60 frames per second instead of 30.",
|
||||
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_30] = "30 FPS",
|
||||
[UI_MENU_REALTIME] = "Game speed follows the clock",
|
||||
[UI_MENU_REALTIME_DESC] = "Steps the game by real time, so a slow frame does not slow the game down.",
|
||||
[UI_MENU_CLOTH_REALTIME] = "Cloth on the clock",
|
||||
[UI_MENU_CLOTH_REALTIME_DESC] = "Steps cloth and hair by real time as well.",
|
||||
[UI_MENU_HIGHFPS_FIX] = "High frame rate physics fix",
|
||||
[UI_MENU_HIGHFPS_FIX_DESC] = "Corrects physics that misbehave above 30 frames per second.",
|
||||
[UI_MENU_GAME_LANG] = "Game language", [UI_MENU_GAME_LANG_DESC] = "Language of the game's text and voices.",
|
||||
[UI_MENU_GAME_LANG_AUTO] = "Automatic",
|
||||
[UI_MENU_OPERATION_MODE] = "Console mode",
|
||||
[UI_MENU_OPERATION_MODE_DESC] = "Whether the game thinks it runs docked or handheld.",
|
||||
[UI_MENU_MODE_DOCKED] = "Docked", [UI_MENU_MODE_HANDHELD] = "Handheld",
|
||||
|
||||
[UI_MENU_VOLUME] = "Volume", [UI_MENU_VOLUME_DESC] = "Master volume of the game.",
|
||||
|
||||
[UI_MENU_MOTION] = "Motion controls", [UI_MENU_MOTION_DESC] = "Aiming with the controller's gyroscope.",
|
||||
[UI_MENU_RUMBLE_STRENGTH] = "Vibration strength",
|
||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "How strong the controller vibrates.",
|
||||
[UI_MENU_RUMBLE_CURVE] = "Vibration curve",
|
||||
[UI_MENU_RUMBLE_CURVE_DESC] = "Lower values make weak vibration stronger.",
|
||||
[UI_MENU_RUMBLE_TRIGGERS] = "Trigger vibration (Xbox)",
|
||||
[UI_MENU_RUMBLE_TRIGGERS_DESC] = "Vibrates the triggers of an Xbox controller too.",
|
||||
[UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity",
|
||||
[UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.",
|
||||
|
||||
[UI_MENU_MENU_LANG] = "Menu language", [UI_MENU_MENU_LANG_DESC] = "Language of this menu and the overlay.",
|
||||
[UI_MENU_MENU_LANG_AUTO] = "Automatic (from Windows)",
|
||||
|
||||
[UI_MENU_ADV_WARNING] = "These settings are for testing and troubleshooting. Change them only when you know why.",
|
||||
[UI_MENU_GROUP_SCHED] = "Scheduling", [UI_MENU_GROUP_SHADERS] = "Shaders and pipelines",
|
||||
[UI_MENU_GROUP_TEXMEM] = "Textures and memory", [UI_MENU_GROUP_FIXES] = "Render fixes",
|
||||
[UI_MENU_GROUP_VULKAN] = "Vulkan", [UI_MENU_GROUP_DIAG] = "Diagnostics",
|
||||
[UI_MENU_ASYNC_PREEMPT] = "Virtual core preemption",
|
||||
[UI_MENU_ASYNC_PREEMPT_DESC] = "Lets a game thread interrupt another one on the same virtual core.",
|
||||
[UI_MENU_PREEMPT_OFF] = "Off", [UI_MENU_PREEMPT_ON] = "On", [UI_MENU_PREEMPT_INHERIT] = "Inheritance only",
|
||||
[UI_MENU_REPLAY_ASYNC] = "Replay on its own thread",
|
||||
[UI_MENU_REPLAY_ASYNC_DESC] = "Runs the recorded GPU commands on a separate thread.",
|
||||
[UI_MENU_FREE_CORES] = "Virtual core gate",
|
||||
[UI_MENU_FREE_CORES_DESC] = "Lets only one thread run per virtual core, as on the console.",
|
||||
[UI_MENU_TIMER_1MS] = "1 ms Windows timer",
|
||||
[UI_MENU_TIMER_1MS_DESC] = "Raises the system timer resolution to 1 ms for steadier frame pacing.",
|
||||
[UI_MENU_PIPE_WAIT] = "Waiting draw handling",
|
||||
[UI_MENU_PIPE_WAIT_DESC] = "Default keeps the current scheduling with a reserved worker for waiting draws; Old (draw) uses the previous scheduling.",
|
||||
[UI_MENU_PIPE_WAIT_DEFAULT] = "Default", [UI_MENU_PIPE_WAIT_DRAW] = "Old (draw)",
|
||||
[UI_MENU_PIPE_SKIP] = "Draws skipped while a pipeline builds",
|
||||
[UI_MENU_PIPE_SKIP_DESC] = "Which draws are dropped instead of waiting for their pipeline.",
|
||||
[UI_MENU_PIPE_SKIP_STRICT] = "Strict", [UI_MENU_PIPE_SKIP_ANY] = "Any",
|
||||
[UI_MENU_PIPE_SKIP_FULLSCREEN] = "Fullscreen passes",
|
||||
[UI_MENU_LIB_PREBUILD] = "Stage library prebuild",
|
||||
[UI_MENU_LIB_PREBUILD_DESC] = "Builds shader stage libraries ahead of time in the background.",
|
||||
[UI_MENU_LIB_PREBUILD_THREADS] = "Stage library prebuild threads",
|
||||
[UI_MENU_LIB_PREBUILD_THREADS_DESC] = "Threads used for the prebuild; empty picks a number from your CPU.",
|
||||
[UI_MENU_PIPE_PREBUILD] = "Pipeline prebuild",
|
||||
[UI_MENU_PIPE_PREBUILD_DESC] = "Builds known pipelines ahead of time.",
|
||||
[UI_MENU_PREWARM_XLATE] = "Translator prewarm",
|
||||
[UI_MENU_PREWARM_XLATE_DESC] = "Threads that translate known shaders at start; empty picks a number.",
|
||||
[UI_MENU_GPL] = "Graphics pipeline library",
|
||||
[UI_MENU_GPL_DESC] = "Uses the Vulkan pipeline library extension; turn off if your driver misbehaves with it.",
|
||||
[UI_MENU_ASTC] = "ASTC texture decoding", [UI_MENU_ASTC_DESC] = "Where compressed ASTC textures are decoded.",
|
||||
[UI_MENU_ASTC_AUTO] = "Automatic", [UI_MENU_ASTC_GPU] = "GPU shader", [UI_MENU_ASTC_NATIVE] = "Native",
|
||||
[UI_MENU_ASTC_CPU] = "CPU",
|
||||
[UI_MENU_MEMORY] = "GPU memory mode", [UI_MENU_MEMORY_DESC] = "How game memory is shared with the GPU.",
|
||||
[UI_MENU_MEMORY_AUTO] = "Automatic", [UI_MENU_MEMORY_IMPORT] = "Import", [UI_MENU_MEMORY_MIRROR] = "Mirror",
|
||||
[UI_MENU_MEMORY_VERIFY] = "Verify",
|
||||
[UI_MENU_TEX_ALIAS] = "Texture aliasing", [UI_MENU_TEX_ALIAS_DESC] = "A new texture created over a live texture's memory starts with that content instead of empty.",
|
||||
[UI_MENU_LOD_GUARD] = "LOD guard", [UI_MENU_LOD_GUARD_DESC] = "Prevents objects flashing in the wrong place or a flat far field for a frame, by waiting for the game to finish rewriting level-of-detail data before the GPU reads it.",
|
||||
[UI_MENU_FIX_C0] = "Constant buffer fix",
|
||||
[UI_MENU_FIX_C0_DESC] = "Fills the driver-reserved constant bank c0 (storage sizes, dispatch size, point size, base instance) instead of reading zeros.",
|
||||
[UI_MENU_FIX_ZERO] = "Zero new GPU memory",
|
||||
[UI_MENU_FIX_ZERO_DESC] = "New GPU memory pools start zero-filled, as Switch memory does.",
|
||||
[UI_MENU_BIND_SKIP] = "Skip repeated binds",
|
||||
[UI_MENU_BIND_SKIP_DESC] = "Optimisation: skips bindings that did not change.",
|
||||
[UI_MENU_SHADER_MEMO] = "Shader memo", [UI_MENU_SHADER_MEMO_DESC] = "Optimisation: remembers shader lookups.",
|
||||
[UI_MENU_DESC_TEMPLATE] = "Descriptor templates",
|
||||
[UI_MENU_DESC_TEMPLATE_DESC] = "Optimisation: updates descriptors in bulk.",
|
||||
[UI_MENU_PUSH_SKIP] = "Skip repeated push constants",
|
||||
[UI_MENU_PUSH_SKIP_DESC] = "Optimisation: skips push constants that did not change.",
|
||||
[UI_MENU_SPLIT_DRAWS] = "Early GPU submission",
|
||||
[UI_MENU_SPLIT_DRAWS_DESC] = "Submits GPU work in parts every N draws between passes so the GPU starts earlier; 0 turns it off.",
|
||||
[UI_MENU_VK_VALIDATION] = "Validation layer",
|
||||
[UI_MENU_VK_VALIDATION_DESC] = "Checks every Vulkan call and slows the game down a lot.",
|
||||
[UI_MENU_VK_VALIDATION_MISSING] = "The validation layer is not installed.",
|
||||
[UI_MENU_VK_DYN_VERTEX] = "Dynamic vertex state",
|
||||
[UI_MENU_VK_DYN_VERTEX_DESC] = "Forces dynamic vertex input on or off; the default depends on the GPU.",
|
||||
[UI_MENU_VK_SUBGROUP_PIN] = "Pin subgroup size", [UI_MENU_VK_SUBGROUP_PIN_DESC] = "Fixes the shader subgroup size.",
|
||||
[UI_MENU_TRACE] = "Performance log", [UI_MENU_TRACE_DESC] = "Writes frame timings to a file.",
|
||||
[UI_MENU_FLIGHT] = "Flight recorder",
|
||||
[UI_MENU_FLIGHT_DESC] = "Keeps a short history and saves it when a frame freezes.",
|
||||
[UI_MENU_FLIGHT_SPIKE_MS] = "Freeze threshold (ms)",
|
||||
[UI_MENU_FLIGHT_SPIKE_MS_DESC] = "Frame time that counts as a freeze.",
|
||||
[UI_MENU_INPUT_RECORD] = "Input recording",
|
||||
[UI_MENU_INPUT_RECORD_DESC] = "Writes your inputs to a file for bug reports.",
|
||||
[UI_MENU_OPEN_LOG] = "Open log folder", [UI_MENU_OPEN_LOG_DESC] = "Shows the folder with the log files.",
|
||||
[UI_MENU_COPY_INFO] = "Copy system info",
|
||||
[UI_MENU_COPY_INFO_DESC] = "Copies GPU, driver, CPU, RAM and changed settings to the clipboard.",
|
||||
[UI_MENU_COPY_INFO_DONE] = "Copied",
|
||||
[UI_MENU_RESET] = "Reset all settings to defaults", [UI_MENU_RESET_DESC] = "Applies to every tab.",
|
||||
[UI_MENU_RESET_CONFIRM] = "Reset every setting to its default?", [UI_MENU_RESET_YES] = "Reset",
|
||||
[UI_MENU_RESET_NO] = "Cancel",
|
||||
|
||||
[UI_MENU_OV_FPS] = "%.0f FPS", [UI_MENU_OV_FRAME_MS] = "%.1f ms", [UI_MENU_OV_GAME_PCT] = "game %.0f%%",
|
||||
[UI_MENU_OV_MAX_MS] = "max %.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] = "Temperature", [UI_MENU_OV_POWER] = "Power", [UI_MENU_OV_CLOCK] = "Clock",
|
||||
[UI_MENU_OV_NONE] = "-",
|
||||
[UI_MENU_OV_REPLAY] = "Replay", [UI_MENU_OV_GPU_TIME] = "GPU time", [UI_MENU_OV_PIPE_WAIT] = "Pipeline waits",
|
||||
[UI_MENU_OV_SHADER_WAIT] = "Shader waits", [UI_MENU_OV_TEX_UPLOADS] = "Texture uploads",
|
||||
};
|
||||
|
||||
static const char *const text_ru[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_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_GPU] = "Видеокарта", [UI_MENU_GPU_DESC] = "Устройство Vulkan, которое рисует игру.",
|
||||
[UI_MENU_GPU_AUTO] = "Автоматически",
|
||||
[UI_MENU_PERF_OVERLAY] = "Индикатор производительности",
|
||||
[UI_MENU_PERF_OVERLAY_DESC] = "Частота кадров и данные о системе поверх картинки; F10 переключает режимы.",
|
||||
[UI_MENU_PERF_OFF] = "Выкл.", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Полный",
|
||||
|
||||
[UI_MENU_FPS60] = "Частота кадров", [UI_MENU_FPS60_DESC] = "Игра идёт в 60 кадров в секунду вместо 30.",
|
||||
[UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_30] = "30 FPS",
|
||||
[UI_MENU_REALTIME] = "Скорость игры по часам",
|
||||
[UI_MENU_REALTIME_DESC] = "Игра идёт по реальному времени, медленный кадр её не замедляет.",
|
||||
[UI_MENU_CLOTH_REALTIME] = "Ткань по часам",
|
||||
[UI_MENU_CLOTH_REALTIME_DESC] = "Ткань и волосы тоже идут по реальному времени.",
|
||||
[UI_MENU_HIGHFPS_FIX] = "Исправление физики на высоком FPS",
|
||||
[UI_MENU_HIGHFPS_FIX_DESC] = "Исправляет физику, которая ломается при частоте выше 30 кадров в секунду.",
|
||||
[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_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_MOUSE_SENS] = "Чувствительность мыши",
|
||||
[UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.",
|
||||
|
||||
[UI_MENU_MENU_LANG] = "Язык меню", [UI_MENU_MENU_LANG_DESC] = "Язык этого меню и индикатора.",
|
||||
[UI_MENU_MENU_LANG_AUTO] = "Автоматически (из Windows)",
|
||||
|
||||
[UI_MENU_ADV_WARNING] = "Эти настройки нужны для тестов и поиска неполадок. Меняйте их, только если знаете зачем.",
|
||||
[UI_MENU_GROUP_SCHED] = "Планирование", [UI_MENU_GROUP_SHADERS] = "Шейдеры и конвейеры",
|
||||
[UI_MENU_GROUP_TEXMEM] = "Текстуры и память", [UI_MENU_GROUP_FIXES] = "Исправления графики",
|
||||
[UI_MENU_GROUP_VULKAN] = "Vulkan", [UI_MENU_GROUP_DIAG] = "Диагностика",
|
||||
[UI_MENU_ASYNC_PREEMPT] = "Вытеснение на виртуальных ядрах",
|
||||
[UI_MENU_ASYNC_PREEMPT_DESC] = "Позволяет потоку игры прервать другой поток на том же виртуальном ядре.",
|
||||
[UI_MENU_PREEMPT_OFF] = "Выкл.", [UI_MENU_PREEMPT_ON] = "Вкл.", [UI_MENU_PREEMPT_INHERIT] = "Только наследование",
|
||||
[UI_MENU_REPLAY_ASYNC] = "Воспроизведение команд GPU в отдельном потоке",
|
||||
[UI_MENU_REPLAY_ASYNC_DESC] = "Записанные команды GPU выполняются в отдельном потоке.",
|
||||
[UI_MENU_FREE_CORES] = "Ограничение виртуальных ядер",
|
||||
[UI_MENU_FREE_CORES_DESC] = "На каждом виртуальном ядре работает один поток, как на консоли.",
|
||||
[UI_MENU_TIMER_1MS] = "Таймер Windows 1 мс",
|
||||
[UI_MENU_TIMER_1MS_DESC] = "Повышает точность системного таймера до 1 мс для ровного темпа кадров.",
|
||||
[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] = "Сколько потоков занято предсборкой; пусто — по числу ядер процессора.",
|
||||
[UI_MENU_PIPE_PREBUILD] = "Предсборка конвейеров",
|
||||
[UI_MENU_PIPE_PREBUILD_DESC] = "Заранее собирает известные конвейеры.",
|
||||
[UI_MENU_PREWARM_XLATE] = "Прогрев транслятора",
|
||||
[UI_MENU_PREWARM_XLATE_DESC] = "Потоки, которые при запуске переводят известные шейдеры; пусто — выбрать самому.",
|
||||
[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] = "Процессор",
|
||||
[UI_MENU_MEMORY] = "Режим памяти GPU", [UI_MENU_MEMORY_DESC] = "Как память игры передаётся видеокарте.",
|
||||
[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_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_DESC_TEMPLATE] = "Шаблоны дескрипторов",
|
||||
[UI_MENU_DESC_TEMPLATE_DESC] = "Оптимизация: обновляет дескрипторы пачками.",
|
||||
[UI_MENU_PUSH_SKIP] = "Пропуск повторных push-констант",
|
||||
[UI_MENU_PUSH_SKIP_DESC] = "Оптимизация: пропускает неизменившиеся push-константы.",
|
||||
[UI_MENU_SPLIT_DRAWS] = "Ранняя отправка работы GPU",
|
||||
[UI_MENU_SPLIT_DRAWS_DESC] = "Отправляет работу GPU частями через каждые N отрисовок между проходами, чтобы GPU начинал раньше; 0 — выключено.",
|
||||
[UI_MENU_VK_VALIDATION] = "Слой проверки",
|
||||
[UI_MENU_VK_VALIDATION_DESC] = "Проверяет каждый вызов Vulkan и сильно замедляет игру.",
|
||||
[UI_MENU_VK_VALIDATION_MISSING] = "Слой проверки не установлен.",
|
||||
[UI_MENU_VK_DYN_VERTEX] = "Динамическое состояние вершин",
|
||||
[UI_MENU_VK_DYN_VERTEX_DESC] = "Принудительно включает или выключает динамический ввод вершин; по умолчанию зависит от GPU.",
|
||||
[UI_MENU_VK_SUBGROUP_PIN] = "Фиксировать размер подгруппы",
|
||||
[UI_MENU_VK_SUBGROUP_PIN_DESC] = "Фиксирует размер подгруппы шейдера.",
|
||||
[UI_MENU_TRACE] = "Журнал производительности", [UI_MENU_TRACE_DESC] = "Пишет время кадров в файл.",
|
||||
[UI_MENU_FLIGHT] = "Запись последних кадров (для отчёта о фризе)",
|
||||
[UI_MENU_FLIGHT_DESC] = "Хранит короткую историю и сохраняет её, когда кадр подвисает.",
|
||||
[UI_MENU_FLIGHT_SPIKE_MS] = "Порог подвисания (мс)",
|
||||
[UI_MENU_FLIGHT_SPIKE_MS_DESC] = "Время кадра, которое считается подвисанием.",
|
||||
[UI_MENU_INPUT_RECORD] = "Запись ввода",
|
||||
[UI_MENU_INPUT_RECORD_DESC] = "Пишет ваш ввод в файл для отчёта об ошибке.",
|
||||
[UI_MENU_OPEN_LOG] = "Открыть папку журналов", [UI_MENU_OPEN_LOG_DESC] = "Показывает папку с файлами журнала.",
|
||||
[UI_MENU_COPY_INFO] = "Копировать сведения о системе",
|
||||
[UI_MENU_COPY_INFO_DESC] = "Копирует в буфер обмена видеокарту, драйвер, процессор, память и изменённые настройки.",
|
||||
[UI_MENU_COPY_INFO_DONE] = "Скопировано",
|
||||
[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 мс", [UI_MENU_OV_GAME_PCT] = "игра %.0f%%",
|
||||
[UI_MENU_OV_MAX_MS] = "макс. %.1f мс",
|
||||
[UI_MENU_OV_GPU] = "GPU", [UI_MENU_OV_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] = "Загрузки текстур",
|
||||
};
|
||||
|
||||
#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");
|
||||
SWKBD_ONLY(text_de, "Texteingabe", "Gib einen Namen ein", "Pferd", "OK", "Abbrechen", "Controller: A = OK, B = Abbrechen");
|
||||
SWKBD_ONLY(text_it, "Inserimento testo", "Inserisci un nome", "Cavallo", "OK", "Annulla", "Controller: A = OK, B = Annulla");
|
||||
SWKBD_ONLY(text_es, "Introducir texto", "Introduce un nombre", "Caballo", "Aceptar", "Cancelar",
|
||||
"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 취소");
|
||||
|
||||
// Columns: TITLE, PROMPT, DEFAULT_NAME (at most 9 UTF-16 units, no '@' '%' '\'), OK, CANCEL, PAD_HINT.
|
||||
static const Row rows[] = {
|
||||
{"en", {"Text entry", "Enter a name", "Horse", "OK", "Cancel", "Controller: A = OK, B = Cancel"}},
|
||||
{"ja", {"文字入力", "名前を入力してください", "ウマ", "OK", "キャンセル", "コントローラー: A = OK、B = キャンセル"}},
|
||||
{"fr", {"Saisie de texte", "Entrez un nom", "Cheval", "OK", "Annuler", "Manette : A = OK, B = Annuler"}},
|
||||
{"de", {"Texteingabe", "Gib einen Namen ein", "Pferd", "OK", "Abbrechen", "Controller: A = OK, B = Abbrechen"}},
|
||||
{"it", {"Inserimento testo", "Inserisci un nome", "Cavallo", "OK", "Annulla", "Controller: A = OK, B = Annulla"}},
|
||||
{"es", {"Introducir texto", "Introduce un nombre", "Caballo", "Aceptar", "Cancelar",
|
||||
"Mando: A = Aceptar, B = Cancelar"}},
|
||||
{"nl", {"Tekstinvoer", "Voer een naam in", "Paard", "OK", "Annuleren", "Controller: A = OK, B = Annuleren"}},
|
||||
{"pt", {"Inserir texto", "Introduz um nome", "Cavalo", "OK", "Cancelar", "Comando: A = OK, B = Cancelar"}},
|
||||
{"ru", {"Ввод текста", "Введите имя", "Лошадь", "ОК", "Отмена", "Контроллер: A — ОК, B — отмена"}},
|
||||
{"zh-Hans", {"文字输入", "请输入名字", "马儿", "确定", "取消", "手柄:A 确定,B 取消"}},
|
||||
{"zh-Hant", {"文字輸入", "請輸入名字", "馬兒", "確定", "取消", "手把:A 確定,B 取消"}},
|
||||
{"ko", {"문자 입력", "이름을 입력하세요", "말", "확인", "취소", "컨트롤러: A 확인, B 취소"}},
|
||||
{"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},
|
||||
};
|
||||
|
||||
const char *ui_text_lang(const char *code) {
|
||||
@@ -34,11 +320,41 @@ const char *ui_text_lang(const char *code) {
|
||||
return code;
|
||||
}
|
||||
|
||||
static const Row *find_row(const char *lang) {
|
||||
for (size_t i = 0; i < sizeof rows / sizeof *rows; i++)
|
||||
if (!strcmp(rows[i].lang, lang)) return &rows[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int ui_text_defined(const char *lang, UiTextId id) {
|
||||
const Row *r = find_row(lang);
|
||||
return (unsigned)id < UI_TEXT_COUNT && r && r->text[id] && *r->text[id];
|
||||
}
|
||||
|
||||
const char *ui_text_in(const char *lang, UiTextId id) {
|
||||
if ((unsigned)id >= UI_TEXT_COUNT) return "";
|
||||
for (size_t i = 0; i < sizeof rows / sizeof *rows; i++)
|
||||
if (!strcmp(rows[i].lang, lang) && rows[i].text[id] && *rows[i].text[id]) return rows[i].text[id];
|
||||
return rows[0].text[id];
|
||||
return ui_text_defined(lang, id) ? find_row(lang)->text[id] : rows[0].text[id];
|
||||
}
|
||||
|
||||
const char *ui_text(UiTextId id) { return ui_text_in(ui_text_lang(ov_language()), id); }
|
||||
|
||||
// The menu language, re-read when cfg_version changes. TOTK_MENU_LANG "ru" or "en"; anything else (unset included)
|
||||
// follows the system UI language: Russian for "ru", "ru-RU", ..., else English.
|
||||
static const char *resolve_menu_lang(void) {
|
||||
const char *v = cfg_value("TOTK_MENU_LANG");
|
||||
if (v && !strcmp(v, "ru")) return "ru";
|
||||
if (v && !strcmp(v, "en")) return "en";
|
||||
const char *sys = plat_ui_language();
|
||||
return sys && (!strcmp(sys, "ru") || !strncmp(sys, "ru-", 3)) ? "ru" : "en";
|
||||
}
|
||||
|
||||
const char *menu_text(UiTextId id) {
|
||||
static _Atomic(const char *) lang = "en";
|
||||
static _Atomic unsigned seen = ~0u;
|
||||
unsigned v = cfg_version();
|
||||
if (v != atomic_load_explicit(&seen, memory_order_relaxed)) {
|
||||
atomic_store_explicit(&lang, resolve_menu_lang(), memory_order_relaxed);
|
||||
atomic_store_explicit(&seen, v, memory_order_relaxed);
|
||||
}
|
||||
return ui_text_in(atomic_load_explicit(&lang, memory_order_relaxed), id);
|
||||
}
|
||||
+101
-2
@@ -1,20 +1,119 @@
|
||||
// Text the host shows the player (runtime/ui_text.c): one catalog, keyed by stable ids, in the game's language.
|
||||
// Text the host shows the player (runtime/ui_text.c): one catalog, keyed by stable ids. The software keyboard reads it
|
||||
// in the game's language (ui_text); the menu and the performance overlay read it in the menu language (menu_text).
|
||||
#pragma once
|
||||
|
||||
typedef enum {
|
||||
// Software keyboard
|
||||
UI_SWKBD_TITLE, // caption of the text-entry window
|
||||
UI_SWKBD_PROMPT, // prompt when the game gives no header, guide or sub text (TotK names a horse)
|
||||
UI_SWKBD_DEFAULT_NAME, // text the entry starts with when the game gives none, so a controller can confirm it
|
||||
UI_SWKBD_OK,
|
||||
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.
|
||||
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,
|
||||
UI_MENU_TAB_ADVANCED,
|
||||
UI_MENU_CONTINUE, UI_MENU_QUIT,
|
||||
UI_MENU_ON, UI_MENU_OFF, UI_MENU_AUTO, UI_MENU_DEFAULT_MARK, // "default" beside the default value
|
||||
UI_MENU_AFTER_RESTART, // note on a setting that is read at start
|
||||
UI_MENU_SET_BY_ENV, // note on a setting an environment variable fixes
|
||||
UI_MENU_SAVE_FAILED,
|
||||
|
||||
// Screen
|
||||
UI_MENU_FULLSCREEN, UI_MENU_FULLSCREEN_DESC,
|
||||
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, UI_MENU_PRESENT_VSYNC, UI_MENU_PRESENT_IMMEDIATE,
|
||||
UI_MENU_GPU, UI_MENU_GPU_DESC, UI_MENU_GPU_AUTO,
|
||||
UI_MENU_PERF_OVERLAY, UI_MENU_PERF_OVERLAY_DESC, UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL,
|
||||
|
||||
// Game
|
||||
UI_MENU_FPS60, UI_MENU_FPS60_DESC, UI_MENU_FPS_60, UI_MENU_FPS_30,
|
||||
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,
|
||||
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,
|
||||
|
||||
// Sound
|
||||
UI_MENU_VOLUME, UI_MENU_VOLUME_DESC,
|
||||
|
||||
// Controls
|
||||
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, UI_MENU_RUMBLE_TRIGGERS_DESC,
|
||||
UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC,
|
||||
|
||||
// Menu tab
|
||||
UI_MENU_MENU_LANG, UI_MENU_MENU_LANG_DESC, UI_MENU_MENU_LANG_AUTO,
|
||||
|
||||
// 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_PT, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS,
|
||||
UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO,
|
||||
|
||||
// Advanced
|
||||
UI_MENU_ADV_WARNING,
|
||||
UI_MENU_GROUP_SCHED, UI_MENU_GROUP_SHADERS, UI_MENU_GROUP_TEXMEM, UI_MENU_GROUP_FIXES, UI_MENU_GROUP_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, UI_MENU_REPLAY_ASYNC_DESC,
|
||||
UI_MENU_FREE_CORES, UI_MENU_FREE_CORES_DESC,
|
||||
UI_MENU_TIMER_1MS, UI_MENU_TIMER_1MS_DESC,
|
||||
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,
|
||||
UI_MENU_PIPE_PREBUILD, UI_MENU_PIPE_PREBUILD_DESC,
|
||||
UI_MENU_PREWARM_XLATE, UI_MENU_PREWARM_XLATE_DESC,
|
||||
UI_MENU_GPL, UI_MENU_GPL_DESC,
|
||||
UI_MENU_ASTC, UI_MENU_ASTC_DESC, UI_MENU_ASTC_AUTO, UI_MENU_ASTC_GPU, UI_MENU_ASTC_NATIVE, UI_MENU_ASTC_CPU,
|
||||
UI_MENU_MEMORY, UI_MENU_MEMORY_DESC, 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_LOD_GUARD, UI_MENU_LOD_GUARD_DESC,
|
||||
UI_MENU_FIX_C0, UI_MENU_FIX_C0_DESC,
|
||||
UI_MENU_FIX_ZERO, UI_MENU_FIX_ZERO_DESC,
|
||||
UI_MENU_BIND_SKIP, UI_MENU_BIND_SKIP_DESC,
|
||||
UI_MENU_SHADER_MEMO, UI_MENU_SHADER_MEMO_DESC,
|
||||
UI_MENU_DESC_TEMPLATE, UI_MENU_DESC_TEMPLATE_DESC,
|
||||
UI_MENU_PUSH_SKIP, UI_MENU_PUSH_SKIP_DESC,
|
||||
UI_MENU_SPLIT_DRAWS, UI_MENU_SPLIT_DRAWS_DESC,
|
||||
UI_MENU_VK_VALIDATION, UI_MENU_VK_VALIDATION_DESC, UI_MENU_VK_VALIDATION_MISSING,
|
||||
UI_MENU_VK_DYN_VERTEX, UI_MENU_VK_DYN_VERTEX_DESC,
|
||||
UI_MENU_VK_SUBGROUP_PIN, UI_MENU_VK_SUBGROUP_PIN_DESC,
|
||||
UI_MENU_TRACE, UI_MENU_TRACE_DESC,
|
||||
UI_MENU_FLIGHT, UI_MENU_FLIGHT_DESC,
|
||||
UI_MENU_FLIGHT_SPIKE_MS, UI_MENU_FLIGHT_SPIKE_MS_DESC,
|
||||
UI_MENU_INPUT_RECORD, UI_MENU_INPUT_RECORD_DESC,
|
||||
UI_MENU_OPEN_LOG, UI_MENU_OPEN_LOG_DESC,
|
||||
UI_MENU_COPY_INFO, UI_MENU_COPY_INFO_DESC, UI_MENU_COPY_INFO_DONE,
|
||||
UI_MENU_RESET, UI_MENU_RESET_DESC, UI_MENU_RESET_CONFIRM, UI_MENU_RESET_YES, UI_MENU_RESET_NO,
|
||||
|
||||
// Performance overlay
|
||||
UI_MENU_OV_FPS, UI_MENU_OV_FRAME_MS, UI_MENU_OV_GAME_PCT, UI_MENU_OV_MAX_MS,
|
||||
UI_MENU_OV_GPU, UI_MENU_OV_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, UI_MENU_OV_GPU_TIME, UI_MENU_OV_PIPE_WAIT, UI_MENU_OV_SHADER_WAIT, UI_MENU_OV_TEX_UPLOADS,
|
||||
UI_MENU_LAST_ID = UI_MENU_OV_TEX_UPLOADS,
|
||||
UI_TEXT_COUNT
|
||||
} UiTextId;
|
||||
|
||||
// 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"), for the probe.
|
||||
// "zh-Hant", "ko"); an empty entry gives the English text.
|
||||
const char *ui_text_in(const char *lang, UiTextId id);
|
||||
// 1 when the row of lang has its own text for id (no fallback to English), for the probe.
|
||||
int ui_text_defined(const char *lang, UiTextId id);
|
||||
// The catalog language for a Switch language code ("en-GB" -> "en", "zh-CN" -> "zh-Hans", ...).
|
||||
const char *ui_text_lang(const char *switch_code);
|
||||
|
||||
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en" / "ru"); unset, Russian when the
|
||||
// system UI language is Russian, else English. Follows a live change of the setting.
|
||||
const char *menu_text(UiTextId id);
|
||||
+2
-2
@@ -309,8 +309,8 @@ int vk_astc_mode(void) {
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
reset_for(c);
|
||||
if (G.mode < 0) {
|
||||
const char *e = cfg_get("TOTK_ASTC");
|
||||
int want = !e || !*e || !strcmp(e, "auto") ? -1 : !strcmp(e, "cpu") ? VK_ASTC_CPU : !strcmp(e, "gpu") ? VK_ASTC_GPU
|
||||
const char *e = cfg_value("TOTK_ASTC");
|
||||
int want = !strcmp(e, "auto") ? -1 : !strcmp(e, "cpu") ? VK_ASTC_CPU : !strcmp(e, "gpu") ? VK_ASTC_GPU
|
||||
: !strcmp(e, "native") ? VK_ASTC_NATIVE : !strcmp(e, "check") ? VK_ASTC_CHECK : -2;
|
||||
if (want == -2) rt_log("vk: TOTK_ASTC=%s is not cpu, gpu, native, check or auto: auto", e), want = -1;
|
||||
if ((want == -1 || want == VK_ASTC_NATIVE) && native_device(c)) m = VK_ASTC_NATIVE;
|
||||
|
||||
@@ -169,8 +169,7 @@ static uint64_t ck_reads, ck_diff, ck_diff_unexplained, ck_diff_idle;
|
||||
int vk_replay_async(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *e = cfg_get("TOTK_REPLAY_ASYNC");
|
||||
on = e && !strcmp(e, "1"); // off by default: no measured gain yet, one more frame of latency
|
||||
on = cfg_bool("TOTK_REPLAY_ASYNC"); // off by default: no measured gain yet, one more frame of latency
|
||||
rt_log("vk: replay %s (TOTK_REPLAY_ASYNC=%d)",
|
||||
on ? "on its own thread, at most one frame behind the game" : "on the submitting thread", on);
|
||||
}
|
||||
|
||||
+2
-2
@@ -40,7 +40,7 @@ int vk_caps_gpl(const VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT *f,
|
||||
const VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT *p) {
|
||||
gpl_lib = f->graphicsPipelineLibrary;
|
||||
gpl_fast = p->graphicsPipelineLibraryFastLinking;
|
||||
vk_caps.gpl = gpl_lib && gpl_fast && env_u32("TOTK_GPL", 1);
|
||||
vk_caps.gpl = gpl_lib && gpl_fast && cfg_bool("TOTK_GPL");
|
||||
return vk_caps.gpl;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ void vk_caps_init(VkCtx *c) {
|
||||
vk_caps.sbuf_align = l->minStorageBufferOffsetAlignment > 4 ? (uint32_t)l->minStorageBufferOffsetAlignment : 0;
|
||||
|
||||
uint32_t want = env_u32("TOTK_VK_SUBGROUP", 32);
|
||||
int pin = f13.subgroupSizeControl && env_u32("TOTK_VK_SUBGROUP_PIN", 1) && p13.minSubgroupSize <= want &&
|
||||
int pin = f13.subgroupSizeControl && cfg_bool("TOTK_VK_SUBGROUP_PIN") && p13.minSubgroupSize <= want &&
|
||||
want <= p13.maxSubgroupSize;
|
||||
vk_caps.sg_size = want;
|
||||
vk_caps.sg_pin_stages = pin ? p13.requiredSubgroupSizeStages : 0;
|
||||
|
||||
+2
-3
@@ -45,8 +45,7 @@ static int create_instance(void) {
|
||||
const char *ext[4] = {VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME};
|
||||
uint32_t n_ext = 2;
|
||||
const char *layers[] = {"VK_LAYER_KHRONOS_validation"};
|
||||
const char *v = cfg_get("TOTK_VK_VALIDATION");
|
||||
int validate = v && *v && *v != '0';
|
||||
int validate = cfg_bool("TOTK_VK_VALIDATION");
|
||||
if (validate && !layer_present(layers[0])) {
|
||||
rt_log("vk: TOTK_VK_VALIDATION set but %s is not installed; continuing without", layers[0]);
|
||||
validate = 0;
|
||||
@@ -115,7 +114,7 @@ static int pick_device(void) {
|
||||
if (!n) { rt_log("vk: no Vulkan device"); return 0; }
|
||||
VkPhysicalDevice *pd = calloc(n, sizeof *pd);
|
||||
vkEnumeratePhysicalDevices(g_vk.instance, &n, pd);
|
||||
const char *e = cfg_get("TOTK_GPU_INDEX");
|
||||
const char *e = cfg_get("TOTK_GPU_INDEX"); // no fixed default: the best device when unset
|
||||
int want = e && *e ? atoi(e) : -1;
|
||||
const char *name = cfg_get("TOTK_GPU_NAME");
|
||||
int best = -1, best_score = -1;
|
||||
|
||||
+1
-2
@@ -599,8 +599,7 @@ static uint64_t n_parts, n_subs;
|
||||
|
||||
static void maybe_split(VkExec *ex) {
|
||||
if (split_n < 0) {
|
||||
const char *e = cfg_get("TOTK_SPLIT_DRAWS");
|
||||
split_n = e ? atoi(e) : 64;
|
||||
split_n = cfg_int("TOTK_SPLIT_DRAWS");
|
||||
if (split_n < 0) split_n = 0;
|
||||
rt_log("vk: replay command buffer split every %d draws between passes%s", split_n, split_n ? "" : " (off)");
|
||||
}
|
||||
|
||||
+8
-10
@@ -725,8 +725,7 @@ void vk_c0_fill(uint8_t bank[VK_C0_BYTES], int stage, const p_bind_buf ssbo[16],
|
||||
static int c0_on(void) { // TOTK_FIX_C0=0: c0 reads zeros, as in M4
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *e = cfg_get("TOTK_FIX_C0");
|
||||
on = !(e && !strcmp(e, "0"));
|
||||
on = cfg_bool("TOTK_FIX_C0");
|
||||
}
|
||||
return on;
|
||||
}
|
||||
@@ -1043,8 +1042,7 @@ static void repeat_stats(const VkExec *ex, const VkPipeInfo *info) {
|
||||
static int push_skip_on(void) { // TOTK_PUSH_SKIP=0: every graphics draw pushes its set again
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *e = cfg_get("TOTK_PUSH_SKIP");
|
||||
on = !(e && !strcmp(e, "0"));
|
||||
on = cfg_bool("TOTK_PUSH_SKIP");
|
||||
}
|
||||
return on;
|
||||
}
|
||||
@@ -1068,8 +1066,8 @@ static int push_skip_on(void) { // TOTK_PUSH_SKIP=0: every graphics draw pushe
|
||||
// writes, census counts or descriptor commands.
|
||||
static int bind_skip_on(void) {
|
||||
if (RS.on < 0) {
|
||||
const char *e = cfg_get("TOTK_BIND_SKIP");
|
||||
RS.on = e && !strcmp(e, "check") ? 2 : !(e && !strcmp(e, "0"));
|
||||
const char *e = cfg_value("TOTK_BIND_SKIP");
|
||||
RS.on = !strcmp(e, "check") ? 2 : strcmp(e, "0") != 0;
|
||||
if (RS.on != 1) rt_log("vk_exec: descriptor build skip %s", RS.on ? "check" : "off");
|
||||
}
|
||||
return RS.on;
|
||||
@@ -1458,8 +1456,8 @@ static void bind_vertex_buffers(VkExec *ex) {
|
||||
static int pipe_skip_mode(void) {
|
||||
static int mode = -1;
|
||||
if (mode < 0) {
|
||||
const char *e = cfg_get("TOTK_PIPE_SKIP");
|
||||
mode = !e || !*e ? 1 : !strcmp(e, "strict") || !strcmp(e, "0") ? 0 : !strcmp(e, "fullscreen") || !strcmp(e, "2") ? 2 : 1;
|
||||
const char *e = cfg_value("TOTK_PIPE_SKIP");
|
||||
mode = !strcmp(e, "strict") || !strcmp(e, "0") ? 0 : !strcmp(e, "fullscreen") || !strcmp(e, "2") ? 2 : 1;
|
||||
static const char *const what[3] = {"only draws into per-frame passes (TOTK_PIPE_SKIP=strict)",
|
||||
"draws into passes with a target the previous frame rendered",
|
||||
"those and full-screen draws (TOTK_PIPE_SKIP=fullscreen)"};
|
||||
@@ -1499,8 +1497,8 @@ static int memo_match(const VkExec *ex, uint32_t gen, const MemoKey *k) {
|
||||
|
||||
static int shader_memo_on(void) {
|
||||
if (SM.on < 0) {
|
||||
const char *e = cfg_get("TOTK_SHADER_MEMO");
|
||||
SM.on = e && !strcmp(e, "check") ? 2 : !(e && !strcmp(e, "0"));
|
||||
const char *e = cfg_value("TOTK_SHADER_MEMO");
|
||||
SM.on = !strcmp(e, "check") ? 2 : strcmp(e, "0") != 0;
|
||||
}
|
||||
return SM.on;
|
||||
}
|
||||
|
||||
@@ -908,7 +908,7 @@ int probe_vkexec(void) {
|
||||
nvnx_bytes);
|
||||
printf("probe-vkexec: c0 and zero parts passed (c0 tables, dispatch size, point size and base instance at their offsets, "
|
||||
"unbound slots zero; %d bytes of an unwritten physical-pool texture read zero, TOTK_FIX_ZERO=%s)\n",
|
||||
zero_bytes, cfg_get("TOTK_FIX_ZERO") ? cfg_get("TOTK_FIX_ZERO") : "1");
|
||||
zero_bytes, cfg_value("TOTK_FIX_ZERO"));
|
||||
if (vk_mirror_on)
|
||||
printf("probe-vkexec: mirror part passed (B2B and fill in a VRAM mirror written back by the fence, a CPU write "
|
||||
"between submissions mirrored, CPU bytes beside a fill kept, %d bytes compared)\n", mirror_bytes);
|
||||
|
||||
+3
-4
@@ -213,8 +213,7 @@ static int alloc_physical(VkCtx *c, PoolRec *r) {
|
||||
int vk_fix_zero(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *e = cfg_get("TOTK_FIX_ZERO");
|
||||
on = !(e && !strcmp(e, "0"));
|
||||
on = cfg_bool("TOTK_FIX_ZERO");
|
||||
}
|
||||
return on;
|
||||
}
|
||||
@@ -969,10 +968,10 @@ static volatile LONG64 m_live_n, m_live_bytes, m_refused_n[MR_N], m_refused_byte
|
||||
static volatile LONG64 m_flush_calls, m_flush_bytes, v_pages, v_skipped, v_mismatch;
|
||||
|
||||
static void mirror_mode(int discrete) {
|
||||
const char *e = cfg_get("TOTK_MEMORY");
|
||||
const char *e = cfg_value("TOTK_MEMORY");
|
||||
int mode = discrete ? 1 : 0; // 0 import, 1 mirror, 2 verify
|
||||
const char *why = discrete ? "auto, discrete gpu" : "auto, uma";
|
||||
if (e && *e && strcmp(e, "auto")) {
|
||||
if (strcmp(e, "auto")) {
|
||||
if (!strcmp(e, "import")) mode = 0, why = "TOTK_MEMORY=import";
|
||||
else if (!strcmp(e, "mirror")) mode = 1, why = "TOTK_MEMORY=mirror";
|
||||
else if (!strcmp(e, "verify")) mode = 2, why = "TOTK_MEMORY=verify";
|
||||
|
||||
+12
-15
@@ -251,8 +251,7 @@ static int ensure_init(void) {
|
||||
// Descriptor update templates (core 1.1; the push variant comes with VK_KHR_push_descriptor on 1.1): the driver
|
||||
// walks a layout prepared when the layout is made instead of parsing write structs every draw (DXVK does so for the
|
||||
// same reason). TOTK_DESC_TEMPLATE=0 keeps the write structs.
|
||||
const char *dt = cfg_get("TOTK_DESC_TEMPLATE");
|
||||
if (dt && !strcmp(dt, "0")) {
|
||||
if (!cfg_bool("TOTK_DESC_TEMPLATE")) {
|
||||
rt_log("vk_pipeline: descriptor update templates off (TOTK_DESC_TEMPLATE=0)");
|
||||
} else if (c->props.apiVersion >= VK_API_VERSION_1_1 && PROC(tpl_create, "vkCreateDescriptorUpdateTemplate") &&
|
||||
PROC(tpl_destroy, "vkDestroyDescriptorUpdateTemplate") && PROC(tpl_update, "vkUpdateDescriptorSetWithTemplate")) {
|
||||
@@ -265,7 +264,7 @@ static int ensure_init(void) {
|
||||
// TOTK_VK_DYN_VERTEX=0/1 forces dynamic vertex input off or on. Default off on Intel's frozen Windows driver for its
|
||||
// older integrated GPUs (UHD 630, Ice Lake: Vulkan 1.3.215 and older), which draws nothing with it (LAS Recomp
|
||||
// 61fe44ff, its issues #8 and #357).
|
||||
const char *dv = cfg_get("TOTK_VK_DYN_VERTEX");
|
||||
const char *dv = cfg_get("TOTK_VK_DYN_VERTEX"); // no fixed default: it depends on the GPU, see above
|
||||
int intel_legacy = c->props.vendorID == 0x8086 && c->props.apiVersion <= VK_MAKE_API_VERSION(0, 1, 3, 215);
|
||||
int dv_on = dv && *dv ? strcmp(dv, "0") != 0 : !intel_legacy;
|
||||
P.dyn_vi = dv_on && c->has_vertex_input_dynamic_state && PROC(set_vi, "vkCmdSetVertexInputEXT");
|
||||
@@ -2119,8 +2118,7 @@ static void workers_drain(void) {
|
||||
}
|
||||
|
||||
void vk_pipeline_async_enable(void) {
|
||||
const char *w = cfg_get("TOTK_PIPE_WAIT");
|
||||
U.on = !(w && !strcmp(w, "draw"));
|
||||
U.on = strcmp(cfg_value("TOTK_PIPE_WAIT"), "draw") != 0;
|
||||
const char *e = cfg_get("TOTK_PIPE_SYNC");
|
||||
if (e && *e && strcmp(e, "0")) return;
|
||||
A.on = 1;
|
||||
@@ -2405,10 +2403,10 @@ static DWORD WINAPI warm_builder(void *arg) {
|
||||
static void lb_start(const uint32_t pr_hist[16], const uint32_t fs_hist[4]);
|
||||
|
||||
void vk_pipeline_prewarm(void) {
|
||||
const char *e = cfg_get("TOTK_PIPE_PREBUILD"), *gpu = rt_config()->gpu;
|
||||
const char *gpu = rt_config()->gpu;
|
||||
uint32_t pr_hist[16] = {0}, fs_hist[4] = {0}; // library state of the recorded pipelines (lb_start)
|
||||
if (!A.on || (gpu && !strcmp(gpu, "null"))) return;
|
||||
if (e && !strcmp(e, "0")) { // prebuild_start logs the off case
|
||||
if (!cfg_bool("TOTK_PIPE_PREBUILD")) { // prebuild_start logs the off case
|
||||
if (ensure_init()) lb_start(pr_hist, fs_hist);
|
||||
return;
|
||||
}
|
||||
@@ -2436,7 +2434,7 @@ void vk_pipeline_prewarm(void) {
|
||||
for (size_t i = 0; i < m; i++)
|
||||
if (!u || memcmp(ids[u - 1], ids[i], 32)) memcpy(ids[u++], ids[i], 32);
|
||||
int cpus = (int)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
|
||||
const char *pe = cfg_get("TOTK_PREWARM_XLATE");
|
||||
const char *pe = cfg_get("TOTK_PREWARM_XLATE"); // no fixed default: half the CPUs, at most 16, when unset
|
||||
int procs = pe && *pe ? atoi(pe) : cpus / 2 > 16 ? 16 : cpus / 2;
|
||||
gfx_shader_prewarm((const uint8_t(*)[32])ids, u, sh, cpus, procs < 1 ? 1 : procs);
|
||||
double t1 = now_ms();
|
||||
@@ -2509,9 +2507,8 @@ void vk_pipeline_prewarm(void) {
|
||||
static void prebuild_start(void) {
|
||||
AcquireSRWLockExclusive(&P.lock);
|
||||
if (K.file && !K.warm) {
|
||||
const char *e = cfg_get("TOTK_PIPE_PREBUILD");
|
||||
rt_log("vk_pipeline: prebuild off%s; %zu records not built",
|
||||
e && !strcmp(e, "0") ? " (TOTK_PIPE_PREBUILD=0)" : " (no boot prewarm)", K.file_n);
|
||||
!cfg_bool("TOTK_PIPE_PREBUILD") ? " (TOTK_PIPE_PREBUILD=0)" : " (no boot prewarm)", K.file_n);
|
||||
free(K.file);
|
||||
K.file = NULL;
|
||||
}
|
||||
@@ -2801,9 +2798,9 @@ static void lb_state(const uint32_t pr_hist[16], const uint32_t fs_hist[4]) {
|
||||
|
||||
// Boot: compute shaders of the warm list (recorded and prepared), then the first KEEP recorded graphics variants.
|
||||
static void lb_start(const uint32_t pr_hist[16], const uint32_t fs_hist[4]) {
|
||||
const char *e = cfg_get("TOTK_LIB_PREBUILD"), *te = cfg_get("TOTK_LIB_PREBUILD_THREADS"),
|
||||
*ke = cfg_get("TOTK_LIB_PREBUILD_KEEP");
|
||||
if (!A.on || (e && !strcmp(e, "0"))) return;
|
||||
const char *e = cfg_value("TOTK_LIB_PREBUILD"), *ke = cfg_get("TOTK_LIB_PREBUILD_KEEP");
|
||||
const char *te = cfg_get("TOTK_LIB_PREBUILD_THREADS"); // no fixed default: a quarter of the CPUs when unset
|
||||
if (!A.on || !cfg_bool("TOTK_LIB_PREBUILD")) return;
|
||||
GfxWarmEnt *all = NULL;
|
||||
size_t total = gfx_shader_warm_list(&all), n = 0, n_cs = 0;
|
||||
LB.keep_n = ke && *ke ? atoi(ke) : 0;
|
||||
@@ -2814,7 +2811,7 @@ static void lb_start(const uint32_t pr_hist[16], const uint32_t fs_hist[4]) {
|
||||
for (size_t i = 0; LB.e && i < total && (LONG)(n - n_cs) < LB.keep_n; i++)
|
||||
if (all[i].stage != GFX_STAGE_CS && all[i].prio == 0) LB.e[n++] = all[i];
|
||||
free(all);
|
||||
if (e && atoi(e) > 0 && (size_t)atoi(e) < n) n = (size_t)atoi(e);
|
||||
if (atoi(e) > 1 && (size_t)atoi(e) < n) n = (size_t)atoi(e); // a count above 1 caps the list; 1 is plain on
|
||||
if (!n) {
|
||||
free(LB.e), LB.e = NULL;
|
||||
return;
|
||||
@@ -2922,7 +2919,7 @@ int vk_pipeline_prepare_shaders(void) {
|
||||
if (!cut) return 1;
|
||||
*cut = 0;
|
||||
int cpus = (int)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
|
||||
const char *pe = cfg_get("TOTK_PREWARM_XLATE");
|
||||
const char *pe = cfg_get("TOTK_PREWARM_XLATE"); // no fixed default: half the CPUs, at most 16, when unset
|
||||
int procs = pe && *pe ? atoi(pe) : cpus / 2 > 16 ? 16 : cpus / 2;
|
||||
int rc = gfx_shader_prepare_seed(dir, cpus, procs < 1 ? 1 : procs);
|
||||
if (!rc) lb_warm_prepared(dir);
|
||||
|
||||
@@ -741,8 +741,7 @@ static Tex *entry_of(const tex_t *t) {
|
||||
Tex *e = nvn_hm_get(&by_key, &k);
|
||||
if (!e) {
|
||||
if (tex_alias < 0) {
|
||||
const char *v = cfg_get("TOTK_TEX_ALIAS");
|
||||
tex_alias = !(v && !strcmp(v, "0"));
|
||||
tex_alias = cfg_bool("TOTK_TEX_ALIAS");
|
||||
rt_log("vk: texture aliases: %s", tex_alias ? "a new image takes the live image's content" : "a new image starts empty");
|
||||
}
|
||||
if (!(e = create_tex(t, &k, tex_alias))) return NULL;
|
||||
|
||||
+6
-4
@@ -173,9 +173,10 @@ RUNTIME = ROOT / 'runtime' # --runtime: a copy of runtime/ lets a task build w
|
||||
|
||||
|
||||
def runtime_sources(skip=()):
|
||||
"""Every runtime/*.c, runtime/platform/*.c and runtime/*.rc except the names in skip, so a task adds a file without
|
||||
editing this script."""
|
||||
pats = ('*.c', '*.cpp', 'platform/*.c', '*.rc')
|
||||
"""Every runtime/*.c, *.cpp, platform/*.c, *.rc, the in-game menu (ui/*.cpp) and Dear ImGui except the names in skip,
|
||||
so a task adds a file without editing this script."""
|
||||
pats = ('*.c', '*.cpp', 'platform/*.c', '*.rc', 'ui/*.cpp', 'third_party/imgui/*.cpp',
|
||||
'third_party/imgui/backends/*.cpp')
|
||||
return sorted(p for pat in pats for p in RUNTIME.glob(pat) if p.name not in skip)
|
||||
|
||||
|
||||
@@ -222,7 +223,8 @@ def ninja_file(gen, out, mods, pool_depth, skip=(), prebuilt=False, runtime_lib=
|
||||
except INSTALL_SIDE. make_lib: build only that library, from the runtime objects except INSTALL_SIDE."""
|
||||
inc = f'-I {cmd_path(RUNTIME)} -I {cmd_path(gen)}'
|
||||
vma = f'{cmd_path(DEPS / "include")} -I {cmd_path(DEPS / "include" / "vma")}' if DEPS else cmd_path(VMA_INCLUDE)
|
||||
rt_inc = f'{inc} -I {cmd_path(out)} -I {vma}' # romfs_config.h, vk_mem_alloc.h (and the deps headers)
|
||||
imgui = cmd_path(RUNTIME / 'third_party' / 'imgui')
|
||||
rt_inc = f'{inc} -I {cmd_path(out)} -I {vma} -I {imgui}' # romfs_config.h, vk_mem_alloc.h (+ deps headers), imgui.h
|
||||
libs = [f'-L {cmd_path(DEPS / "lib")}'] + LLVM_LINK_LIBS if DEPS else LINK_LIBS
|
||||
lines = [
|
||||
'# Written by tools/build_game.py; do not edit.',
|
||||
|
||||
@@ -21,6 +21,10 @@
|
||||
[display]
|
||||
# Presentation mode: mailbox (default when the driver offers it, vsync otherwise), fifo (vsync) or immediate.
|
||||
# vk_present = mailbox
|
||||
# Window client area in pixels (640x360 to 7680x4320), and borderless fullscreen. F11 switches fullscreen and saves it
|
||||
# here. Changes while the game runs take effect at once.
|
||||
# window_size = 1920x1080
|
||||
# fullscreen = 0
|
||||
# Which GPU to use: its index in the log, or part of its name. Default: the first discrete GPU with Vulkan 1.3.
|
||||
# gpu_index = 0
|
||||
# gpu_name = NVIDIA
|
||||
@@ -37,6 +41,8 @@
|
||||
# audio = default
|
||||
# Audio the output queues before it starts, in ms (0 to 500).
|
||||
# audio_prefill_ms = 20
|
||||
# Volume in percent (0 to 100), on top of the game's own. Changes while the game runs take effect at once.
|
||||
# volume = 100
|
||||
|
||||
[input]
|
||||
# Gamepad motion controls (0 = off) and vibration (0 = off).
|
||||
|
||||
Reference in new issue
Block a user