diff --git a/nx2navi.ini.example b/nx2navi.ini.example index fb8a3fd9..220e2228 100644 --- a/nx2navi.ini.example +++ b/nx2navi.ini.example @@ -15,6 +15,12 @@ # at the cost of tearing. A monitor running with variable refresh (FreeSync, G-Sync) follows the frames instead, so # there any limit inside its range is even. # fps_limit = 60 +# Where RivaTuner Statistics Server is installed and running, the limit goes into its profile for the game's +# executable and RTSS does the limiting instead of the game; closing the game puts back what the profile held. +# Changing that profile needs the game run as administrator (RTSS keeps its profiles under Program Files); without +# it, or with frame generation on, the game limits by itself, and also when RTSS's own frame counter shows the game +# well past the limit (RTSS then hooks the game without holding it back). rtss = 0 always leaves it to the game. +# rtss = 1 # Older key, read only while fps_limit is unset: fps60 = 0 means a limit of 30. # fps60 = 1 # Real-time frame step: game speed follows the clock instead of the frame count. diff --git a/runtime/boot.c b/runtime/boot.c index d32ab68b..33cc0b55 100644 --- a/runtime/boot.c +++ b/runtime/boot.c @@ -320,6 +320,7 @@ void rt_frame_presented(const tex_t *t, uint64_t n) { fs_save_flush(); vk_pipeline_save(); // no-op without the Vulkan back end prof_write(); + rtss_limit_restore(); fflush(stderr); plat_exit(0); } diff --git a/runtime/cfg.c b/runtime/cfg.c index ada22e63..73fc3ef4 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -52,7 +52,7 @@ static const char *const known[] = { "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PACE_HZ", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_RES_FIXED", "PATCH_SCENE", "PATCH_WIDE_ASPECT", "PATCH_WIDE_HUD", "PATCH_WIDE_MOVIE", "PATCH_WIDE_OUT", "PATCH_WIDE_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_WAIT_MS", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES", "PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC", - "RENDER_SCALE", "REPLAY_ASYNC", + "RENDER_SCALE", "REPLAY_ASYNC", "RTSS", "REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES", "ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE", "SHADER_MEMO", "SHADOW_COMPARE", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", @@ -66,7 +66,7 @@ static const char *const known[] = { // The nx2navi.ini section a key cfg_set may write goes to when the file lacks it (nx2navi.ini.example's sections). static const struct { const char *key, *section; } sections[] = { - {"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, + {"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"RTSS", "frame rate"}, {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"GAME_ASPECT", "display"}, {"GAME_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, @@ -140,6 +140,7 @@ static const CfgMeta metas[] = { {"PCSS", "0", "0..200", RESTART}, // Game {"FPS_LIMIT", "60", "30|40|45|60|90|120|144|165|240|display|unlimited", LIVE}, {"FPS60", "1", "0|1", LIVE}, + {"RTSS", "1", "0|1", RESTART}, // rtss_limit.c: RivaTuner Statistics Server takes the limit where it runs {"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART}, {"MODS_REBUILD", "auto", "auto|off", RESTART}, {"HIGHFPS_FIX", "1", "0|1", RESTART}, diff --git a/runtime/cheats.c b/runtime/cheats.c index cffde38b..2708b2ac 100644 --- a/runtime/cheats.c +++ b/runtime/cheats.c @@ -505,6 +505,7 @@ static void rebuild_if_needed(const char *dir) { return; } prof_write(); // plat_exit runs no atexit handlers + rtss_limit_restore(); plat_exit(0); } diff --git a/runtime/frame_rate.c b/runtime/frame_rate.c index d58b87da..26642e40 100644 --- a/runtime/frame_rate.c +++ b/runtime/frame_rate.c @@ -52,6 +52,7 @@ #include "host.h" #include "layout.h" #include "platform/platform.h" +#include "vk_fg.h" #define STEP_SAMPLES 5 #define STEP_MAX_S (1.0 / 15.0) // longest step; a longer frame slows the game down @@ -180,13 +181,25 @@ static void frame_limit_live(void) { else rt_log("frame rate: limit at the monitor's refresh rate (60 until the window measures it)"); } +// RivaTuner Statistics Server (rtss_limit.c) gets the same limit; while it limits this process the pacer holds no +// frames, so the two never stack. NX2NAVI_RTSS=0 and frame generation (RTSS would count the generated frames) keep it out. uint64_t frame_step_cap_ns(void) { frame_limit_live(); - if (limit_hz == -2) return 0; // unlimited: the pacer does not hold frames + static int rtss = -1; + if (rtss < 0) { + const char *e = cfg_get("NX2NAVI_RTSS"); + rtss = !(e && !strcmp(e, "0")) && !vk_fg_wanted(); + } + if (limit_hz == -2) { // unlimited: the pacer does not hold frames, and RTSS's limit is cleared + rtss_limit_want(rtss ? 0 : -1); + return 0; + } double hz = limit_hz ? limit_hz : gfx_window_refresh_hz(); if (hz < LIMIT_MIN_HZ) hz = 60; // display rate unknown (no window yet) double max = frame_free_running() ? LIMIT_FREE_MAX_HZ : LIMIT_MAX_HZ; if (hz > max) hz = max; + rtss_limit_want(rtss ? (int64_t)(hz * 1000 + 0.5) : -1); + if (rtss_limit_active()) return 0; return (uint64_t)(1e9 / hz + 0.5); } diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index 622f3c69..b2c2e6b7 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -74,6 +74,7 @@ void gfx_window_closed(void) { cfg_save(); // a menu change saves 400 ms later on the render thread (option_rows.cpp); closing sooner kept the old file vk_pipeline_save(); prof_write(); // plat_exit runs no atexit handlers + rtss_limit_restore(); // RivaTuner Statistics Server's profile as it was fs_save_flush(); // last: the game's threads still run until plat_exit, and a Commit after this one is refused if (restart) { plat_setenv("NX2NAVI_REEXEC", NULL); // the new process counts its own address-space retries (memory.c) diff --git a/runtime/host.h b/runtime/host.h index 8c3bb39f..869a93c9 100644 --- a/runtime/host.h +++ b/runtime/host.h @@ -298,6 +298,12 @@ uint64_t frame_step_cap_ns(void); // with the real-time int frame_limit_adjustable(void); // the frame limit setting changes the rate (always) int frame_free_running(void); // no fps60/realtime patch set: the game steps by the clock double frame_step_limit_hz(void); // the frame rate the limit gives (overlay); 0 unknown +// rtss_limit.c: RivaTuner Statistics Server takes the frame limit where it runs +void rtss_limit_want(int64_t mhz); // the pacer's limit in millihertz: >0, 0 none, -1 keep RTSS out +int rtss_limit_active(void); // RTSS limits this process: the pacer holds no frames +int rtss_limit_state(void); // menu: 1 RTSS limits, 2 its profile is read-only, 3 it let the + // game run past its limit +void rtss_limit_restore(void); // before the process ends: the profile's old limit back int64_t frame_step_world_us(void); // game time since the loaded save's first frame, -1 before // (NX2NAVI_FPS_LIMIT, live) uint64_t frame_step_ticks(void); // game time since the first present in 60 Hz ticks (input scripts) diff --git a/runtime/main.c b/runtime/main.c index 4fb74ac7..eb342c1f 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -264,6 +264,7 @@ static void crash_handler(const PlatCrash *x) { rt_logf(" not on a guest thread\n"); } kern_free_cores_note(); + rtss_limit_restore(); // after the report: RivaTuner Statistics Server's profile as it was fflush(stderr); plat_exit(71); } diff --git a/runtime/rtss_limit.c b/runtime/rtss_limit.c new file mode 100644 index 00000000..538cf37b --- /dev/null +++ b/runtime/rtss_limit.c @@ -0,0 +1,344 @@ +// RivaTuner Statistics Server as the frame limiter (frame_rate.c frame_step_cap_ns): where RTSS is installed and running, +// the frame limit goes into RTSS's profile for this executable and the game's own pacer holds no frames, so there is +// one limiter. Anywhere else, or when any step fails, the game's own limiter works as it always did. +// +// RTSS's hooks library (RTSSHooks64.dll in the folder its installer records under +// HKLM\SOFTWARE\WOW6432Node\Unwinder\RTSS, InstallDir) exports the profile calls, loaded here at run time: +// LoadProfile(name) reads a profile (the global one for a name without its own), Get/SetProfileProperty read and change +// the loaded copy, SaveProfile(name) writes it to Profiles\.cfg, UpdateProfiles makes every hooked process +// read its profile again, EnumProfiles lists the profiles that exist, DeleteProfile removes one. "FramerateLimit" is +// the limit in frames per second (0: none); "FramerateLimitDenominator" divides it, so 59940 over 1000 limits to +// 59.94 (a monitor's measured rate). SaveProfile reports nothing: RTSS's Profiles folder sits under Program Files, which +// a process without administrator rights cannot write, and the save then fails silently. So every change is read back +// from the saved profile, and a limit that did not stick leaves the game's own limiter in charge for the session. +// +// RTSS runs when its shared memory "RTSSSharedMemoryV2" carries the signature 'RTSS'; it limits this process once the +// memory's application list holds this process id (RTSS hooks a process some seconds after it starts, its injection +// delay). Until then, and again if RTSS quits, the game's own limiter paces the frames. While RTSS limits, the frame +// rate RTSS itself measures for the game is checked against the limit: well above it for three seconds, and the game +// takes the limiting back for the rest of the run. +// +// The calls run on a thread of their own, every half second, so a present never waits on profile files. On exit +// (rtss_limit_restore, from every path that ends the process) the profile gets back what it held before the game +// changed it: the old limit, or no profile of its own when there was none. A crash before that leaves the game's +// limit in the profile until the next run changes it. +// +// NX2NAVI_RTSS=0 keeps RTSS out of it. Frame generation keeps it out too: RTSS counts every presented frame, the +// generated ones included, and would halve the limit. +#include +#include +#include +#include + +#include "host.h" +#include "platform/platform.h" + +#ifdef _WIN32 +#include + +typedef DWORD (*EnumProfilesFn)(LPSTR list, DWORD size); +typedef void (*ProfileFn)(LPCSTR name); +typedef BOOL (*PropertyFn)(LPCSTR property, LPBYTE data, DWORD size); +typedef void (*UpdateFn)(void); + +#define RTSS_SIGNATURE 0x52545353u // 'RTSS' as RTSS writes it: the memory holds valid data +#define POLL_MS 500 +#define CHECK_POLLS 6 // polls in a row RTSS's own frame rate of the game may stay above the limit +#define CHECK_SLACK 1.2 // above limit * this, RTSS is taken not to hold the game to it + +enum { FAIL_NONE, FAIL_LIBRARY, FAIL_READONLY, FAIL_NOT_LIMITING }; + +static PlatMutex lock = PLAT_MUTEX_INIT; // the hooks calls and the state below +static _Atomic int64_t want = -2; // millihertz from the pacer: >0 a limit, 0 none, -1 RTSS kept out; -2 unset +static _Atomic int active; // RTSS limits this process now +static _Atomic int failed; // FAIL_*: RTSS is out of it for the rest of the run +static int started; +static char dll_path[MAX_PATH], profile[MAX_PATH]; +static HMODULE dll; +static EnumProfilesFn enum_profiles; +static ProfileFn load_profile, save_profile, delete_profile; +static PropertyFn get_property, set_property; +static UpdateFn update_profiles; +static int has_denominator; // this RTSS knows FramerateLimitDenominator +static int64_t applied = -1; // the millihertz the profile holds from this run; -1 untouched +static int64_t refused = -1; // a limit RTSS refused (out of its range): the game's own limiter keeps that one +static int changed; // the profile holds a value from this run: put the old one back on exit +static int had_profile; // the profile existed before this run changed it +static DWORD old_limit, old_denominator = 1; + +// RTSS's shared memory: running (1), whether its application list holds this process, and the frame rate RTSS measured +// for it over its last period (0 unknown). The header: signature, version, application entry size, offset of the +// application array, its length. An entry: the process id, the executable path (MAX_PATH), flags, then the period's +// start and end in ms and the frames in it. +static int rtss_running(int *hooked, double *fps) { + *hooked = 0, *fps = 0; + HANDLE m = OpenFileMappingA(FILE_MAP_READ, FALSE, "RTSSSharedMemoryV2"); + if (!m) return 0; + const uint8_t *p = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); + int run = 0; + MEMORY_BASIC_INFORMATION mi; + if (p && VirtualQuery(p, &mi, sizeof mi) && mi.RegionSize >= 20) { + DWORD h[5]; + memcpy(h, p, sizeof h); + run = h[0] == RTSS_SIGNATURE && h[1] >= 0x20000; + DWORD pid = GetCurrentProcessId(); + enum { PERIOD_AT = 4 + MAX_PATH + 4, ENTRY_MIN = PERIOD_AT + 12 }; + for (DWORD i = 0; run && h[2] >= ENTRY_MIN && i < h[4] && i < 4096; i++) { + uint64_t at = (uint64_t)h[3] + (uint64_t)i * h[2]; + if (at + ENTRY_MIN > mi.RegionSize) break; + DWORD id, t[3]; + memcpy(&id, p + at, 4); + if (id != pid) continue; + *hooked = 1; + memcpy(t, p + at + PERIOD_AT, sizeof t); // start, end, frames + if (t[1] > t[0]) *fps = 1000.0 * t[2] / (t[1] - t[0]); + break; + } + } + if (p) UnmapViewOfFile(p); + CloseHandle(m); + return run; +} + +static int load_hooks(void) { + if (dll) return 1; + dll = LoadLibraryA(dll_path); + if (!dll) { + rt_log("frame rate: RivaTuner Statistics Server's %s did not load (%lu)", dll_path, GetLastError()); + return 0; + } + enum_profiles = (EnumProfilesFn)(void *)GetProcAddress(dll, "EnumProfiles"); + load_profile = (ProfileFn)(void *)GetProcAddress(dll, "LoadProfile"); + save_profile = (ProfileFn)(void *)GetProcAddress(dll, "SaveProfile"); + delete_profile = (ProfileFn)(void *)GetProcAddress(dll, "DeleteProfile"); + get_property = (PropertyFn)(void *)GetProcAddress(dll, "GetProfileProperty"); + set_property = (PropertyFn)(void *)GetProcAddress(dll, "SetProfileProperty"); + update_profiles = (UpdateFn)(void *)GetProcAddress(dll, "UpdateProfiles"); + if (enum_profiles && load_profile && save_profile && delete_profile && get_property && set_property && update_profiles) + return 1; + rt_log("frame rate: RivaTuner Statistics Server's hooks library lacks the profile calls"); + FreeLibrary(dll); + dll = NULL; + return 0; +} + +// The profile exists on its own (EnumProfiles: a comma-separated list of names). +static int profile_exists(void) { + char list[8192]; + DWORD need = enum_profiles(list, sizeof list); + list[sizeof list - 1] = 0; + if (need > sizeof list) + rt_log("frame rate: RivaTuner Statistics Server lists %lu bytes of profiles; reading the first %zu", need, sizeof list); + size_t n = strlen(profile); + for (char *s = list; *s;) { + char *end = strchr(s, ','); + size_t len = end ? (size_t)(end - s) : strlen(s); + if (len == n && !_strnicmp(s, profile, n)) return 1; + if (!end) break; + s = end + 1; + } + return 0; +} + +// Writes limit/denominator into the profile and reads them back from the saved file: 1 when they stuck, 0 when RTSS +// refused a value, -1 when the save did not reach the file. RTSS checks each value against the other one already in +// the profile (the limit over the denominator must be a rate it accepts: 165080 is refused over 1 and taken over 1000), +// so the limit goes to 0 (none) before the denominator changes. +static int write_limit(DWORD limit, DWORD denominator) { + load_profile(profile); + DWORD none = 0; + if (!set_property("FramerateLimit", (LPBYTE)&none, sizeof none)) return 0; + if (has_denominator && !set_property("FramerateLimitDenominator", (LPBYTE)&denominator, sizeof denominator)) return 0; + if (limit && !set_property("FramerateLimit", (LPBYTE)&limit, sizeof limit)) return 0; + save_profile(profile); + load_profile(profile); + DWORD l = ~0u, d = 1; + if (!get_property("FramerateLimit", (LPBYTE)&l, sizeof l)) return -1; + if (has_denominator && !get_property("FramerateLimitDenominator", (LPBYTE)&d, sizeof d)) return -1; + return l == limit && (!has_denominator || d == denominator) ? 1 : -1; +} + +// 1: the profile holds mhz; 0: RTSS refused it (the profile then holds no limit of this run); -1: the profile cannot be +// written. +static int apply(int64_t mhz) { + if (!changed) { // what to put back on exit + had_profile = profile_exists(); + load_profile(profile); + old_limit = 0, old_denominator = 1; + get_property("FramerateLimit", (LPBYTE)&old_limit, sizeof old_limit); + has_denominator = get_property("FramerateLimitDenominator", (LPBYTE)&old_denominator, sizeof old_denominator); + if (!old_denominator) old_denominator = 1; + } + DWORD limit, denominator = 1; + if (mhz % 1000 == 0) limit = (DWORD)(mhz / 1000); + else if (has_denominator) limit = (DWORD)mhz, denominator = 1000; + else limit = (DWORD)((mhz + 500) / 1000); + int r = write_limit(limit, denominator); + if (r < 0) { + rt_log("frame rate: RivaTuner Statistics Server's profile %s did not keep the limit: its Profiles folder needs the " + "game run as administrator", profile); + return -1; + } + if (!changed) { + if (!had_profile) + rt_log("frame rate: RivaTuner Statistics Server profile %s created; it goes away when the game closes", profile); + else + rt_log("frame rate: RivaTuner Statistics Server profile %s held a limit of %lu/%lu; it gets that back when the " + "game closes", profile, old_limit, old_denominator); + changed = 1; + } + if (r == 0) { // RTSS must not keep an earlier limit of this run under the game's own one + rt_log("frame rate: RivaTuner Statistics Server refused a limit of %.3f fps", mhz / 1000.0); + if (applied != 0 && write_limit(0, 1) > 0) applied = 0, update_profiles(); + refused = mhz; + return 0; + } + applied = mhz; + update_profiles(); + if (mhz) rt_log("frame rate: RivaTuner Statistics Server's profile %s limits to %.3f fps", profile, mhz / 1000.0); + else rt_log("frame rate: RivaTuner Statistics Server's profile %s has no limit (unlimited)", profile); + return 1; +} + +static void put_back(void) { + if (!changed) return; + changed = 0; + applied = -1; + if (!had_profile) { + delete_profile(profile); + rt_log("frame rate: RivaTuner Statistics Server profile %s removed, as before the game started", profile); + } else if (write_limit(old_limit, old_denominator) > 0) { + rt_log("frame rate: RivaTuner Statistics Server profile %s has its limit of %lu/%lu back", profile, old_limit, + old_denominator); + } else { + rt_log("frame rate: RivaTuner Statistics Server profile %s did not take its old limit back", profile); + } + update_profiles(); +} + +// Logs which limiter is in use: the first decision, then each change. +static void set_active(int on, const char *why) { + static int logged = -1; + atomic_store(&active, on); + if (logged == on) return; + logged = on; + if (on) rt_log("frame rate: RivaTuner Statistics Server does the limiting; the game's own limiter stands aside"); + else rt_log("frame rate: the game's own limiter (%s)", why); +} + +static const char *fail_reason(int f) { + return f == FAIL_READONLY ? "RivaTuner Statistics Server's profile cannot be changed" + : f == FAIL_NOT_LIMITING ? "RivaTuner Statistics Server does not hold the game to the limit" + : "RivaTuner Statistics Server's hooks library did not load"; +} + +static void worker(void *arg) { + (void)arg; + int was_running = -1, was_hooked = 0, over = 0; + for (;; plat_sleep_ms(POLL_MS)) { + int64_t w = atomic_load(&want); + if (w == -2) continue; + plat_mutex_lock(&lock); + int hooked; + double fps; + int run = rtss_running(&hooked, &fps), f = atomic_load(&failed); + if (run != was_running || hooked != was_hooked) { + if (!run) rt_log("frame rate: RivaTuner Statistics Server is installed but not running"); + else if (!hooked) rt_log("frame rate: RivaTuner Statistics Server runs; it has not hooked the game yet"); + else rt_log("frame rate: RivaTuner Statistics Server has hooked the game"); + was_running = run, was_hooked = hooked; + } + if (w < 0) { + if (dll) put_back(); + set_active(0, "RivaTuner Statistics Server kept out: NX2NAVI_RTSS=0 or frame generation"); + } else if (f) { + set_active(0, fail_reason(f)); + } else if (!run) { + set_active(0, "RivaTuner Statistics Server is not running"); + } else if (!load_hooks()) { + atomic_store(&failed, FAIL_LIBRARY); + set_active(0, fail_reason(FAIL_LIBRARY)); + } else if (w == refused) { + set_active(0, "RivaTuner Statistics Server refused this limit"); + } else if (w != applied) { + int r = apply(w); + over = 0; + if (r < 0) atomic_store(&failed, FAIL_READONLY), set_active(0, fail_reason(FAIL_READONLY)); + else if (r == 0) set_active(0, "RivaTuner Statistics Server refused this limit"); + else set_active(hooked, "RivaTuner Statistics Server has not hooked the game yet"); + } else { + set_active(hooked, "RivaTuner Statistics Server has not hooked the game yet"); + // RTSS's own count of the game's frames while the game's limiter stands aside: well above the limit for + // three seconds means RTSS does not hold the game to it, and the game takes the limiting back for the run + if (!hooked || w == 0 || fps <= w / 1000.0 * CHECK_SLACK) over = 0; + else if (++over == CHECK_POLLS) { + rt_log("frame rate: RivaTuner Statistics Server measures %.1f fps with its limit at %.3f fps", fps, + w / 1000.0); + atomic_store(&failed, FAIL_NOT_LIMITING); + put_back(); + set_active(0, fail_reason(FAIL_NOT_LIMITING)); + } + } + plat_mutex_unlock(&lock); + } +} + +static void start(void) { + started = 1; + char dir[MAX_PATH]; + DWORD size = sizeof dir; + if (RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Unwinder\\RTSS", "InstallDir", RRF_RT_REG_SZ, NULL, dir, + &size) != ERROR_SUCCESS) { + rt_log("frame rate: RivaTuner Statistics Server is not installed; the game's own limiter"); + return; + } + snprintf(dll_path, sizeof dll_path, "%s\\RTSSHooks64.dll", dir); + if (GetFileAttributesA(dll_path) == INVALID_FILE_ATTRIBUTES) { + rt_log("frame rate: RivaTuner Statistics Server's folder %s has no RTSSHooks64.dll; the game's own limiter", dir); + return; + } + char exe[MAX_PATH]; + DWORD n = GetModuleFileNameA(NULL, exe, sizeof exe); + if (!n || n >= sizeof exe) return; + const char *base = exe; + for (const char *s = exe; *s; s++) + if (*s == '\\' || *s == '/') base = s + 1; + snprintf(profile, sizeof profile, "%s", base); // RTSS names a profile after the executable, as ocarina.exe + rt_log("frame rate: RivaTuner Statistics Server found in %s; it takes the frame limit while it runs", dir); + if (!plat_thread_spawn(worker, NULL, "rtss", 0)) rt_log("frame rate: the RivaTuner Statistics Server thread did not start"); +} + +void rtss_limit_want(int64_t mhz) { + if (!started && mhz < 0) return; // kept out from the start, for the whole run (both reasons need a restart) + if (!started) start(); + atomic_store(&want, mhz); +} + +int rtss_limit_active(void) { return atomic_load_explicit(&active, memory_order_relaxed); } + +int rtss_limit_state(void) { + int f = atomic_load_explicit(&failed, memory_order_relaxed); + if (atomic_load(&want) >= 0 && (f == FAIL_READONLY || f == FAIL_NOT_LIMITING)) return f == FAIL_READONLY ? 2 : 3; + return rtss_limit_active() && atomic_load(&want) > 0; +} + +void rtss_limit_restore(void) { + if (!started || !*profile) return; + // the exit may come from a crash on any thread: give up after a second rather than wait on a lock held there + for (int i = 0; i < 100; i++) { + if (plat_mutex_trylock(&lock)) { + if (dll) put_back(); + atomic_store(&want, -2); // the worker leaves the profile alone from now on + plat_mutex_unlock(&lock); + return; + } + plat_sleep_ms(10); + } +} + +#else +void rtss_limit_want(int64_t mhz) { (void)mhz; } +int rtss_limit_active(void) { return 0; } +int rtss_limit_state(void) { return 0; } +void rtss_limit_restore(void) {} +#endif diff --git a/runtime/svc.c b/runtime/svc.c index ccc40c6a..386b995a 100644 --- a/runtime/svc.c +++ b/runtime/svc.c @@ -246,6 +246,7 @@ static void svc_body(Cpu *c, uint32_t imm, uint64_t pc) { fs_save_flush(); vk_pipeline_save(); prof_write(); + rtss_limit_restore(); fflush(NULL); if (svc_test_exit_hook) return svc_test_exit_hook(0); plat_exit(0); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 131f5377..1fa84b40 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -62,6 +62,7 @@ int vk_hdr_wanted(void); int vk_hdr_active(void); double frame_step_limit_hz(void); int frame_limit_adjustable(void); +int rtss_limit_state(void); int frame_free_running(void); extern const int rt_game_version; extern const char rt_port_version[]; @@ -700,6 +701,8 @@ static void row_game_lang(void) { } // The frame limit (frame_rate.c): unset, the older fps60 = 0 still means 30. The monitor choice shows the rate it gives. +// The note says when RivaTuner Statistics Server does the limiting (rtss_limit.c), cannot change its profile, or let the +// game run past its limit. static void row_fps_limit() { // 40 and 45: the Steam Deck's screen runs at 40 to 60 Hz (the OLED to 90); 40 divides 40 and 120 Hz evenly // 165 and 240: common gaming monitors; unlimited only where the game steps by the clock (frame_rate.c) @@ -719,7 +722,12 @@ static void row_fps_limit() { } const char *set = cfg_get("NX2NAVI_FPS_LIMIT"), *old = cfg_get("NX2NAVI_FPS60"); int cur = (!set || !*set) && old && !strcmp(old, "0") ? 0 : -1; - opt_choice_list("NX2NAVI_FPS_LIMIT", UI_MENU_FPS_LIMIT, vals, names, n, UI_MENU_FPS_LIMIT_DESC, cur); + int rtss = rtss_limit_state(); + const char *note = rtss == 1 ? menu_text(UI_MENU_FPS_RTSS) + : rtss == 2 ? menu_text(UI_MENU_FPS_RTSS_READONLY) + : rtss == 3 ? menu_text(UI_MENU_FPS_RTSS_IGNORED) + : nullptr; + opt_choice_list("NX2NAVI_FPS_LIMIT", UI_MENU_FPS_LIMIT, vals, names, n, UI_MENU_FPS_LIMIT_DESC, cur, note); } // The menu's name of a NX2NAVI_VK_PRESENT mode (gfx_window_present_mode); NULL for another. diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 6996db0f..0107c1e1 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -180,6 +180,10 @@ static const char *const text_en[UI_TEXT_COUNT] = { // the monitor's refresh rate; printf format with the rate in Hz when it is known [UI_MENU_FPS_DISPLAY] = "Monitor rate", [UI_MENU_FPS_DISPLAY_HZ] = "Monitor rate (%.0f Hz)", [UI_MENU_FPS_UNLIMITED] = "Unlimited", + // notes under the frame rate value: RivaTuner Statistics Server (rtss_limit.c) limits the game, or cannot + [UI_MENU_FPS_RTSS] = "limited by RivaTuner Statistics Server", + [UI_MENU_FPS_RTSS_READONLY] = "RivaTuner needs the game run as administrator", + [UI_MENU_FPS_RTSS_IGNORED] = "RivaTuner does not limit this game; the game does", [UI_MENU_REALTIME] = "Game speed follows the clock", [UI_MENU_REALTIME_DESC] = "Steps the game by real time, so a slow frame does not slow the game down.", [UI_MENU_CLOTH_REALTIME] = "Cloth on the clock", @@ -691,6 +695,9 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS", [UI_MENU_FPS_DISPLAY] = "Как у монитора", [UI_MENU_FPS_DISPLAY_HZ] = "Как у монитора (%.0f Гц)", [UI_MENU_FPS_UNLIMITED] = "Без ограничения", + [UI_MENU_FPS_RTSS] = "ограничивает RivaTuner Statistics Server", + [UI_MENU_FPS_RTSS_READONLY] = "RivaTuner нужен запуск игры от администратора", + [UI_MENU_FPS_RTSS_IGNORED] = "RivaTuner не ограничивает эту игру; ограничивает игра", [UI_MENU_REALTIME] = "Скорость игры по часам", [UI_MENU_REALTIME_DESC] = "Игра идёт по реальному времени, медленный кадр её не замедляет.", [UI_MENU_CLOTH_REALTIME] = "Ткань по часам", @@ -1132,6 +1139,9 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { "assim pode parar de vez.", [UI_MENU_FPS_DISPLAY] = "Taxa do monitor", [UI_MENU_FPS_DISPLAY_HZ] = "Taxa do monitor (%.0f Hz)", [UI_MENU_FPS_UNLIMITED] = "Sem limite", + [UI_MENU_FPS_RTSS] = "limitado pelo RivaTuner Statistics Server", + [UI_MENU_FPS_RTSS_READONLY] = "o RivaTuner pede o jogo como administrador", + [UI_MENU_FPS_RTSS_IGNORED] = "o RivaTuner não limita este jogo; o jogo limita", [UI_MENU_REALTIME] = "Velocidade do jogo pelo relógio", [UI_MENU_REALTIME_DESC] = "Avança o jogo pelo tempo real, para que um quadro lento não deixe o jogo mais lento.", [UI_MENU_CLOTH_REALTIME] = "Tecidos pelo relógio", @@ -1673,6 +1683,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_FPS_DISPLAY] = "显示器刷新率", [UI_MENU_FPS_DISPLAY_HZ] = "显示器刷新率(%.0f Hz)", [UI_MENU_FPS_UNLIMITED] = "不限制", + [UI_MENU_FPS_RTSS] = "由 RivaTuner Statistics Server 限制", + [UI_MENU_FPS_RTSS_READONLY] = "RivaTuner 需要以管理员身份运行游戏", + [UI_MENU_FPS_RTSS_IGNORED] = "RivaTuner 未限制本游戏;由游戏自行限制", [UI_MENU_REALTIME] = "游戏速度跟随时钟", [UI_MENU_REALTIME_DESC] = "按真实时间推进游戏,帧率低时游戏速度也不会变慢。", [UI_MENU_CLOTH_REALTIME] = "布料跟随时钟", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index d16f68ab..94ac0e6b 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -63,7 +63,7 @@ typedef enum { // Game UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_40, UI_MENU_FPS_45, UI_MENU_FPS_60, UI_MENU_FPS_90, UI_MENU_FPS_120, UI_MENU_FPS_144, - UI_MENU_FPS_DISPLAY, UI_MENU_FPS_DISPLAY_HZ, UI_MENU_FPS_UNLIMITED, + UI_MENU_FPS_DISPLAY, UI_MENU_FPS_DISPLAY_HZ, UI_MENU_FPS_UNLIMITED, UI_MENU_FPS_RTSS, UI_MENU_FPS_RTSS_READONLY, UI_MENU_FPS_RTSS_IGNORED, UI_MENU_REALTIME, UI_MENU_REALTIME_DESC, UI_MENU_CLOTH_REALTIME, UI_MENU_CLOTH_REALTIME_DESC, UI_MENU_HIGHFPS_FIX, UI_MENU_HIGHFPS_FIX_DESC,