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.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..3558cfd9 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,29 @@ 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; 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); + ImGui::SetScrollHereY(g_take_first ? 0.0f : 0.5f); + 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 +141,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 +175,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 +204,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 +221,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 +258,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 +270,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 +286,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 +294,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..6210d78a 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -39,6 +39,7 @@ 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", @@ -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,6 +184,7 @@ 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] = "Индикатор производительности", @@ -288,7 +293,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 +306,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..8511f4b8 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -26,6 +26,7 @@ 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, @@ -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);