From 3209ea4358b43325e5c8f04dc30a517befcdd016 Mon Sep 17 00:00:00 2001 From: Tears of the SteelTemple Date: Sat, 7 Nov 2026 12:17:17 +0200 Subject: [PATCH] Implement Native NVIDIA Reflex Low Latency (VK_NV_low_latency2) - Enable VK_NV_low_latency2 and VK_KHR_present_id with present ID features - Add VkSwapchainLatencyCreateInfoNV to swapchain creation - Link present and submission IDs with standard Vulkan latency types - Insert latency markers: simulation start/end, input sample, render submit, and present - Gate all extensions and latency chains on reflex != off (RESTART setting) - Log graceful notice when Reflex is requested on unsupported hardware - Add UI menu setting and translations for en, ru, pt-BR, zh-Hans - Document reflex setting in totk.ini.example and docs/settings.md --- docs/settings.md | 1 + runtime/cfg.c | 6 +- runtime/gfx_present.c | 131 +++++++++++++++++++++++++++++++++++++++++- runtime/nvn_api_obj.c | 6 ++ runtime/ov_input.c | 3 + runtime/ui/menu.cpp | 2 + runtime/ui_text.c | 20 +++++++ runtime/ui_text.h | 1 + runtime/vk.h | 7 ++- runtime/vk_device.c | 17 +++++- runtime/vk_sync.c | 8 +++ totk.ini.example | 3 + 12 files changed, 196 insertions(+), 9 deletions(-) diff --git a/docs/settings.md b/docs/settings.md index e1163426..da5ca279 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -178,6 +178,7 @@ Many rows below are developer tools that only act together with another setting | `mvprev_grow` (default `1`) | `0` keeps only three banks in the previous-frame tables. | Object motion that depends on the other banks is no longer tracked. | Caution | | `mvprev_skip` | Hex bank mask of banks left out of the previous-frame copy, replacing the default. | Different banks are tracked, which changes object motion. | Caution | | `mvprev_trust` | Hex bank mask of banks whose found previous-frame copy is taken without the check. | A copy that does not match is used anyway, which can give wrong motion. | Caution | +| `reflex` (default `off`) | `off`, `on`, or `boost`; enables NVIDIA Reflex Low Latency (`VK_NV_low_latency2`) to reduce system input latency. Read at start. | On NVIDIA GPUs supporting the extension, coordinates simulation and presentation cadence to lower latency; `boost` keeps GPU clocks high in CPU-bound scenes. Has no effect on non-NVIDIA GPUs. | Safe | ## Scheduling and host diff --git a/runtime/cfg.c b/runtime/cfg.c index dbb73f7d..7a802afe 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -53,7 +53,7 @@ static const char *const known[] = { "ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_BENCH", "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_ASYNC", "REC_END", "REC_SPIN_US", "REEXEC", - "RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHUNKS", "REPLAY_CHUNK_DRAWS", "REPLAY_SKEW_US", "REPLAY_STATE_CHECK", "REPLAY_WORKERS", + "RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHUNKS", "REPLAY_CHUNK_DRAWS", "REPLAY_SKEW_US", "REPLAY_STATE_CHECK", "REPLAY_WORKERS", "REFLEX", "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_DEFER", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", @@ -77,7 +77,7 @@ static const struct { const char *key, *section; } sections[] = { {"COLOR_BRIGHTNESS", "display"}, {"COLOR_CONTRAST", "display"}, {"COLOR_SATURATION", "display"}, {"COLOR_GAMMA", "display"}, {"HDR", "display"}, {"HDR_PEAK_NITS", "display"}, {"HDR_GAME_NITS", "display"}, {"HDR_UI_NITS", "display"}, {"HDR_HUE", "display"}, {"SHADOW_RES", "display"}, - {"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "display"}, {"FXAA", "display"}, + {"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "display"}, {"REFLEX", "display"}, {"FXAA", "display"}, {"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"}, {"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, @@ -124,7 +124,7 @@ static const CfgMeta metas[] = { {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"DLAA", "0", "0|1", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE}, {"DLSS_PRESET", "default", "default|k|j", LIVE}, - {"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"FXAA", "1", "0|1", LIVE}, + {"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"REFLEX", "off", "off|on|boost", RESTART}, {"FXAA", "1", "0|1", LIVE}, {"ASPECT", "fit", "fit|stretch", LIVE}, {"MOVIE_ASPECT", "keep", "keep|stretch", LIVE}, {"FOV", "100", "70..140", LIVE}, {"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features // colour adjustment (vk_color.c); the preset is the menu's, the four values are what the present uses diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index f936b721..04b389da 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -239,6 +239,8 @@ unsigned gfx_window_focus_messages(void) { return (unsigned)g_focus_msgs; } // Present path (g_pl held): a settings change (cfg_version) reaches the window thread, which applies a changed size or // fullscreen; a changed TOTK_VK_PRESENT rebuilds the swapchain at this present. +static void reflex_apply_locked(void); + static void window_settings_live(void) { static unsigned seen; static int started; @@ -254,9 +256,108 @@ static void window_settings_live(void) { if (started) plat_xchg32(&g_dirty, 1); } if (started) gfx_window_apply_settings(); + reflex_apply_locked(); started = 1; } +// ---- NVIDIA Reflex Low Latency (VK_NV_low_latency2) +static PFN_vkSetLatencySleepModeNV g_reflex_set_mode; +static PFN_vkLatencySleepNV g_reflex_sleep; +static PFN_vkSetLatencyMarkerNV g_reflex_marker; +static VkSemaphore g_reflex_sem; +static uint64_t g_reflex_val; +static uint64_t g_reflex_present_id = 1; +static int g_reflex_mode = -1; // 0=off, 1=on, 2=boost +static uint32_t g_reflex_min_us = 1; + +static int reflex_mode_from_cfg(void) { + const char *v = cfg_value("TOTK_REFLEX"); + if (!v || !strcmp(v, "off") || !strcmp(v, "0")) return 0; + if (!strcmp(v, "boost") || !strcmp(v, "2")) return 2; + return 1; +} + +static void reflex_apply_locked(void) { + VkCtx *c = vk_ctx(); + if (!c || !c->has_nv_reflex || !g_sc) return; + if (!g_reflex_set_mode) { + g_reflex_set_mode = (PFN_vkSetLatencySleepModeNV)vkGetDeviceProcAddr(c->device, "vkSetLatencySleepModeNV"); + g_reflex_sleep = (PFN_vkLatencySleepNV)vkGetDeviceProcAddr(c->device, "vkLatencySleepNV"); + g_reflex_marker = (PFN_vkSetLatencyMarkerNV)vkGetDeviceProcAddr(c->device, "vkSetLatencyMarkerNV"); + } + if (!g_reflex_set_mode) return; + if (!g_reflex_sem) { + VkSemaphoreTypeCreateInfo ti = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO, + .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE, + .initialValue = 0 + }; + VkSemaphoreCreateInfo si = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = &ti}; + if (vkCreateSemaphore(c->device, &si, NULL, &g_reflex_sem) != VK_SUCCESS) return; + } + int mode = reflex_mode_from_cfg(); + uint32_t min_us = 0; + int limit = cfg_int("TOTK_FPS_LIMIT"); + if (limit > 0) min_us = (uint32_t)(1000000 / limit); + if (mode == g_reflex_mode && min_us == g_reflex_min_us) return; + g_reflex_mode = mode; + g_reflex_min_us = min_us; + VkLatencySleepModeInfoNV mi = { + .sType = VK_STRUCTURE_TYPE_LATENCY_SLEEP_MODE_INFO_NV, + .lowLatencyMode = mode > 0 ? VK_TRUE : VK_FALSE, + .lowLatencyBoost = mode == 2 ? VK_TRUE : VK_FALSE, + .minimumIntervalUs = min_us + }; + VkResult r = g_reflex_set_mode(c->device, g_sc, &mi); + rt_log("REFLEX: NVIDIA Reflex Low Latency -> %s (minInterval=%u us, VK_NV_low_latency2=%s)", + mode == 2 ? "ON + BOOST" : mode == 1 ? "ON" : "OFF", min_us, r == VK_SUCCESS ? "OK" : "ERR"); +} + +int vk_has_reflex(void) { + VkCtx *c = vk_ctx(); + return c && c->has_nv_reflex; +} + +uint64_t vk_reflex_current_present_id(void) { + return __atomic_load_n(&g_reflex_present_id, __ATOMIC_RELAXED); +} + +void vk_reflex_marker(int marker) { + VkCtx *c = vk_ctx(); + if (!c || !c->has_nv_reflex || !g_reflex_marker || g_reflex_mode <= 0 || !g_sc) return; + plat_rmutex_lock(&g_pl); + if (g_sc && g_reflex_marker) { + uint64_t pid = __atomic_load_n(&g_reflex_present_id, __ATOMIC_RELAXED); + VkSetLatencyMarkerInfoNV mi = { + .sType = VK_STRUCTURE_TYPE_SET_LATENCY_MARKER_INFO_NV, + .presentID = pid, + .marker = (VkLatencyMarkerNV)marker + }; + g_reflex_marker(c->device, g_sc, &mi); + } + plat_rmutex_unlock(&g_pl); +} + +void vk_reflex_sleep(void) { + VkCtx *c = vk_ctx(); + if (!c || !c->has_nv_reflex || !g_reflex_sleep || !g_reflex_sem || g_reflex_mode <= 0 || !g_sc) return; + uint64_t val = __atomic_add_fetch(&g_reflex_val, 1, __ATOMIC_RELAXED); + VkLatencySleepInfoNV si = { + .sType = VK_STRUCTURE_TYPE_LATENCY_SLEEP_INFO_NV, + .signalSemaphore = g_reflex_sem, + .value = val + }; + if (g_reflex_sleep(c->device, g_sc, &si) == VK_SUCCESS) { + VkSemaphoreWaitInfo wi = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO, + .semaphoreCount = 1, + .pSemaphores = &g_reflex_sem, + .pValues = &val + }; + vkWaitSemaphores(c->device, &wi, 100000000ULL); + } +} + // ---- swapchain static const char *g_present_got = ""; // the TOTK_VK_PRESENT value of the mode the swapchain got; "" before one @@ -289,12 +390,25 @@ static void flip_locked(void) { if (!g_flip_on) return; g_flip_on = 0; if (!g_sc) return; - VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, + VkCtx *c = vk_ctx(); + uint64_t pid = 0; + VkPresentIdKHR pid_info = {0}; + if (c && c->has_nv_reflex) { + pid = __atomic_add_fetch(&g_reflex_present_id, 1, __ATOMIC_RELAXED); + pid_info.sType = VK_STRUCTURE_TYPE_PRESENT_ID_KHR; + pid_info.swapchainCount = 1; + pid_info.pPresentIds = &pid; + vk_reflex_marker(4); // VK_LATENCY_MARKER_PRESENT_START_NV + } + VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, + .pNext = (c && c->has_nv_reflex) ? &pid_info : NULL, + .waitSemaphoreCount = 1, .pWaitSemaphores = &g_render_done[g_flip_idx], .swapchainCount = 1, .pSwapchains = &g_sc, .pImageIndices = &g_flip_idx}; vk_queue_lock(); - VkResult r = vkQueuePresentKHR(vk_ctx()->gfx_queue, &pi); + VkResult r = vkQueuePresentKHR(c->gfx_queue, &pi); vk_queue_unlock(); + if (c && c->has_nv_reflex) vk_reflex_marker(5); // VK_LATENCY_MARKER_PRESENT_END_NV vk_device_fault_report(r); if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) plat_xchg32(&g_dirty, 1); } @@ -338,8 +452,14 @@ static int build_swapchain(void) { vk_queue_lock(); vkDeviceWaitIdle(c->device); VkSwapchainKHR old = g_sc; + VkSwapchainLatencyCreateInfoNV sci = { + .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_LATENCY_CREATE_INFO_NV, + .latencyModeEnable = VK_TRUE + }; VkSwapchainCreateInfoKHR ci = { - .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .surface = g_surface, .minImageCount = count, + .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, + .pNext = (c->has_nv_reflex) ? &sci : NULL, + .surface = g_surface, .minImageCount = count, .imageFormat = sf.format, .imageColorSpace = sf.colorSpace, .imageExtent = ext, .imageArrayLayers = 1, .imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, // every surface supports it (the menu overlay draws into it) @@ -800,6 +920,11 @@ void gfx_window_release_vk(void) { vk_color_release(); vk_hdr_release(); vk_contact_release(); + if (g_reflex_sem) { + vkDestroySemaphore(c->device, g_reflex_sem, NULL); + g_reflex_sem = VK_NULL_HANDLE; + } + g_reflex_mode = -1; free_capture(); free_thumbs(); for (int i = 0; i < FRAMES; i++) { diff --git a/runtime/nvn_api_obj.c b/runtime/nvn_api_obj.c index 644acc8d..22fb03dd 100644 --- a/runtime/nvn_api_obj.c +++ b/runtime/nvn_api_obj.c @@ -19,6 +19,9 @@ #include "nvn_tex.h" #include "platform/platform.h" +void vk_reflex_marker(int marker); +void vk_reflex_sleep(void); + // ---------- Descriptor pools // NVNboolean nvnTexturePoolInitialize(NVNtexturePool *tp, const NVNmemoryPool *p, ptrdiff_t offset, int n) NVN_API(nvnTexturePoolInitialize) { @@ -687,6 +690,8 @@ NVN_API(nvnWindowAcquireTexture) { sleep_until(at); perf_end(PERF_PACE, p0); } + vk_reflex_sleep(); + vk_reflex_marker(0); // VK_LATENCY_MARKER_SIMULATION_START_NV // The sync means "the display no longer reads this image". Presents are copies queued in submit order, so it is // already satisfied: fenced = 3 with fence 0. if (s) { @@ -710,6 +715,7 @@ NVN_API(nvnQueuePresentTexture) { if (o->magic != NVN_WIN_MAGIC || idx < 0 || idx >= o->ntex || idx >= 4 || !o->tex[idx]) rt_fatal("nvn: QueuePresentTexture of image %d on window %p", idx, (void *)o); o->presents++; + vk_reflex_marker(1); // VK_LATENCY_MARKER_SIMULATION_END_NV const tex_t *t = (const tex_t *)o->tex[idx]; uint64_t period = present_period(o), now = kern_now_ns(); uint64_t slot = now + pace(&o->pace, now, period); diff --git a/runtime/ov_input.c b/runtime/ov_input.c index 3cbc6cfb..ac38f9c9 100644 --- a/runtime/ov_input.c +++ b/runtime/ov_input.c @@ -17,6 +17,8 @@ #include "ov.h" #include "platform/platform.h" +void vk_reflex_marker(int marker); + typedef struct { int64_t sampling; uint64_t buttons; int32_t lx, ly, rx, ry; uint32_t attributes, pad; } NpadState; typedef struct { int64_t sampling; int32_t x, y, dx, dy, wx, wy; uint32_t buttons, attributes; } MouseState; typedef struct { int64_t sampling; uint32_t modifiers, attributes; uint64_t keys[4]; } KeyboardState; @@ -93,6 +95,7 @@ static void npad_states(Cpu *c, uint32_t want) { if (live) { s.attributes = ATTR_CONNECTED; input_poll(&s.buttons, &s.lx, &s.ly, &s.rx, &s.ry); + vk_reflex_marker(6); // VK_LATENCY_MARKER_INPUT_SAMPLE_NV } *out = s; ret_x(c, 1); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 2bed97ed..df366614 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -694,6 +694,8 @@ static void tab_screen(float scale) { static const UiTextId chars[] = {UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM, UI_MENU_DLSS_CHARS_FULL}; opt_choice("TOTK_DLSS_CHAR_MASK", UI_MENU_DLSS_CHARS, chars, 4, UI_MENU_DLSS_CHARS_DESC); + static const UiTextId reflex[] = {UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST}; + opt_choice("TOTK_REFLEX", UI_MENU_REFLEX, reflex, 3, UI_MENU_REFLEX_DESC); opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC); rows_color(); opt_group(UI_MENU_HDR_GROUP); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 690383b7..5b1be433 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -166,6 +166,11 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_DLSS_PERFORMANCE] = "Performance", [UI_MENU_DLSS_ULTRA] = "Ultra Performance", [UI_MENU_FXAA] = "Game anti-aliasing (FXAA)", [UI_MENU_FXAA_DESC] = "The game's own FXAA edge smoothing. It blurs fine detail a little; with DLAA on it is not needed.", + [UI_MENU_REFLEX] = "NVIDIA Reflex Low Latency", + [UI_MENU_REFLEX_DESC] = "Reduces system latency on NVIDIA GPUs using VK_NV_low_latency2. On + Boost keeps GPU clocks high in CPU-bound scenes.", + [UI_MENU_REFLEX_OFF] = "Off", + [UI_MENU_REFLEX_ON] = "On", + [UI_MENU_REFLEX_BOOST] = "On + Boost", [UI_MENU_FPS_LIMIT] = "Frame rate limit", [UI_MENU_FPS_LIMIT_DESC] = "The most frames per second the game draws. Above 60 is experimental and needs Game speed " @@ -649,6 +654,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_DLSS_PERFORMANCE] = "Производительность", [UI_MENU_DLSS_ULTRA] = "Макс. производительность", [UI_MENU_FXAA] = "Сглаживание игры (FXAA)", [UI_MENU_FXAA_DESC] = "Собственное сглаживание FXAA. Слегка размывает мелкие детали; с DLAA оно не нужно.", + [UI_MENU_REFLEX] = "NVIDIA Reflex Low Latency", + [UI_MENU_REFLEX_DESC] = "Снижает задержку системы на видеокартах NVIDIA с помощью VK_NV_low_latency2. On + Boost удерживает высокие частоты GPU при упоре в процессор.", + [UI_MENU_REFLEX_OFF] = "Выкл", + [UI_MENU_REFLEX_ON] = "Вкл", + [UI_MENU_REFLEX_BOOST] = "Вкл + Ускорение", [UI_MENU_FPS_LIMIT] = "Ограничение частоты кадров", [UI_MENU_FPS_LIMIT_DESC] = "Наибольшее число кадров в секунду. Выше 60 — экспериментальный режим, нужна «Скорость " @@ -1486,6 +1496,11 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_FXAA] = "Antisserrilhado do jogo (FXAA)", [UI_MENU_FXAA_DESC] = "A suavização de bordas FXAA do próprio jogo. Borra um pouco os detalhes finos; com o DLAA " "ligado não é necessária.", + [UI_MENU_REFLEX] = "NVIDIA Reflex Low Latency", + [UI_MENU_REFLEX_DESC] = "Reduz a latência do sistema em GPUs NVIDIA usando VK_NV_low_latency2. On + Boost mantém os clocks da GPU altos quando limitado pela CPU.", + [UI_MENU_REFLEX_OFF] = "Desligado", + [UI_MENU_REFLEX_ON] = "Ligado", + [UI_MENU_REFLEX_BOOST] = "Ligado + Boost", [UI_MENU_TAB_CHEATS] = "Cheats", [UI_MENU_CHEATS_NONE] = "Nenhum cheat para esta versão do jogo. Os cheats de um mod são um arquivo de cheats do " "Atmosphere na pasta cheats dele, com o nome da build do jogo: mods\\\\cheats\\%s. " @@ -2096,6 +2111,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_DLSS_CHARS_FULL] = "强", [UI_MENU_FXAA] = "游戏抗锯齿(FXAA)", [UI_MENU_FXAA_DESC] = "游戏自身的 FXAA 边缘平滑。会让细节略微模糊;开启 DLAA 时不需要。", + [UI_MENU_REFLEX] = "NVIDIA Reflex 低延迟", + [UI_MENU_REFLEX_DESC] = "在支持 VK_NV_low_latency2 的 NVIDIA 显卡上降低系统延迟。开 + 增强 (On + Boost) 会在 CPU 瓶颈时保持 GPU 高频率。", + [UI_MENU_REFLEX_OFF] = "关", + [UI_MENU_REFLEX_ON] = "开", + [UI_MENU_REFLEX_BOOST] = "开 + 增强", [UI_MENU_TAB_CHEATS] = "金手指", [UI_MENU_CHEATS_NONE] = "此游戏版本没有金手指。模组的金手指是它的 cheats 文件夹中以游戏构建命名的 Atmosphere " "金手指文件:mods\\<模组>\\cheats\\%s。重启游戏后才会读取。对于修改游戏代码的金手指," diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 3bed8949..04093308 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -59,6 +59,7 @@ typedef enum { UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA, UI_MENU_DLSS_PRESET, UI_MENU_DLSS_PRESET_DESC, UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J, UI_MENU_DLSS_CHARS, UI_MENU_DLSS_CHARS_DESC, UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM, UI_MENU_DLSS_CHARS_FULL, UI_MENU_FXAA, UI_MENU_FXAA_DESC, + UI_MENU_REFLEX, UI_MENU_REFLEX_DESC, UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST, // 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, diff --git a/runtime/vk.h b/runtime/vk.h index bb705ebd..23d78fe8 100644 --- a/runtime/vk.h +++ b/runtime/vk.h @@ -36,7 +36,8 @@ typedef struct VkCtx { has_nv_checkpoints, // VK_NV_device_diagnostic_checkpoints (TOTK_PASS_CRUMBS=1, vk_crumbs.c) has_astc_ldr, // textureCompressionASTC_LDR (enabled when reported) has_calibrated, // VK_KHR/EXT_calibrated_timestamps (GPU idle split in the perf line) - has_hdr_metadata; // VK_EXT_hdr_metadata (vk_hdr.c vk_hdr_metadata) + has_hdr_metadata, // VK_EXT_hdr_metadata (vk_hdr.c vk_hdr_metadata) + has_nv_reflex; // VK_NV_low_latency2 (NVIDIA Reflex Low Latency) // Feedback loops (maxwell.md 1.9, vk_exec_draw.c feedback_prepare): a draw samples a target of its open pass that // an earlier draw of the pass wrote. TOTK_FEEDBACK=0: VK_FEEDBACK_OFF (sampled in GENERAL without a barrier, the // old behaviour); VK_FEEDBACK_LAYOUT with VK_EXT_attachment_feedback_loop_layout and dynamicRenderingLocalRead @@ -147,6 +148,10 @@ void vk_present_blit(VkImage src, VkImageLayout layout, VkFormat fmt, int w, int int vk_fsr_record(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, int sw, int sh, const int crop[4], VkImage dst, const int out[4]); void vk_fsr_release(void); // before the device goes away +void vk_reflex_marker(int marker); +void vk_reflex_sleep(void); +int vk_has_reflex(void); +uint64_t vk_reflex_current_present_id(void); // Colour adjustment on the present (vk_color.c): with TOTK_COLOR_* away from their defaults, records a pass that writes // src's crop rectangle {x, y, w, h}, adjusted, into an RGBA16F image of that size in GENERAL and returns it (the caller // scales that one instead, crop {0, 0, w, h}); VK_NULL_HANDLE = nothing recorded. src is in GENERAL, fmt its format. diff --git a/runtime/vk_device.c b/runtime/vk_device.c index 760a3a46..6a613450 100644 --- a/runtime/vk_device.c +++ b/runtime/vk_device.c @@ -283,6 +283,7 @@ typedef struct { VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT fbl; VkPhysicalDeviceDynamicRenderingLocalReadFeaturesKHR lr; VkPhysicalDeviceAddressBindingReportFeaturesEXT abr; + VkPhysicalDevicePresentIdFeaturesKHR pid; } FeatureChain; static int create_device(void) { @@ -290,7 +291,7 @@ static int create_device(void) { vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, NULL); VkExtensionProperties *ep = calloc(ne ? ne : 1, sizeof *ep); vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, ep); - const char *ext[48]; + const char *ext[52]; uint32_t n_ext = 0; for (size_t i = 0; i < sizeof k_required_ext / sizeof *k_required_ext; i++) ext[n_ext++] = k_required_ext[i]; @@ -334,7 +335,7 @@ static int create_device(void) { CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT); CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR); } - vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's; the eight slots after it stay for the seven below + vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's; the twelve slots after it stay for the nine below if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; } // GPU timestamps on the CPU clock (vk_sync.c): the perf line splits GPU idle time into waiting for a submission or not. if (has_ext(ep, ne, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 2; ext[n_ext++] = VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; } @@ -351,6 +352,18 @@ static int create_device(void) { g_vk.has_nv_checkpoints = 1; ext[n_ext++] = VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME; } + // NVIDIA Reflex Low Latency (VK_NV_low_latency2 requires VK_KHR_present_id) + const char *rv = cfg_value("TOTK_REFLEX"); + if (rv && strcmp(rv, "off") != 0 && strcmp(rv, "0") != 0) { + if (has_ext(ep, ne, VK_KHR_PRESENT_ID_EXTENSION_NAME) && has_ext(ep, ne, "VK_NV_low_latency2")) { + g_vk.has_nv_reflex = 1; + ext[n_ext++] = VK_KHR_PRESENT_ID_EXTENSION_NAME; + ext[n_ext++] = "VK_NV_low_latency2"; + CHAIN(pid, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR); + } else { + rt_log("Reflex: VK_NV_low_latency2 not available"); + } + } // Graphics pipeline library: chained last so it can be dropped again when vk_caps_gpl declines it. void **gpl_link = NULL; if (has_ext(ep, ne, VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME) && has_ext(ep, ne, VK_EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME)) { diff --git a/runtime/vk_sync.c b/runtime/vk_sync.c index 6626e96f..40421122 100644 --- a/runtime/vk_sync.c +++ b/runtime/vk_sync.c @@ -474,12 +474,20 @@ uint64_t vk_sync_submit(const uint64_t *handles, int n) { {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO, .commandBuffer = s->cb}}; VkSemaphoreSubmitInfo sig = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO, .semaphore = c->timeline, .value = fence, .stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}; + VkLatencySubmissionPresentIdNV lsid = { + .sType = VK_STRUCTURE_TYPE_LATENCY_SUBMISSION_PRESENT_ID_NV, + .pNext = NULL, + .presentID = vk_reflex_current_present_id() + }; VkSubmitInfo2 si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2, + .pNext = (c->has_nv_reflex) ? &lsid : NULL, .commandBufferInfoCount = (pro ? 1u : 0u) + (recorded ? 1u : 0u), .pCommandBufferInfos = pro ? cbi : cbi + 1, .signalSemaphoreInfoCount = 1, .pSignalSemaphoreInfos = &sig}; ts_submitted(); + if (recorded && c->has_nv_reflex) vk_reflex_marker(2); // VK_LATENCY_MARKER_RENDERSUBMIT_START_NV VkResult r = rec_submit(&si); // by the recorder when it recorded the part + if (recorded && c->has_nv_reflex) vk_reflex_marker(3); // VK_LATENCY_MARKER_RENDERSUBMIT_END_NV if (r != VK_SUCCESS) { vk_device_fault_report(r); rt_fatal("vk: vkQueueSubmit2 of value %llu failed (%d)", (unsigned long long)fence, (int)r); diff --git a/totk.ini.example b/totk.ini.example index c45a74b2..b7fd8962 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -259,6 +259,9 @@ # frame before, DLSS is told to favour the current frame by this percentage (0, 35, 65 or 100; 0 off). Higher removes # more of the trails and leaves those edges a little less smooth. Changes while the game runs take effect at once. # dlss_char_mask = 65 +# NVIDIA Reflex Low Latency (NVIDIA GPUs supporting VK_NV_low_latency2): off, on, or boost. +# Reduces system input latency; boost keeps GPU clocks high in CPU-bound scenes. Read at start. +# reflex = off # The game's own FXAA after the post effects; with DLAA on it is not needed. Changes while the game runs take effect at # once. # fxaa = 1