diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index ad327b53..406efdae 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -24,6 +24,7 @@ Code copied or adapted from another project is listed here with its source, the | 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` | +| SavageWindRecomp performance overlay: the frame ring and its one-second summary, the NVML calls, the sampling loop, the full panel's layout | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/perfmon.c`, `runtime/perfmon.h`, `perf_overlay_draw` in `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/perfmon.c`, `runtime/perfmon.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` | diff --git a/runtime/cfg.c b/runtime/cfg.c index 328a8443..828dbf16 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -247,6 +247,20 @@ int cfg_reset(const char *const *keys, int n) { int cfg_last_save_ok(void) { return __atomic_load_n(&save_ok, __ATOMIC_ACQUIRE); } +void cfg_each_active(void (*cb)(const char *key, const char *value, int from_env, void *ctx), void *ctx) { + int n = __atomic_load_n(&n_entries, __ATOMIC_ACQUIRE); + for (int i = 0; i < n; i++) { + const char *v = __atomic_load_n(&entries[i].value, __ATOMIC_ACQUIRE); + if (v) cb(entries[i].key, v, 0, ctx); + } + for (size_t i = 0; i < sizeof known / sizeof *known; i++) { + char var[80]; + snprintf(var, sizeof var, PREFIX "%s", known[i]); + const char *e = getenv(var); + if (e) cb(known[i], e, 1, ctx); + } +} + const CfgMeta *cfg_meta(const char *key) { char k[64]; snprintf(k, sizeof k, "%s", key); diff --git a/runtime/cfg.h b/runtime/cfg.h index 0fb1468f..7d641216 100644 --- a/runtime/cfg.h +++ b/runtime/cfg.h @@ -34,6 +34,9 @@ int cfg_save_to(const char *path); 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); +// Every setting with a value, for a bug report ("Copy system info"): the totk.ini and cfg_set keys (name without +// TOTK_, upper case; from_env 0), then the known TOTK_ variables the environment sets (from_env 1). +void cfg_each_active(void (*cb)(const char *key, const char *value, int from_env, void *ctx), void *ctx); // 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 diff --git a/runtime/gfx_window.c b/runtime/gfx_window.c index 3ba52f1e..691b99e0 100644 --- a/runtime/gfx_window.c +++ b/runtime/gfx_window.c @@ -433,6 +433,8 @@ static DWORD WINAPI window_main(void *arg) { } // ---- swapchain +static const char *g_present_got = ""; // the TOTK_VK_PRESENT value of the mode the swapchain got; "" before one + static VkPresentModeKHR pick_present_mode(VkPhysicalDevice pd) { const char *e = cfg_value("TOTK_VK_PRESENT"); VkPresentModeKHR want = !strcmp(e, "mailbox") ? VK_PRESENT_MODE_MAILBOX_KHR @@ -444,15 +446,18 @@ static VkPresentModeKHR pick_present_mode(VkPhysicalDevice pd) { vkGetPhysicalDeviceSurfacePresentModesKHR(pd, g_surface, &n, m); VkPresentModeKHR got = VK_PRESENT_MODE_FIFO_KHR; for (uint32_t i = 0; i < n; i++) if (m[i] == want) got = want; + const char *name = got == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : got == VK_PRESENT_MODE_IMMEDIATE_KHR ? "immediate" : "fifo"; + __atomic_store_n(&g_present_got, name, __ATOMIC_RELEASE); 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); + rt_log("gfx: present mode %s (TOTK_VK_PRESENT=%s)", name, e); } return got; } +const char *gfx_window_present_mode(void) { return __atomic_load_n(&g_present_got, __ATOMIC_ACQUIRE); } + // Queues the present of a blit vk_present_blit left waiting (g_pl held). A swapchain rebuild and the next blit flush it // first; the device release drops it. static void flip_locked(void) { diff --git a/runtime/host.h b/runtime/host.h index ff2e9cb3..497ad917 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -52,6 +52,12 @@ typedef struct { uint64_t vram_used, vram_budget; } PerfGpu; extern void (*perf_gpu_stats)(PerfGpu *out); +// The performance overlay (perfmon.c): mode 0 off, 1 fps, 2 full. While it is on, perf_present hands every frame to +// perfmon_frame; full also takes the event counts (perf_count) and the GPU timestamps as TOTK_TRACE=perf does. +void perf_set_overlay(int mode); +int perf_gpu_timing(void); // GPU timestamps wanted: TOTK_TRACE=perf or the full overlay +void perf_gpu_busy(uint64_t ns); // GPU busy time of a timed submission part (vk_sync.c, any thread) +uint64_t perf_gpu_busy_total(void); // its running total (the overlay's GPU time per frame) #define RT_RESULT(module, desc) ((uint32_t)(module) | ((uint32_t)(desc) << 9)) void rt_sha256(const void *p, size_t n, uint8_t out[32]); // BCrypt; fatal if the provider fails diff --git a/runtime/perfmon.c b/runtime/perfmon.c new file mode 100644 index 00000000..d5a3f8d8 --- /dev/null +++ b/runtime/perfmon.c @@ -0,0 +1,252 @@ +// Performance overlay numbers (runtime/perfmon.h). Frame times come from the game's presents (perf_present, only while +// the overlay is on); the per-frame waits from the perf counters prof_win.c keeps. The machine's numbers are sampled +// twice a second on a thread of their own (some calls take milliseconds), which runs only while the overlay is full. +// The OS calls sit behind platform.h (plat_cpu_load, plat_mem_info, plat_gpu_load); NVML (NVIDIA's driver library, +// for temperature, power and clock) is loaded at run time and is missing on other machines: its numbers stay -1. +// +// Adapted from SavageWindRecomp's runtime/perfmon.c (https://github.com/Revivedx/SavageWindRecomp @ +// 575ad88e02f9a89a9a885d90039d48af33c982f4, MIT, Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, +// Copyright (c) 2026 Peiikai): the frame ring and its one-second summary, the NVML calls, the sampler loop. The +// Windows, Linux and macOS sampling moved behind platform.h, GPU load and video memory come from the system's counters +// for every vendor, and the sampler stops when the overlay leaves full. +#include +#include + +#include "host.h" +#include "perfmon.h" +#include "platform/platform.h" +#include "sysinfo.h" + +static PlatMutex g_lock = PLAT_MUTEX_INIT; // everything below +static PerfStats g_stats; // the machine numbers the sampler wrote; the rest is made per snapshot + +// ---- frames +static float g_ring[PERF_HISTORY]; +static uint64_t g_ring_at[PERF_HISTORY]; // when each frame ended +static int g_ring_n, g_ring_pos; + +// The per-frame counters, summed since t0 (the overlay's lines are averages over half a second). +static struct { + uint64_t t0, frames, gpu0; + double replay, pipe, xlate, tex; + int64_t up0, up; +} g_win; + +void perfmon_frame(uint64_t now, uint64_t interval_ns, const uint64_t *wait_ns, uint64_t replay_ns, + int64_t tex_uploads) { + plat_mutex_lock(&g_lock); + if (interval_ns) { + g_ring[g_ring_pos] = (float)(interval_ns / 1e6); + g_ring_at[g_ring_pos] = now; + g_ring_pos = (g_ring_pos + 1) % PERF_HISTORY; + if (g_ring_n < PERF_HISTORY) g_ring_n++; + } + g_win.frames++; + g_win.replay += replay_ns / 1e6; + g_win.pipe += wait_ns[PERF_PIPE] / 1e6; + g_win.xlate += wait_ns[PERF_XLATE] / 1e6; + g_win.tex += wait_ns[PERF_TEX] / 1e6; + g_win.up = tex_uploads; + plat_mutex_unlock(&g_lock); +} + +static void frames_summary(PerfStats *s, uint64_t now) { // (lock held) + double sum = 0, mx = 0; + int n = 0; + for (int i = 0; i < g_ring_n; i++) { + int k = (g_ring_pos - 1 - i + PERF_HISTORY) % PERF_HISTORY; + if (now - g_ring_at[k] > 1000000000ull) break; // the last second + sum += g_ring[k]; + if (g_ring[k] > mx) mx = g_ring[k]; + n++; + } + s->fps = n && sum > 0 ? (float)(n * 1000.0 / sum) : 0; + s->frame_ms_avg = n ? (float)(sum / n) : 0; + s->frame_ms_max = (float)mx; + for (int i = 0; i < PERF_HISTORY; i++) { // oldest first; frames not seen yet read 0 + int age = PERF_HISTORY - 1 - i; + s->frame_ms[i] = age < g_ring_n ? g_ring[(g_ring_pos - 1 - age + 2 * PERF_HISTORY) % PERF_HISTORY] : 0; + } +} + +// Every half second: the window's sums as per-frame averages into g_stats, and a new window. (lock held) +static void counters_summary(uint64_t now) { + if (now - g_win.t0 < 500000000ull) return; + uint64_t gpu = perf_gpu_busy_total(); + if (g_win.t0 && g_win.frames) { + double n = (double)g_win.frames; + g_stats.replay_ms = (float)(g_win.replay / n); + g_stats.pipe_wait_ms = (float)(g_win.pipe / n); + g_stats.xlate_ms = (float)(g_win.xlate / n); + g_stats.tex_ms = (float)(g_win.tex / n); + g_stats.tex_uploads = (float)((g_win.up - g_win.up0) / n); + // no GPU time over a window of frames: no timestamps on this device (or not yet set up) + g_stats.gpu_ms = gpu > g_win.gpu0 ? (float)((gpu - g_win.gpu0) / 1e6 / n) : -1; + } + g_win.t0 = now; + g_win.frames = 0; + g_win.gpu0 = gpu; + g_win.replay = g_win.pipe = g_win.xlate = g_win.tex = 0; + g_win.up0 = g_win.up; +} + +// ---- NVML (NVIDIA): loaded once on the sampler thread, kept for the process +typedef struct { unsigned gpu, memory; } NvmlUtil; +typedef struct { unsigned long long total, free, used; } NvmlMem; +static struct { + int tried, ok; + void *dev; + int (*util)(void *, NvmlUtil *); + int (*temp)(void *, int, unsigned *); + int (*mem)(void *, NvmlMem *); + int (*power)(void *, unsigned *); + int (*clock)(void *, int, unsigned *); +} nv; + +static char g_gpu_name[96]; +static uint8_t g_gpu_luid[8]; +static int g_gpu_luid_ok; +static float g_vram_total_mb = -1; + +void perfmon_set_gpu(const char *name, const uint8_t *luid, float vram_total_mb) { + plat_mutex_lock(&g_lock); + snprintf(g_gpu_name, sizeof g_gpu_name, "%s", name ? name : ""); + g_gpu_luid_ok = luid != NULL; + if (luid) memcpy(g_gpu_luid, luid, sizeof g_gpu_luid); + g_vram_total_mb = vram_total_mb > 0 ? vram_total_mb : -1; + plat_mutex_unlock(&g_lock); +} + +static void nvml_open(const char *hint) { + nv.tried = 1; +#ifdef _WIN32 + static const char *const names[] = {"nvml.dll", "C:\\Program Files\\NVIDIA Corporation\\NVSMI\\nvml.dll"}; +#else + static const char *const names[] = {"libnvidia-ml.so.1"}; +#endif + void *lib = NULL; + for (size_t i = 0; !lib && i < sizeof names / sizeof *names; i++) lib = plat_lib_open(names[i]); + if (!lib) return; + int (*init)(void) = (int (*)(void))plat_lib_sym(lib, "nvmlInit_v2"); + int (*count)(unsigned *) = (int (*)(unsigned *))plat_lib_sym(lib, "nvmlDeviceGetCount_v2"); + int (*handle)(unsigned, void **) = (int (*)(unsigned, void **))plat_lib_sym(lib, "nvmlDeviceGetHandleByIndex_v2"); + int (*name)(void *, char *, unsigned) = (int (*)(void *, char *, unsigned))plat_lib_sym(lib, "nvmlDeviceGetName"); + nv.util = (int (*)(void *, NvmlUtil *))plat_lib_sym(lib, "nvmlDeviceGetUtilizationRates"); + nv.temp = (int (*)(void *, int, unsigned *))plat_lib_sym(lib, "nvmlDeviceGetTemperature"); + nv.mem = (int (*)(void *, NvmlMem *))plat_lib_sym(lib, "nvmlDeviceGetMemoryInfo"); + nv.power = (int (*)(void *, unsigned *))plat_lib_sym(lib, "nvmlDeviceGetPowerUsage"); + nv.clock = (int (*)(void *, int, unsigned *))plat_lib_sym(lib, "nvmlDeviceGetClockInfo"); + if (!init || !count || !handle || init() != 0) return; + unsigned n = 0; + if (count(&n) != 0 || !n) return; + // the device Vulkan renders on (by name; an NVIDIA name only matches an NVIDIA GPU), else none: on a machine + // that renders on another vendor's GPU, NVML's numbers would belong to the wrong card + for (unsigned i = 0; i < n && !nv.dev; i++) { + void *d = NULL; + char nm[96] = ""; + if (handle(i, &d) != 0 || !name || name(d, nm, sizeof nm) != 0 || !nm[0]) continue; + if (hint[0] && (strstr(hint, nm) || strstr(nm, hint))) nv.dev = d; + } + nv.ok = nv.dev != NULL; + rt_log("perfmon: NVML %s", nv.ok ? "found the rendering GPU" : "has no device matching the rendering GPU"); +} + +static void nvml_sample(PerfStats *s) { + if (!nv.ok) return; + NvmlUtil u; + NvmlMem m; + unsigned v; + if (s->gpu_pct < 0 && nv.util && nv.util(nv.dev, &u) == 0) s->gpu_pct = (float)u.gpu; // the system's counters first + if (nv.mem && nv.mem(nv.dev, &m) == 0) { + if (s->vram_used_mb < 0) s->vram_used_mb = (float)(m.used >> 20); + s->vram_total_mb = (float)(m.total >> 20); + } + if (nv.temp && nv.temp(nv.dev, 0 /* NVML_TEMPERATURE_GPU */, &v) == 0) s->gpu_temp_c = (float)v; + if (nv.power && nv.power(nv.dev, &v) == 0) s->gpu_power_w = v / 1000.0f; + if (nv.clock && nv.clock(nv.dev, 0 /* NVML_CLOCK_GRAPHICS */, &v) == 0) s->gpu_clock_mhz = (float)v; +} + +// ---- the machine sampler: runs while want is set, twice a second +static struct { + int want, alive; + PlatCond cv; +} g_smp = {0, 0, PLAT_COND_INIT}; + +static void machine_clear(PerfStats *s) { + s->cpu_total_pct = s->cpu_game_pct = s->cpu_temp_c = -1; + s->ram_used_mb = s->ram_total_mb = s->ram_game_mb = -1; + s->gpu_pct = s->gpu_temp_c = s->gpu_power_w = s->gpu_clock_mhz = s->vram_used_mb = s->vram_total_mb = -1; +} + +static void machine_copy(PerfStats *d, const PerfStats *s) { + memcpy(d->cpu_name, s->cpu_name, sizeof d->cpu_name); + memcpy(d->gpu_name, s->gpu_name, sizeof d->gpu_name); + d->cpu_total_pct = s->cpu_total_pct, d->cpu_game_pct = s->cpu_game_pct, d->cpu_temp_c = s->cpu_temp_c; + d->ram_used_mb = s->ram_used_mb, d->ram_total_mb = s->ram_total_mb, d->ram_game_mb = s->ram_game_mb; + d->gpu_pct = s->gpu_pct, d->gpu_temp_c = s->gpu_temp_c, d->gpu_power_w = s->gpu_power_w; + d->gpu_clock_mhz = s->gpu_clock_mhz, d->vram_used_mb = s->vram_used_mb, d->vram_total_mb = s->vram_total_mb; +} + +static void sampler(void *arg) { + (void)arg; + PerfStats s; + memset(&s, 0, sizeof s); + plat_mutex_lock(&g_lock); + uint8_t luid[8]; + int have_luid = g_gpu_luid_ok; + memcpy(luid, g_gpu_luid, sizeof luid); + snprintf(s.gpu_name, sizeof s.gpu_name, "%s", g_gpu_name); + float vram_total = g_vram_total_mb; + plat_mutex_unlock(&g_lock); + sysinfo_cpu_name(s.cpu_name, sizeof s.cpu_name); + if (!nv.tried) nvml_open(s.gpu_name); + PlatLoad *l = plat_load_open(have_luid ? luid : NULL); + plat_mutex_lock(&g_lock); + while (g_smp.want) { + plat_mutex_unlock(&g_lock); + machine_clear(&s); + plat_cpu_load(l, &s.cpu_total_pct, &s.cpu_game_pct, &s.cpu_temp_c); + plat_mem_info(&s.ram_used_mb, &s.ram_total_mb, &s.ram_game_mb); + plat_gpu_load(l, &s.gpu_pct, &s.vram_used_mb); + s.vram_total_mb = vram_total; + nvml_sample(&s); + plat_mutex_lock(&g_lock); + machine_copy(&g_stats, &s); + if (g_smp.want) plat_cond_wait_ns(&g_smp.cv, &g_lock, 500000000ull); + } + g_smp.alive = 0; // in the same locked section as the last want check: a new perfmon_mode(2) starts a new thread + plat_mutex_unlock(&g_lock); + plat_load_close(l); +} + +void perfmon_mode(int mode) { + perf_set_overlay(mode); + plat_mutex_lock(&g_lock); + if (mode == 2) { + g_smp.want = 1; + if (!g_smp.alive) { + machine_clear(&g_stats); // "-" until the first sample, not the numbers of the last time + PlatThread *t = plat_thread_new(sampler, NULL, "perfmon"); + g_smp.alive = t != NULL; + if (t) plat_thread_detach(t); + else rt_log("perfmon: cannot start the sampling thread; the machine numbers stay empty"); + } + } else { + g_smp.want = 0; + plat_cond_signal(&g_smp.cv); + } + if (!mode) { // the next start begins a new graph and a new counter window + g_ring_n = g_ring_pos = 0; + memset(&g_win, 0, sizeof g_win); + } + plat_mutex_unlock(&g_lock); +} + +void perfmon_snapshot(PerfStats *out) { + uint64_t now = plat_now_ns(); + plat_mutex_lock(&g_lock); + frames_summary(&g_stats, now); + counters_summary(now); + *out = g_stats; + plat_mutex_unlock(&g_lock); +} diff --git a/runtime/perfmon.h b/runtime/perfmon.h new file mode 100644 index 00000000..2d06c8cc --- /dev/null +++ b/runtime/perfmon.h @@ -0,0 +1,52 @@ +// Performance overlay numbers (runtime/perfmon.c): the game's frame rate and frame times, the render thread's waits +// from the perf counters, and the machine's CPU, memory and GPU load and temperatures. A value the machine does not give +// is negative. +// +// Adapted from SavageWindRecomp's runtime/perfmon.h (https://github.com/Revivedx/SavageWindRecomp @ +// 575ad88e02f9a89a9a885d90039d48af33c982f4, MIT, Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, +// Copyright (c) 2026 Peiikai). +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define PERF_HISTORY 120 // frame times kept for the graph + +typedef struct { + // the game's frames (presents), over the last second + float fps, frame_ms_avg, frame_ms_max; + float frame_ms[PERF_HISTORY]; // oldest first + // CPU: the whole machine and this process, percent of all logical processors + char cpu_name[64]; + float cpu_total_pct, cpu_game_pct, cpu_temp_c; + // memory, MB + float ram_used_mb, ram_total_mb, ram_game_mb; + // GPU: load and dedicated memory from the system's counters, temperature, power and clock from NVML (NVIDIA) + char gpu_name[96]; + float gpu_pct, gpu_temp_c, gpu_power_w, gpu_clock_mhz, vram_used_mb, vram_total_mb; + // per frame, averaged over the last half second: replay (NVN to Vulkan recording), GPU busy time (timestamps; -1 + // without them), the render thread's waits for pipeline builds, shader translation and texture uploads, and the + // textures uploaded + float replay_ms, gpu_ms, pipe_wait_ms, xlate_ms, tex_ms, tex_uploads; +} PerfStats; + +// Overlay mode 0 off, 1 fps, 2 full (TOTK_PERF_OVERLAY), from the present path when the setting changes. Full starts +// the machine sampling thread (twice a second) and turns on the event counts and GPU timestamps; leaving full stops +// them. Off: perf_present skips perfmon_frame and nothing samples. +void perfmon_mode(int mode); +// The Vulkan device the game renders on: its name, its LUID (8 bytes; NULL when the driver gives none) and its +// device-local memory. Before the first perfmon_mode(2). +void perfmon_set_gpu(const char *name, const uint8_t *luid, float vram_total_mb); +// A game frame was presented (perf_present, the render thread, only while the overlay is on): the time since the last +// one, the render thread's waits of this frame (PERF_N entries, host.h), its replay time and the running count of +// texture uploads. +void perfmon_frame(uint64_t now_ns, uint64_t interval_ns, const uint64_t *wait_ns, uint64_t replay_ns, + int64_t tex_uploads); +// The latest numbers (the overlay, present path). +void perfmon_snapshot(PerfStats *out); + +#ifdef __cplusplus +} +#endif diff --git a/runtime/platform/platform.h b/runtime/platform/platform.h index 35205e57..d863a021 100644 --- a/runtime/platform/platform.h +++ b/runtime/platform/platform.h @@ -72,6 +72,35 @@ uint32_t plat_thread_id(void); // id of the calling t // 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); +// The operating system and its build ("Windows 10.0.28000") into out; 0 when unknown. +int plat_os_version(char *out, size_t cap); +// The file the process's stderr (the log) goes to, as a UTF-8 path; 0 when stderr is not a file (a console, a pipe). +int plat_stderr_path(char *out, size_t cap); + +// ---- desktop: the in-game menu's "Copy system info" and "Open log folder" +int plat_clipboard_set(const char *utf8); // replaces the clipboard's text; 1 on success +int plat_open_folder(const char *path); // shows the folder in the file manager; 1 on success + +// ---- dynamic libraries: a library some machines lack (a GPU vendor's), loaded at run time. A bare name is searched +// in the system directories only. NULL when missing. +void *plat_lib_open(const char *name); +void *plat_lib_sym(void *lib, const char *name); + +// ---- machine load for the performance overlay (perfmon.c's sampling thread; each call can take milliseconds). A number +// the system does not give is -1. +typedef struct PlatLoad PlatLoad; +// Opens the counters: CPU times, the thermal zones, and the GPU engine and memory counters of the adapter whose LUID is +// gpu_luid (8 bytes, Vulkan's deviceLUID; NULL: the busiest adapter). Never NULL. +PlatLoad *plat_load_open(const uint8_t *gpu_luid); +void plat_load_close(PlatLoad *l); +// Since the previous call on l (the first call gives -1): CPU use of the machine and of this process, percent of all +// logical processors, and the hottest ACPI thermal zone in degrees Celsius. +void plat_cpu_load(PlatLoad *l, float *total_pct, float *proc_pct, float *temp_c); +// Since the previous call on l: the busiest GPU engine type in percent (as Task Manager shows it), and the adapter's +// dedicated memory in use in MB. Any GPU vendor. +void plat_gpu_load(PlatLoad *l, float *load_pct, float *vram_used_mb); +// Physical memory in MB: in use and installed on the machine, and this process's working set. +void plat_mem_info(float *used_mb, float *total_mb, float *proc_mb); // ---- child processes: a program with stdin and stdout piped to us (stderr discarded), no console window. typedef struct PlatChild PlatChild; diff --git a/runtime/platform/win32.c b/runtime/platform/win32.c index e46759be..7dd424fd 100644 --- a/runtime/platform/win32.c +++ b/runtime/platform/win32.c @@ -2,9 +2,14 @@ // SRW locks and condition variables. #include #include +#include +#include +#include +#include #include #include #include +#include #include "platform.h" @@ -330,6 +335,265 @@ int plat_font_path(const char *lang, char *out, size_t cap) { return 0; } +int plat_os_version(char *out, size_t cap) { + // GetVersionEx reports the version the manifest asks for; ntdll's RtlGetVersion the real one + typedef LONG(WINAPI * RtlGetVersion_t)(OSVERSIONINFOW *); + HMODULE nt = GetModuleHandleW(L"ntdll.dll"); + RtlGetVersion_t get = nt ? (RtlGetVersion_t)(void *)GetProcAddress(nt, "RtlGetVersion") : NULL; + OSVERSIONINFOW v = {.dwOSVersionInfoSize = sizeof v}; + if (!get || get(&v) != 0) return 0; + DWORD ubr = 0, size = sizeof ubr; // the update build revision, the number after the build + if (RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"UBR", RRF_RT_REG_DWORD, + NULL, &ubr, &size) != ERROR_SUCCESS) + ubr = 0; + snprintf(out, cap, ubr ? "Windows %lu.%lu.%lu.%lu" : "Windows %lu.%lu.%lu", v.dwMajorVersion, v.dwMinorVersion, + v.dwBuildNumber, ubr); + return 1; +} + +int plat_stderr_path(char *out, size_t cap) { + HANDLE h = GetStdHandle(STD_ERROR_HANDLE); + wchar_t w[WPATH]; + if (!h || h == INVALID_HANDLE_VALUE || GetFileType(h) != FILE_TYPE_DISK) return 0; + DWORD n = GetFinalPathNameByHandleW(h, w, WPATH, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); + if (!n || n >= WPATH) return 0; + const wchar_t *p = wcsncmp(w, L"\\\\?\\", 4) ? w : w + 4; // the \\?\ prefix + return WideCharToMultiByte(CP_UTF8, 0, p, -1, out, (int)cap, NULL, NULL) != 0; +} + +// ---- desktop + +int plat_clipboard_set(const char *utf8) { + int n = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); + if (n <= 0) return 0; + HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)n * sizeof(wchar_t)); + if (!mem) return 0; + wchar_t *w = GlobalLock(mem); + MultiByteToWideChar(CP_UTF8, 0, utf8, -1, w, n); + GlobalUnlock(mem); + // A clipboard opened without a window gets no owner, and SetClipboardData may then fail: a message-only window of + // the calling thread owns it for the call. + HWND owner = CreateWindowExW(0, L"STATIC", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); + int ok = 0; + if (OpenClipboard(owner)) { + ok = EmptyClipboard() && SetClipboardData(CF_UNICODETEXT, mem) != NULL; + CloseClipboard(); + } + if (owner) DestroyWindow(owner); + if (!ok) GlobalFree(mem); // after a successful SetClipboardData the system owns it + return ok; +} + +static DWORD WINAPI open_folder_main(void *arg) { + ShellExecuteW(NULL, L"open", arg, NULL, NULL, SW_SHOWNORMAL); + free(arg); + return 0; +} + +int plat_open_folder(const char *path) { + wchar_t *w = malloc(WPATH * sizeof *w); + if (!w || !widen(path, w, WPATH)) return free(w), 0; + DWORD a = GetFileAttributesW(w); + if (a == INVALID_FILE_ATTRIBUTES || !(a & FILE_ATTRIBUTE_DIRECTORY)) return free(w), 0; + // the shell can take a while to answer: not on the caller's thread (the present path) + HANDLE t = CreateThread(NULL, 0, open_folder_main, w, 0, NULL); + if (!t) return free(w), 0; + CloseHandle(t); + return 1; +} + +// ---- dynamic libraries + +void *plat_lib_open(const char *name) { + wchar_t w[WPATH]; + if (!widen(name, w, WPATH)) return NULL; + int bare = !wcschr(w, L'\\') && !wcschr(w, L'/'); + return (void *)LoadLibraryExW(w, NULL, bare ? LOAD_LIBRARY_SEARCH_SYSTEM32 : 0); +} + +void *plat_lib_sym(void *lib, const char *name) { return lib ? (void *)GetProcAddress((HMODULE)lib, name) : NULL; } + +// ---- machine load: GetSystemTimes for the CPU, PDH (pdh.dll, loaded on first use) for the thermal zones and the GPU +// engine and adapter memory counters that Task Manager reads. + +typedef PDH_STATUS(WINAPI *PdhOpenQueryW_t)(LPCWSTR, DWORD_PTR, PDH_HQUERY *); +typedef PDH_STATUS(WINAPI *PdhAddEnglishCounterW_t)(PDH_HQUERY, LPCWSTR, DWORD_PTR, PDH_HCOUNTER *); +typedef PDH_STATUS(WINAPI *PdhCollectQueryData_t)(PDH_HQUERY); +typedef PDH_STATUS(WINAPI *PdhGetFormattedCounterArrayW_t)(PDH_HCOUNTER, DWORD, LPDWORD, LPDWORD, + PPDH_FMT_COUNTERVALUE_ITEM_W); +typedef PDH_STATUS(WINAPI *PdhCloseQuery_t)(PDH_HQUERY); +static struct { + INIT_ONCE once; + PdhOpenQueryW_t open; + PdhAddEnglishCounterW_t add; + PdhCollectQueryData_t collect; + PdhGetFormattedCounterArrayW_t get; + PdhCloseQuery_t close; +} pdh = {INIT_ONCE_STATIC_INIT}; + +static BOOL CALLBACK pdh_load(INIT_ONCE *o, void *p, void **c) { + (void)o, (void)p, (void)c; + HMODULE l = plat_lib_open("pdh.dll"); + if (!l) return TRUE; + pdh.add = (PdhAddEnglishCounterW_t)(void *)GetProcAddress(l, "PdhAddEnglishCounterW"); + pdh.collect = (PdhCollectQueryData_t)(void *)GetProcAddress(l, "PdhCollectQueryData"); + pdh.get = (PdhGetFormattedCounterArrayW_t)(void *)GetProcAddress(l, "PdhGetFormattedCounterArrayW"); + pdh.close = (PdhCloseQuery_t)(void *)GetProcAddress(l, "PdhCloseQuery"); + PdhOpenQueryW_t open = (PdhOpenQueryW_t)(void *)GetProcAddress(l, "PdhOpenQueryW"); + if (pdh.add && pdh.collect && pdh.get && pdh.close) pdh.open = open; // open set: all of them are there + return TRUE; +} + +// One PDH query with its wildcard counters ("\Object(*)\Counter"). A query whose open failed stays NULL. +typedef struct { PDH_HQUERY q; PDH_HCOUNTER c[2]; } PdhQuery; + +static void pdh_query(PdhQuery *pq, const wchar_t *c0, const wchar_t *c1) { + InitOnceExecuteOnce(&pdh.once, pdh_load, NULL, NULL); + pq->q = NULL; + if (!pdh.open || pdh.open(NULL, 0, &pq->q) != ERROR_SUCCESS) { + pq->q = NULL; + return; + } + if (pdh.add(pq->q, c0, 0, &pq->c[0]) != ERROR_SUCCESS) pq->c[0] = NULL; + if (!c1 || pdh.add(pq->q, c1, 0, &pq->c[1]) != ERROR_SUCCESS) pq->c[1] = NULL; + if (!pq->c[0] && !pq->c[1]) { + pdh.close(pq->q); + pq->q = NULL; + } +} + +// The counter's instances as a malloc'd array (free it), *count of them; NULL when there is no valid data yet (a rate +// counter needs two collections). +static PDH_FMT_COUNTERVALUE_ITEM_W *pdh_items(PDH_HCOUNTER c, DWORD *count) { + DWORD size = 0; + *count = 0; + if (!c || pdh.get(c, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100, &size, count, NULL) != PDH_MORE_DATA || !size) return NULL; + PDH_FMT_COUNTERVALUE_ITEM_W *items = malloc(size); + if (items && pdh.get(c, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100, &size, count, items) == ERROR_SUCCESS) return items; + free(items); + *count = 0; + return NULL; +} + +struct PlatLoad { + uint64_t idle, kernel, user, proc; // the previous call's times; kernel 0 before the first + PdhQuery thermal, gpu; // gpu: engine utilisation, adapter dedicated memory + wchar_t luid[40]; // "luid_0x_0x" of the adapter, lower case; empty for any +}; + +PlatLoad *plat_load_open(const uint8_t *gpu_luid) { + PlatLoad *l = calloc(1, sizeof *l); + if (!l) return NULL; + if (gpu_luid) { // Vulkan's deviceLUID is the LUID struct's memory: LowPart, then HighPart + uint32_t lo, hi; + memcpy(&lo, gpu_luid, 4); + memcpy(&hi, gpu_luid + 4, 4); + swprintf(l->luid, sizeof l->luid / sizeof *l->luid, L"luid_0x%08x_0x%08x", hi, lo); + } + pdh_query(&l->thermal, L"\\Thermal Zone Information(*)\\Temperature", NULL); + pdh_query(&l->gpu, L"\\GPU Engine(*)\\Utilization Percentage", L"\\GPU Adapter Memory(*)\\Dedicated Usage"); + return l; +} + +void plat_load_close(PlatLoad *l) { + if (!l) return; + if (l->thermal.q) pdh.close(l->thermal.q); + if (l->gpu.q) pdh.close(l->gpu.q); + free(l); +} + +static uint64_t ft64(FILETIME f) { return (uint64_t)f.dwHighDateTime << 32 | f.dwLowDateTime; } + +void plat_cpu_load(PlatLoad *l, float *total_pct, float *proc_pct, float *temp_c) { + *total_pct = *proc_pct = *temp_c = -1; + if (!l) return; + FILETIME idle, kern, user, cr, ex, pk, pu; + if (GetSystemTimes(&idle, &kern, &user) && GetProcessTimes(GetCurrentProcess(), &cr, &ex, &pk, &pu)) { + uint64_t i = ft64(idle), k = ft64(kern), u = ft64(user), p = ft64(pk) + ft64(pu); + uint64_t total = (k - l->kernel) + (u - l->user); // kernel time includes idle time + if (l->kernel && total) { + *total_pct = 100.0f * (float)(total - (i - l->idle)) / (float)total; + *proc_pct = 100.0f * (float)(p - l->proc) / (float)total; + } + l->idle = i, l->kernel = k, l->user = u, l->proc = p; + } + // the firmware's ACPI zones, near the CPU on most boards; the exact package temperature needs a kernel driver + DWORD n; + PDH_FMT_COUNTERVALUE_ITEM_W *it; + if (l->thermal.q && pdh.collect(l->thermal.q) == ERROR_SUCCESS && (it = pdh_items(l->thermal.c[0], &n))) { + for (DWORD i = 0; i < n; i++) { // the hottest zone, in kelvin + double c = it[i].FmtValue.doubleValue - 273.15; + if (it[i].FmtValue.CStatus == PDH_CSTATUS_VALID_DATA && c > *temp_c && c < 150) *temp_c = (float)c; + } + free(it); + } +} + +// The adapter part of an instance name, "luid_0x..._0x...", lower case, into out (40 wide characters). +static void inst_luid(const wchar_t *name, wchar_t *out) { + const wchar_t *p = wcsstr(name, L"luid_"); + size_t n = 0; + while (p && p[n] && n < 26 && n < 39) out[n] = (wchar_t)towlower(p[n]), n++; // luid_0x%08x_0x%08x: 26 + out[n] = 0; +} + +void plat_gpu_load(PlatLoad *l, float *load_pct, float *vram_used_mb) { + *load_pct = *vram_used_mb = -1; + if (!l || !l->gpu.q || pdh.collect(l->gpu.q) != ERROR_SUCCESS) return; + // Engine instances: "pid__luid_0x.._0x.._phys__eng__engtype_". Per adapter and engine type the + // processes' shares add up; the load is the busiest engine type. + enum { TYPES = 32 }; + struct { wchar_t luid[40], type[32]; double sum; } t[TYPES]; + int nt = 0; + DWORD n; + PDH_FMT_COUNTERVALUE_ITEM_W *it = pdh_items(l->gpu.c[0], &n); + for (DWORD i = 0; it && i < n; i++) { + if (it[i].FmtValue.CStatus != PDH_CSTATUS_VALID_DATA) continue; + wchar_t lu[40]; + inst_luid(it[i].szName, lu); + if (l->luid[0] && wcscmp(lu, l->luid)) continue; + const wchar_t *ty = wcsstr(it[i].szName, L"engtype_"); + ty = ty ? ty + 8 : L""; + int k = 0; + while (k < nt && (wcscmp(t[k].luid, lu) || wcsncmp(t[k].type, ty, 31))) k++; + if (k == nt) { + if (nt == TYPES) continue; + wcscpy(t[k].luid, lu); + wcsncpy(t[k].type, ty, 31); + t[k].type[31] = 0; + t[k].sum = 0; + nt++; + } + t[k].sum += it[i].FmtValue.doubleValue; + } + free(it); + for (int k = 0; k < nt; k++) + if (t[k].sum > *load_pct) *load_pct = (float)(t[k].sum > 100 ? 100 : t[k].sum); + // Adapter memory instances: "luid_0x.._0x.._phys_", bytes. Without a LUID: the adapter that uses the most. + it = pdh_items(l->gpu.c[1], &n); + double sum = 0, best = -1; + for (DWORD i = 0; it && i < n; i++) { + if (it[i].FmtValue.CStatus != PDH_CSTATUS_VALID_DATA) continue; + wchar_t lu[40]; + inst_luid(it[i].szName, lu); + if (l->luid[0] ? !wcscmp(lu, l->luid) : 0) sum += it[i].FmtValue.doubleValue; + if (it[i].FmtValue.doubleValue > best) best = it[i].FmtValue.doubleValue; + } + if (it && (l->luid[0] ? sum > 0 : best >= 0)) *vram_used_mb = (float)((l->luid[0] ? sum : best) / 1048576.0); + free(it); +} + +void plat_mem_info(float *used_mb, float *total_mb, float *proc_mb) { + *used_mb = *total_mb = *proc_mb = -1; + MEMORYSTATUSEX ms = {.dwLength = sizeof ms}; + if (GlobalMemoryStatusEx(&ms)) { + *total_mb = (float)(ms.ullTotalPhys >> 20); + *used_mb = (float)((ms.ullTotalPhys - ms.ullAvailPhys) >> 20); + } + PROCESS_MEMORY_COUNTERS pmc; + if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) *proc_mb = (float)(pmc.WorkingSetSize >> 20); +} + // ---- child processes struct PlatChild { diff --git a/runtime/prof_win.c b/runtime/prof_win.c index 90cd26be..99888984 100644 --- a/runtime/prof_win.c +++ b/runtime/prof_win.c @@ -20,6 +20,7 @@ #include "flight.h" #include "gfx.h" #include "host.h" +#include "perfmon.h" #define PROF_SLOTS (1u << 16) // Rip hash table, open addressing; a full table drops new Rips #define PROF_TOP 4000 // more than the 200 asked for: the report sums per function @@ -233,12 +234,29 @@ void prof_write(void) { rt_log("prof: %llu samples, %d Rips -> %s", (unsigned long long)total, cnt, out_path); } -static int perf_on; // TOTK_TRACE=perf or TOTK_FLIGHT=1: event counts are taken. Wait times are always taken (frame-time summary). +// TOTK_TRACE=perf, TOTK_FLIGHT=1 or the full performance overlay: event counts are taken. Wait times are always taken +// (frame-time summary). perf_base: the part fixed at start. +static int perf_on, perf_base; +static int overlay; // performance overlay mode (perf_set_overlay): 0 off, 1 fps, 2 full + +void perf_set_overlay(int mode) { + __atomic_store_n(&overlay, mode, __ATOMIC_RELAXED); + __atomic_store_n(&perf_on, perf_base || mode == 2, __ATOMIC_RELAXED); +} + +int perf_gpu_timing(void) { return (rt_trace & RT_TRACE_PERF) || __atomic_load_n(&overlay, __ATOMIC_RELAXED) == 2; } + +static volatile LONG64 gpu_busy_total; + +void perf_gpu_busy(uint64_t ns) { InterlockedAdd64(&gpu_busy_total, (LONG64)ns); } + +uint64_t perf_gpu_busy_total(void) { return (uint64_t)__atomic_load_n(&gpu_busy_total, __ATOMIC_RELAXED); } void prof_start(void) { flight_init(); atexit(perf_summary_flush); // boot.c's _exit path goes through prof_write instead - perf_on = (rt_trace & RT_TRACE_PERF) || flight_on; + perf_base = (rt_trace & RT_TRACE_PERF) || flight_on; + perf_on = perf_base || overlay == 2; out_path = cfg_get("TOTK_PROFILE"); if (!out_path || !*out_path) { out_path = NULL; @@ -292,7 +310,7 @@ static volatile LONG64 render_wait_ns; // the same on the render thread void (*perf_gpu_stats)(PerfGpu *out); void perf_gpu_wait(uint64_t t0) { - if (!t0 || !perf_on) return; + if (!t0 || !__atomic_load_n(&perf_on, __ATOMIC_RELAXED)) return; LONG64 d = (LONG64)(kern_now_ns() - t0); InterlockedAdd64(GetCurrentThreadId() == render_tid ? &render_wait_ns : &other_wait_ns, d); } @@ -304,13 +322,13 @@ void perf_replay(uint64_t t0) { if (!t0) return; LONG64 d = (LONG64)(kern_now_ns() - t0); InterlockedAdd64(&frame_replay_ns, d); - if (perf_on) InterlockedAdd64(&replay_ns, d); + if (__atomic_load_n(&perf_on, __ATOMIC_RELAXED)) InterlockedAdd64(&replay_ns, d); } static volatile LONG64 counts[PERF_CNT_N]; // running totals: the perf log and the flight recorder take differences void perf_count(int kind) { - if (perf_on) InterlockedIncrement64(&counts[kind]); + if (__atomic_load_n(&perf_on, __ATOMIC_RELAXED)) InterlockedIncrement64(&counts[kind]); } // ---- Frame-time summary, always on: every 60 s of play and at exit one line of frame count, mean fps, 1% low and the @@ -360,12 +378,13 @@ void perf_summary_flush(void) { // at exit (prof_write) summary_t0 = 0; } -static void ft_frame(uint64_t frame, uint64_t now, uint64_t d) { +// Returns the replay time since the previous present. +static uint64_t ft_frame(uint64_t frame, uint64_t now, uint64_t d) { LONG64 rep = InterlockedExchange64(&frame_replay_ns, 0); if (!summary_t0) { // the first present starts the period; there is no interval yet summary_t0 = now; ft.t0 = now; - return; + return (uint64_t)rep; } ft.frames++; ft.sum += d; @@ -386,6 +405,7 @@ static void ft_frame(uint64_t frame, uint64_t now, uint64_t d) { ft_report(now, "60 s"); summary_t0 = now; } + return (uint64_t)rep; } // The second line of the 60-frame window: GPU busy time (timestamps), the time threads waited for GPU fences, VRAM and @@ -424,7 +444,9 @@ void perf_present(uint64_t frame) { cur_frame = frame; if (rt_trace & RT_TRACE_SCHED) kern_sched_report(frame); uint64_t now = kern_now_ns(), d = last ? now - last : 0; - ft_frame(frame, now, d); // d is 0 on the first present: it only starts the period + uint64_t rep = ft_frame(frame, now, d); // d is 0 on the first present: it only starts the period + if (__atomic_load_n(&overlay, __ATOMIC_RELAXED)) // the overlay's only cost while it is off: this branch + perfmon_frame(now, d, frame_ns, rep, __atomic_load_n(&counts[PERF_CNT_TEX_UP], __ATOMIC_RELAXED)); kern_core_diag_frame(frame, d); if (flight_on) flight_frame(frame, now, d, frame_ns, counts); if (!(rt_trace & RT_TRACE_PERF)) { diff --git a/runtime/sysinfo.c b/runtime/sysinfo.c new file mode 100644 index 00000000..3c060bd8 --- /dev/null +++ b/runtime/sysinfo.c @@ -0,0 +1,90 @@ +// What a bug report needs about the machine (sysinfo.h). The OS calls sit behind platform.h; the GPU and driver come +// from the Vulkan device the game renders on. +#include +#include +#include +#if defined(__x86_64__) || defined(__i386__) +#include +#endif + +#include "cfg.h" +#include "platform/platform.h" +#include "sysinfo.h" +#include "vk.h" + +void sysinfo_cpu_name(char *out, size_t n) { + out[0] = 0; +#if defined(__x86_64__) || defined(__i386__) + unsigned r[12]; + if (__get_cpuid_max(0x80000000, NULL) < 0x80000004) return; + for (unsigned i = 0; i < 3; i++) __get_cpuid(0x80000002 + i, &r[i * 4], &r[i * 4 + 1], &r[i * 4 + 2], &r[i * 4 + 3]); + char b[49]; + memcpy(b, r, 48); + b[48] = 0; + const char *p = b; + while (*p == ' ') p++; + snprintf(out, n, "%s", p); + for (char *e = out + strlen(out); e > out && e[-1] == ' '; e--) e[-1] = 0; +#endif +} + +int sysinfo_log_folder(char *out, size_t n) { + if (!plat_stderr_path(out, n) && !plat_exe_path(out, n)) return 0; + char *s = strrchr(out, '\\'), *f = strrchr(out, '/'); + if (f > s) s = f; + if (!s) return 0; + *s = 0; + return 1; +} + +typedef struct { char *buf; size_t n, at; } Out; + +static void put(Out *o, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static void put(Out *o, const char *fmt, ...) { + if (o->at + 1 >= o->n) return; + va_list ap; + va_start(ap, fmt); + int k = vsnprintf(o->buf + o->at, o->n - o->at, fmt, ap); + va_end(ap); + if (k > 0) o->at = o->at + (size_t)k < o->n ? o->at + (size_t)k : o->n - 1; +} + +static void put_setting(const char *key, const char *value, int from_env, void *ctx) { + put(ctx, from_env ? " TOTK_%s=%s (environment)\n" : " %s = %s\n", key, value); +} + +int sysinfo_text(char *buf, size_t n) { + if (!n) return 0; + Out o = {buf, n, 0}; + buf[0] = 0; + char s[256]; + put(&o, "TotK Recomp system info\n"); + put(&o, "OS: %s\n", plat_os_version(s, sizeof s) ? s : "unknown"); + sysinfo_cpu_name(s, sizeof s); + put(&o, "CPU: %s, %u logical processors\n", s[0] ? s : "unknown", plat_cpu_count()); + float used, total, proc; + plat_mem_info(&used, &total, &proc); + if (total > 0) put(&o, "RAM: %.1f GB, %.1f GB in use, the game %.1f GB\n", total / 1024, used / 1024, proc / 1024); + VkCtx *c = vk_ctx(); + if (c) { + VkPhysicalDeviceDriverProperties dp = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; + VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &dp}; + vkGetPhysicalDeviceProperties2(c->phys, &p2); + const VkPhysicalDeviceProperties *p = &p2.properties; + uint64_t vram = 0; + for (uint32_t h = 0; h < c->mem_props.memoryHeapCount; h++) + if (c->mem_props.memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) vram += c->mem_props.memoryHeaps[h].size; + put(&o, "GPU: %s (vendor 0x%04x, device 0x%04x), %.1f GB device-local memory\n", p->deviceName, p->vendorID, + p->deviceID, vram / 1073741824.0); + put(&o, "Driver: %s %s, driver version 0x%08x, Vulkan %u.%u.%u\n", dp.driverName, dp.driverInfo, + p->driverVersion, VK_API_VERSION_MAJOR(p->apiVersion), VK_API_VERSION_MINOR(p->apiVersion), + VK_API_VERSION_PATCH(p->apiVersion)); + } else { + put(&o, "GPU: no Vulkan device yet\n"); + } + put(&o, "Settings with a value:\n"); + size_t before = o.at; + cfg_each_active(put_setting, &o); + if (o.at == before) put(&o, " none\n"); + return (int)o.at; +} diff --git a/runtime/sysinfo.h b/runtime/sysinfo.h new file mode 100644 index 00000000..b28b6a9d --- /dev/null +++ b/runtime/sysinfo.h @@ -0,0 +1,20 @@ +// What a bug report needs about the machine (runtime/sysinfo.c), for the menu's "Copy system info" and "Open log folder". +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Plain text, one item per line: OS and build, CPU, RAM, the GPU and its driver as the Vulkan device reports them, and +// every setting with a value (totk.ini, the menu, the environment). Technical text for the developers, in English like +// the log. The length written (truncated to n - 1), or 0 on failure. +int sysinfo_text(char *buf, size_t n); +// The CPU's brand string ("AMD Ryzen 7 7800X3D 8-Core Processor"); "" when the CPU has none. +void sysinfo_cpu_name(char *out, size_t n); +// The folder with the log: the folder of the file stderr goes to, else the folder of totk.exe. 0 on failure. +int sysinfo_log_folder(char *out, size_t n); + +#ifdef __cplusplus +} +#endif diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index cc896b76..fb4e7624 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -25,7 +25,9 @@ extern "C" { #include "cfg.h" #include "input.h" #include "input_map.h" +#include "perfmon.h" #include "platform/platform.h" +#include "sysinfo.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. @@ -290,7 +292,7 @@ extern "C" void menu_vk_release(void) { // TOTK_MENU_TEST_SET=:=[,=...][;:...]: cfg_set of each key (TOTK_ prefix // optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by // the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note). -enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_COUNT }; +enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_ADVANCED, TAB_COUNT }; enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 }; struct TestSet { uint64_t frame; char key[64], value[64]; }; static struct { @@ -413,12 +415,13 @@ static void row_gpu(void) { 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. +// The game language: one entry per language TotK ships (a Switch code that names it), each under its own name. The +// Switch's Portuguese is not among them. 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}, + {"nl", UI_MENU_LANGNAME_NL}, {"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 }; @@ -453,13 +456,27 @@ static void row_fps_limit() { opt_choice_list("TOTK_FPS_LIMIT", UI_MENU_FPS_LIMIT, vals, names, N, UI_MENU_FPS_LIMIT_DESC, cur); } +// "in use: VSync" under the Presentation value when the swapchain got another mode than the setting (a driver without +// mailbox gets fifo); NULL when they agree or before the first swapchain. +static const char *present_note(void) { + static const struct { const char *mode; UiTextId name; } names[] = { + {"mailbox", UI_MENU_PRESENT_MAILBOX}, {"fifo", UI_MENU_PRESENT_VSYNC}, {"immediate", UI_MENU_PRESENT_IMMEDIATE}, + }; + const char *got = gfx_window_present_mode(); + if (!*got || !strcmp(got, cfg_value("TOTK_VK_PRESENT"))) return nullptr; + static char note[96]; + for (const auto &n : names) + if (!strcmp(n.mode, got)) snprintf(note, sizeof note, menu_text(UI_MENU_PRESENT_IN_USE), menu_text(n.name)); + return note; +} + // ---- 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); + opt_choice("TOTK_VK_PRESENT", UI_MENU_PRESENT, present, 3, UI_MENU_PRESENT_DESC, present_note()); row_gpu(); static const UiTextId perf[] = {UI_MENU_PERF_OFF, UI_MENU_PERF_FPS, UI_MENU_PERF_FULL}; opt_choice("TOTK_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC); @@ -501,8 +518,162 @@ static void tab_menu(float scale) { opt_end(); } +// ---- Advanced: the testing and troubleshooting keys, the bug report helpers and the reset of every setting +static bool g_modal; // the reset confirmation is open: B and Esc close it, not the menu; L / R stay on the page + +// A thread count with no fixed default: Automatic (unset), then the common counts. +static void row_threads(const char *key, UiTextId label, UiTextId desc) { + static const char *const vals[] = {"", "1", "2", "4", "6", "8", "12", "16", "24", "32", "48", "64"}; + enum { N = sizeof vals / sizeof *vals }; + const char *names[N]; + names[0] = menu_text(UI_MENU_AUTO); + for (int i = 1; i < N; i++) names[i] = vals[i]; + opt_choice_list(key, label, vals, names, N, desc); +} + +// A free-text key shown as Off (unset) / On (value set): On writes on_value, any set value reads as On. +static void row_set_or_not(const char *key, UiTextId label, UiTextId desc, const char *on_value) { + const char *vals[] = {"", on_value}, *names[] = {menu_text(UI_MENU_OFF), menu_text(UI_MENU_ON)}; + opt_choice_list(key, label, vals, names, 2, desc, *cfg_value(key) ? 1 : 0); +} + +static bool validation_layer_present(void) { + static int have = -1; + if (have < 0) { + uint32_t n = 0; + vkEnumerateInstanceLayerProperties(&n, nullptr); + VkLayerProperties *l = (VkLayerProperties *)calloc(n ? n : 1, sizeof *l); + if (l && vkEnumerateInstanceLayerProperties(&n, l) >= 0) + for (uint32_t i = 0; i < n && have <= 0; i++) have = !strcmp(l[i].layerName, "VK_LAYER_KHRONOS_validation"); + free(l); + if (have < 0) have = 0; + } + return have != 0; +} + +// Every setting the menu shows back to its default (the environment's keys stay), written to totk.ini. +static void reset_all(void) { + const char *keys[128]; + int n = 0; + for (const CfgMeta *m; n < 128 && (m = cfg_meta_at(n)); n++) keys[n] = m->key; + int done = cfg_reset(keys, n); + opt_save_soon(); + rt_log("menu: reset %d settings to their defaults", done); +} + +// A button's result shown in its value for a few seconds: 1 done (done_text), -1 failed. +struct ActionNote { uint64_t until; int result; }; + +static const char *action_value(const ActionNote &a, UiTextId done_text) { + if (!a.result || plat_now_ns() > a.until) return ""; + return menu_text(a.result > 0 ? done_text : UI_MENU_ACTION_FAILED); +} + +static void action_done(ActionNote &a, bool ok) { a = {plat_now_ns() + 3000000000ull, ok ? 1 : -1}; } + +static void tab_advanced(float scale) { + static ActionNote copy_note, log_note; + opt_begin("##advanced", scale); + opt_text(UI_MENU_ADV_WARNING, true); + + opt_group(UI_MENU_GROUP_SCHED); + static const UiTextId preempt[] = {UI_MENU_PREEMPT_OFF, UI_MENU_PREEMPT_ON, UI_MENU_PREEMPT_INHERIT}; // 0|1|2 + opt_choice("TOTK_ASYNC_PREEMPT", UI_MENU_ASYNC_PREEMPT, preempt, 3, UI_MENU_ASYNC_PREEMPT_DESC); + opt_toggle("TOTK_REPLAY_ASYNC", UI_MENU_REPLAY_ASYNC, UI_MENU_REPLAY_ASYNC_DESC); + opt_toggle("TOTK_FREE_CORES", UI_MENU_FREE_CORES, UI_MENU_FREE_CORES_DESC); + opt_toggle("TOTK_TIMER_1MS", UI_MENU_TIMER_1MS, UI_MENU_TIMER_1MS_DESC); + + opt_group(UI_MENU_GROUP_SHADERS); + static const UiTextId wait[] = {UI_MENU_PIPE_WAIT_DEFAULT, UI_MENU_PIPE_WAIT_DRAW}; + opt_choice("TOTK_PIPE_WAIT", UI_MENU_PIPE_WAIT, wait, 2, UI_MENU_PIPE_WAIT_DESC); + static const UiTextId skip[] = {UI_MENU_PIPE_SKIP_STRICT, UI_MENU_PIPE_SKIP_ANY, UI_MENU_PIPE_SKIP_FULLSCREEN}; + opt_choice("TOTK_PIPE_SKIP", UI_MENU_PIPE_SKIP, skip, 3, UI_MENU_PIPE_SKIP_DESC); + opt_toggle("TOTK_LIB_PREBUILD", UI_MENU_LIB_PREBUILD, UI_MENU_LIB_PREBUILD_DESC); + row_threads("TOTK_LIB_PREBUILD_THREADS", UI_MENU_LIB_PREBUILD_THREADS, UI_MENU_LIB_PREBUILD_THREADS_DESC); + opt_toggle("TOTK_PIPE_PREBUILD", UI_MENU_PIPE_PREBUILD, UI_MENU_PIPE_PREBUILD_DESC); + row_threads("TOTK_PREWARM_XLATE", UI_MENU_PREWARM_XLATE, UI_MENU_PREWARM_XLATE_DESC); + opt_toggle("TOTK_GPL", UI_MENU_GPL, UI_MENU_GPL_DESC); + + opt_group(UI_MENU_GROUP_TEXMEM); + static const UiTextId astc[] = {UI_MENU_ASTC_AUTO, UI_MENU_ASTC_GPU, UI_MENU_ASTC_NATIVE, UI_MENU_ASTC_CPU}; + opt_choice("TOTK_ASTC", UI_MENU_ASTC, astc, 4, UI_MENU_ASTC_DESC); + static const UiTextId mem[] = {UI_MENU_MEMORY_AUTO, UI_MENU_MEMORY_IMPORT, UI_MENU_MEMORY_MIRROR, + UI_MENU_MEMORY_VERIFY}; + opt_choice("TOTK_MEMORY", UI_MENU_MEMORY, mem, 4, UI_MENU_MEMORY_DESC); + opt_toggle("TOTK_TEX_ALIAS", UI_MENU_TEX_ALIAS, UI_MENU_TEX_ALIAS_DESC); + + opt_group(UI_MENU_GROUP_FIXES); + opt_toggle("TOTK_LOD_GUARD", UI_MENU_LOD_GUARD, UI_MENU_LOD_GUARD_DESC); + opt_toggle("TOTK_FIX_C0", UI_MENU_FIX_C0, UI_MENU_FIX_C0_DESC); + opt_toggle("TOTK_FIX_ZERO", UI_MENU_FIX_ZERO, UI_MENU_FIX_ZERO_DESC); + opt_toggle("TOTK_BIND_SKIP", UI_MENU_BIND_SKIP, UI_MENU_BIND_SKIP_DESC); + opt_toggle("TOTK_SHADER_MEMO", UI_MENU_SHADER_MEMO, UI_MENU_SHADER_MEMO_DESC); + opt_toggle("TOTK_DESC_TEMPLATE", UI_MENU_DESC_TEMPLATE, UI_MENU_DESC_TEMPLATE_DESC); + opt_toggle("TOTK_PUSH_SKIP", UI_MENU_PUSH_SKIP, UI_MENU_PUSH_SKIP_DESC); + opt_slider("TOTK_SPLIT_DRAWS", UI_MENU_SPLIT_DRAWS, 0, 1000, UI_MENU_SPLIT_DRAWS_DESC, 8, "%.0f"); + + opt_group(UI_MENU_GROUP_VULKAN); + if (!validation_layer_present() && !cfg_bool("TOTK_VK_VALIDATION")) opt_disable_next(UI_MENU_VK_VALIDATION_MISSING); + opt_toggle("TOTK_VK_VALIDATION", UI_MENU_VK_VALIDATION, UI_MENU_VK_VALIDATION_DESC); + static const UiTextId dyn[] = {UI_MENU_AUTO, UI_MENU_OFF, UI_MENU_ON}; // unset, 0, 1 + opt_choice("TOTK_VK_DYN_VERTEX", UI_MENU_VK_DYN_VERTEX, dyn, 3, UI_MENU_VK_DYN_VERTEX_DESC); + opt_toggle("TOTK_VK_SUBGROUP_PIN", UI_MENU_VK_SUBGROUP_PIN, UI_MENU_VK_SUBGROUP_PIN_DESC); + + opt_group(UI_MENU_GROUP_DIAG); + row_set_or_not("TOTK_TRACE", UI_MENU_TRACE, UI_MENU_TRACE_DESC, "perf"); + opt_toggle("TOTK_FLIGHT", UI_MENU_FLIGHT, UI_MENU_FLIGHT_DESC); + opt_slider("TOTK_FLIGHT_SPIKE_MS", UI_MENU_FLIGHT_SPIKE_MS, 20, 1000, UI_MENU_FLIGHT_SPIKE_MS_DESC, 10, "%.0f"); + static char rec_path[600]; // the recording goes beside the log + if (!rec_path[0]) { + char dir[512]; + snprintf(rec_path, sizeof rec_path, "%s\\input-record.txt", sysinfo_log_folder(dir, sizeof dir) ? dir : "."); + } + row_set_or_not("TOTK_INPUT_RECORD", UI_MENU_INPUT_RECORD, UI_MENU_INPUT_RECORD_DESC, rec_path); + if (opt_button("##open_log", UI_MENU_OPEN_LOG, UI_MENU_OPEN_LOG_DESC, action_value(log_note, UI_MENU_OPEN_LOG))) { + char dir[512]; + bool ok = sysinfo_log_folder(dir, sizeof dir) && plat_open_folder(dir); + if (!ok) action_done(log_note, false); // success shows as the opened folder + } + if (opt_button("##copy_info", UI_MENU_COPY_INFO, UI_MENU_COPY_INFO_DESC, + action_value(copy_note, UI_MENU_COPY_INFO_DONE))) { + static char text[16384]; + action_done(copy_note, sysinfo_text(text, sizeof text) > 0 && plat_clipboard_set(text)); + } + bool ask = opt_button("##reset", UI_MENU_RESET, UI_MENU_RESET_DESC); + opt_end(); + if (ask) ImGui::OpenPopup("##reset_confirm"); // at the level BeginPopupModal looks it up + + // the confirmation, over the menu; Cancel has the cursor first + g_modal = false; + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + if (ImGui::BeginPopupModal("##reset_confirm", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize)) { + g_modal = true; + ImGui::TextUnformatted(menu_text(UI_MENU_RESET_CONFIRM)); + ImGui::Spacing(); + const char *yes = menu_text(UI_MENU_RESET_YES), *no = menu_text(UI_MENU_RESET_NO); + const ImGuiStyle &st = ImGui::GetStyle(); + float bw = fmaxf(ImGui::CalcTextSize(yes).x, ImGui::CalcTextSize(no).x) + st.FramePadding.x * 4; + bool close = false; + if (ImGui::Button(no, ImVec2(bw, 0))) close = true; + if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + if (ImGui::Button(yes, ImVec2(bw, 0))) { + reset_all(); + close = true; + } + if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) + close = true; + if (close) { + ImGui::CloseCurrentPopup(); + opt_focus_key("##reset"); // back on the row it came from + } + ImGui::EndPopup(); + } +} + static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, - UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU}; + UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED}; static int g_tab; // the tab shown static int g_tab_request = -1; // select this tab at the next layout; -1 none static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none @@ -518,7 +689,8 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { 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 + int step = g_modal ? 0 + : 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; @@ -544,6 +716,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { case TAB_SOUND: tab_sound(scale); break; case TAB_CONTROLS: tab_controls(scale); break; case TAB_MENU: tab_menu(scale); break; + case TAB_ADVANCED: tab_advanced(scale); break; } ImGui::EndChild(); ImGui::EndTabItem(); @@ -565,14 +738,19 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { 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); + bool was_modal = g_modal; + if (g_tab != TAB_ADVANCED) g_modal = false; + if (!was_modal && (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) -// ---- the performance overlay (TOTK_PERF_OVERLAY): the frame rate over the presents of the last half second, in "full" -// also their mean and longest interval, in the top right corner. Off, it costs a cfg_version load per present. +// ---- the performance overlay (TOTK_PERF_OVERLAY), in the top right corner. "fps": the frame rate over the presents of +// the last half second. "full": a panel of perfmon.c's numbers, in the style of SavageWindRecomp's perf_overlay_draw +// (menu.mm): the machine's load and temperatures, the frame rate and frame times with a graph, the render thread's waits. +// Off, it costs a cfg_version load per present. static unsigned g_perf_ver = ~0u; static int g_perf_mode; // 0 off, 1 fps, 2 full static std::atomic g_perf_save; // F10 changed the mode: totk.ini is written on the present thread @@ -588,14 +766,34 @@ extern "C" void menu_perf_cycle(void) { g_perf_save.store(1); } -static void perf_tick(uint64_t now) { +// The device the game renders on, for perfmon's GPU counters (by LUID) and NVML (by name); once, before full mode. +static void perf_gpu_once(const MenuTarget *t) { + static bool done; + if (done) return; + done = true; + VkPhysicalDeviceIDProperties id = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; + VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; + vkGetPhysicalDeviceProperties2(t->phys, &p2); + VkPhysicalDeviceMemoryProperties mp; + vkGetPhysicalDeviceMemoryProperties(t->phys, &mp); + uint64_t vram = 0; + for (uint32_t h = 0; h < mp.memoryHeapCount; h++) + if (mp.memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) vram += mp.memoryHeaps[h].size; + perfmon_set_gpu(p2.properties.deviceName, id.deviceLUIDValid ? id.deviceLUID : NULL, (float)(vram >> 20)); +} + +static void perf_tick(uint64_t now, const MenuTarget *t) { if (cfg_version() != g_perf_ver) { g_perf_ver = cfg_version(); int m = perf_mode_of(cfg_value("TOTK_PERF_OVERLAY")); - if (m != g_perf_mode) g_perf_last_ns = 0, g_perf_text[0] = 0; + if (m != g_perf_mode) { + g_perf_last_ns = 0, g_perf_text[0] = 0; + if (m == 2) perf_gpu_once(t); + perfmon_mode(m); + } g_perf_mode = m; } - if (!g_perf_mode) return; + if (g_perf_mode != 1) return; uint64_t d = now - g_perf_last_ns; if (!g_perf_last_ns || d > 2000000000ull) { // first frame, or a stall the window should not average in g_perf_win_ns = g_perf_max_ns = 0; @@ -605,12 +803,7 @@ static void perf_tick(uint64_t now) { g_perf_frames++; if (d > g_perf_max_ns) g_perf_max_ns = d; if (g_perf_win_ns >= 500000000ull) { - double fps = g_perf_frames * 1e9 / g_perf_win_ns; - if (g_perf_mode == 2) - snprintf(g_perf_text, sizeof g_perf_text, menu_text(UI_PERF_LINE_FULL), fps, - g_perf_win_ns / 1e6 / g_perf_frames, g_perf_max_ns / 1e6); - else - snprintf(g_perf_text, sizeof g_perf_text, menu_text(UI_PERF_LINE_FPS), fps); + snprintf(g_perf_text, sizeof g_perf_text, menu_text(UI_PERF_LINE_FPS), g_perf_frames * 1e9 / g_perf_win_ns); g_perf_win_ns = g_perf_max_ns = 0; g_perf_frames = 0; } @@ -618,7 +811,122 @@ static void perf_tick(uint64_t now) { g_perf_last_ns = now; } +// The panel keeps its width while the numbers change: every column is as wide as the widest text it can show, measured +// on samples of 8s (Roboto's digits share one width), and the numbers are right-aligned in it. +struct PerfCol { UiTextId fmt; float sample; }; + +static float perf_text_w(UiTextId fmt, float v) { + char b[64]; + snprintf(b, sizeof b, menu_text(fmt), v); + return ImGui::CalcTextSize(b).x; +} + +// A fixed column as wide as the widest of the formats (with their samples) and labels given. +static void perf_column(const char *id, const PerfCol *cols, int n, const UiTextId *labels = nullptr, int nl = 0) { + float w = ImGui::CalcTextSize(menu_text(UI_MENU_OV_NONE)).x; + for (int i = 0; i < n; i++) w = fmaxf(w, perf_text_w(cols[i].fmt, cols[i].sample)); + for (int i = 0; i < nl; i++) w = fmaxf(w, ImGui::CalcTextSize(menu_text(labels[i])).x); + ImGui::TableSetupColumn(id, ImGuiTableColumnFlags_WidthFixed, w); +} + +static void perf_right(const char *s, bool dim) { + float pad = ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize(s).x; + if (pad > 0) ImGui::SetCursorPosX(ImGui::GetCursorPosX() + pad); + if (dim) ImGui::TextDisabled("%s", s); + else ImGui::TextUnformatted(s); +} + +// One cell of the full panel's table: fmt (a catalog format, one number) with v, or "-" when the machine gives none. +static void perf_cell(UiTextId fmt, float v) { + ImGui::TableNextColumn(); + if (v < 0) return perf_right(menu_text(UI_MENU_OV_NONE), true); + char b[64]; + snprintf(b, sizeof b, menu_text(fmt), v); + perf_right(b, false); +} + +static void perf_label(UiTextId label, const ImVec4 &c) { + ImGui::TableNextColumn(); + ImGui::TextColored(c, "%s", menu_text(label)); +} + +static float perf_gb(float mb) { return mb < 0 ? -1 : mb / 1024; } + +static void perf_full_draw(float w, float scale) { + PerfStats s; + perfmon_snapshot(&s); + ImGui::SetNextWindowPos(ImVec2(w - 12 * scale, 12 * scale), ImGuiCond_Always, ImVec2(1, 0)); + ImGui::SetNextWindowBgAlpha(0.6f); + ImGui::Begin("##perf", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoNav | + ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoSavedSettings); + ImGui::BringWindowToDisplayFront(ImGui::GetCurrentWindow()); // over the menu while it is open + ImGui::SetWindowFontScale(0.72f); + const ImVec4 gpu_c(0.55f, 0.83f, 0.31f, 1), cpu_c(0.18f, 0.59f, 0.80f, 1), ram_c(0.80f, 0.45f, 0.70f, 1), + fps_c(0.95f, 0.95f, 0.95f, 1), wait_c(0.93f, 0.76f, 0.33f, 1); + if (ImGui::BeginTable("##perft", 4, ImGuiTableFlags_SizingFixedFit)) { + static const UiTextId labels[] = {UI_MENU_OV_GPU, UI_MENU_OV_VRAM, UI_MENU_OV_CPU, UI_MENU_OV_RAM}; + static const PerfCol c0[] = {{UI_MENU_OV_FPS, 888}}; + static const PerfCol c1[] = {{UI_MENU_OV_FMT_PCT, 100}, {UI_MENU_OV_FMT_GB, 888.8f}, {UI_MENU_OV_FRAME_MS, 888.8f}}; + static const PerfCol c2[] = {{UI_MENU_OV_FMT_TEMP, 188}, {UI_MENU_OV_FMT_GB_OF, 888.8f}, {UI_MENU_OV_MAX_MS, 8888.8f}}; + static const PerfCol c3[] = {{UI_MENU_OV_FMT_POWER, 888}, {UI_MENU_OV_FMT_MHZ, 8888}, {UI_MENU_OV_GAME_PCT, 100}, + {UI_MENU_OV_GAME_GB, 888.8f}}; + perf_column("##c0", c0, 1, labels, 4); + perf_column("##c1", c1, 3); + perf_column("##c2", c2, 3); + perf_column("##c3", c3, 4); + perf_label(UI_MENU_OV_GPU, gpu_c); + perf_cell(UI_MENU_OV_FMT_PCT, s.gpu_pct); + perf_cell(UI_MENU_OV_FMT_TEMP, s.gpu_temp_c); + perf_cell(UI_MENU_OV_FMT_POWER, s.gpu_power_w); + perf_label(UI_MENU_OV_VRAM, gpu_c); + perf_cell(UI_MENU_OV_FMT_GB, perf_gb(s.vram_used_mb)); + perf_cell(UI_MENU_OV_FMT_GB_OF, perf_gb(s.vram_total_mb)); + perf_cell(UI_MENU_OV_FMT_MHZ, s.gpu_clock_mhz); + perf_label(UI_MENU_OV_CPU, cpu_c); + perf_cell(UI_MENU_OV_FMT_PCT, s.cpu_total_pct); + perf_cell(UI_MENU_OV_FMT_TEMP, s.cpu_temp_c); + perf_cell(UI_MENU_OV_GAME_PCT, s.cpu_game_pct); + perf_label(UI_MENU_OV_RAM, ram_c); + perf_cell(UI_MENU_OV_FMT_GB, perf_gb(s.ram_used_mb)); + perf_cell(UI_MENU_OV_FMT_GB_OF, perf_gb(s.ram_total_mb)); + perf_cell(UI_MENU_OV_GAME_GB, perf_gb(s.ram_game_mb)); + ImGui::TableNextColumn(); // the frame row: no label, the rate in its place + char b[64]; + snprintf(b, sizeof b, menu_text(UI_MENU_OV_FPS), s.fps); + ImGui::TextColored(fps_c, "%s", b); + perf_cell(UI_MENU_OV_FRAME_MS, s.frame_ms_avg); + perf_cell(UI_MENU_OV_MAX_MS, s.frame_ms_max); + ImGui::EndTable(); + } + float top = s.frame_ms_max > 50 ? s.frame_ms_max : 50; + ImGui::PlotLines("##ft", s.frame_ms, PERF_HISTORY, 0, nullptr, 0, top, ImVec2(330 * scale, 48 * scale)); + // per frame, averaged over the last half second + if (ImGui::BeginTable("##perfw", 2, ImGuiTableFlags_SizingFixedFit)) { + static const UiTextId labels[] = {UI_MENU_OV_REPLAY, UI_MENU_OV_GPU_TIME, UI_MENU_OV_PIPE_WAIT, + UI_MENU_OV_SHADER_WAIT, UI_MENU_OV_TEX_UPLOADS}; + static const PerfCol c1[] = {{UI_MENU_OV_FMT_MS, 888.88f}, {UI_MENU_OV_PER_FRAME, 888.8f}}; + perf_column("##w0", nullptr, 0, labels, 5); + perf_column("##w1", c1, 2); + perf_label(UI_MENU_OV_REPLAY, wait_c); + perf_cell(UI_MENU_OV_FMT_MS, s.replay_ms); + perf_label(UI_MENU_OV_GPU_TIME, wait_c); + perf_cell(UI_MENU_OV_FMT_MS, s.gpu_ms); + perf_label(UI_MENU_OV_PIPE_WAIT, wait_c); + perf_cell(UI_MENU_OV_FMT_MS, s.pipe_wait_ms); + perf_label(UI_MENU_OV_SHADER_WAIT, wait_c); + perf_cell(UI_MENU_OV_FMT_MS, s.xlate_ms); + perf_label(UI_MENU_OV_TEX_UPLOADS, wait_c); + perf_cell(UI_MENU_OV_PER_FRAME, s.tex_uploads); + ImGui::EndTable(); + } + if (s.gpu_name[0]) ImGui::TextDisabled("%s", s.gpu_name); + if (s.cpu_name[0]) ImGui::TextDisabled("%s", s.cpu_name); + ImGui::End(); +} + static void perf_draw(float w, float scale) { + if (g_perf_mode == 2) return perf_full_draw(w, scale); if (!g_perf_mode || !g_perf_text[0]) return; ImDrawList *dl = ImGui::GetForegroundDrawList(); ImVec2 sz = ImGui::CalcTextSize(g_perf_text); @@ -633,7 +941,7 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha if (!g_test.parsed) test_parse(); if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame); if (g_perf_save.exchange(0)) cfg_save(); - perf_tick(plat_now_ns()); + perf_tick(plat_now_ns(), t); bool open = g_open.load(std::memory_order_relaxed); if (!open) { if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now @@ -673,6 +981,8 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha 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 + if (GImGui->OpenPopupStack.Size) ImGui::ClosePopupToLevel(0, false); // a confirmation left open on closing + g_modal = false; } io.DisplaySize = ImVec2((float)t->width, (float)t->height); double dt = g_last_ns ? (t0 - g_last_ns) / 1e9 : 1 / 60.0; diff --git a/runtime/ui/menu.h b/runtime/ui/menu.h index a4343d50..2a1b1bc1 100644 --- a/runtime/ui/menu.h +++ b/runtime/ui/menu.h @@ -57,6 +57,9 @@ void gfx_window_apply_settings(void); // TOTK_FULLSCREEN or TOTK_WINDOW_SIZE 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 double gfx_window_refresh_hz(void); // its refresh rate (TOTK_FPS_LIMIT=display); 0 when unknown +// The present mode the swapchain got, as a TOTK_VK_PRESENT value ("fifo" when mailbox is missing); "" before the first +// swapchain. Any thread. +const char *gfx_window_present_mode(void); #ifdef __cplusplus } diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp index 90252135..e6ac8ca2 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -29,16 +29,22 @@ 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 char g_focus_key[64]; // opt_focus_key: the row that takes the cursor when it is next drawn static bool g_held; // the last row's left / right has been held a while (steppers go faster) +static bool g_disable_next; // opt_disable_next: the next row is greyed out with g_disable_note +static UiTextId g_disable_note; // The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown. struct Desc { char text[512]; }; static Desc g_hover, g_focus, g_first, g_shown; -static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m) { +// disabled: the note of a row opt_disable_next greyed out, else NULL. +static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m, const char *disabled) { int n = snprintf(d.text, sizeof d.text, "%s", menu_text(desc)); if (n < 0 || n >= (int)sizeof d.text) return; - if (cfg_from_env(key)) + if (disabled) + snprintf(d.text + n, sizeof d.text - n, "\n\n%s", disabled); + else 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)); @@ -46,6 +52,13 @@ static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m) void opt_focus_first(void) { g_focus_req = true; } +void opt_focus_key(const char *key) { snprintf(g_focus_key, sizeof g_focus_key, "%s", key); } + +void opt_disable_next(UiTextId note) { + g_disable_next = true; + g_disable_note = note; +} + void opt_begin(const char *id, float scale) { g_scale = scale; g_take_first = g_focus_req; @@ -86,24 +99,32 @@ 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 + const char *note; // under the value instead of the "default" mark; NULL for none }; // 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; + const char *disabled = g_disable_next ? menu_text(g_disable_note) : NULL; + g_disable_next = false; + bool off = disabled || cfg_from_env(key) != 0; ImGui::PushID(key); ImVec2 p = ImGui::GetCursorScreenPos(); - float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x, h = fs * 2.2f; + // h whole pixels: ImGui truncates cursor positions, which rounds a fractional height the other way above the window's + // top (negative y), so the page grew a pixel per row scrolled out and a row scrolled to the bottom was cut off + float fs = ImGui::GetFontSize(), w = ImGui::GetContentRegionAvail().x, h = floorf(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; + bool to_key = g_focus_key[0] && !strcmp(key, g_focus_key); + if (g_take_first || to_key) { ImGui::SetFocusID(ImGui::GetItemID(), ImGui::GetCurrentWindow()); ImGui::SetNavCursorVisible(true); - ImGui::SetScrollHereY(0); + if (g_take_first) ImGui::SetScrollY(0); // the page's top: text and a heading above the first row show + else ImGui::ScrollToItem(ImGuiScrollFlags_KeepVisibleEdgeY); // as a cursor move would (the last row whole) + g_take_first = false; + if (to_key) g_focus_key[0] = 0; } bool hov = ImGui::IsItemHovered(), foc = ImGui::IsItemFocused() && ImGui::GetCurrentContext()->NavCursorVisible; int step = clicked && !off ? 2 : 0; @@ -123,9 +144,9 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) // 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); + if (foc) desc_set(g_focus, desc, key, m, disabled); + if (hov) desc_set(g_hover, desc, key, m, disabled); + if (!g_first.text[0]) desc_set(g_first, desc, key, m, disabled); ImDrawList *dl = ImGui::GetWindowDrawList(); ImFont *font = ImGui::GetFont(); @@ -157,16 +178,19 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) 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); + if (v.note || v.is_default) { // under the value, right-aligned with it + const char *t = v.note ? v.note : 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); + dl->AddText(font, small, ImVec2(right - tw, ny), v.note ? IM_COL32(220, 170, 100, 255) : 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; + const char *note = disabled ? disabled + : 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; @@ -183,9 +207,11 @@ static void apply(const char *key, const char *value) { const char *k = key; cfg_reset(&k, 1); } - g_save_at = plat_now_ns() + 400000000ull; + opt_save_soon(); } +void opt_save_soon(void) { 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; @@ -198,17 +224,35 @@ int opt_save_tick(int force) { // ---- rows -bool opt_toggle(const char *key, UiTextId label, UiTextId desc) { +bool opt_toggle(const char *key, UiTextId label, UiTextId desc, bool inverted) { 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}; + bool set = cfg_bool(key) != 0, def = m && strcmp(m->def, "0") != 0; + bool on = set != inverted; // what the row shows + RowView v = {menu_text(on ? UI_MENU_ON : UI_MENU_OFF), set == def, false, NULL}; if (!row(key, label, desc, v)) return false; // any step flips it - apply(key, on ? "0" : "1"); + apply(key, set ? "0" : "1"); return true; } +bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value) { + RowView v = {value ? value : "", false, false, NULL}; + return row(id, label, desc, v) == 2; // A or a click; left and right do nothing +} + +void opt_group(UiTextId title) { + ImGui::Dummy(ImVec2(0, 6 * g_scale)); + ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(title)); +} + +void opt_text(UiTextId text, bool warn) { + ImGui::PushTextWrapPos(0); + if (warn) ImGui::TextColored(ImVec4(0.95f, 0.66f, 0.40f, 1), "%s", menu_text(text)); + else ImGui::TextUnformatted(menu_text(text)); + ImGui::PopTextWrapPos(); +} + bool opt_choice_list(const char *key, UiTextId label, const char *const *values, const char *const *names, int n, - UiTextId desc, int cur) { + UiTextId desc, int cur, const char *note) { const CfgMeta *m = cfg_meta(key); const char *now = cfg_value(key); if (cur < 0) @@ -217,7 +261,7 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values, 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}; + RowView v = {cur >= 0 ? names[cur] : now, cur == def, true, note}; int step = row(key, label, desc, v); if (!step || n <= 0) return false; int nv; @@ -229,7 +273,7 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values, return true; } -bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc) { +bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc, const char *note) { enum { MAX = 32 }; const CfgMeta *m = cfg_meta(key); const char *values[MAX], *shown[MAX]; @@ -245,7 +289,7 @@ bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, U } 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); + return opt_choice_list(key, label, values, shown, n, desc, -1, note); } bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt) { @@ -253,7 +297,7 @@ bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId de 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}; + RowView rv = {shown, fabs(v - def) < step * 0.01, true, NULL}; int s = row(key, label, desc, rv); if (!s) return false; int steps = g_held && (hi - lo) > 40 * step ? 10 : 1; // held: ten steps at a time over a long range diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 54bde931..ac023901 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -19,16 +19,30 @@ 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 row of key (or button id) takes the cursor, scrolled into view, when it is next drawn. +void opt_focus_key(const char *key); +// The next row is greyed out like one the environment fixes, with note under its label and in its description. +void opt_disable_next(UiTextId note); + +// Page text that is not a row: a group heading in the accent colour, a wrapped paragraph (warn: the warning colour). +void opt_group(UiTextId title); +void opt_text(UiTextId text, bool warn = false); // The return value of every row: true when it changed the setting this frame. -bool opt_toggle(const char *key, UiTextId label, UiTextId desc); +// inverted: the row shows "on" while the key is 0 (a setting whose key names the opposite). +bool opt_toggle(const char *key, UiTextId label, UiTextId desc, bool inverted = false); // 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); +// def), names[0] is the automatic choice (the key unset) and names[1..] follow the values. note: a short line under +// the value in place of the "default" mark (NULL: none). +bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, UiTextId desc, + const char *note = nullptr); // 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); + UiTextId desc, int cur = -1, const char *note = nullptr); +// A row that runs an action: true on A or a click. id: unique on the page and not a setting ("##copy_info"); value: +// shown on the right ("" none). +bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value = ""); // 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"); @@ -37,3 +51,5 @@ bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId de // 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); +// A change made outside a row (Reset, F10): totk.ini is written as after a row's change. +void opt_save_soon(void); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 2ac4ef66..69af8480 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -15,7 +15,7 @@ typedef struct { const char *lang; const char *const *text; } 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_NL] = "Nederlands", [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. @@ -39,14 +39,15 @@ static const char *const text_en[UI_TEXT_COUNT] = { [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_PRESENT_IN_USE] = "in use: %s", [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 in the top right corner; Full adds the mean and the longest frame time of the " - "last half second. F10 cycles the modes.", + [UI_MENU_PERF_OVERLAY_DESC] = "Frame rate in the top right corner. Full adds frame times with a graph, CPU, GPU and " + "memory load, temperatures and the render thread's waits. F10 cycles the modes.", [UI_MENU_PERF_OFF] = "Off", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Full", - // printf formats of the overlay line: frame rate; frame rate, mean and longest frame time in ms - [UI_PERF_LINE_FPS] = "%.0f fps", [UI_PERF_LINE_FULL] = "%.0f fps %.1f ms max %.1f ms", + // printf format of the overlay line in FPS mode: the frame rate + [UI_PERF_LINE_FPS] = "%.0f fps", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -104,11 +105,11 @@ static const char *const text_en[UI_TEXT_COUNT] = { [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_LIB_PREBUILD_THREADS_DESC] = "Threads used for the prebuild; Automatic 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_PREWARM_XLATE_DESC] = "Threads that translate known shaders at start; Automatic takes half the CPU threads, at most 16.", [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.", @@ -148,7 +149,7 @@ static const char *const text_en[UI_TEXT_COUNT] = { [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_COPY_INFO_DONE] = "Copied", [UI_MENU_ACTION_FAILED] = "did not work", [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", @@ -160,6 +161,9 @@ static const char *const text_en[UI_TEXT_COUNT] = { [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", + [UI_MENU_OV_FMT_PCT] = "%.0f%%", [UI_MENU_OV_FMT_TEMP] = "%.0f °C", [UI_MENU_OV_FMT_POWER] = "%.0f W", + [UI_MENU_OV_FMT_MHZ] = "%.0f MHz", [UI_MENU_OV_FMT_GB] = "%.1f GB", [UI_MENU_OV_FMT_GB_OF] = "/ %.1f GB", + [UI_MENU_OV_GAME_GB] = "game %.1f GB", [UI_MENU_OV_FMT_MS] = "%.2f ms", [UI_MENU_OV_PER_FRAME] = "%.1f per frame", }; static const char *const text_ru[UI_TEXT_COUNT] = { @@ -180,13 +184,15 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_PRESENT] = "Вывод кадров", [UI_MENU_PRESENT_DESC] = "Как готовые кадры попадают на экран.", [UI_MENU_PRESENT_MAILBOX] = "Mailbox", [UI_MENU_PRESENT_VSYNC] = "Вертикальная синхронизация", [UI_MENU_PRESENT_IMMEDIATE] = "Без ожидания", + [UI_MENU_PRESENT_IN_USE] = "сейчас: %s", [UI_MENU_GPU] = "Видеокарта", [UI_MENU_GPU_DESC] = "Устройство Vulkan, которое рисует игру.", [UI_MENU_GPU_AUTO] = "Автоматически", [UI_MENU_PERF_OVERLAY] = "Индикатор производительности", - [UI_MENU_PERF_OVERLAY_DESC] = "Частота кадров в правом верхнем углу; «Полный» добавляет среднее и самое долгое время " - "кадра за последние полсекунды. F10 переключает режимы.", + [UI_MENU_PERF_OVERLAY_DESC] = "Частота кадров в правом верхнем углу. «Полный» добавляет время кадров с графиком, " + "загрузку ЦП, GPU и памяти, температуры и ожидания потока отрисовки. F10 переключает " + "режимы.", [UI_MENU_PERF_OFF] = "Выкл.", [UI_MENU_PERF_FPS] = "FPS", [UI_MENU_PERF_FULL] = "Полный", - [UI_PERF_LINE_FPS] = "%.0f к/с", [UI_PERF_LINE_FULL] = "%.0f к/с %.1f мс макс. %.1f мс", + [UI_PERF_LINE_FPS] = "%.0f к/с", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " @@ -243,11 +249,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_LIB_PREBUILD] = "Предсборка библиотек стадий", [UI_MENU_LIB_PREBUILD_DESC] = "Заранее собирает библиотеки стадий шейдеров в фоне.", [UI_MENU_LIB_PREBUILD_THREADS] = "Потоки предсборки библиотек", - [UI_MENU_LIB_PREBUILD_THREADS_DESC] = "Сколько потоков занято предсборкой; пусто — по числу ядер процессора.", + [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_PREWARM_XLATE_DESC] = "Потоки, которые при запуске переводят известные шейдеры; «Автоматически» — половина потоков процессора, не больше 16.", [UI_MENU_GPL] = "Библиотека графических конвейеров", [UI_MENU_GPL_DESC] = "Использует расширение Vulkan для библиотек конвейеров; выключите, если драйвер с ним сбоит.", [UI_MENU_ASTC] = "Распаковка текстур ASTC", [UI_MENU_ASTC_DESC] = "Где распаковываются сжатые текстуры ASTC.", @@ -288,7 +294,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [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_COPY_INFO_DONE] = "Скопировано", [UI_MENU_ACTION_FAILED] = "не получилось", [UI_MENU_RESET] = "Сбросить все настройки", [UI_MENU_RESET_DESC] = "Действует на все вкладки.", [UI_MENU_RESET_CONFIRM] = "Сбросить все настройки к значениям по умолчанию?", [UI_MENU_RESET_YES] = "Сбросить", [UI_MENU_RESET_NO] = "Отмена", @@ -301,6 +307,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_OV_REPLAY] = "Воспроизведение команд GPU", [UI_MENU_OV_GPU_TIME] = "Время GPU", [UI_MENU_OV_PIPE_WAIT] = "Ожидания конвейеров", [UI_MENU_OV_SHADER_WAIT] = "Ожидания шейдеров", [UI_MENU_OV_TEX_UPLOADS] = "Загрузки текстур", + [UI_MENU_OV_FMT_PCT] = "%.0f%%", [UI_MENU_OV_FMT_TEMP] = "%.0f °C", [UI_MENU_OV_FMT_POWER] = "%.0f Вт", + [UI_MENU_OV_FMT_MHZ] = "%.0f МГц", [UI_MENU_OV_FMT_GB] = "%.1f ГБ", [UI_MENU_OV_FMT_GB_OF] = "/ %.1f ГБ", + [UI_MENU_OV_GAME_GB] = "игра %.1f ГБ", [UI_MENU_OV_FMT_MS] = "%.2f мс", [UI_MENU_OV_PER_FRAME] = "%.1f за кадр", }; #define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)} diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 519ee901..e391aeb3 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -26,9 +26,10 @@ typedef enum { 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_PRESENT_IN_USE, // "in use: %s" under the value when the swapchain got another mode than the setting 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, - UI_PERF_LINE_FPS, UI_PERF_LINE_FULL, + UI_PERF_LINE_FPS, // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_60, UI_MENU_FPS_120, UI_MENU_FPS_144, @@ -54,7 +55,7 @@ typedef enum { // Language names, each in its own language and the same in every row (game language and menu language lists) UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_DE, UI_MENU_LANGNAME_IT, - UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_PT, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS, + UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS, UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO, // Advanced @@ -95,6 +96,7 @@ typedef enum { 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_ACTION_FAILED, // beside a button whose action did not work (no clipboard, no folder) UI_MENU_RESET, UI_MENU_RESET_DESC, UI_MENU_RESET_CONFIRM, UI_MENU_RESET_YES, UI_MENU_RESET_NO, // Performance overlay @@ -102,7 +104,10 @@ typedef enum { 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, + // number formats of the overlay's cells (printf, one number each) + UI_MENU_OV_FMT_PCT, UI_MENU_OV_FMT_TEMP, UI_MENU_OV_FMT_POWER, UI_MENU_OV_FMT_MHZ, UI_MENU_OV_FMT_GB, + UI_MENU_OV_FMT_GB_OF, UI_MENU_OV_GAME_GB, UI_MENU_OV_FMT_MS, UI_MENU_OV_PER_FRAME, + UI_MENU_LAST_ID = UI_MENU_OV_PER_FRAME, UI_TEXT_COUNT } UiTextId; diff --git a/runtime/vk_sync.c b/runtime/vk_sync.c index b3a2a1bb..fbbf465e 100644 --- a/runtime/vk_sync.c +++ b/runtime/vk_sync.c @@ -62,9 +62,9 @@ static int ts_cur = -1; // the pair of the part being recorde static uint64_t ts_last_end; // completion thread: end of the latest part read (ticks) static volatile LONG64 ts_busy_ns, ts_parts, ts_missed; +// On the first submission that wants timing (perf_gpu_timing: TOTK_TRACE=perf or the full performance overlay). static void ts_setup(VkCtx *c) { ts_state = -1; - if (!(rt_trace & RT_TRACE_PERF)) return; uint32_t nq = 0; vkGetPhysicalDeviceQueueFamilyProperties(c->phys, &nq, NULL); VkQueueFamilyProperties *qp = calloc(nq ? nq : 1, sizeof *qp); @@ -99,7 +99,11 @@ static void ts_read_cb(void *arg) { // completion thread, in submission order uint64_t s = v[0] & ts_mask, e = v[1] & ts_mask; if (e >= s) { uint64_t from = s > ts_last_end ? s : ts_last_end; - if (e > from) InterlockedAdd64(&ts_busy_ns, (LONG64)((double)(e - from) * ts_period)); + if (e > from) { + LONG64 ns = (LONG64)((double)(e - from) * ts_period); + InterlockedAdd64(&ts_busy_ns, ns); + perf_gpu_busy((uint64_t)ns); + } if (e > ts_last_end) ts_last_end = e; InterlockedIncrement64(&ts_parts); } else InterlockedIncrement64(&ts_missed); // the counter wrapped @@ -110,7 +114,11 @@ static void ts_read_cb(void *arg) { // completion thread, in submission order // At the start of a command buffer (sub_lock held): the pair it times, -1 untimed. static int ts_open(VkCommandBuffer cb) { - if (ts_state != 1) return -1; + if (ts_state != 1 || !perf_gpu_timing()) { + if (ts_state || !perf_gpu_timing()) return -1; + ts_setup(vk_ctx()); // the overlay turned full: timestamps from now on + if (ts_state != 1) return -1; + } uint32_t p = ts_next % TS_PAIRS; if (__atomic_load_n(&ts_busy[p], __ATOMIC_ACQUIRE)) { InterlockedIncrement64(&ts_missed); return -1; } ts_next++; @@ -212,7 +220,7 @@ void vk_sync_start(void) { .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, .queueFamilyIndex = c->gfx_family}; if (vkCreateCommandPool(c->device, &pi, NULL, &cmd_pool) != VK_SUCCESS) rt_fatal("vk: submission command pool"); - if (!ts_state) ts_setup(c); + if (!ts_state && perf_gpu_timing()) ts_setup(c); perf_gpu_stats = gpu_stats; uint64_t now = 0; vkGetSemaphoreCounterValue(c->device, c->timeline, &now);