From e70b21d66f4ce09a596d4d50f46c1133366f1098 Mon Sep 17 00:00:00 2001 From: Fayber Date: Mon, 9 Nov 2026 14:20:50 +0100 Subject: [PATCH 01/18] Key bindings: moving a menu button no longer drags its game actions along (#608) A factory-default action is answered by the game from the Switch layer, so rebinding the raw "Menu: sort / sensor" slot (Y) also moved Attack. An action whose Switch button was rebound now answers from its own host bindings, like a changed one. --- docs/ACTIONS.md | 5 +++-- runtime/hle/bindings.c | 16 +++++++++++++++- tools/test_actions.c | 41 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/docs/ACTIONS.md b/docs/ACTIONS.md index 184110fb7..c7dd6d58d 100644 --- a/docs/ACTIONS.md +++ b/docs/ACTIONS.md @@ -3,7 +3,7 @@ Each game action owns one keyboard/mouse binding and one controller binding. Its factory defaults are copied from its Switch button's original layout using the fixed 1.9.0 mask table below: Jump starts on Space / North, Interact on E / East, and so on. If either device differs from its factory default, the action reads its own host bindings on -both devices, independent of raw Switch rebinds. With both devices at factory defaults, the game answers through the +both devices, independent of raw Switch rebinds. With both devices at factory defaults and the action's Switch button not rebound, the game answers through the Switch layer as before, preserving its Jump button change option and raw Switch injection. Multiple actions may share an input. Reset restores each action's factory defaults. `ACT_FOLLOW` remains a reset command accepted by `act_set`; it is no longer stored in `g_act_key` or `g_act_pad`. `ACT_NONE` unbinds an action side. @@ -16,7 +16,8 @@ Walk, Tilt, gyro and game action bindings allow shared inputs on both devices. A slot, including raw Switch menu buttons; rebinding a raw slot also leaves these shared bindings intact. Legacy host slots still swap among themselves on the same device, including the raw Switch buttons (0 to 15). -The game's title, pause and map menus still use the raw Switch layer, including legacy raw-button rebinds. The runtime +The game's title, pause and map menus still use the raw Switch layer, including legacy raw-button rebinds. Rebinding a raw Switch button (for example "Menu: sort / sensor", Y) makes the actions that read it answer from their own +host bindings, so they stay where they were instead of following the menu button (#608). The runtime overlay and launcher keep their fixed navigation shortcuts. The separate UI update can use `bind_input_name`, and `bind_input_group` ("gyro" or NULL). Raw Switch inputs are named by what they do (`bind_input_name(BIND_A)` is "Menu: confirm"), never by the button. No slots are hidden by these helpers; the page and overlay simply do not list diff --git a/runtime/hle/bindings.c b/runtime/hle/bindings.c index 109f3f10d..14bd2c8e8 100644 --- a/runtime/hle/bindings.c +++ b/runtime/hle/bindings.c @@ -148,6 +148,8 @@ int bind_label_family(void) { static void result(int kind, int dev, int slot, int other); static int act_default(int dev, int id); +static void act_refresh(void); +static bool act_raw_moved(int id); void bind_reset(int dev) { if (dev == BIND_DEV_PAD) memcpy(g_bind_pad, k_def_pad, sizeof g_bind_pad); @@ -166,6 +168,7 @@ void bind_reset_slot(int slot) { if (slot < 0 || slot >= BIND_KEY_COUNT) return; g_bind_key[slot] = k_def_key[slot]; if (bind_pad_slot(slot)) g_bind_pad[slot] = k_def_pad[slot]; + act_refresh(); } bool bind_is_default(int dev) { @@ -245,6 +248,7 @@ static void assign(int dev, int slot, int host) { dev == BIND_DEV_PAD ? k_pad_ini[host] : bind_key_label(host), other >= 0 ? " (swapped with " : "", other >= 0 ? k_names[other] : "", other >= 0 ? ")" : ""); if (other >= 0) LOG("[input] %s -> %s\n", k_names[other], dev == BIND_DEV_PAD ? bind_pad_label(t[other], 0) : bind_key_label(t[other])); + act_refresh(); // a moved Switch button must not drag the game's actions along (see act_refresh) result(other >= 0 ? 2 : 1, dev, slot, other); } @@ -324,6 +328,7 @@ bool bind_settings_load(const char *key, const char *val) { } if (i < BIND_PAD_COUNT) act_migrate(pad ? BIND_DEV_PAD : BIND_DEV_KEY, i); } + act_refresh(); return true; } @@ -373,10 +378,13 @@ bool act_is_default(int id) { (g_act_key[id] == act_default(BIND_DEV_KEY, id) && g_act_pad[id] == act_default(BIND_DEV_PAD, id)); } +// An action answers from its own host bindings when it differs from its factory default, and also when its Switch +// button was rebound: the game would answer from the Switch layer and the action would follow that button (#608: +// moving "Menu: sort / sensor" took Attack along). The menus keep reading the Switch layer either way. static void act_refresh(void) { uint64_t custom = 0; for (int id = 0; id < ACT_COUNT; id++) - if (!act_is_default(id)) custom |= 1ull << id; + if (!act_is_default(id) || act_raw_moved(id)) custom |= 1ull << id; a_custom = custom; } @@ -433,6 +441,12 @@ static const uint32_t k_masks_190[ACT_COUNT] = { 0x10000, 0x20000, 0x10000, 0x20000, 0x2, 0x1, 0x2000, 0x4000, 0x4, 0x2, 0x4000, 0x4000, 0x2000, 0x1, 0x20000, 0x10, 0x20000, 0x1, 0x2, 0x2000}; +// The Switch button an action reads in the 1.9.0 table has been rebound (the menu rows of the Key bindings page). +static bool act_raw_moved(int id) { + int b = mask_button(k_masks_190[id]); + return b >= 0 && (g_bind_key[b] != k_def_key[b] || (bind_pad_slot(b) && g_bind_pad[b] != k_def_pad[b])); +} + static int act_default(int dev, int id) { int b = mask_button(k_masks_190[id]); if (b < 0) return ACT_NONE; diff --git a/tools/test_actions.c b/tools/test_actions.c index c84598669..df10dc3b1 100644 --- a/tools/test_actions.c +++ b/tools/test_actions.c @@ -360,7 +360,8 @@ static void schema_migration_is_one_time(void) { assert(g_act_key[19] == SDL_SCANCODE_H && g_act_pad[19] == SDL_GAMEPAD_BUTTON_SOUTH); host(0, 0, 0); act_poll(true); - assert(hold(JUMP) == -1 && trig(JUMP) == -1 && hold(19) == 0); + // (X is rebound, so Jump answers from its own Space / north, not from the moved Switch button) + assert(hold(JUMP) == 0 && trig(JUMP) == 0 && hold(19) == 0); char *again = save_bindings(); assert(!strcmp(saved, again)); free(saved); @@ -507,6 +508,43 @@ static void names_and_groups(void) { for (unsigned i = 0; i < sizeof raw / sizeof *raw; i++) assert(strcmp(bind_input_name(slot), raw[i])); } +// #608: moving "Menu: sort / sensor" (the raw Y slot) used to take Attack along, because a factory-default action is +// answered by the game from the Switch layer. The action keeps its own key; the menus still see the moved button. +static void a_moved_menu_button_leaves_its_actions_alone(void) { + SDL_Event e = {0}; + reset_bindings(); + bind_settings_load("act_schema", "2"); + act_poll(true); + assert(hold(ATTACK) == -1); // all defaults: the game answers + bind_capture_begin(BIND_DEV_KEY, BIND_Y); + e.type = SDL_EVENT_KEY_DOWN; e.key.scancode = SDL_SCANCODE_LALT; + assert(bind_capture_event(&e) && g_bind_key[BIND_Y] == SDL_SCANCODE_LALT); + assert(g_act_key[ATTACK] == BIND_MOUSE + SDL_BUTTON_LEFT && act_is_default(ATTACK)); + act_poll(true); + assert(hold(ATTACK) == 0 && hold(JUMP) == -1); // Attack now answered from its own (unchanged) key; Jump reads X + key_down[SDL_SCANCODE_LALT] = 1; + host(0, 0, 0); + act_poll(true); + assert(hold(ATTACK) == 0 && trig(ATTACK) == 0); // Alt is the menu's sort button, not Attack + key_down[SDL_SCANCODE_LALT] = 0; + key_down[BIND_MOUSE + SDL_BUTTON_LEFT] = 1; + host(0, 0, 0); + act_poll(true); + assert(hold(ATTACK) == 1 && trig(ATTACK) == 1); + act_poll(false); + assert(hold(ATTACK) == -1); // menus: the Switch layer answers + key_down[BIND_MOUSE + SDL_BUTTON_LEFT] = 0; + host(0, 0, 0); + // the same through the controller side, and a reset puts the game back in charge + bind_capture_begin(BIND_DEV_PAD, BIND_Y); + e.type = SDL_EVENT_GAMEPAD_BUTTON_DOWN; e.gbutton.button = SDL_GAMEPAD_BUTTON_LEFT_SHOULDER; + assert(bind_capture_event(&e)); + bind_reset_slot(BIND_Y); + act_poll(true); + assert(hold(ATTACK) == -1); + reset_bindings(); +} + int main(void) { for (int i = 0; i < ACT_COUNT; i++) masks[i] = 0x1; masks[JUMP] = 0x8, masks[ATTACK] = 0x10, masks[INTERACT] = 0x1, masks[CANCEL] = 0x2; @@ -525,6 +563,7 @@ int main(void) { captures_allow_shared_action_inputs(); host_pad_slots(); names_and_groups(); + a_moved_menu_button_leaves_its_actions_alone(); puts("action bindings: default fallthrough, custom host bindings, schema migration, held / pressed, menus, shared keys, pad capture, contexts, reset and ini passed"); return 0; } From 3b774b3fd7837f42c52564d044945a43fc43c901 Mon Sep 17 00:00:00 2001 From: Fayber Date: Mon, 9 Nov 2026 19:44:16 +0100 Subject: [PATCH 02/18] Key bindings: actions only, no more raw-button swapping; menu rows no longer reach play (#608) In play the raw A/B/X/Y/L/R/ZL/ZR/stick bits now come only from actions still at their factory binding, so a key given to "Menu: sort / sensor" cannot press Attack and rebinding Jump leaves the other actions on that button alone. Raw slots share inputs instead of swapping. Replaces the act_raw_moved stopgap. --- docs/ACTIONS.md | 18 ++++--- runtime/hle/bindings.c | 65 +++++++++++++---------- runtime/hle/input.c | 16 ++++-- runtime/input_bind.h | 17 ++++-- runtime/ui/controls_ui.mm | 12 ++--- runtime/ui/i18n/de.inc | 3 +- runtime/ui/i18n/es.inc | 3 +- runtime/ui/i18n/fr.inc | 3 +- runtime/ui/i18n/he.inc | 3 +- runtime/ui/i18n/it.inc | 3 +- runtime/ui/i18n/ja.inc | 3 +- runtime/ui/i18n/ko.inc | 3 +- runtime/ui/i18n/nl.inc | 3 +- runtime/ui/i18n/pt.inc | 3 +- runtime/ui/i18n/ru.inc | 3 +- runtime/ui/i18n/th.inc | 3 +- runtime/ui/i18n/zh-Hans.inc | 3 +- runtime/ui/i18n/zh-Hant.inc | 3 +- tools/test_actions.c | 97 +++++++++++++++++++++-------------- tools/test_bind_capture.c | 6 ++- tools/test_input_focus.c | 4 ++ tools/test_quick_drop_input.c | 4 ++ 22 files changed, 162 insertions(+), 116 deletions(-) diff --git a/docs/ACTIONS.md b/docs/ACTIONS.md index c7dd6d58d..757813abd 100644 --- a/docs/ACTIONS.md +++ b/docs/ACTIONS.md @@ -3,7 +3,7 @@ Each game action owns one keyboard/mouse binding and one controller binding. Its factory defaults are copied from its Switch button's original layout using the fixed 1.9.0 mask table below: Jump starts on Space / North, Interact on E / East, and so on. If either device differs from its factory default, the action reads its own host bindings on -both devices, independent of raw Switch rebinds. With both devices at factory defaults and the action's Switch button not rebound, the game answers through the +both devices, independent of raw Switch rebinds. With both devices at factory defaults, the game answers through the Switch layer as before, preserving its Jump button change option and raw Switch injection. Multiple actions may share an input. Reset restores each action's factory defaults. `ACT_FOLLOW` remains a reset command accepted by `act_set`; it is no longer stored in `g_act_key` or `g_act_pad`. `ACT_NONE` unbinds an action side. @@ -13,11 +13,17 @@ seven gyro slots accept both devices; their new controller sides default to unbo left stick to 40%. Tilt holds the mouse clutch and enables the existing sensorless controller stick tilt path. Gyro buttons and keys combine per direction, only while `gyro_keys_live()`; simultaneous opposite directions cancel. Walk, Tilt, gyro and game action bindings allow shared inputs on both devices. Assigning one never changes another -slot, including raw Switch menu buttons; rebinding a raw slot also leaves these shared bindings intact. Legacy -host slots still swap among themselves on the same device, including the raw Switch buttons (0 to 15). +slot, including raw Switch menu buttons; rebinding a raw slot also leaves these shared bindings intact. Raw Switch +slots (0 to 15) no longer swap either: a host input already on another slot is simply shared (result kind 2 is unused). -The game's title, pause and map menus still use the raw Switch layer, including legacy raw-button rebinds. Rebinding a raw Switch button (for example "Menu: sort / sensor", Y) makes the actions that read it answer from their own -host bindings, so they stay where they were instead of following the menu button (#608). The runtime +In play, the raw A / B / X / Y / L / R / ZL / ZR / stick-press bits the game reads are built only from actions still at +their factory binding (`act_play_keys` / `act_play_pads`), never from the "Menu: ..." rows. So a key given to +"Menu: sort / sensor" cannot press Attack, rebinding Jump leaves Space on the raw X bit for the other X actions, and the +new key does not set it. D-pad, Plus and Minus stay on their rows (quick menu, pause, map). The menus and the title keep +using the rows. This only switches on once the game has asked about an action (`act_play_active()`); before that, and on +game versions without the hook, the rows drive every button as before. + +The game's title, pause and map menus still use the raw Switch layer, including legacy raw-button rebinds. The runtime overlay and launcher keep their fixed navigation shortcuts. The separate UI update can use `bind_input_name`, and `bind_input_group` ("gyro" or NULL). Raw Switch inputs are named by what they do (`bind_input_name(BIND_A)` is "Menu: confirm"), never by the button. No slots are hidden by these helpers; the page and overlay simply do not list @@ -171,7 +177,7 @@ synthetic rows (needs no game files). `make test-actions` (no game files): the answers to the hold / pressed queries, menus falling back, two actions on one key, factory-default fallthrough, customization on either device, legacy migration in either order, one-time schema -migration and reload idempotence, shared action/Walk/Tilt/gyro captures on both devices, preserved raw Switch swaps, +migration and reload idempotence, shared action/Walk/Tilt/gyro captures on both devices, raw Switch slots sharing instead of swapping, menu rows not reaching the play bits, reset and ini round trips (`tools/test_actions.c`), and the generated hook (`tools/test_act_site.py`). `make test-pc-controls` also checks Walk scaling, shared key/pad Tilt, mouse routing, sensorless dual-stick eligibility, diff --git a/runtime/hle/bindings.c b/runtime/hle/bindings.c index 14bd2c8e8..97a13065e 100644 --- a/runtime/hle/bindings.c +++ b/runtime/hle/bindings.c @@ -148,8 +148,6 @@ int bind_label_family(void) { static void result(int kind, int dev, int slot, int other); static int act_default(int dev, int id); -static void act_refresh(void); -static bool act_raw_moved(int id); void bind_reset(int dev) { if (dev == BIND_DEV_PAD) memcpy(g_bind_pad, k_def_pad, sizeof g_bind_pad); @@ -168,7 +166,6 @@ void bind_reset_slot(int slot) { if (slot < 0 || slot >= BIND_KEY_COUNT) return; g_bind_key[slot] = k_def_key[slot]; if (bind_pad_slot(slot)) g_bind_pad[slot] = k_def_pad[slot]; - act_refresh(); } bool bind_is_default(int dev) { @@ -227,9 +224,9 @@ int bind_last_result(int *dev, int *slot, int *other, int *serial) { return res_kind; } -// Bind `host` to `slot`; only legacy host slots swap. Actions, Walk, Tilt and gyro allow shared inputs. +// Bind `host` to `slot`. Every input may share its key or button with any other: nothing swaps and nothing else moves. static void assign(int dev, int slot, int host) { - if (bind_slot_is_action(slot)) { // an action may share its key with any other: nothing swaps + if (bind_slot_is_action(slot)) { act_set(dev, slot - BIND_ACTION, host); LOG("[input] %s action %d -> %s\n", dev == BIND_DEV_PAD ? "controller" : "keyboard", slot - BIND_ACTION, dev == BIND_DEV_PAD ? k_pad_ini[host] : bind_key_label(host)); @@ -237,19 +234,10 @@ static void assign(int dev, int slot, int host) { return; } int16_t *t = dev == BIND_DEV_PAD ? g_bind_pad : g_bind_key; - int other = -1; - for (int i = 0; i < BIND_KEY_COUNT; i++) - if (i != slot && (dev == BIND_DEV_KEY ? bind_key_same_context(i, slot) : (bind_pad_slot(i) && bind_key_same_context(i, slot))) && t[i] == host) { - other = i; - t[i] = t[slot]; - } t[slot] = (int16_t)host; - LOG("[input] %s %s -> %s%s%s%s\n", dev == BIND_DEV_PAD ? "controller" : "keyboard", k_names[slot], - dev == BIND_DEV_PAD ? k_pad_ini[host] : bind_key_label(host), other >= 0 ? " (swapped with " : "", - other >= 0 ? k_names[other] : "", other >= 0 ? ")" : ""); - if (other >= 0) LOG("[input] %s -> %s\n", k_names[other], dev == BIND_DEV_PAD ? bind_pad_label(t[other], 0) : bind_key_label(t[other])); - act_refresh(); // a moved Switch button must not drag the game's actions along (see act_refresh) - result(other >= 0 ? 2 : 1, dev, slot, other); + LOG("[input] %s %s -> %s\n", dev == BIND_DEV_PAD ? "controller" : "keyboard", k_names[slot], + dev == BIND_DEV_PAD ? k_pad_ini[host] : bind_key_label(host)); + result(1, dev, slot, -1); } bool bind_capture_event(const SDL_Event *e) { @@ -328,7 +316,6 @@ bool bind_settings_load(const char *key, const char *val) { } if (i < BIND_PAD_COUNT) act_migrate(pad ? BIND_DEV_PAD : BIND_DEV_KEY, i); } - act_refresh(); return true; } @@ -378,13 +365,10 @@ bool act_is_default(int id) { (g_act_key[id] == act_default(BIND_DEV_KEY, id) && g_act_pad[id] == act_default(BIND_DEV_PAD, id)); } -// An action answers from its own host bindings when it differs from its factory default, and also when its Switch -// button was rebound: the game would answer from the Switch layer and the action would follow that button (#608: -// moving "Menu: sort / sensor" took Attack along). The menus keep reading the Switch layer either way. static void act_refresh(void) { uint64_t custom = 0; for (int id = 0; id < ACT_COUNT; id++) - if (!act_is_default(id) || act_raw_moved(id)) custom |= 1ull << id; + if (!act_is_default(id)) custom |= 1ull << id; a_custom = custom; } @@ -441,12 +425,6 @@ static const uint32_t k_masks_190[ACT_COUNT] = { 0x10000, 0x20000, 0x10000, 0x20000, 0x2, 0x1, 0x2000, 0x4000, 0x4, 0x2, 0x4000, 0x4000, 0x2000, 0x1, 0x20000, 0x10, 0x20000, 0x1, 0x2, 0x2000}; -// The Switch button an action reads in the 1.9.0 table has been rebound (the menu rows of the Key bindings page). -static bool act_raw_moved(int id) { - int b = mask_button(k_masks_190[id]); - return b >= 0 && (g_bind_key[b] != k_def_key[b] || (bind_pad_slot(b) && g_bind_pad[b] != k_def_pad[b])); -} - static int act_default(int dev, int id) { int b = mask_button(k_masks_190[id]); if (b < 0) return ACT_NONE; @@ -470,6 +448,37 @@ int act_switch_button(int id) { return mask_button((k_masks ? k_masks : k_masks_190)[id]); } +// In play the game's A / B / X / Y / L / R / ZL / ZR / stick-press bits are built from the actions, never from the menu +// rows: a key given to "Menu: sort / sensor" must not press Attack, and rebinding Jump must not take Space away from the +// other actions that default to the same Switch button. A bit is set by the default binding of an action (still on its +// factory binding, so the game answers it from this bit) that reads that button. The menus keep using the menu rows. +#define ACT_RAW_SLOTS ((1u << BIND_A) | (1u << BIND_B) | (1u << BIND_X) | (1u << BIND_Y) | (1u << BIND_LSTICK) | \ + (1u << BIND_RSTICK) | (1u << BIND_L) | (1u << BIND_R) | (1u << BIND_ZL) | (1u << BIND_ZR)) +uint64_t act_raw_slots(void) { return ACT_RAW_SLOTS; } +// Only once the game has asked about an action (its hook is there); until then, and for game versions without the hook, +// the menu rows keep driving every button as before. +bool act_play_active(void) { return k_masks != NULL; } + +uint64_t act_play_keys(int (*held)(int scancode)) { + uint64_t out = 0; + for (int id = 0; id < ACT_COUNT; id++) { + int slot = act_switch_button(id), k = g_act_key[id]; + if (slot < 0 || !(ACT_RAW_SLOTS >> slot & 1) || (a_custom >> id & 1)) continue; + if (k > 0 && held(k)) out |= 1ull << slot; + } + return out; +} + +uint64_t act_play_pads(uint32_t host_buttons) { + uint64_t out = 0; + for (int id = 0; id < ACT_COUNT; id++) { + int slot = act_switch_button(id), k = g_act_pad[id]; + if (slot < 0 || !(ACT_RAW_SLOTS >> slot & 1) || (a_custom >> id & 1)) continue; + if (k >= 0 && k < PADB_HOST_COUNT && (host_buttons >> k & 1)) out |= 1ull << slot; + } + return out; +} + uint64_t act_scan_keys(uint64_t key_buttons, int (*held)(int scancode)) { (void)key_buttons; // kept for callers; actions read host inputs, never the live Switch layout uint64_t out = 0, custom = a_custom; diff --git a/runtime/hle/input.c b/runtime/hle/input.c index d570b9ff3..7521a37fb 100644 --- a/runtime/hle/input.c +++ b/runtime/hle/input.c @@ -35,6 +35,7 @@ enum { _Static_assert(BTN_DOWN == BIND_DOWN && BTN_ZL == BIND_ZL, "bindings follow the button bits"); static _Atomic uint64_t key_buttons, pad_buttons; +static _Atomic uint64_t key_play, pad_play; // the same in play: the action-driven bits replace the menu rows' (act_play_keys) // A contextual action consumes a held button until release, while observers // still read the raw snapshot to detect the next physical press. static _Atomic uint64_t consumed_buttons; @@ -157,6 +158,7 @@ static void recompute_keyboard(void) { for (int i = 0; i < BIND_PAD_COUNT; i++) if (game_key(g_bind_key[i])) b |= 1ull << i; key_buttons = b; + key_play = (b & ~act_raw_slots()) | act_play_keys(game_key); act_publish(act_scan_keys(b, game_key), ~0ull); // actions read their own host keys int tilt = game_key(g_bind_key[BIND_WALK]) ? 13107 : 32767; // walk: 40% (BOTW walks below about half) key_lx = (game_key(g_bind_key[BIND_LS_RIGHT]) - game_key(g_bind_key[BIND_LS_LEFT])) * tilt; @@ -185,6 +187,7 @@ static void dead_zone(_Atomic int32_t *x, _Atomic int32_t *y, int32_t rx, int32_ static void recompute_pad(void) { if (!win_focused && !host_test) { pad_buttons = 0; + pad_play = 0; host_buttons = 0; recompute_motion(); act_publish(~0ull, 0); @@ -224,6 +227,7 @@ static void recompute_pad(void) { photo_pad(host); // (hle/photo.c: the d-pad's filter, hour and picture) } pad_buttons = 0; + pad_play = 0; host_buttons = 0; // (the bindings see nothing either: the free camera has the controller) recompute_motion(); act_publish(~0ull, 0); @@ -239,6 +243,7 @@ static void recompute_pad(void) { for (int i = 0; i < BIND_PAD_COUNT; i++) if (g_bind_pad[i] >= 0 && g_bind_pad[i] < PADB_HOST_COUNT && (host >> g_bind_pad[i] & 1)) b |= 1ull << i; pad_buttons = b; + pad_play = (b & ~act_raw_slots()) | act_play_pads(host); act_publish(~0ull, act_scan_pad(b, host)); // actions read their own host buttons // Fly mode (test builds): the press of its controller button toggles it. Not while the menu or a rebind has the pad // (the held state is still tracked, so letting go of a button that was just bound does not toggle). @@ -1000,7 +1005,9 @@ void input_frame(uint64_t frame) { // Buttons held right now (keyboard, gamepad, test script), independent of whether the game polls (movies). uint64_t input_buttons_now(void) { bool muted = (!win_focused && !host_test) || menu_input_captured(); - uint64_t b = (muted ? 0 : key_buttons | pad_buttons | escape_buttons) | script_buttons; + bool play = !muted && !framepace_title_ui() && !framepace_menu_ui() && act_play_active(); + uint64_t user = play ? key_play | pad_play : key_buttons | pad_buttons; + uint64_t b = (muted ? 0 : user | escape_buttons) | script_buttons; control_input_apply(&b, NULL, NULL, NULL, NULL); return b; } @@ -1029,9 +1036,12 @@ static void fill_state(Cpu *c) { bool menu = (!win_focused && !host_test) || menu_input_captured(); // host controls belong to the focused game window // Customized actions use host bindings during play. Factory-default actions and all queries in menus, with // the window unfocused or the overlay up, use the Switch layer, so no binding can lock the player out. - act_poll(!menu && !framepace_title_ui() && !framepace_menu_ui()); + bool play = !menu && !framepace_title_ui() && !framepace_menu_ui(); + act_poll(play); uint64_t bow = pc_bow_sample(); - uint64_t b = menu ? script_buttons : key_buttons | pad_buttons | escape_buttons | bow | script_buttons; + // In play the game's buttons come from the actions, not from the menu rows (act_play_keys); menus read the rows + uint64_t user = play && act_play_active() ? key_play | pad_play : key_buttons | pad_buttons; + uint64_t b = menu ? script_buttons : user | escape_buttons | bow | script_buttons; if (!menu) b |= auto_continue_buttons(b); // (not while the overlay has the controls) b=pc_cursor_buttons(b); { // injected Plus: held for ~10 presented frames (the game polls several times per frame) diff --git a/runtime/input_bind.h b/runtime/input_bind.h index 45c7b6861..bc8f01f3d 100644 --- a/runtime/input_bind.h +++ b/runtime/input_bind.h @@ -68,7 +68,7 @@ bool bind_is_default(int dev); bool bind_is_default_slot(int dev, int slot); // "Click a binding, then press": begun from the UI; the next press (any thread's SDL event) is taken. Escape cancels, -// as does BIND_CAPTURE_MS without a press. On a conflict the two inputs swap. +// as does BIND_CAPTURE_MS without a press. Any input may share its key or button with another: nothing swaps. #define BIND_CAPTURE_MS 5000 void bind_capture_begin(int dev, int slot); void bind_capture_cancel(void); @@ -76,7 +76,7 @@ void bind_capture_cancel(void); bool bind_capture_active(int *dev, int *slot, int *ms_left); // Main thread, before anything else sees the event: true = consumed by a capture bool bind_capture_event(const SDL_Event *e); -// Last change for the UI: 0 none, 1 set, 2 swapped (with *other), 3 cancelled, 4 timed out, 5 reset; *serial bumps +// Last change for the UI: 0 none, 1 set, 2 (unused: nothing swaps any more), 3 cancelled, 4 timed out, 5 reset; *serial bumps int bind_last_result(int *dev, int *slot, int *other, int *serial); // savagewind.ini: bind_pad_ / bind_key_ (only the ones that differ from the defaults are written) @@ -92,8 +92,9 @@ int bind_pad_from_name(const char *name); // Switch button (a table in the game: several actions share a button). Every action owns an explicit host key and // controller binding, initially copied from that button's factory defaults for 1.9.0. An action differing on either // device reads both host bindings directly. A factory-default action leaves the game to answer from its Switch layer, -// preserving JumpButtonChange and raw Switch injection. Before act_schema = 2, legacy ini raw-button rebinds migrate -// for action/device pairs without an act_* line. Menus also use the Switch layer. input.c publishes host state. +// preserving JumpButtonChange and raw Switch injection; in play that layer's bits come from the default actions, not from +// the menu rows (act_play_keys). Before act_schema = 2, legacy ini raw-button rebinds migrate for action/device pairs +// without an act_* line. Menus use the Switch layer, driven by the menu rows. input.c publishes host state. #define ACT_COUNT 41 enum { ACT_FOLLOW = -1, ACT_NONE = -2 }; extern int16_t g_act_key[ACT_COUNT]; // SDL_Scancode / BIND_MOUSE + button, or ACT_NONE @@ -110,6 +111,14 @@ int act_switch_button(int id); // the Switch input (BIND_*) in th void act_masks(const uint32_t *table); // the game's table of one mask per action (its address, from the patch) void act_reset(void); // every action back to the default +// In play the game's A / B / X / Y / L / R / ZL / ZR / stick-press bits come from the actions (the default binding of every +// action still on its factory binding), never from the menu rows; the menus keep using the menu rows. act_play_active() +// is false until the game has asked about an action (and on game versions without the hook): then the rows drive everything. +bool act_play_active(void); +uint64_t act_raw_slots(void); // the BIND_* bits above (1 << slot) +uint64_t act_play_keys(int (*held)(int scancode)); // those bits, keyboard side +uint64_t act_play_pads(uint32_t host_buttons); // ... controller side + // Host state in, from runtime/hle/input.c. Main thread, on every key / button event: uint64_t act_scan_keys(uint64_t key_buttons, int (*held)(int scancode)); // actions the keyboard side holds uint64_t act_scan_pad(uint64_t pad_buttons, uint32_t host_buttons); // ... the controller side holds diff --git a/runtime/ui/controls_ui.mm b/runtime/ui/controls_ui.mm index b987df30e..e96b4ff7b 100644 --- a/runtime/ui/controls_ui.mm +++ b/runtime/ui/controls_ui.mm @@ -3,7 +3,7 @@ // controller button and a key of its own: two actions can share one, and an action keeps the button of its Switch // input until it is given a binding. Below it the inputs no action covers (sticks, camera, motion, menus), and, folded, // the Switch buttons the actions follow. Select a binding, then press the new button / key (Esc or 5 s without a -// press cancels; a Switch input's button already in use swaps over). Drawn in whichever ImGui context is current. +// press cancels; a button already in use is shared). Drawn in whichever ImGui context is current. #include #include @@ -163,7 +163,7 @@ static void switch_table(const char *id, const int *order, int rows, int fam, in ImGui::TextUnformatted(line); ImGui::PushTextWrapPos(0); ImGui::TextDisabled("%s", tr("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button " - "that's already in use swaps with the old one.")); + "that's already in use can be shared.")); ImGui::PopTextWrapPos(); int cd, cs, ms; @@ -177,19 +177,15 @@ static void switch_table(const char *id, const int *order, int rows, int fam, in if (serial != seen_serial) { seen_serial = serial; const char *now = rslot < 0 ? "" : slot_binding(rdev, rslot, fam); - char name[64] = "", other[64] = ""; + char name[64] = ""; if (rslot >= 0) slot_name(rslot, name, sizeof name); - if (rother >= 0) slot_name(rother, other, sizeof other); if (kind == 5) snprintf(msg, sizeof msg, "%s", tr(rdev == BIND_DEV_PAD ? "Controller bindings reset to the defaults." : "Keyboard bindings reset to the defaults.")); else if (kind == 1) snprintf(msg, sizeof msg, tr("%s is now %s."), name, now); - else if (kind == 2) - snprintf(msg, sizeof msg, tr("%s is now %s; %s moved to %s (swapped)."), name, now, other, - slot_binding(rdev, rother, fam)); else if (kind == 3) snprintf(msg, sizeof msg, tr("Cancelled: %s unchanged."), name); else if (kind == 4) snprintf(msg, sizeof msg, tr("Nothing pressed: %s unchanged."), name); - if (kind == 1 || kind == 2 || kind == 5) settings_save(); + if (kind == 1 || kind == 5) settings_save(); } if (msg[0]) ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", msg); diff --git a/runtime/ui/i18n/de.inc b/runtime/ui/i18n/de.inc index 8994da1bc..9cc1b095a 100644 --- a/runtime/ui/i18n/de.inc +++ b/runtime/ui/i18n/de.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "X / Y tauschen") T("Controller: %s (%s button names)", "Controller: %s (Knopfnamen: %s)") T("connected", "verbunden") T("No controller connected (%s button names shown)", "Kein Controller verbunden (Knopfnamen: %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Wähle eine Belegung und drücke dann den neuen Knopf oder die neue Taste. Esc (oder 5 Sekunden) bricht ab. Ein bereits belegter Knopf wird mit dem alten getauscht.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Wähle eine Belegung und drücke dann den neuen Knopf oder die neue Taste. Esc (oder 5 Sekunden) bricht ab. Ein bereits belegter Knopf kann mehrfach verwendet werden.") T("Controller bindings reset to the defaults.", "Controller-Belegung auf Standard zurückgesetzt.") T("Keyboard bindings reset to the defaults.", "Tastaturbelegung auf Standard zurückgesetzt.") T("%s is now %s.", "%s ist jetzt %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s ist jetzt %s; %s liegt jetzt auf %s (getauscht).") T("Cancelled: %s unchanged.", "Abgebrochen: %s unverändert.") T("Nothing pressed: %s unchanged.", "Nichts gedrückt: %s unverändert.") T("Controller", "") diff --git a/runtime/ui/i18n/es.inc b/runtime/ui/i18n/es.inc index 2b0c450a1..a76cdc014 100644 --- a/runtime/ui/i18n/es.inc +++ b/runtime/ui/i18n/es.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "Intercambiar X / Y") T("Controller: %s (%s button names)", "Mando: %s (nombres de botones de %s)") T("connected", "conectado") T("No controller connected (%s button names shown)", "Ningún mando conectado (se muestran los nombres de botones de %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Elige una asignación y pulsa el nuevo botón o tecla. Esc (o 5 segundos) cancela. Un botón que ya está en uso se intercambia con el anterior.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Elige una asignación y pulsa el nuevo botón o tecla. Esc (o 5 segundos) cancela. Un botón que ya está en uso se puede compartir.") T("Controller bindings reset to the defaults.", "Asignaciones del mando restablecidas a las predeterminadas.") T("Keyboard bindings reset to the defaults.", "Asignaciones del teclado restablecidas a las predeterminadas.") T("%s is now %s.", "%s ahora es %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s ahora es %s; %s pasó a %s (intercambiados).") T("Cancelled: %s unchanged.", "Cancelado: %s sin cambios.") T("Nothing pressed: %s unchanged.", "No se pulsó nada: %s sin cambios.") T("Controller", "Mando") diff --git a/runtime/ui/i18n/fr.inc b/runtime/ui/i18n/fr.inc index 42ffb610d..2a8377200 100644 --- a/runtime/ui/i18n/fr.inc +++ b/runtime/ui/i18n/fr.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "Inverser X / Y") T("Controller: %s (%s button names)", "Manette : %s (noms des boutons %s)") T("connected", "connectée") T("No controller connected (%s button names shown)", "Aucune manette connectée (noms des boutons %s affichés)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Choisissez une commande, puis appuyez sur le nouveau bouton ou la nouvelle touche. Échap (ou 5 secondes) annule. Un bouton déjà utilisé est échangé avec l'ancien.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Choisissez une commande, puis appuyez sur le nouveau bouton ou la nouvelle touche. Échap (ou 5 secondes) annule. Un bouton déjà utilisé peut être partagé.") T("Controller bindings reset to the defaults.", "Commandes de la manette réinitialisées.") T("Keyboard bindings reset to the defaults.", "Commandes du clavier réinitialisées.") T("%s is now %s.", "%s est maintenant %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s est maintenant %s ; %s passe à %s (échangés).") T("Cancelled: %s unchanged.", "Annulé : %s inchangé.") T("Nothing pressed: %s unchanged.", "Rien n'a été pressé : %s inchangé.") T("Controller", "Manette") diff --git a/runtime/ui/i18n/he.inc b/runtime/ui/i18n/he.inc index d2ca3064f..173438614 100644 --- a/runtime/ui/i18n/he.inc +++ b/runtime/ui/i18n/he.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "החלף X / Y") T("Controller: %s (%s button names)", "בקר: %s (שמות כפתורים של %s)") T("connected", "מחובר") T("No controller connected (%s button names shown)", "אין בקר מחובר (מוצגים שמות כפתורים של %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "בחרו הקצאה ולחצו על הכפתור או המקש החדש. לביטול: Esc (או המתנה של 5 שניות). אם הכפתור כבר בשימוש, הוא מתחלף עם הכפתור הקודם.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "בחרו הקצאה ולחצו על הכפתור או המקש החדש. לביטול: Esc (או המתנה של 5 שניות). אפשר להשתמש באותו כפתור ליותר מהקצאה אחת.") T("Controller bindings reset to the defaults.", "הקצאות הבקר אופסו לברירת המחדל.") T("Keyboard bindings reset to the defaults.", "הקצאות המקלדת אופסו לברירת המחדל.") T("%s is now %s.", "ההקצאה החדשה של %s: %s.") -T("%s is now %s; %s moved to %s (swapped).", "ההקצאה החדשה של %s: %s, ושל %s: %s (הוחלפו).") T("Cancelled: %s unchanged.", "בוטל: ההקצאה של %s לא השתנתה.") T("Nothing pressed: %s unchanged.", "לא נלחץ שום דבר: ההקצאה של %s לא השתנתה.") T("Controller", "בקר") diff --git a/runtime/ui/i18n/it.inc b/runtime/ui/i18n/it.inc index c1ee83002..34589da3d 100644 --- a/runtime/ui/i18n/it.inc +++ b/runtime/ui/i18n/it.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "Scambia X / Y") T("Controller: %s (%s button names)", "Controller: %s (nomi dei pulsanti %s)") T("connected", "connesso") T("No controller connected (%s button names shown)", "Nessun controller connesso (nomi dei pulsanti %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Scegli un'assegnazione, poi premi il nuovo pulsante o tasto. Esc (o 5 secondi) annulla. Un pulsante già in uso viene scambiato con quello vecchio.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Scegli un'assegnazione, poi premi il nuovo pulsante o tasto. Esc (o 5 secondi) annulla. Un pulsante già in uso può essere condiviso.") T("Controller bindings reset to the defaults.", "Assegnazioni del controller ripristinate.") T("Keyboard bindings reset to the defaults.", "Assegnazioni della tastiera ripristinate.") T("%s is now %s.", "%s ora è %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s ora è %s; %s passa a %s (scambiati).") T("Cancelled: %s unchanged.", "Annullato: %s invariato.") T("Nothing pressed: %s unchanged.", "Nessun input: %s invariato.") T("Controller", "") diff --git a/runtime/ui/i18n/ja.inc b/runtime/ui/i18n/ja.inc index 3d98d830a..df2ad913f 100644 --- a/runtime/ui/i18n/ja.inc +++ b/runtime/ui/i18n/ja.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "X / Y を入れ替え") T("Controller: %s (%s button names)", "コントローラー:%s (%sのボタン名)") T("connected", "接続済み") T("No controller connected (%s button names shown)", "コントローラー未接続 (%sのボタン名を表示)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "割り当てを選んでから、新しいボタンかキーを押してください。Esc(または5秒)でキャンセルします。すでに使われているボタンは元のボタンと入れ替わります。") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "割り当てを選んでから、新しいボタンかキーを押してください。Esc(または5秒)でキャンセルします。すでに使われているボタンも共有できます。") T("Controller bindings reset to the defaults.", "コントローラーの割り当てを初期設定に戻しました。") T("Keyboard bindings reset to the defaults.", "キーボードの割り当てを初期設定に戻しました。") T("%s is now %s.", "%sを%sにしました。") -T("%s is now %s; %s moved to %s (swapped).", "%sを%sにしました。%sは%sに移動しました(入れ替え)。") T("Cancelled: %s unchanged.", "キャンセル:%sは変更されていません。") T("Nothing pressed: %s unchanged.", "入力なし:%sは変更されていません。") T("Controller", "コントローラー") diff --git a/runtime/ui/i18n/ko.inc b/runtime/ui/i18n/ko.inc index 8555461df..b24f9cc8d 100644 --- a/runtime/ui/i18n/ko.inc +++ b/runtime/ui/i18n/ko.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "X / Y 바꾸기") T("Controller: %s (%s button names)", "컨트롤러: %s (%s 버튼 이름)") T("connected", "연결됨") T("No controller connected (%s button names shown)", "연결된 컨트롤러 없음 (%s 버튼 이름 표시)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "할당할 항목을 선택한 다음 새 버튼이나 키를 누르세요. Esc(또는 5초)로 취소합니다. 이미 사용 중인 버튼은 이전 버튼과 서로 바뀝니다.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "할당할 항목을 선택한 다음 새 버튼이나 키를 누르세요. Esc(또는 5초)로 취소합니다. 이미 사용 중인 버튼도 함께 사용할 수 있습니다.") T("Controller bindings reset to the defaults.", "컨트롤러 할당을 기본값으로 되돌렸습니다.") T("Keyboard bindings reset to the defaults.", "키보드 할당을 기본값으로 되돌렸습니다.") T("%s is now %s.", "%s: 이제 %s입니다.") -T("%s is now %s; %s moved to %s (swapped).", "%s: 이제 %s입니다. %s: %s(으)로 옮겼습니다(교체).") T("Cancelled: %s unchanged.", "취소됨: %s 변경 없음.") T("Nothing pressed: %s unchanged.", "입력 없음: %s 변경 없음.") T("Controller", "컨트롤러") diff --git a/runtime/ui/i18n/nl.inc b/runtime/ui/i18n/nl.inc index 043a8d8cc..f4dd861b6 100644 --- a/runtime/ui/i18n/nl.inc +++ b/runtime/ui/i18n/nl.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "X / Y wisselen") T("Controller: %s (%s button names)", "Controller: %s (knopnamen van %s)") T("connected", "verbonden") T("No controller connected (%s button names shown)", "Geen controller verbonden (knopnamen van %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Kies een toewijzing en druk dan op de nieuwe knop of toets. Esc (of 5 seconden) annuleert. Een knop die al in gebruik is, wisselt met de oude.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Kies een toewijzing en druk dan op de nieuwe knop of toets. Esc (of 5 seconden) annuleert. Een knop die al in gebruik is, kan gedeeld worden.") T("Controller bindings reset to the defaults.", "Controllertoewijzingen teruggezet naar de standaard.") T("Keyboard bindings reset to the defaults.", "Toetsenbordtoewijzingen teruggezet naar de standaard.") T("%s is now %s.", "%s is nu %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s is nu %s; %s is verplaatst naar %s (gewisseld).") T("Cancelled: %s unchanged.", "Geannuleerd: %s ongewijzigd.") T("Nothing pressed: %s unchanged.", "Niets ingedrukt: %s ongewijzigd.") T("Controller", "") diff --git a/runtime/ui/i18n/pt.inc b/runtime/ui/i18n/pt.inc index e989f7a11..43bf3d4a0 100644 --- a/runtime/ui/i18n/pt.inc +++ b/runtime/ui/i18n/pt.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "Trocar X / Y") T("Controller: %s (%s button names)", "Controle: %s (nomes dos botões de %s)") T("connected", "conectado") T("No controller connected (%s button names shown)", "Nenhum controle conectado (nomes dos botões de %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Escolha um comando e pressione o novo botão ou tecla. Esc (ou 5 segundos) cancela. Um botão que já está em uso troca de lugar com o anterior.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Escolha um comando e pressione o novo botão ou tecla. Esc (ou 5 segundos) cancela. Um botão que já está em uso pode ser compartilhado.") T("Controller bindings reset to the defaults.", "Comandos do controle restaurados para o padrão.") T("Keyboard bindings reset to the defaults.", "Comandos do teclado restaurados para o padrão.") T("%s is now %s.", "%s agora é %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s agora é %s; %s passou para %s (trocados).") T("Cancelled: %s unchanged.", "Cancelado: %s sem alterações.") T("Nothing pressed: %s unchanged.", "Nada pressionado: %s sem alterações.") T("Controller", "Controle") diff --git a/runtime/ui/i18n/ru.inc b/runtime/ui/i18n/ru.inc index 7aaaf822b..14382e6d5 100644 --- a/runtime/ui/i18n/ru.inc +++ b/runtime/ui/i18n/ru.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "Поменять X / Y") T("Controller: %s (%s button names)", "Контроллер: %s (названия кнопок %s)") T("connected", "подключён") T("No controller connected (%s button names shown)", "Контроллер не подключён (названия кнопок %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "Выберите назначение и нажмите новую кнопку или клавишу. Esc (или 5 секунд) — отмена. Уже занятая кнопка меняется местами со старой.") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "Выберите назначение и нажмите новую кнопку или клавишу. Esc (или 5 секунд) — отмена. Уже занятую кнопку можно использовать повторно.") T("Controller bindings reset to the defaults.", "Назначения контроллера сброшены.") T("Keyboard bindings reset to the defaults.", "Назначения клавиатуры сброшены.") T("%s is now %s.", "%s теперь %s.") -T("%s is now %s; %s moved to %s (swapped).", "%s теперь %s; %s перенесено на %s (обмен).") T("Cancelled: %s unchanged.", "Отменено: %s без изменений.") T("Nothing pressed: %s unchanged.", "Ничего не нажато: %s без изменений.") T("Controller", "Контроллер") diff --git a/runtime/ui/i18n/th.inc b/runtime/ui/i18n/th.inc index 60e38ac73..84d89e6e3 100644 --- a/runtime/ui/i18n/th.inc +++ b/runtime/ui/i18n/th.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "สลับ X / Y") T("Controller: %s (%s button names)", "คอนโทรลเลอร์: %s (ชื่อปุ่มแบบ %s)") T("connected", "เชื่อมต่อแล้ว") T("No controller connected (%s button names shown)", "ไม่มีคอนโทรลเลอร์เชื่อมต่อ (แสดงชื่อปุ่มแบบ %s)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "เลือกการกำหนดปุ่ม แล้วกดปุ่มหรือแป้นใหม่ Esc (หรือ 5 วินาที) ยกเลิก ปุ่มที่ใช้อยู่แล้วจะสลับกับปุ่มเดิม") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "เลือกการกำหนดปุ่ม แล้วกดปุ่มหรือแป้นใหม่ Esc (หรือ 5 วินาที) ยกเลิก ปุ่มที่ใช้อยู่แล้วก็ใช้ร่วมกันได้") T("Controller bindings reset to the defaults.", "รีเซ็ตการกำหนดปุ่มคอนโทรลเลอร์เป็นค่าเริ่มต้นแล้ว") T("Keyboard bindings reset to the defaults.", "รีเซ็ตการกำหนดแป้นคีย์บอร์ดเป็นค่าเริ่มต้นแล้ว") T("%s is now %s.", "ตอนนี้ %s คือ %s") -T("%s is now %s; %s moved to %s (swapped).", "ตอนนี้ %s คือ %s; %s ย้ายไปที่ %s (สลับกัน)") T("Cancelled: %s unchanged.", "ยกเลิกแล้ว: %s ไม่เปลี่ยน") T("Nothing pressed: %s unchanged.", "ไม่มีการกด: %s ไม่เปลี่ยน") T("Controller", "คอนโทรลเลอร์") diff --git a/runtime/ui/i18n/zh-Hans.inc b/runtime/ui/i18n/zh-Hans.inc index 6e1729e83..f59530ee3 100644 --- a/runtime/ui/i18n/zh-Hans.inc +++ b/runtime/ui/i18n/zh-Hans.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "交换 X / Y") T("Controller: %s (%s button names)", "手柄:%s (%s按键名称)") T("connected", "已连接") T("No controller connected (%s button names shown)", "未连接手柄 (显示%s按键名称)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "选择一项按键设置,然后按下新的手柄按键或键盘按键。按Esc(或等待5秒)取消。已被占用的按键会与原来的按键互换。") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "选择一项按键设置,然后按下新的手柄按键或键盘按键。按Esc(或等待5秒)取消。已被占用的按键也可以共用。") T("Controller bindings reset to the defaults.", "手柄按键设置已恢复默认。") T("Keyboard bindings reset to the defaults.", "键盘按键设置已恢复默认。") T("%s is now %s.", "%s现在是%s。") -T("%s is now %s; %s moved to %s (swapped).", "%s现在是%s;%s改为%s(已互换)。") T("Cancelled: %s unchanged.", "已取消:%s未更改。") T("Nothing pressed: %s unchanged.", "未按下任何键:%s未更改。") T("Controller", "手柄") diff --git a/runtime/ui/i18n/zh-Hant.inc b/runtime/ui/i18n/zh-Hant.inc index 9c669925e..7233b0d58 100644 --- a/runtime/ui/i18n/zh-Hant.inc +++ b/runtime/ui/i18n/zh-Hant.inc @@ -13,11 +13,10 @@ T("Swap X / Y", "交換 X / Y") T("Controller: %s (%s button names)", "控制器:%s (%s按鈕名稱)") T("connected", "已連接") T("No controller connected (%s button names shown)", "未連接控制器 (顯示%s按鈕名稱)") -T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use swaps with the old one.", "選擇一項按鈕設定,然後按下新的控制器按鈕或鍵盤按鍵。按Esc(或等待5秒)取消。已被使用的按鈕會與原本的按鈕互換。") +T("Select a binding, then press the new button or key. Esc (or 5 seconds) cancels. A button that's already in use can be shared.", "選擇一項按鈕設定,然後按下新的控制器按鈕或鍵盤按鍵。按Esc(或等待5秒)取消。已被使用的按鈕也可以共用。") T("Controller bindings reset to the defaults.", "控制器按鈕設定已恢復預設值。") T("Keyboard bindings reset to the defaults.", "鍵盤按鍵設定已恢復預設值。") T("%s is now %s.", "%s現在是%s。") -T("%s is now %s; %s moved to %s (swapped).", "%s現在是%s;%s改為%s(已互換)。") T("Cancelled: %s unchanged.", "已取消:%s未變更。") T("Nothing pressed: %s unchanged.", "未按下任何按鍵:%s未變更。") T("Controller", "控制器") diff --git a/tools/test_actions.c b/tools/test_actions.c index df10dc3b1..d88f57db3 100644 --- a/tools/test_actions.c +++ b/tools/test_actions.c @@ -360,8 +360,7 @@ static void schema_migration_is_one_time(void) { assert(g_act_key[19] == SDL_SCANCODE_H && g_act_pad[19] == SDL_GAMEPAD_BUTTON_SOUTH); host(0, 0, 0); act_poll(true); - // (X is rebound, so Jump answers from its own Space / north, not from the moved Switch button) - assert(hold(JUMP) == 0 && trig(JUMP) == 0 && hold(19) == 0); + assert(hold(JUMP) == -1 && trig(JUMP) == -1 && hold(19) == 0); char *again = save_bindings(); assert(!strcmp(saved, again)); free(saved); @@ -474,15 +473,15 @@ static void captures_allow_shared_action_inputs(void) { for (int id = 0; id < ACT_COUNT; id++) act_set(dev, id, raw[BIND_A]); for (int id = 0; id < ACT_COUNT; id++) assert(actions[id] == raw[BIND_A]); assert(raw[BIND_B] == host); - // Raw Switch slots still swap with each other without displacing any shared host actions. + // Menu rows share inputs like actions: nothing swaps and no shared host action is displaced. int old_a = raw[BIND_A]; bind_capture_begin(dev, BIND_A); assert(bind_capture_event(&e)); - assert(raw[BIND_A] == host && raw[BIND_B] == old_a); + assert(raw[BIND_A] == host && raw[BIND_B] == host); for (int slot = BIND_WALK; slot <= BIND_GYRO_CENTER; slot++) assert(raw[slot] == host); for (int id = 0; id < ACT_COUNT; id++) assert(actions[id] == old_a); int other; - assert(bind_last_result(NULL, NULL, &other, NULL) == 2 && other == BIND_B); + assert(bind_last_result(NULL, NULL, &other, NULL) == 1 && other == -1); } } reset_bindings(); @@ -508,41 +507,61 @@ static void names_and_groups(void) { for (unsigned i = 0; i < sizeof raw / sizeof *raw; i++) assert(strcmp(bind_input_name(slot), raw[i])); } -// #608: moving "Menu: sort / sensor" (the raw Y slot) used to take Attack along, because a factory-default action is -// answered by the game from the Switch layer. The action keeps its own key; the menus still see the moved button. -static void a_moved_menu_button_leaves_its_actions_alone(void) { - SDL_Event e = {0}; +// In play the raw A/B/X/Y bits come only from actions still at their factory binding, so a menu row never presses an +// action and a rebound action stops driving its old button, while the other actions on that button keep it. +static void play_bits_ignore_menu_rows(void) { reset_bindings(); - bind_settings_load("act_schema", "2"); - act_poll(true); - assert(hold(ATTACK) == -1); // all defaults: the game answers - bind_capture_begin(BIND_DEV_KEY, BIND_Y); - e.type = SDL_EVENT_KEY_DOWN; e.key.scancode = SDL_SCANCODE_LALT; - assert(bind_capture_event(&e) && g_bind_key[BIND_Y] == SDL_SCANCODE_LALT); - assert(g_act_key[ATTACK] == BIND_MOUSE + SDL_BUTTON_LEFT && act_is_default(ATTACK)); - act_poll(true); - assert(hold(ATTACK) == 0 && hold(JUMP) == -1); // Attack now answered from its own (unchanged) key; Jump reads X - key_down[SDL_SCANCODE_LALT] = 1; - host(0, 0, 0); - act_poll(true); - assert(hold(ATTACK) == 0 && trig(ATTACK) == 0); // Alt is the menu's sort button, not Attack - key_down[SDL_SCANCODE_LALT] = 0; - key_down[BIND_MOUSE + SDL_BUTTON_LEFT] = 1; - host(0, 0, 0); - act_poll(true); - assert(hold(ATTACK) == 1 && trig(ATTACK) == 1); - act_poll(false); - assert(hold(ATTACK) == -1); // menus: the Switch layer answers - key_down[BIND_MOUSE + SDL_BUTTON_LEFT] = 0; - host(0, 0, 0); - // the same through the controller side, and a reset puts the game back in charge - bind_capture_begin(BIND_DEV_PAD, BIND_Y); - e.type = SDL_EVENT_GAMEPAD_BUTTON_DOWN; e.gbutton.button = SDL_GAMEPAD_BUTTON_LEFT_SHOULDER; - assert(bind_capture_event(&e)); - bind_reset_slot(BIND_Y); - act_poll(true); - assert(hold(ATTACK) == -1); + act_masks(masks); + assert(act_play_active()); + int hy = g_bind_key[BIND_Y], hx = g_bind_key[BIND_X]; + key_down[hy] = 1; + assert(act_play_keys(held) >> BIND_Y & 1); // the factory key of Attack still gives raw Y + key_down[hy] = 0; + + // "Menu: sort" moved to another key: Attack keeps its own key and the new key presses nothing in play + g_bind_key[BIND_Y] = SDL_SCANCODE_Q; + key_down[SDL_SCANCODE_Q] = 1; + assert(!(act_play_keys(held) >> BIND_Y & 1)); + key_down[SDL_SCANCODE_Q] = 0; + key_down[hy] = 1; + assert(act_play_keys(held) >> BIND_Y & 1); + key_down[hy] = 0; reset_bindings(); + + // Jump -> G: G is no longer raw X, the other X actions keep the factory X key. The factory binding of an action + // comes from the 1.9.0 table, so take another action whose factory key is X and let the live table agree. + reset_bindings(); + int twin = -1; + for (int id = 0; id < ACT_COUNT && twin < 0; id++) + if (id != JUMP && g_act_key[id] == hx && act_is_default(id)) twin = id; + assert(twin >= 0); + uint32_t saved = masks[twin]; + masks[twin] = masks[JUMP]; + act_set(BIND_DEV_KEY, JUMP, SDL_SCANCODE_G); + key_down[SDL_SCANCODE_G] = 1; + assert(!(act_play_keys(held) >> BIND_X & 1)); + key_down[SDL_SCANCODE_G] = 0; + key_down[hx] = 1; + assert(act_play_keys(held) >> BIND_X & 1); + key_down[hx] = 0; + masks[twin] = saved; + reset_bindings(); + + // The pad side does the same + uint32_t pad_y = 1u << g_act_pad[ATTACK]; + assert(act_play_pads(pad_y) >> BIND_Y & 1); + g_bind_pad[BIND_Y] = SDL_GAMEPAD_BUTTON_START; + assert(act_play_pads(pad_y) >> BIND_Y & 1); + assert(!(act_play_pads(1u << SDL_GAMEPAD_BUTTON_START) >> BIND_Y & 1)); + reset_bindings(); + + // D-pad / Plus / Minus are not isolated: they stay on their rows + assert(!(act_raw_slots() >> BIND_UP & 1) && !(act_raw_slots() >> BIND_PLUS & 1)); + + // Before the game asked about any action nothing is isolated + act_masks(NULL); + assert(!act_play_active()); + act_masks(masks); } int main(void) { @@ -563,7 +582,7 @@ int main(void) { captures_allow_shared_action_inputs(); host_pad_slots(); names_and_groups(); - a_moved_menu_button_leaves_its_actions_alone(); + play_bits_ignore_menu_rows(); puts("action bindings: default fallthrough, custom host bindings, schema migration, held / pressed, menus, shared keys, pad capture, contexts, reset and ini passed"); return 0; } diff --git a/tools/test_bind_capture.c b/tools/test_bind_capture.c index f6e26a5a5..3b7579a39 100644 --- a/tools/test_bind_capture.c +++ b/tools/test_bind_capture.c @@ -55,7 +55,8 @@ int main(void) { e = (SDL_Event){0}; e.type = SDL_EVENT_GAMEPAD_BUTTON_UP; e.gbutton.button = SDL_GAMEPAD_BUTTON_EAST; release_to_game(e); waiting(); e.type = SDL_EVENT_GAMEPAD_BUTTON_DOWN; e.gbutton.button = SDL_GAMEPAD_BUTTON_SOUTH; - assert(bind_capture_event(&e)); ended(2); // B already uses the south button: swap + assert(bind_capture_event(&e)); ended(1); // B already uses the south button: shared, nothing swaps + assert(g_bind_pad[BIND_RIGHT] == SDL_GAMEPAD_BUTTON_SOUTH && g_bind_pad[BIND_B] == SDL_GAMEPAD_BUTTON_SOUTH); const int devices[] = {BIND_DEV_KEY, BIND_DEV_PAD}; for (unsigned i = 0; i < sizeof devices / sizeof *devices; i++) { @@ -85,7 +86,8 @@ int main(void) { e.gaxis.axis = SDL_GAMEPAD_AXIS_LEFT_TRIGGER; assert(bind_capture_event(&e)); assert(g_bind_pad[BIND_A] == PADB_LTRIGGER); - ended(2); // ZL already uses the left trigger + ended(1); // ZL already uses the left trigger: shared, nothing swaps + assert(g_bind_pad[BIND_ZL] == PADB_LTRIGGER); // Optional gyro bindings may overlap normal keys and each other without mutating existing bindings. bind_reset(BIND_DEV_KEY); int camera_up=g_bind_key[BIND_RS_UP]; diff --git a/tools/test_input_focus.c b/tools/test_input_focus.c index f9d218795..c3f4b7ccc 100644 --- a/tools/test_input_focus.c +++ b/tools/test_input_focus.c @@ -46,6 +46,10 @@ uint64_t act_scan_keys(uint64_t b, int (*held)(int)) { (void)b; (void)held; retu uint64_t act_scan_pad(uint64_t b, uint32_t host) { (void)b; (void)host; return 0; } void act_publish(uint64_t keys, uint64_t pads) { (void)keys; (void)pads; } void act_poll(bool live) { (void)live; } +bool act_play_active(void) { return false; } +uint64_t act_raw_slots(void) { return 0; } +uint64_t act_play_keys(int (*held)(int)) { (void)held; return 0; } +uint64_t act_play_pads(uint32_t host) { (void)host; return 0; } void motion_script(float p, float r, float ps, float ys) { (void)p; (void)r; (void)ps; (void)ys; unexpected_helper(); } // (the control endpoint, the virtual gyro and the DSU poll: off here) bool control_enabled(void) { return false; } diff --git a/tools/test_quick_drop_input.c b/tools/test_quick_drop_input.c index 7e1d49876..25b986df6 100644 --- a/tools/test_quick_drop_input.c +++ b/tools/test_quick_drop_input.c @@ -11,6 +11,10 @@ Settings g_settings; void act_poll(bool live) { (void)live; } +bool act_play_active(void) { return false; } +uint64_t act_raw_slots(void) { return 0; } +uint64_t act_play_keys(int (*held)(int)) { (void)held; return 0; } +uint64_t act_play_pads(uint32_t host) { (void)host; return 0; } uint64_t g_watch_lo, g_watch_hi; static uint64_t test_frame = 100, pointer_injection, control_injection; static bool game_menu = true; From 04aa6421d430613529b24d8ff2c1313ee6d6023c Mon Sep 17 00:00:00 2001 From: guill Date: Thu, 12 Nov 2026 17:55:01 -0500 Subject: [PATCH 03/18] Bug-fix PRs of 2026-11-12: water, vibration, folder picker, pipeline links, hybrid CPUs, refresh rate, haze, taller windows, horse keyboard - Water: a barrier after a new colour image's clear, before its uploads (PR #756, fixes #649). - Vibration: SDL_RumbleGamepad on a worker thread, so Bluetooth controllers no longer stall input (PR #757, fixes #730). - Launcher: folder picker errors are shown, and the game folder path can be typed (PR #758, fixes #724). - Vulkan: pipelines that can't be skipped are linked inline, and build jobs are drained during stalls (PR #651, fixes #591). - Windows: every logical processor is kept on hybrid CPUs, and critical threads get a higher priority (PR #650, fixes #639). - Window: the monitor's real refresh rate is detected, and higher-Hz display modes are picked (PR #641, fixes #623). - Video > Haze: 75 % or more (PR #601). - Taller windows: HUD, menus and map layouts on 16:10 and other tall views (PR #720). Conflict with vdyn_reset resolved. - Keyboard on horseback: forward is ignored while steering, and the horse camera site comes from game_sites.py (PR #343, fixes #290). Conflicts resolved; the input focus test keeps a single photo_pad stub. Not included: PR #642 (#608). In play it cleared A/B/X/Y unless an action held them, so scripted and console buttons stopped reaching the game (test-input-focus). Checked: game code regenerated (169 sites), game sites, layout codegen, i18n, launch flags, input focus, PC controls, GPU settings and vibration tests; a hidden run in the Lanayru rain; and a visible playtest from a 100% save. Co-authored-by: jfpaardoo Co-authored-by: devall96 Co-authored-by: sabeliam <50827860+sabeliam@users.noreply.github.com> Co-authored-by: rvsting <347107652+rvsting@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 ++- Makefile | 10 +- docs/SAVAGE-WIND.md | 2 +- runtime/framepace.h | 2 + runtime/game_sites.h | 3 +- runtime/hle/framepace.c | 25 +++- runtime/hle/input.c | 29 +++- runtime/hle/vibration.c | 84 ++++++++++- runtime/kernel.c | 2 + runtime/nvn/cmdbuf.c | 47 +++++- runtime/nvn/hud_scale.h | 78 ++++++++++ runtime/nvn/nvn.h | 8 +- runtime/nvn/objects.c | 2 + runtime/nvn/output_scale.c | 48 +++++- runtime/nvn/output_scale.h | 9 ++ runtime/nvn/renderer.m | 1 + runtime/nvn/vulkan/exec.c | 252 +++++++++++++++++++++++++------- runtime/nvn/vulkan/record.c | 1 + runtime/nvn/vulkan/textures.c | 1 + runtime/pc_cursor.c | 52 +++++-- runtime/pc_cursor_math.h | 15 +- runtime/platform.h | 1 + runtime/platform/linux.c | 2 + runtime/platform/macos.c | 2 + runtime/platform/windows.c | 30 +++- runtime/services/fs.c | 9 +- runtime/settings.c | 5 +- runtime/settings.h | 3 +- runtime/ui/i18n/de.inc | 5 + runtime/ui/i18n/es.inc | 5 + runtime/ui/i18n/fr.inc | 5 + runtime/ui/i18n/he.inc | 5 + runtime/ui/i18n/it.inc | 5 + runtime/ui/i18n/ja.inc | 5 + runtime/ui/i18n/ko.inc | 5 + runtime/ui/i18n/nl.inc | 5 + runtime/ui/i18n/pt.inc | 5 + runtime/ui/i18n/ru.inc | 5 + runtime/ui/i18n/th.inc | 5 + runtime/ui/i18n/zh-Hans.inc | 5 + runtime/ui/i18n/zh-Hant.inc | 5 + runtime/ui/launcher.mm | 35 ++++- runtime/ui/menu.mm | 2 +- runtime/ui_layout.c | 108 ++++++++++++++ runtime/ui_layout.h | 12 ++ runtime/vibration.h | 2 + runtime/window_size.c | 52 ++++--- tests/test_cursor_math.c | 37 +++-- tests/test_hud_scale.c | 72 +++++++++ tests/test_options_pointer.c | 31 +++- tests/test_output_scale.c | 57 ++++++-- tests/test_pc_controls.c | 1 + tests/test_ui_layout.c | 182 +++++++++++++++++++++++ tools/game_sites.py | 12 ++ tools/patches.py | 24 +++ tools/test_gyro_bindings.c | 1 + tools/test_input_focus.c | 45 +++++- tools/test_ui_layout_codegen.py | 48 ++++++ tools/test_vibration.c | 76 +++++++--- 59 files changed, 1412 insertions(+), 192 deletions(-) create mode 100644 runtime/ui_layout.c create mode 100644 runtime/ui_layout.h create mode 100644 tests/test_ui_layout.c create mode 100644 tools/test_ui_layout_codegen.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 692e25bb7..ef418ec8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,24 @@ What changed in each Savage Wind release. The `test` branch holds what the next ## Next (on the `test` branch) -Nothing yet. +### Fixes + +- **Water** drawn transparent where a new image was read before its clear finished + ([#649](https://github.com/Revivedx/SavageWindRecomp/issues/649), by jfpaardoo). +- **Bluetooth controllers** (DualSense on Windows): vibration no longer stalls input; it runs on a thread of its own + ([#730](https://github.com/Revivedx/SavageWindRecomp/issues/730), by jfpaardoo). +- **Game files folder** on Linux without a working file dialog: the error is shown and the path can be typed in + ([#724](https://github.com/Revivedx/SavageWindRecomp/issues/724), by jfpaardoo). +- **Stutter** while pipelines were linked ([#591](https://github.com/Revivedx/SavageWindRecomp/issues/591), by jfpaardoo). +- **Hybrid CPUs** (Intel 12th gen and later): every logical processor is kept, and the game's critical threads run at a + higher priority ([#639](https://github.com/Revivedx/SavageWindRecomp/issues/639), by jfpaardoo). +- **Refresh rate:** the monitor's real refresh rate is detected, and higher-Hz display modes are picked + ([#623](https://github.com/Revivedx/SavageWindRecomp/issues/623), by jfpaardoo). +- **Video > Haze** keeps to 75 % or more: lower values turned the picture teal (by devall96). +- **Taller windows** (16:10 and others) with Fill wide screens: the HUD, dialogue, pause menu, title screen and world map + keep their layout (by sabeliam). +- **Keyboard on horseback:** W with A or D steers without speeding forward + ([#290](https://github.com/Revivedx/SavageWindRecomp/issues/290), by rvsting). ## 0.5.3 (0.5.3-alpha.5) - 2026-11-12 diff --git a/Makefile b/Makefile index 1b519d127..147d50366 100644 --- a/Makefile +++ b/Makefile @@ -570,7 +570,7 @@ test-hud-button-layout: $(B)/test_hud_button_layout .PHONY: test-hud-button-layout -$(B)/test_options_pointer: tests/test_options_pointer.c runtime/pc_cursor.c runtime/pc_cursor.h runtime/pc_cursor_math.h +$(B)/test_options_pointer: tests/test_options_pointer.c runtime/pc_cursor.c runtime/pc_cursor.h runtime/pc_cursor_math.h runtime/nvn/hud_scale.h @mkdir -p $(dir $@) $(CC) -O2 -ffunction-sections -fdata-sections -DSDL_STATIC_LIB $(OSFLAGS) $(DEPINC) -Iruntime -isystem third_party -o $@ $< -fuse-ld=lld -Wl,--gc-sections $(if $(filter windows,$(PLATFORM)),-Wl$(comma)--exclude-all-symbols) -lSDL3 -lm @@ -926,3 +926,11 @@ test-quick-drop: test-quick-drop-native $(B)/test_quick_drop_input .PHONY: test-quick-drop test-quick-drop-native endif + +$(B)/test_ui_layout: tests/test_ui_layout.c runtime/ui_layout.c runtime/ui_layout.h runtime/nvn/cmdbuf.c runtime/nvn/nvn.h runtime/nvn/hud_scale.h + @mkdir -p $(dir $@) + $(CC) -O1 -ffunction-sections -fdata-sections $(DEPINC) -Iruntime -o $@ $< -fuse-ld=lld -Wl,--gc-sections -lpthread -lm + +test-ui-layout: $(B)/test_ui_layout + $(B)/test_ui_layout +.PHONY: test-ui-layout diff --git a/docs/SAVAGE-WIND.md b/docs/SAVAGE-WIND.md index 7a88785c3..1d1ece02e 100644 --- a/docs/SAVAGE-WIND.md +++ b/docs/SAVAGE-WIND.md @@ -785,7 +785,7 @@ Pendiente: - Bruma (Vídeo > Opciones avanzadas > Bruma, `haze` en el ini, `services/fs.c` `haze_patch`): la neblina del exterior de BOTW es su dispersión atmosférica, por clima en `Pack/TitleBG.pack` `WorldMgr/normal.bwinfo` (AAMP, 20 climas en el objeto raíz): `CalcMie` y `CalcRayleigh` (lo blanco y lo azul del aire: más bajos, más claro; a 0,6x el cielo se oscurece - y vira a turquesa) y `CalcSfParamNear` (0 o negativo: la bruma de cerca, la mínima en 0). El ajuste k (0-100 %) + y vira a turquesa) y `CalcSfParamNear` (0 o negativo: la bruma de cerca, la mínima en 0). El ajuste k (75-100 %) da 0,7 + 0,3 k veces los dos primeros y k veces el tercero, como un parche de lectura sobre los bytes del archivo (mismo tamaño; AAMP comparte los valores iguales entre parámetros: cada uno se cambia una vez). El juego lo lee al arrancar: el cambio vale desde el siguiente inicio. 100 % no toca nada. Los objetos Fog de los perfiles de diff --git a/runtime/framepace.h b/runtime/framepace.h index a6e527b44..92c2da791 100644 --- a/runtime/framepace.h +++ b/runtime/framepace.h @@ -12,6 +12,8 @@ uint64_t framepace_period_ns(void); bool framepace_on(void); // An event is running: a cutscene, a talk, an item fanfare (the game's event manager has an active event) bool framepace_in_event(void); +// A MessageDialog layout is still drawable, including its closing animation. +bool framepace_dialogue_ui(void); // The start screen or one of its menus is up (a 16:9 layout over pictures of its own) bool framepace_title_ui(void); // The "downloadable content" notice the game shows over the start screen (only B closes it) diff --git a/runtime/game_sites.h b/runtime/game_sites.h index 04bc80498..e513db64a 100644 --- a/runtime/game_sites.h +++ b/runtime/game_sites.h @@ -64,7 +64,8 @@ X(player_actor) \ X(quick_drop_trash_prohibited) \ X(quick_drop_actor_method) \ - X(actor_info) + X(actor_info) \ + X(horse_cam_lr) /* CameraHorse's return address after calling the camera stick input */ typedef struct { #define GAME_SITE_FIELD(n) uint64_t n; diff --git a/runtime/hle/framepace.c b/runtime/hle/framepace.c index 3b14695d5..c512ed4a5 100644 --- a/runtime/hle/framepace.c +++ b/runtime/hle/framepace.c @@ -50,6 +50,7 @@ #include "../rt.h" #include "../settings.h" #include "../framepace.h" +#include "../ui_layout.h" #include "../gamelib.h" #include "../window_size.h" @@ -144,12 +145,25 @@ static bool event_at_30(void) { return hold; } -// The game's UI screen `id` exists (the screen manager's array; ids as runtime/ui/game_options.mm uses them) -static bool screen_up(uint32_t id) { +// The game's UI screen `id` (the screen manager's array; ids as runtime/ui/game_options.mm uses them) +static uint64_t screen_at(uint32_t id) { uint64_t mgr = *(uint64_t *)(uintptr_t)g_site.screen_mgr; - if (!mgr || VF(uint32_t, mgr, 0x28) <= id) return false; + if (!mgr || VF(uint32_t, mgr, 0x28) <= id) return 0; uint64_t arr = VF(uint64_t, mgr, 0x30); - return arr && *(uint64_t *)(uintptr_t)(arr + 8 * id); + return arr ? VF(uint64_t, arr, 8 * id) : 0; +} + +static bool screen_up(uint32_t id) { return screen_at(id) != 0; } + +// MessageDialog can keep drawing its close animation after the event manager clears its active event. +// Use the native layout draw conditions, which include the closing state (+0xfe == 3). +static bool screen_draws(uint64_t screen) { + return screen && VF(uint8_t, screen, 0x100) && !VF(uint8_t, screen, 0x102) && + VF(uint8_t, screen, 0xfe) && VF(uint8_t, screen, 0xff) != 2; +} + +bool framepace_dialogue_ui(void) { + return screen_draws(screen_at(0x11)) || screen_draws(screen_at(0x4a)) || screen_draws(screen_at(0x4c)); } // (screens: 1 the start screen, 0x38 its load and confirmation menus; 0x38 can also be used over a paused game) @@ -165,6 +179,9 @@ bool framepace_loading_ui(void) { return screen_up(0x55); } // (pause state 2: the pause menu's pages and the map; 4 is the quick menus over the game) bool framepace_menu_ui(void) { return *(uint32_t *)(uintptr_t)PAUSE_STATE == 2; } bool framepace_map_ui(void) { + uint64_t screen = screen_at(0x2a); + int mode = ui_layout_map_mode(screen); + if (mode >= 0) return mode && screen_draws(screen); if (!framepace_menu_ui()) return false; uint64_t mgr = *(uint64_t *)(uintptr_t)g_site.screen_mgr; if (!mgr || VF(uint32_t, mgr, 0x28) <= 0x2f) return false; diff --git a/runtime/hle/input.c b/runtime/hle/input.c index de8a32291..d40c62abe 100644 --- a/runtime/hle/input.c +++ b/runtime/hle/input.c @@ -14,6 +14,7 @@ #include "../hle.h" #include "../platform.h" #include "../control.h" +#include "../game_sites.h" #include "../nvn/nvn.h" #include "../nvn/renderer.h" #include "../settings.h" @@ -361,9 +362,30 @@ void input_cam_frame(float ratio) { cam_mouse = true; } +// Riding is detected through the camera: CameraHorse reads the right stick through rt_cam_stick, from a call site +// (its lr) that no other camera uses. While it was read in the last quarter second Link is riding. +#define CAM_CALLER_NS 250000000ull +static _Atomic uint64_t horse_cam_ns; // CameraHorse's last read (game thread) + +static uint64_t horse_cam_lr(void) { + return g_site.horse_cam_lr; +} + +static void cam_caller(uint64_t lr, uint64_t now) { + uint64_t site = horse_cam_lr(); + if (site && lr == site) horse_cam_ns = now; +} + +static bool horse_riding(void) { + if (!horse_cam_lr()) return false; + uint64_t t = horse_cam_ns; + return t && plat_now_ns() - t < CAM_CALLER_NS; +} + // tools/patches.py _cam_stick: the camera's stick input (two floats at out) when the mouse gives it; 0: the stick's int rt_cam_stick(uint64_t out, uint64_t lr) { cam_read_ns = plat_now_ns(); + cam_caller(lr, cam_read_ns); bool mouse = cam_mouse && cam_native_on(); if (cam_log_left()) { const float *p = (const float *)(uintptr_t)out; // (CameraChase's main update: radius, pitch, yaw after it) @@ -722,6 +744,7 @@ void input_handle_event(const SDL_Event *e) { SDL_Gamepad *gone = pads[i]; pads[i] = pads[--npads]; if (gone == pad) pad_use(npads ? pads[0] : NULL); // (the one in use: another connected one, if any) + vibration_pad_closed(gone); SDL_CloseGamepad(gone); break; } @@ -1029,6 +1052,7 @@ static void fill_state(Cpu *c) { LOG("[input] watching controller object %llx\n", (unsigned long long)(c->x[1] - 8)); } bool menu = (!win_focused && !host_test) || menu_input_captured(); // host controls belong to the focused game window + // Customized actions use host bindings during play. Factory-default actions and all queries in menus, with // the window unfocused or the overlay up, use the Switch layer, so no binding can lock the player out. act_poll(!menu && !framepace_title_ui() && !framepace_menu_ui()); @@ -1046,7 +1070,10 @@ static void fill_state(Cpu *c) { bool sticks = !menu && !dualstick_on(); int32_t plx = sticks ? pad_lx : 0, ply = sticks ? pad_ly : 0, prx = sticks ? pad_rx : 0, pry = sticks ? pad_ry : 0; bool map_keys=pc_cursor_map_navigation(); - int32_t lx = clamp_axis((menu ? 0 : (map_keys?0:key_lx) + plx) + script_lx), ly = clamp_axis((menu ? 0 : (map_keys?0:key_ly) + ply) + script_ly); + int32_t klx = menu || map_keys ? 0 : key_lx, kly = menu || map_keys ? 0 : key_ly; + if (horse_riding() && klx && kly > 0) kly = 0; + int32_t lx = clamp_axis(klx + plx + script_lx); + int32_t ly = clamp_axis(kly + ply + script_ly); // Gate at each poll: an arrow or Enter held when a menu closes must never move the player or press A. // Event activity also includes cutscenes and fanfares, so it cannot identify dialogue choices safely. if (!menu && (framepace_title_ui() || framepace_menu_ui())) { diff --git a/runtime/hle/vibration.c b/runtime/hle/vibration.c index bbfc1a741..d1ef222bf 100644 --- a/runtime/hle/vibration.c +++ b/runtime/hle/vibration.c @@ -71,18 +71,76 @@ RT_ON_RESET(vibration_reset) { vibration_permit(true); } +static pthread_mutex_t rumble_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t rumble_cond = PTHREAD_COND_INITIALIZER; +static pthread_cond_t rumble_done_cond = PTHREAD_COND_INITIALIZER; +static SDL_Gamepad *req_pad, *inflight_pad, *failed_pad; +static uint16_t req_low, req_high; +static uint64_t req_seq, done_seq; +static bool worker_started; + +static void *rumble_worker(void *arg) { + (void)arg; + pthread_mutex_lock(&rumble_lock); + for (;;) { + while (done_seq == req_seq || !req_pad) { + if (!req_pad && done_seq < req_seq) { + done_seq = req_seq; + pthread_cond_broadcast(&rumble_done_cond); + } + pthread_cond_wait(&rumble_cond, &rumble_lock); + } + SDL_Gamepad *p = req_pad; + uint16_t lo = req_low, hi = req_high; + uint64_t seq = req_seq; + inflight_pad = p; + pthread_mutex_unlock(&rumble_lock); + + if (!SDL_RumbleGamepad(p, lo, hi, 100)) { + pthread_mutex_lock(&rumble_lock); + if (failed_pad != p) { + failed_pad = p; + LOG("[input] controller rumble unavailable: %s\n", SDL_GetError()); + } + pthread_mutex_unlock(&rumble_lock); + } + + pthread_mutex_lock(&rumble_lock); + inflight_pad = NULL; + if (seq > done_seq) done_seq = seq; + pthread_cond_broadcast(&rumble_done_cond); + } + return NULL; +} + +void vibration_pad_closed(SDL_Gamepad *gone) { + if (!gone) return; + pthread_mutex_lock(&rumble_lock); + if (req_pad == gone) { + req_pad = NULL; + done_seq = req_seq; + } + if (failed_pad == gone) failed_pad = NULL; + while (inflight_pad == gone) pthread_cond_wait(&rumble_done_cond, &rumble_lock); + pthread_mutex_unlock(&rumble_lock); +} + +void vibration_flush(void) { + pthread_mutex_lock(&rumble_lock); + while (done_seq < req_seq) pthread_cond_wait(&rumble_done_cond, &rumble_lock); + pthread_mutex_unlock(&rumble_lock); +} + void vibration_update(SDL_Gamepad *pad, bool focused) { static SDL_Gamepad *last_pad; static uint16_t last_low, last_high; static uint64_t last_ms; - static bool failed; if (!pad || !focused || !g_settings.rumble) vibration_clear(); bool changed = pad != last_pad; if (changed) { last_pad = pad; last_low = last_high = 0; last_ms = 0; - failed = false; } if (!pad) return; pthread_mutex_lock(&lock); @@ -93,10 +151,6 @@ void vibration_update(SDL_Gamepad *pad, bool focused) { uint64_t now = SDL_GetTicks(); // A short lease stops the motors if the event loop stalls; refresh unchanged effects while it is alive. if (!changed && low == last_low && high == last_high && (!(low || high) || now - last_ms < 50)) return; - if (!SDL_RumbleGamepad(pad, low, high, 100) && !failed) { - LOG("[input] controller rumble unavailable: %s\n", SDL_GetError()); - failed = true; - } static int nlog; // (SAVAGEWIND_MOTION_LOG: rumble going on and off, next to the sensor stream's health - a // controller might change its sensor reports once it rumbles, #220) if (!(low || high) != !(last_low || last_high) && ENV("SAVAGEWIND_MOTION_LOG") && nlog < 200) { @@ -106,4 +160,22 @@ void vibration_update(SDL_Gamepad *pad, bool focused) { last_low = low; last_high = high; last_ms = now; + // SDL_RumbleGamepad can block on Bluetooth HID writes (e.g. DualSense on Windows); run it off the event thread + // and coalesce in-flight updates to the latest request. + pthread_mutex_lock(&rumble_lock); + if (!worker_started) { + pthread_t t; + if (pthread_create(&t, NULL, rumble_worker, NULL) == 0) { + pthread_detach(t); + worker_started = true; + } + } + if (worker_started) { + req_pad = pad; + req_low = low; + req_high = high; + req_seq++; + pthread_cond_signal(&rumble_cond); + } + pthread_mutex_unlock(&rumble_lock); } diff --git a/runtime/kernel.c b/runtime/kernel.c index 194e3e1b6..128f1b466 100644 --- a/runtime/kernel.c +++ b/runtime/kernel.c @@ -7,6 +7,7 @@ #include "hle.h" #include "kernel.h" +#include "platform.h" #include "prof.h" // ------------------------------------------------------------------ results @@ -394,6 +395,7 @@ void rt_unwind_point(void) { static void *thread_main(void *arg) { KThread *t = arg; t_cur = t; + if (t->id == 1) plat_thread_elevate(); { char pn[32]; snprintf(pn, sizeof pn, "guest-%x", t->handle); diff --git a/runtime/nvn/cmdbuf.c b/runtime/nvn/cmdbuf.c index f74a411f9..dc0d8800b 100644 --- a/runtime/nvn/cmdbuf.c +++ b/runtime/nvn/cmdbuf.c @@ -52,6 +52,7 @@ static uint64_t g_free_bytes; static HBlock *g_grave; // dead blocks, oldest first, until three frames have passed static int g_ngrave, g_capgrave; static KMutex g_shadow_lock = KMUTEX_INIT; +static NvnCmdBuf *g_command_buffers; uint64_t renderer_present_count(void); static void push_block(HBlock **v, int *n, int *cap, HBlock b) { @@ -222,6 +223,11 @@ static HBlock shadow_block(Shadow *sh, int i, uint64_t want) { RT_ON_RESET(cmdbuf_shadow_reset) { // (reboot: every list is dead; command buffers were guest objects) kmutex_lock(&g_shadow_lock); + while (g_command_buffers) { + NvnCmdBuf *cb = g_command_buffers; + g_command_buffers = cb->registry_next; + free(cb); + } for (int i = 0; i < g_nlive; i++) { for (int k = 0; k < g_live[i]->nblocks; k++) free(g_live[i]->blocks[k].mem); free(g_live[i]->blocks); @@ -238,11 +244,19 @@ static NvnCmdBuf *cb_of(uint64_t guest) { return HOST(NvnCmdBuf, guest); } NVN(nvnCommandBufferInitialize) { NvnCmdBuf *cb = calloc(1, sizeof *cb); cb->guest = A(0); + kmutex_lock(&g_shadow_lock); + cb->registry_next = g_command_buffers; g_command_buffers = cb; + kmutex_unlock(&g_shadow_lock); SET_HOST(A(0), cb); RET(1); } NVN(nvnCommandBufferFinalize) { NvnCmdBuf *cb = cb_of(A(0)); + kmutex_lock(&g_shadow_lock); + NvnCmdBuf **link = &g_command_buffers; + while (*link && *link != cb) link = &(*link)->registry_next; + if (*link) *link = cb->registry_next; + kmutex_unlock(&g_shadow_lock); if (cb && cb->shadow) shadow_leave(cb->shadow, cb->gused); free(cb); SET_HOST(A(0), 0); @@ -306,11 +320,21 @@ NVN(nvnCommandBufferSetMemoryCallbackData) { cb_of(A(0))->callback_data = A(1); NVN(nvnCommandBufferGetMemoryCallbackData) { RET(cb_of(A(0))->callback_data); } NVN(nvnCommandBufferSetCommandMemoryCallbackEnabled) { (void)c; } +// Append a host record without touching guest command-memory accounting. +static CmdRec *host_rec(NvnCmdBuf *cb, uint32_t op, uint32_t extra) { + uint32_t size = (uint32_t)((sizeof(CmdRec) + extra + 7) & ~7u); + if (cb->used + size + JUMP_RESERVE > cb->size) { + uint64_t want = size + JUMP_RESERVE; + use_block(cb, cb->block + 1, want > cb->size * 2 ? want : cb->size * 2); + } + CmdRec *r = raw_rec(cb->mem + cb->used, op, size); + cb->used += size; + return r; +} // Reserve a record costing `cost` guest bytes. May call back into the guest for more memory, so callers snapshot // their arguments first. When the game adds no more (BOTW gives some command buffers a callback that is a bare // ret), recording goes on past the guest chunk: only the accounting is over, the records have room. static CmdRec *rec_cost(Cpu *c, NvnCmdBuf *cb, uint32_t op, uint32_t extra, uint32_t cost) { - uint32_t size = (uint32_t)((sizeof(CmdRec) + extra + 7) & ~7u); for (int tries = 0; !cb->shadow || cb->gused + cost > cb->gsize; tries++) { if (!cb->callback || tries == 2) { if (!cb->shadow) use_guest_chunk(cb, 0, 0); // never given memory: the records still need a home @@ -327,14 +351,21 @@ static CmdRec *rec_cost(Cpu *c, NvnCmdBuf *cb, uint32_t op, uint32_t extra, uint } cb->gused += cost; shadow_claim(cb->shadow, cb->gmem + cb->gused); - if (cb->used + size + JUMP_RESERVE > cb->size) { - uint64_t want = size + JUMP_RESERVE; - use_block(cb, cb->block + 1, want > cb->size * 2 ? want : cb->size * 2); - } - CmdRec *r = raw_rec(cb->mem + cb->used, op, size); - cb->used += size; - return r; + return host_rec(cb, op, extra); +} +bool nvn_ui_scope(uint64_t commands, unsigned kind) { + // The native screen can be called before its context is ready. Never dereference a candidate host pointer. + kmutex_lock(&g_shadow_lock); + NvnCmdBuf *cb = g_command_buffers; + while (cb && cb->guest != commands) cb = cb->registry_next; + kmutex_unlock(&g_shadow_lock); + if (!cb || !cb->recording || !cb->shadow || !cb->mem) return false; + // A host marker never allocates guest memory or invokes a guest out-of-memory callback. + CmdRec *r = host_rec(cb, CMD_UI_SCOPE, 0); + r->x[0] = kind; + return true; } + static CmdRec *rec(Cpu *c, NvnCmdBuf *cb, uint32_t op, uint32_t extra) { return rec_cost(c, cb, op, extra, cmd_cost(op, extra)); } diff --git a/runtime/nvn/hud_scale.h b/runtime/nvn/hud_scale.h index 9e20485c8..3fb427413 100644 --- a/runtime/nvn/hud_scale.h +++ b/runtime/nvn/hud_scale.h @@ -4,6 +4,7 @@ // screen a point p goes to anchor + (p - anchor) x s. #pragma once #include +#include // The anchor of a pane centred at c, on a screen from -edge to edge static inline float hud_anchor(float c, float edge) { return c < -edge / 3 ? -edge : c > edge / 3 ? edge : 0; } @@ -14,6 +15,41 @@ static inline bool hud_quick_keeps(float x, float y, float edge_x, float edge_y) return x > -0.72f * edge_x && x < 0.72f * edge_x && y > -0.4f * edge_y && y < 0.85f * edge_y; } +// PauseMenuInfo's header/footer occupy the outer bands; the inventory and description stay centered. +static inline float hud_pause_anchor(float y, float edge_y) { + if (edge_y <= 0 || !isfinite(y)) return 0; + return y > (250.0f / 360) * edge_y ? 1 : y < -(280.0f / 360) * edge_y ? -1 : 0; +} + +static inline float hud_pause_edge_dy(float y, float shape) { + return shape > 0 && shape < 1 ? hud_pause_anchor(y, shape) * (1 - shape) : 0; +} + +// ui2d's four window pieces share parent bounds and border margins. Recognize their relationships, +// so only a screen-wide pause frame expands; an item description or a modal window keeps its geometry. +// 1/-1: horizontal top/bottom strip; 2: vertical end, which must grow with both strips. +static inline int hud_pause_frame_part(const float *margin, float w, float h, const float *rc) { + float rw = rc[0], rh = rc[1], x = rc[2], y = rc[3]; + if (!isfinite(w) || !isfinite(h) || w <= 0 || h <= 0 || rw <= 0 || rh <= 0 || rw >= w || rh >= h) + return 0; + float tol = 1e-5f * fmaxf(w, h); + bool horizontal = fabsf(w - rw - rh) < tol, vertical = fabsf(h - rh - rw) < tol; + bool border = false; + for (int i = 0; i < 4; i++) border |= isfinite(margin[i]) && fabsf(margin[i] - (horizontal ? rh : rw)) < tol; + if (!border) return 0; + if (horizontal && fabsf(x + w / 2) < tol && fabsf(y - h / 2) < tol) return 1; + if (horizontal && fabsf(x + w / 2 - rh) < tol && fabsf(y + h / 2 - rh) < tol) return -1; + if (vertical && ((fabsf(x - w / 2 + rw) < tol && fabsf(y - h / 2) < tol) || + (fabsf(x + w / 2) < tol && fabsf(y - h / 2 + rw) < tol))) return 2; + return 0; +} + +// DoCommand's action cluster stays in the same native band as conversation prompts through event entry/exit. +static inline bool hud_context_keeps(bool enabled, float x, float y, float edge_x, float edge_y) { + return enabled && x > -0.2f * edge_x && x < 0.45f * edge_x && + y > -(300.0f / 360) * edge_y && y < -(160.0f / 360) * edge_y; +} + // A pane's view rows (3 x 4, row 2 its depth: projected x = m00 x / -z, y = m11 y / -z) static inline void hud_scale_view(float *v, float s, float m00, float m11, float ax, float ay) { for (int k = 0; k < 4; k++) { @@ -22,6 +58,19 @@ static inline void hud_scale_view(float *v, float s, float m00, float m11, float } } +// Combined HUD matrices need the flat console projection corrected once. ui2d glyphs (128 bytes, Y flipped) +// already use the taller projection, including nonuniform scale during a location title's appearance. +static inline bool hud_combined_shape(const float *m, unsigned long long size, float shape, float scale[2]) { + if (!(m[0] > 0 && m[5] != 0 && m[14] == -1 && m[15] > 0 && + !m[1] && !m[2] && !m[4] && !m[6] && !m[8] && !m[9] && !m[12] && !m[13] && (m[3] || m[7]))) + return false; + bool flat = fabsf(fabsf(m[5]) / m[0] - 16.0f / 9.0f) < 0.002f; + if (!flat && !(shape < 1 && size == 128 && m[5] < 0)) return false; + scale[0] = flat && shape > 1 ? 1 / shape : 1; + scale[1] = flat && shape < 1 ? shape : 1; + return true; +} + // A matrix with the view already in it (4 x 4 rows, row 3 its w: text, the clock) static inline void hud_scale_matrix(float *m, float s, float ax, float ay) { for (int k = 0; k < 4; k++) { @@ -55,6 +104,11 @@ static inline bool hud_quick_bar_px(double cx, double cy, double gw, double gh, return gw > 0 && gh > 0 && hud_quick_bar((float)(cx / gw * 2 - 1), (float)(1 - cy / gh * 2), 1, (float)shape); } +// A talk's layout can outlive its event while it fades. Incidental speech in play must not acquire this hold. +static inline bool hud_dialogue_holds(bool held, bool event, bool draws) { + return draws && (event || held); +} + // HUD at edges this frame: 0 off, 1 the HUD in play, 2 an event. Off in menus, the title and a load, like HUD size. In // an event (a talk, a chest's "You got" box) only the top part moves (hud_edge_moves): a box's top edge went to the // window's edge while the box and its text stayed in the 16:9 band (#599), and the area name, still fading out when an @@ -100,3 +154,27 @@ static inline double hud_edge_scissor_dy(double y_center, double gh, double shap double dir = my > 1.0f / 3.0f ? 1.0 : my < -1.0f / 3.0f ? -1.0 : 0.0; return dir * (gh / 2.0) * (1.0 - shape); } + +// Executing scopes may nest through cached command lists. Overflow preserves the outer owner. +typedef struct { unsigned kind, depth, overflow, parent[16]; } HudScope; +static inline void hud_scope_enter(HudScope *s, unsigned kind) { + if (s->depth == 16 || s->overflow) { s->overflow++; return; } + s->parent[s->depth++] = s->kind; s->kind = kind; +} +static inline void hud_scope_leave(HudScope *s) { + if (s->overflow) { s->overflow--; return; } + s->kind = s->depth ? s->parent[--s->depth] : 0; +} + + +// A window's local background capture samples the final image in console UV coordinates. +// Reshape that source rectangle and move its center with the window, leaving the local mask alone. +static inline bool hud_capture_crop(float *g, float shape, float dy) { + if (!(shape > 0 && shape < 1 && isfinite(g[22]) && isfinite(g[23]) && + isfinite(g[24]) && g[24] > 0 && isfinite(g[25]) && g[25] > 0 && isfinite(g[26]))) return false; + g[25] *= shape; + float shift = -dy / (2 * g[25]); + g[22] += sinf(g[26]) * shift; + g[23] += cosf(g[26]) * shift; + return true; +} diff --git a/runtime/nvn/nvn.h b/runtime/nvn/nvn.h index 84a7b1ddd..04c6915e3 100644 --- a/runtime/nvn/nvn.h +++ b/runtime/nvn/nvn.h @@ -106,7 +106,7 @@ typedef struct NvnSync { } NvnSync; // ---- command recording (runtime/nvn/cmdbuf.c: records in host memory, accounted to guest command memory) -typedef struct { +typedef struct NvnCmdBuf { uint64_t gmem, gsize, gused; // the guest command memory chunk, and the GPU bytes the game is told are used struct Shadow *shadow; // host storage for what is recorded while that chunk is current int block; // the shadow's block in use @@ -117,6 +117,7 @@ typedef struct { uint64_t callback, callback_data; bool recording; uint64_t guest; // the guest NVNcommandBuffer* + struct NvnCmdBuf *registry_next; } NvnCmdBuf; void cmdbuf_pool_gone(uint64_t lo, uint64_t hi); // a memory pool is finalized: lists recorded in it die @@ -144,7 +145,7 @@ enum { CMD_COPY_TEXTURE_TO_TEXTURE, CMD_DOWNSAMPLE, CMD_UPDATE_UNIFORM_BUFFER, CMD_FENCE_SYNC, CMD_WAIT_SYNC, CMD_BARRIER, CMD_SIGNAL_EVENT, CMD_WAIT_EVENT, CMD_REPORT_COUNTER, CMD_DISCARD_COLOR, CMD_DISCARD_DEPTH_STENCIL, CMD_SET_COPY_STRIDES, CMD_DRAW_TEXTURE, CMD_RESOLVE_DEPTH, CMD_BIND_TEXTURES_DEFERRED, - CMD_SET_DEPTH_CLAMP, CMD_RESET_COUNTER, CMD_SET_RASTERIZER_DISCARD, + CMD_SET_DEPTH_CLAMP, CMD_RESET_COUNTER, CMD_SET_RASTERIZER_DISCARD, CMD_UI_SCOPE, CMD_COUNT }; @@ -158,3 +159,6 @@ void backend_texture_destroyed(NvnTexture *tex); void backend_pool_written(uint64_t addr, uint64_t size); void backend_debug_copies_at(uint64_t addr); // (debugging) log the recent texture-to-buffer copies that wrote addr void nvn_debug_textures_at(uint64_t addr); // (objects.c, debugging) log the textures whose storage holds addr + +// A host-only balanced UI scope. kind0 pops the executing scope; no guest command-memory cost. +bool nvn_ui_scope(uint64_t commands, unsigned kind); diff --git a/runtime/nvn/objects.c b/runtime/nvn/objects.c index 8fe09649c..0578a4c32 100644 --- a/runtime/nvn/objects.c +++ b/runtime/nvn/objects.c @@ -5,6 +5,7 @@ #include "../framepace.h" #include "../game_sites.h" #include "../kernel.h" +#include "../platform.h" #include "../prof.h" #include "../perfmon.h" #include "nvn.h" @@ -224,6 +225,7 @@ static void qop_run(const QOp *o) { static void *queue_thread(void *arg) { (void)arg; prof_thread_name("nvn-queue"); + plat_thread_elevate(); kernel_sample_host_thread(); extern void control_prof_thread(const char *name); // runtime/control_prof.c (`threads`) control_prof_thread("render"); diff --git a/runtime/nvn/output_scale.c b/runtime/nvn/output_scale.c index 7b58caab6..f9b708c94 100644 --- a/runtime/nvn/output_scale.c +++ b/runtime/nvn/output_scale.c @@ -101,7 +101,7 @@ double upscale_factor(void) { // The window's shape over 16:9 while the game's views are widened to fill it, else 1; the field of view's factor in // use (rt_persp) -static volatile float g_view_shape = 1, g_fov = 1; +static volatile float g_view_shape = 1, g_fov = 1, g_map_extra_y; static uint32_t g_world_proj[4]; // tan(fovy / 2), aspect, near, far of the world camera's last matrix (rt_persp), float bits void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { @@ -111,10 +111,15 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { if (wide_test < 0) wide_test = getenv("SAVAGEWIND_WIDE_TEST") ? atof(getenv("SAVAGEWIND_WIDE_TEST")) : 0; double shape = wide_test > 0 ? wide_test : (dw / dh) / (16.0 / 9.0); // A wider window (21:9, 32:9) sees more to the sides, a taller one (16:10, 4:3: shape < 1) more above and below - // (#125); the HUD keeps its 16:9 layout in the middle either way. The start screen and its menus, a 16:9 layout - // over 16:9 pictures with no world to show more of, keep the 16:9 picture with bars, and so does the loading screen - // (#98: widened, its tip went to the window's edges and its logo stayed in the 16:9 middle). - bool reshape = reshape_allowed && fabs(shape - 1.0) > 0.005 && !framepace_title_ui() && !framepace_loading_ui(); + // (#125); the HUD keeps its 16:9 layout in the middle either way. Taller title screens fill the window too. + // Fit wider title/loading layouts to keep their artwork and text aligned (#98). Taller views keep their shape + // through the loading overlay so the world doesn't change aspect while fading out or back in. + bool title_fit = framepace_title_ui(); +#ifndef __APPLE__ + title_fit = title_fit && shape >= 1; // Vulkan cover-crops the artwork on taller title screens. +#endif + bool reshape = reshape_allowed && fabs(shape - 1.0) > 0.005 && !title_fit && + (shape < 1 || !framepace_loading_ui()); if (!reshape) shape = 1.0; // render height in units of the Switch's 1080 lines: the window's (Metal: divided by the upscaler's factor) #ifdef __APPLE__ @@ -149,9 +154,10 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { } o->vx = (dw - o->vw) / 2; o->vy = (dh - o->vh) / 2; o->crop[0] = o->crop[1] = 0, o->crop[2] = o->crop[3] = 1; - // The map's frame stays 16:9, but its scrollable background can draw beyond the frame on taller windows - // (#303). Present only that centered 16:9 region, without resizing its targets or changing cursor coordinates. - if (reshape && shape < 1 && framepace_map_ui()) { + bool tall_map = output_tall_map((float)shape); + g_map_extra_y = tall_map ? (float)(360 * (1 / shape - 1)) : 0; + // Renderers and aspect ratios without the taller map layout keep the centered 16:9 frame (#303). + if (reshape && shape < 1 && !tall_map && framepace_map_ui()) { double map_h = o->vh * shape; o->vy += (o->vh - map_h) / 2; o->vh = map_h; @@ -180,6 +186,32 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { } float output_view_shape(void) { return g_view_shape; } +float output_map_extra_y(void) { return g_map_extra_y; } + +float output_pause_extra_y(void) { +#ifdef __APPLE__ + return 0; +#else + static int off = -1; + if (off < 0) off = getenv("SAVAGEWIND_NO_HUD_FIX") != NULL; + float shape = g_view_shape; + return !off && g_settings.hud_edges && shape >= 0.75f && shape < 1 && + framepace_menu_ui() && !framepace_map_ui() ? 360 * (1 / shape - 1) : 0; +#endif +} + +float output_ui_extra_y(void) { return fmaxf(g_map_extra_y, output_pause_extra_y()); } + +// The taller world-map layout is implemented by Vulkan. Very narrow windows keep the console frame. +bool output_tall_map(float shape) { +#ifdef __APPLE__ + return false; +#else + static int off = -1; + if (off < 0) off = getenv("SAVAGEWIND_NO_HUD_FIX") != NULL; + return !off && shape >= 0.75f && shape < 1 && framepace_map_ui(); +#endif +} // The game's perspective views, as each one's matrix is built (tools/patches.py _persp_matrix: sead's // PerspectiveProjection; tan_fovy = tan(fovy / 2) at +0xac, aspect at +0xb0, as float bits; near at +0x98). Every 16:9 diff --git a/runtime/nvn/output_scale.h b/runtime/nvn/output_scale.h index 098981ba8..a6401d4e4 100644 --- a/runtime/nvn/output_scale.h +++ b/runtime/nvn/output_scale.h @@ -43,3 +43,12 @@ unsigned shadow_map_size(unsigned long long frame); typedef struct { float tan_half_fovy, aspect, near_, far_; unsigned long long serial; } WorldProj; void output_world_proj_set(float t, float a, float n, float f); bool output_world_proj(WorldProj *p); + +float output_view_shape(void); +bool output_tall_map(float shape); +// Extra layout space above and below the visible world map, in native 1280x720 units. +float output_map_extra_y(void); + +// Extra pause header/footer space, and the full visible pointer canvas (map or pause). +float output_pause_extra_y(void); +float output_ui_extra_y(void); diff --git a/runtime/nvn/renderer.m b/runtime/nvn/renderer.m index 0e99aa3db..cf820e126 100644 --- a/runtime/nvn/renderer.m +++ b/runtime/nvn/renderer.m @@ -2303,6 +2303,7 @@ static void exec_list(uint64_t handle, int depth) { void *x = r->extra; if (r->op < CMD_COUNT) op_counts[r->op]++; switch (r->op) { + case CMD_UI_SCOPE: break; case CMD_END: return; case CMD_JUMP: p = r->x[0]; continue; case CMD_CALL: { diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index 14ca2379c..3360e87e5 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -12,6 +12,7 @@ #include #include #include +#include "../../ui_layout.h" #ifdef _WIN32 #define NOUSER #include @@ -1103,6 +1104,20 @@ static void *worker(void *a) { return NULL; } +static bool job_run_one(void) { + pthread_mutex_lock(&jobs_lock); + Job *j = jobs_head; + if (j) { + jobs_head = j->next; + if (!jobs_head) jobs_tail = NULL; + } + pthread_mutex_unlock(&jobs_lock); + if (!j) return false; + j->fn(j->arg); + free(j); + return true; +} + // Shaders and pipelines compile where they are first needed, the draw waiting for them (a short stutter the first time // an effect appears), unless the "Asynchronous shaders" setting is on: then they compile on other threads and draws // that need them are skipped meanwhile. That loses what the game draws only once: the save file's screenshot (a @@ -1398,34 +1413,51 @@ void renderer_save_texture_tex(TexBackend *b, const char *path); static float pass_sx = 1, pass_sy = 1; static bool pass_out; // the pass draws into the game's final image (RS_OUT: the HUD and menus draw there) static bool hud_clip; // the draw in progress is a 16:9 layout's pane wholly off a 16:9 screen: not drawn (hud_patch) -// Gameplay > HUD size this frame, 1: none. Only the HUD in play: not in menus, the title, a load or an event (a talk's text). -#define HUD_QUICK_HOLD_NS 500000000ull // (a quick menu's bar fades out after the pause state ends) -static bool hud_quick; // a quick menu's bar may be on screen: it keeps the game's size (hud_quick_keeps) -static float hud_scale_now(void) { - extern bool framepace_menu_ui(void), framepace_title_ui(void), framepace_loading_ui(void), framepace_in_event(void); - extern bool framepace_quick_ui(void); - static uint64_t frame = ~0ull; - static float s = 1; +// Snapshot shared state once per presented frame. Ownership is recorded alongside the actual UI draw. +extern bool framepace_quick_ui(void); +static HudScope hud_scope; +static bool hud_event_dialogue; +static uint64_t hud_frame = UINT64_MAX, hud_quick_ns; +static bool hud_event, hud_menu, hud_title, hud_loading; +static bool hud_quick; +#define HUD_QUICK_HOLD_NS 500000000ull +static void hud_frame_update(void) { uint64_t now = renderer_present_count(); - if (now != frame) { - frame = now; - // (not the quick menus, pause state 4: the game keeps the HUD up around them) - static uint64_t quick_ns; - uint64_t ns = plat_now_ns(); - if (hud_quick_tracked(g_settings.hud_size, g_settings.hud_edges) && framepace_quick_ui()) quick_ns = ns; - hud_quick = quick_ns && ns - quick_ns < HUD_QUICK_HOLD_NS; - s = g_settings.hud_size == 100 || framepace_menu_ui() || framepace_title_ui() || framepace_loading_ui() || - framepace_in_event() ? 1 : (float)g_settings.hud_size / 100; - } - return s; + if (now == hud_frame) return; + hud_frame = now; + hud_event = framepace_in_event(); + hud_event_dialogue = hud_dialogue_holds(hud_event_dialogue, hud_event, framepace_dialogue_ui()); + hud_menu = framepace_menu_ui(); hud_title = framepace_title_ui(); hud_loading = framepace_loading_ui(); + uint64_t ns = plat_now_ns(); + if (hud_quick_tracked(g_settings.hud_size, g_settings.hud_edges) && framepace_quick_ui()) hud_quick_ns = ns; + hud_quick = hud_quick_ns && ns - hud_quick_ns < HUD_QUICK_HOLD_NS; +} +static bool hud_owned(void) { + return hud_scope.kind == UI_LAYOUT_HUD || hud_scope.kind == UI_LAYOUT_CONTEXT; } -// Video > HUD at edges this frame, on a window of this shape (hud_edge_mode). Also brings hud_quick up to this frame. -// Video > HUD at edges this frame, on a window of this shape (hud_edge_mode). Also brings hud_quick up to this frame. +static bool hud_native_layout(void) { + return hud_scope.kind == UI_LAYOUT_DIALOGUE || hud_scope.kind == UI_LAYOUT_MENU || hud_scope.kind == UI_LAYOUT_TALK; +} +static float hud_scale_now(void) { + hud_frame_update(); + if (hud_native_layout()) return 1; + return hud_owned() || !(hud_event || hud_event_dialogue || hud_menu || hud_title || hud_loading) ? + (float)g_settings.hud_size / 100 : 1; +} +// HUD edge placement follows the recorded layout owner. static int hud_edges_now(float shape) { - extern bool framepace_menu_ui(void), framepace_title_ui(void), framepace_loading_ui(void), framepace_in_event(void); - hud_scale_now(); - return hud_edge_mode(g_settings.hud_edges, shape, framepace_menu_ui(), framepace_title_ui(), framepace_loading_ui(), - framepace_in_event()); + hud_frame_update(); + if (hud_native_layout()) return 0; + return hud_edge_mode(g_settings.hud_edges, shape, !hud_owned() && hud_menu, !hud_owned() && hud_title, + !hud_owned() && hud_loading, !hud_owned() && (hud_event || hud_event_dialogue)); +} +// Dock a conversation as one layout, including choices and its close animation. +static float hud_layout_dy(float shape) { + if (!g_settings.hud_edges || shape >= 1) return 0; + return hud_scope.kind == UI_LAYOUT_TALK ? shape - 1 : 0; +} +static bool hud_context_native(float shape, float x, float y, float ex, float ey) { + return hud_scope.kind != UI_LAYOUT_CONTEXT && hud_context_keeps(g_settings.hud_edges && shape < 1, x, y, ex, ey); } // HUD at edges leaves a shop's panel where it is: its list, the item's panel and their frames are one 16:9 layout that @@ -1466,6 +1498,7 @@ static TexBackend *post_image(int i, uint32_t w, uint32_t h, VkFormat f); static TexBackend *map_background; static NvnTexture *map_background_target; static uint64_t map_background_frame = UINT64_MAX, map_background_main_frame = UINT64_MAX; +static uint64_t map_chrome_frame = UINT64_MAX; static void map_background_before_cursor(void); static VkImageView post_view(TexBackend *d); @@ -2416,11 +2449,15 @@ static VkRect2D scissor_rect(void) { if (y > 0 || y + sh < gh - 0.5) { double c = gh / 2, y0 = c + (y - c) * shape, y1 = c + (y + sh - c) * shape; y = (int)floor(y0); sh = (int)ceil(y1) - y; + if (output_pause_extra_y() > 0) + y -= (int)round(hud_pause_edge_dy((float)(1 - (y0 + y1) / gh), shape) * gh / 2); + y -= (int)round(hud_layout_dy(shape) * gh / 2); int edge_mode = hud_edges_now(shape); if (edge_mode) { double sdy = hud_edge_scissor_dy((y0 + y1) / 2.0, gh, shape); double gw = pass_sx > 0 ? w / pass_sx : w; // (a quick menu's bar, an event: as for the panes) - if (sdy != 0 && hud_edge_moves(edge_mode, (float)(1 - (y0 + y1) / gh), (float)shape) && + if (!hud_context_native(shape, (float)((x + sw / 2.0) / gw * 2 - 1), + (float)(1 - (y0 + y1) / gh), 1, shape) && sdy != 0 && hud_edge_moves(edge_mode, (float)(1 - (y0 + y1) / gh), (float)shape) && !(hud_quick && hud_quick_bar_px(x + sw / 2.0, (y0 + y1) / 2.0, gw, gh, shape))) y += (int)round(sdy); } @@ -2430,7 +2467,8 @@ static VkRect2D scissor_rect(void) { if (hud_s != 1) { // (the minimap's mask goes with the minimap: a scissor over about the whole image is left alone) double gw = w / pass_sx, gh = h / pass_sy; float mx = (float)((x + sw / 2.0) / gw * 2 - 1), my = (float)((y + sh / 2.0) / gh * 2 - 1); - if (sw < gw * 0.9 && sh < gh * 0.9 && !(hud_quick && fabsf(mx) < 0.72f && fabsf(my) < 0.6f)) { + if (!hud_context_native(shape, mx, -my, 1 / fmaxf(shape, 1), fminf(shape, 1)) && + sw < gw * 0.9 && sh < gh * 0.9 && !(hud_quick && fabsf(mx) < 0.72f && fabsf(my) < 0.6f)) { double px = x, py = y, pw = sw, ph = sh; hud_scale_span(&px, &pw, gw / 2, gw / 2 / fmax(shape, 1), hud_s); hud_scale_span(&py, &ph, gh / 2, gh / 2 * fmin(shape, 1), hud_s); @@ -4680,20 +4718,67 @@ static bool hud_frame_end(const float *g, const float *mv, const float *rc, floa return end; } +// AppMap draws its terrain into a fixed 1500x720 layout capture (at 1.5x). Let the +// same texture contain more rows of terrain, then undo that scale on the display quad. +static bool map_capture_patch(const float *g, uint64_t size, float shape, VkDescriptorBufferInfo *out) { + const NvnTexture *rt = st.rt.color[0]; + if (rt->width != 2250 || rt->height != 1080 || rt->format != 0x3d || + fabsf(g[0] - 2.0f / 1500) > 1e-6f || fabsf(g[5] - 2.0f / 720) > 1e-6f || g[15] != 1) + return false; + static float buf[0x10000 / 4]; + uint64_t n = size > sizeof buf ? sizeof buf : size; + memcpy(buf, g, n); + for (int k = 4; k < 8; k++) buf[k] *= shape; + *out = ubo_span(vk_transient_copy(buf, n, 256), n); + return true; +} + static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) { static int off = -1; if (off < 0) off = getenv("SAVAGEWIND_NO_HUD_FIX") != NULL; extern float output_view_shape(void); float shape = off ? 1 : output_view_shape(); if (size < 64 || !st.rt.ncolor || !st.rt.color[0]) return false; + const float *g = (const float *)(uintptr_t)addr; + bool map_layout = shape >= 0.75f && shape < 1; + bool tall_map = map_layout && (hud_scope.kind == UI_LAYOUT_MENU || + (hud_scope.kind == UI_LAYOUT_NONE && output_tall_map(shape))); + // The terrain capture is prepared before AppMap switches presentation. Its fixed target + // must already contain the taller view on the first visible map frame. + if (map_layout && map_capture_patch(g, size, shape, out)) return true; TexBackend *tb = (TexBackend *)st.rt.color[0]->backend; + // MessageDialog captures the background before drawing each window. Its crop uses a separate + // source rectangle; translating the pane alone makes the captured location title/choice text repeat. + if ((!tb || tb->rs_group != RS_OUT) && hud_scope.kind == UI_LAYOUT_TALK && + g_settings.hud_edges && shape > 0 && shape < 1 && size >= 27 * 4 && + g_cur_fs_hash == UINT64_C(0x90b79e85a3d120e3) && st.program && + hmix(1469598103934665603ull, (const void *)(uintptr_t)(st.program->stages[0].code_addr + 0x30), 0x200) == + UINT64_C(0x33067840cc99b18a)) { + ShaderTexture texture = {.handle_offset = 0x20}; + NvnTexture *src = shader_texture_object(1, &texture); + TexBackend *source = src ? (TexBackend *)src->backend : NULL; + if (source && source->rs_group == RS_OUT) { + static float crop[0x10000 / 4]; + uint64_t n = size > sizeof crop ? sizeof crop : size; + memcpy(crop, g, n); + if (hud_capture_crop(crop, shape, hud_layout_dy(shape))) { + *out = ubo_span(vk_transient_copy(crop, n, 256), n); + return true; + } + } + } if (!tb || tb->rs_group != RS_OUT) return false; float hud_s = hud_scale_now(); if (shape == 1 && hud_s == 1) return false; int edge_mode = hud_edges_now(shape); bool hud_edge_active = edge_mode != 0; + bool pause_edges = output_pause_extra_y() > 0; float edge_x = 1 / fmaxf(shape, 1), edge_y = fminf(shape, 1); // (where the 16:9 HUD ends on this window) - const float *g = (const float *)(uintptr_t)addr; + // AppHome's first map-frame fog strip follows the world labels and marker panes. + if (tall_map && g_cur_fs_hash == UINT64_C(0x3911f651724ed296) && + size >= 28 * 4 && g[14] == -1 && g[15] == 0 && fabsf(g[23]) == 304) + map_chrome_frame = renderer_present_count(); + bool map_chrome = tall_map && map_chrome_frame == renderer_present_count(); // ui2d text combines the projection and each label's position into this smaller, Y-flipped matrix. // A cached 16:9 projection can survive a live resize; scale the whole X row so glyph widths and // positions follow the widened HUD together. @@ -4704,25 +4789,30 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) memcpy(text_matrix, g, sizeof text_matrix); for (int k = 0; k < 4; k++) text_matrix[k] /= shape; float tx = text_matrix[3] / text_matrix[15], ty = text_matrix[7] / text_matrix[15]; - if (hud_s != 1 && !(hud_quick && hud_quick_keeps(tx, ty, edge_x, edge_y))) + if (hud_s != 1 && !hud_context_native(shape, tx, ty, edge_x, edge_y) && + !(hud_quick && hud_quick_keeps(tx, ty, edge_x, edge_y))) hud_scale_matrix(text_matrix, hud_s, hud_anchor(tx, edge_x), hud_anchor(ty, edge_y)); *out = ubo_span(vk_transient_copy(text_matrix, sizeof text_matrix, 256), sizeof text_matrix); return true; } - // A layer whose matrix comes with its view already in it (projection x view, a translation in column 3; the HUD's - // clock and some texts): 16:9 (|m11| / m00), it gets its first row / shape (a taller window: its second x shape), - // so it stays in the 16:9 layout with the rest of the HUD instead of moving outwards with the wider view. - if (g[0] > 0 && g[5] != 0 && g[14] == -1 && !g[1] && !g[2] && !g[4] && !g[6] && !g[8] && !g[9] && !g[12] && !g[13] && - (g[3] || g[7]) && g[15] > 0 && fabsf(fabsf(g[5]) / g[0] - 16.0f / 9.0f) < 0.002f) { + // Combined projection/view matrices also include ui2d glyphs that already use the taller view. + // Keep their projection and apply the same HUD placement as their captured shadow or button plate. + float combined_scale[2]; + if (hud_combined_shape(g, size, shape, combined_scale)) { static float buf[0x10000 / 4]; uint64_t n = size > sizeof buf ? sizeof buf : size; memcpy(buf, g, n); - if (shape > 1) buf[0] /= shape, buf[3] /= shape; - else buf[5] *= shape, buf[7] *= shape; + buf[0] *= combined_scale[0], buf[3] *= combined_scale[0]; + buf[5] *= combined_scale[1], buf[7] *= combined_scale[1]; float tx = buf[3] / buf[15], ty = buf[7] / buf[15]; - if (hud_s != 1 && !(hud_quick && hud_quick_keeps(tx, ty, edge_x, edge_y))) + if (hud_s != 1 && !hud_context_native(shape, tx, ty, edge_x, edge_y) && + !(hud_quick && hud_quick_keeps(tx, ty, edge_x, edge_y))) hud_scale_matrix(buf, hud_s, hud_anchor(tx, edge_x), hud_anchor(ty, edge_y)); - if (hud_edge_active && hud_edge_moves(edge_mode, ty, edge_y) && + if (pause_edges) hud_edge_matrix(buf, hud_pause_edge_dy(ty, shape)); + hud_edge_matrix(buf, hud_layout_dy(shape)); + if (map_chrome && fabsf(ty) > shape * (200.0f / 360)) + hud_edge_matrix(buf, copysignf(1 - shape, ty)); + if (hud_edge_active && !hud_context_native(shape, tx, ty, edge_x, edge_y) && hud_edge_moves(edge_mode, ty, edge_y) && !(hud_quick && hud_quick_bar(tx, ty, edge_x, edge_y))) { float ay = hud_anchor(ty, edge_y); float dy = hud_edge_dy(ay, edge_y, shape); @@ -4735,14 +4825,16 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) // place in the stamp atlas), then a 2D transform straight to clip space, the sprite's place on the 16:9 screen (rows // x: scale 0 0 offset, y: 0 scale 0 offset, 0 0 0 -1). Unchanged they spread over the whole wider window while the // map and its icons keep the 16:9 layout, so the stamps slid ~shape x faster than the map when it scrolled. On a - // wider window they narrow like the rest; taller map views are cropped to 16:9 at presentation (output_scale.c). + // wider window they narrow like the rest. Taller windows compress their Y scale and translation together, + // matching the map's projection in both the full-height layout and the centered 16:9 fallback. // (The same shader's whole-screen quads, scale 2, are left as they are.) - if (shape > 1 && size >= 64 && framepace_map_ui() && g[4] > 0 && g[4] < 1 && !g[5] && !g[6] && !g[8] && g[9] > 0 && + if (shape != 1 && size >= 64 && framepace_map_ui() && g[4] > 0 && g[4] < 1 && !g[5] && !g[6] && !g[8] && g[9] > 0 && g[9] < 1 && !g[10] && !g[12] && !g[13] && !g[14] && g[15] == -1) { static float buf[0x10000 / 4]; uint64_t n = size > sizeof buf ? sizeof buf : size; memcpy(buf, g, n); - buf[4] /= shape, buf[7] /= shape; + if (shape > 1) buf[4] /= shape, buf[7] /= shape; + else buf[9] *= shape, buf[11] *= shape; *out = ubo_span(vk_transient_copy(buf, n, 256), n); return true; } @@ -4755,6 +4847,22 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) if (!is_flat && !is_wide) return false; float m00 = is_flat && !tall ? g[0] / shape : g[0]; // the widened matrix's float m11 = is_flat && tall ? g[5] * shape : g[5]; + if (tall_map && g_cur_fs_hash == UINT64_C(0xc94630386244616e)) { + m11 /= shape; // AppMap's terrain capture display quad + map_chrome_frame = UINT64_MAX; + } + // The frame's refraction and the map shadow both end at the inner edges of the bezel. + if (tall_map && (g_cur_fs_hash == UINT64_C(0xe91b1fb6e1eb920b) || + (g_cur_fs_hash == UINT64_C(0xd4fa32dabc35066c) && size >= 114 * 4 && + !g[19] && !g[23] && g[108] == 1500 && g[109] == 608 && + fabsf(g[112] - 1.0f / 352) < 1e-6f && fabsf(g[113] - 1.0f / 162) < 1e-6f))) + m11 *= (720 / shape - 112) / 608; + + // BootUp's centered artwork covers a taller title view at uniform scale. Logos and menu panes keep their size. + if (tall && framepace_title_ui() && g_cur_fs_hash == UINT64_C(0xd4fa32dabc35066c) && + size >= 34 * 16 && !g[19] && !g[23] && + g[132] == 1280 && g[133] == 720 && g[134] == -640 && g[135] == 360) + m00 /= shape, m11 /= shape; // a 40-degree HUD layer's pane over the whole 16:9 width (a taller window: height) -> the 16:9 matrix float m11_flat = tall ? m11 / shape : m11, edge = tall ? shape : 1 / shape; if (size >= 34 * 16 && fabsf(m11_flat - 2.74748f) < 0.001f) { @@ -4786,13 +4894,31 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) if (tall) m11 /= shape; else m00 *= shape; } - if (lo < 1e8f && (hi <= -edge || lo >= edge)) hud_clip = true; // (wholly off a 16:9 screen) + float clip_edge = tall_map ? 1 : edge; + if (lo < 1e8f && (hi <= -clip_edge || lo >= clip_edge)) hud_clip = true; // (wholly off the view) + } + } + // Pause chrome moves to the taller view's edges. Its window ends grow between the relocated strips. + float pause_dy = 0, pause_stretch = 1, pause_center = 0; + if (pause_edges && size >= 34 * 16 && fabsf(m11 / shape - 2.74748f) < 0.001f) { + const float *mv = g + 16, *rc = g + 132; + if (!mv[1] && !mv[4] && !mv[8] && !mv[9] && mv[11] < 0 && rc[0] > 0 && rc[1] > 0) { + float y0 = m11 * (mv[5] * rc[3] + mv[7]) / -mv[11]; + float y1 = m11 * (mv[5] * (rc[3] - rc[1]) + mv[7]) / -mv[11]; + float center = (y0 + y1) / 2; + int part = fabsf(m00 * mv[0] * g[108] / mv[11]) >= 2 ? + hud_pause_frame_part(g + 104, g[108], g[109], rc) : 0; + if (part == 2 && fabsf(y1 - y0) > 0.01f) { + pause_stretch += 2 * (1 - shape) / fabsf(y1 - y0); + pause_center = center; + } else if (part) pause_dy = part * (1 - shape); + else pause_dy = hud_pause_edge_dy(center, shape); } } // Gameplay > HUD size: a pane of a 40-degree layer, and not one over about the whole screen (a fade, a picture) float hud_ax = 0, hud_ay = 0; bool hud_scale = false; - float edge_dy = 0; + float edge_dy = hud_layout_dy(shape); if ((hud_s != 1 || hud_edge_active) && size >= 28 * 4 && fabsf((tall ? m11 / shape : m11) - 2.74748f) < 0.001f) { const float *mv = g + 16, *rc = g + 33 * 4; bool has_rect = size >= 34 * 16 && rc[0] > 0 && rc[1] > 0; @@ -4806,6 +4932,7 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) x0 = fminf(x0, nx), x1 = fmaxf(x1, nx), y0 = fminf(y0, ny), y1 = fmaxf(y1, ny); } if (x1 - x0 >= 1.8f * edge_x || y1 - y0 >= 1.8f * edge_y) hud_scale = false; + if (hud_context_native(shape, (x0 + x1) / 2, (y0 + y1) / 2, edge_x, edge_y)) hud_scale = false; float cx = (x0 + x1) / 2, cy = (y0 + y1) / 2; if (hud_scale) { // (a quick menu's bar: HUD size keeps its middle at the game's size, HUD at edges the bar) hud_ax = hud_anchor(cx, edge_x); @@ -4816,13 +4943,22 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) hud_scale = hud_s != 1 && !(hud_quick && hud_quick_keeps(cx, cy, edge_x, edge_y)); } } - if (m00 == g[0] && m11 == g[5] && !hud_scale && edge_dy == 0) return false; + if (tall_map && size >= 28 * 4 && ((map_chrome && fabsf(g[23]) > 200) || + (g_cur_fs_hash == UINT64_C(0xd4fa32dabc35066c) && !g[19] && fabsf(g[23]) == 360))) + edge_dy = copysignf(1 - shape, g[23]); // frame chrome and AppMap's black edge strips + if (m00 == g[0] && m11 == g[5] && !hud_scale && edge_dy == 0 && pause_dy == 0 && pause_stretch == 1) return false; static float buf[0x10000 / 4]; uint64_t n = size > sizeof buf ? sizeof buf : size; memcpy(buf, g, n); buf[0] = m00, buf[5] = m11; if (hud_scale) hud_scale_view(buf + 16, hud_s, m00, m11, hud_ax, hud_ay); if (edge_dy != 0) hud_edge_view(buf + 16, m11, edge_dy); + if (pause_stretch != 1) { + float *v = buf + 16; + for (int k = 0; k < 4; k++) + v[4 + k] = pause_stretch * v[4 + k] - (1 - pause_stretch) * pause_center / m11 * v[8 + k]; + } + if (pause_dy != 0) hud_edge_view(buf + 16, m11, pause_dy); *out = ubo_span(vk_transient_copy(buf, n, 256), n); return true; } @@ -6383,8 +6519,12 @@ static uint32_t g_cs_cap, g_cs_n; // programs, shared copies - and the heap import: its pages are replaced (re-imported on first use). void vk_exec_reset(void) { vdyn_reset(); + hud_event_dialogue = false; + hud_scope = (HudScope){0}; + hud_frame = UINT64_MAX; hud_quick_ns = 0; hud_quick = false; map_background_target = NULL; map_background_frame = map_background_main_frame = UINT64_MAX; + map_chrome_frame = UINT64_MAX; oq_counting = false; oq_nrun = oq_nreports = 0; // (pending reports pointed at the old boot's memory) ngw = 0; @@ -7832,7 +7972,7 @@ static bool one_shot_target(void) { // stalls on them - where a first boot linked 236 pipelines in one 109 ms frame. A stage library still to compile // (5-50 ms) always goes to a worker. SAVAGEWIND_PIPE_LINK_MS=0: every build on a worker, as before. static void build_pipeline(void *arg); -static bool link_now(Pipe *pp) { +static bool link_now(Pipe *pp, bool must_happen) { static int64_t budget = -1; if (budget < 0) budget = (getenv("SAVAGEWIND_PIPE_LINK_MS") ? atoi(getenv("SAVAGEWIND_PIPE_LINK_MS")) : 3) * 1000000ll; const Prog *pr = pp->k.prog; @@ -7844,7 +7984,7 @@ static bool link_now(Pipe *pp) { static uint64_t frame, spent; uint64_t now = renderer_present_count(); if (now != frame) { frame = now; spent = 0; } - if (spent >= (uint64_t)budget) return false; + if (!must_happen && spent >= (uint64_t)budget) return false; uint64_t t0 = SDL_GetTicksNS(); build_pipeline(pp); spent += SDL_GetTicksNS() - t0; @@ -7858,8 +7998,11 @@ static bool link_now(Pipe *pp) { static void wait_built(_Atomic int *state) { // (0 building: until built or failed, 5 s at most) if (atomic_load(state) != 0 || sync_shaders()) return; uint64_t t0 = SDL_GetTicksNS(); - while (atomic_load(state) == 0 && SDL_GetTicksNS() - t0 < 2000000ull) SDL_CPUPauseInstruction(); - while (atomic_load(state) == 0 && SDL_GetTicksNS() - t0 < 5000000000ull) SDL_Delay(1); + while (atomic_load(state) == 0 && SDL_GetTicksNS() - t0 < 5000000000ull) { + if (job_run_one()) continue; + if (SDL_GetTicksNS() - t0 < 2000000ull) { SDL_CPUPauseInstruction(); continue; } + SDL_Delay(1); + } stat_build_waits++; perfcount_add(PC_BUILD_WAITS, 1); perfcount_add(PC_BUILD_WAIT_NS, SDL_GetTicksNS() - t0); @@ -8275,9 +8418,10 @@ static void draw_(CmdRec *r, bool indexed) { pipe_tab[pslot].key = ph; pipe_tab[pslot].pipe = pp; pipe_n++; + bool must = one_shot_target() || draw_must_happen(); VkPipeline ready = sync_shaders() ? VK_NULL_HANDLE : warm_ready(pr->vi, pr->fi, &k.s); if (ready) { pp->pipe = ready; atomic_store(&pp->state, 1); atomic_fetch_add(&stat_warm, 1); } - else if (sync_shaders() || !link_now(pp)) run_job(build_pipeline, pp); // (asynchronous: a link alone is done here) + else if (sync_shaders() || !link_now(pp, must)) run_job(build_pipeline, pp); // (asynchronous: a link alone is done here) } pipe_memo.k = k; pipe_memo.pp = pp; @@ -9323,10 +9467,12 @@ static void map_background_before_cursor(void) { if (!map_background) return; VkCommandBuffer cb = vk_cmd(); vk_full_barrier(cb); + float shape = output_view_shape(); + float edge = (56.0f / 720) * (output_tall_map(shape) ? shape : 1); VkImageBlit region = { .srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, (int32_t)(src->height * 56 / 720), 0}, - {(int32_t)src->width, (int32_t)(src->height * 664 / 720), 1}}, + .srcOffsets = {{0, (int32_t)(src->height * edge), 0}, + {(int32_t)src->width, (int32_t)(src->height * (1 - edge)), 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {1920, 912, 1}} }; @@ -10805,6 +10951,10 @@ static void exec_list(uint64_t handle, int depth) { (unsigned long long)r->x[2], (unsigned long long)r->x[3], (unsigned long long)r->x[4]); if (lst_on) { lst_op(depth, r); lst_depth = depth; } switch (r->op) { // (key_gen: what the program and pipeline keys read) + case CMD_UI_SCOPE: + if (r->x[0]) hud_scope_enter(&hud_scope, (unsigned)r->x[0]); + else hud_scope_leave(&hud_scope); + break; case CMD_BIND_PROGRAM: case CMD_BIND_BLEND: case CMD_BIND_CHANNEL_MASK: case CMD_BIND_COLOR: case CMD_BIND_MULTISAMPLE: case CMD_BIND_POLYGON: case CMD_BIND_VERTEX_ATTRIB: case CMD_BIND_VERTEX_STREAM: case CMD_SET_RENDER_TARGETS: case CMD_SET_DEPTH_CLAMP: diff --git a/runtime/nvn/vulkan/record.c b/runtime/nvn/vulkan/record.c index 2d13fae96..6f6dfa31f 100644 --- a/runtime/nvn/vulkan/record.c +++ b/runtime/nvn/vulkan/record.c @@ -181,6 +181,7 @@ static uint64_t spin_for_work(uint64_t t) { // the published end once it moves static void *run(void *arg) { (void)arg; prof_thread_name("vk-record"); + plat_thread_elevate(); extern void control_prof_thread(const char *name); // runtime/control_prof.c (`threads`) control_prof_thread("recorder"); uint64_t t = 0; diff --git a/runtime/nvn/vulkan/textures.c b/runtime/nvn/vulkan/textures.c index 4c9ab339e..263726404 100644 --- a/runtime/nvn/vulkan/textures.c +++ b/runtime/nvn/vulkan/textures.c @@ -696,6 +696,7 @@ static void create_image(NvnTexture *t, TexBackend *b) { VkClearColorValue zero = {{0}}; VkImageSubresourceRange rg = {VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS}; rec_CmdClearColorImage(cb, b->image, VK_IMAGE_LAYOUT_GENERAL, &zero, 1, &rg); + vk_full_barrier(cb); } { // (debugging) SAVAGEWIND_DEBUG_NEW_FILL=1: every new colour image starts magenta (texels nothing wrote yet) static int fill = -1; diff --git a/runtime/pc_cursor.c b/runtime/pc_cursor.c index 5b0028120..8530105f5 100644 --- a/runtime/pc_cursor.c +++ b/runtime/pc_cursor.c @@ -9,6 +9,8 @@ #include "game_sites.h" #include "framepace.h" #include "hle.h" +#include "nvn/output_scale.h" +#include "nvn/hud_scale.h" #include "settings.h" static _Atomic bool active, focused = true; @@ -275,7 +277,7 @@ static void sample_pointer(void) { static void window_position(float x,float y) { if(window_width<=0||window_height<=0)return; - float p[2];position_inside=pc_cursor_to_layout(window_width,window_height,x,y,p); + float p[2];position_inside=pc_cursor_to_layout(window_width,window_height,x,y,output_ui_extra_y(),p); uint32_t xy[2];memcpy(xy,p,8);position=(uint64_t)xy[0]|(uint64_t)xy[1]<<32; } @@ -286,9 +288,12 @@ void pc_cursor_window(SDL_Window *w) { float x, y; SDL_GetWindowSize(w, &width, &height); window_width=width;window_height=height; + float extra_y=output_map_extra_y(); if(pc_cursor_map_navigation()&&focused) { - float scale=fminf(width/1280.f,height/720.f); - SDL_Rect rect={(int)(width*.5f-632*scale),(int)(height*.5f-280*scale),(int)(1264*scale),(int)(560*scale)}; + float scale=pc_cursor_layout_scale(width,height,extra_y); + // In the taller map let the pointer reach the relocated footer as well as the canvas. + float half_y=extra_y>0?360+extra_y:280; + SDL_Rect rect={(int)(width*.5f-632*scale),(int)(height*.5f-half_y*scale),(int)(1264*scale),(int)(2*half_y*scale)}; const SDL_Rect *old=SDL_GetWindowMouseRect(w); if(!old||memcmp(old,&rect,sizeof rect))SDL_SetWindowMouseRect(w,&rect); } else if(SDL_GetWindowMouseRect(w))SDL_SetWindowMouseRect(w,NULL); @@ -296,7 +301,7 @@ void pc_cursor_window(SDL_Window *w) { if (width <= 0 || height <= 0) return; // eui HitTest uses layout space, centered, Y up. Full pause screens use a fitted 16:9 view. float p[2]; - position_inside=pc_cursor_to_layout(width,height,x,y,p); + position_inside=pc_cursor_to_layout(width,height,x,y,output_ui_extra_y(),p); uint32_t xy[2]; memcpy(xy, p, sizeof xy); position = (uint64_t)xy[0] | (uint64_t)xy[1] << 32; } @@ -1004,7 +1009,8 @@ static bool native_special(Cpu *c,uint64_t screens,uint64_t bounds) { *(float*)(d+0x870+4*axis)=center*zoom; if(map_view_valid)map_view_center[axis]=pc_map_clamp_center(map_view_center[axis],lo,hi); } - bool area=fabsf(point[0])<=633&&fabsf(point[1])<=285; + float extra_y=output_map_extra_y(); + bool area=fabsf(point[0])<=633&&fabsf(point[1])<=285+extra_y; int scroll=atomic_exchange(&wheel,0); map_canvas_active=true; bool zooming=scroll||map_zoom_anchored||fabsf(zoom-*(float*)(d+0x888))>.001f; @@ -1080,7 +1086,8 @@ static bool native_special(Cpu *c,uint64_t screens,uint64_t bounds) { } memcpy(map_last,point,sizeof point); } - float cursor[2]={fmaxf(-632,fminf(632,point[0])),fmaxf(-280,fminf(280,point[1]))},best_snap=1e9f; + float half_y=280+extra_y; + float cursor[2]={fmaxf(-632,fminf(632,point[0])),fmaxf(-half_y,fminf(half_y,point[1]))},best_snap=1e9f; uint64_t snapped=0; // Native map markers need not be registered in the screen's AnimButton list. // A target changed from the point we sent last frame is the game's marker @@ -1103,7 +1110,7 @@ static bool native_special(Cpu *c,uint64_t screens,uint64_t bounds) { float w=box[2]-box[0],h=box[3]-box[1]; float x=(box[0]+box[2])*.5f,y=(box[1]+box[3])*.5f; float distance=hypotf(point[0]-x,point[1]-y),radius=button==map_snap_button?14:10; - if(w>=10&&w<=80&&h>=10&&h<=80&&fabsf(x)<600&&fabsf(y)<285&&distance=10&&w<=80&&h>=10&&h<=80&&fabsf(x)<600&&fabsf(y)<285+extra_y&&distancebox[2]||point[1]box[3])continue; @@ -1451,7 +1459,7 @@ static int guide_button(uint16_t glyph) { static bool pane_shown(uint64_t pane) { return ptr(pane)&&(LD8(pane+0x58)&1)&&LD8(pane+0x5a)>=0x80; // visible, global alpha at least half } -static bool guide_hit(Cpu *c,uint64_t info,unsigned i,const char *slot,uint64_t icon,uint64_t label,uint64_t area); +static bool guide_hit(Cpu *c,uint64_t info,unsigned i,const char *slot,uint64_t icon,uint64_t label,uint64_t area,float dy); static bool pause_guides(Cpu *c,uint64_t screen,uint64_t screens,unsigned count) { if(!ptr(screen)||LD64(screen)!=0x7001cf9ad8ull||LD8(screen+0xfe)!=2||count<=0x2f)return false; for(unsigned i=0x30;i<=0x3a&&ibox[2]||point[1]box[3])return false; set_hover_rect(box); pointer_hover_sound(c,info,info+0x400+i); @@ -1610,6 +1620,15 @@ static bool shop_pointer(Cpu *c) { return false; } +static float dialogue_extra_y(void) { +#ifdef __APPLE__ + return 0; +#else + float shape=output_view_shape(); + return g_settings.hud_edges&&shape>0&&shape<1?360*(1/shape-1):0; +#endif +} + static bool quantity_pointer(Cpu *c,uint64_t screens,unsigned count) { if(!dialogue_active)return false; for(unsigned i=0;i1){x/=n;y/=n;} diff --git a/runtime/platform.h b/runtime/platform.h index 528ac31cb..c9295a220 100644 --- a/runtime/platform.h +++ b/runtime/platform.h @@ -54,6 +54,7 @@ uint64_t plat_now_ns(void); // monotonic void plat_sleep_until_ns(uint64_t t); // precise wait for plat_now_ns() >= t void plat_wait_until_ns(uint64_t t); // wait for plat_now_ns() >= t without spinning (the OS timer's precision) void plat_thread_realtime(uint64_t period_ns); // periodic timing thread (vsync): don't coalesce its timers +void plat_thread_elevate(void); // latency-critical thread (game main, render, recorder): favor P-cores on hybrid architectures int plat_cpu_count(void); // logical processors this process may run on (its affinity, after plat_cpu_placement) void plat_cpu_placement(void); // (game start) one logical processor per core where plat_one_per_core_default says // Whether the game runs on one logical processor per core when SAVAGEWIND_ONE_PER_CORE doesn't say (cores: physical diff --git a/runtime/platform/linux.c b/runtime/platform/linux.c index 9f629b228..9979d79d2 100644 --- a/runtime/platform/linux.c +++ b/runtime/platform/linux.c @@ -134,6 +134,8 @@ void plat_thread_realtime(uint64_t period_ns) { setpriority(PRIO_PROCESS, (id_t)gettid(), -10); // (per thread on Linux; fails quietly without CAP_SYS_NICE) } +void plat_thread_elevate(void) {} + // ---- process // stdout / stderr go to savagewind.log in the data folder (runtime/paths.h; rt_paths_init runs later, so the same rule // is applied here). Processes started by this one (the start screen re-executing itself for the game) append to the diff --git a/runtime/platform/macos.c b/runtime/platform/macos.c index 11fb6efdb..60e3d233a 100644 --- a/runtime/platform/macos.c +++ b/runtime/platform/macos.c @@ -83,6 +83,8 @@ void plat_thread_realtime(uint64_t period_ns) { THREAD_TIME_CONSTRAINT_POLICY_COUNT); } +void plat_thread_elevate(void) {} + const char *plat_log_path(void) { return ""; } // (the log goes to stderr) bool plat_exe_path(char *buf, size_t size) { diff --git a/runtime/platform/windows.c b/runtime/platform/windows.c index 5c2d23d2b..a42b0208f 100644 --- a/runtime/platform/windows.c +++ b/runtime/platform/windows.c @@ -325,6 +325,10 @@ void plat_thread_realtime(uint64_t period_ns) { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); } +void plat_thread_elevate(void) { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); +} + // ---- process // Release builds are GUI-subsystem executables (no console window): stdout / stderr go to savagewind.log next to the // exe, and a fatal error shows a message box (plat_fatal_notice) instead of vanishing. Processes started by this one @@ -434,9 +438,11 @@ void plat_init(void) { // never share a core with another busy thread of the game. With fewer cores than the game's busy threads (main, two job // workers, render, recorder, audio, file loading) they queue for one instead: by default with SMT and 4 or more // physical cores (plat_one_per_core_default). SAVAGEWIND_ONE_PER_CORE=1: always, 0: never. Called when the game -// starts, so what the start screen runs (the game code build) keeps every logical processor. Under Wine / Proton the -// Linux kernel schedules the threads, and there the Steam Deck measured one processor per core as a loss -// (platform.h): the default keeps every logical processor, as the Linux build does. +// starts, so what the start screen runs (the game code build) keeps every logical processor. On hybrid architectures +// (Intel 12th+ Gen, Core Ultra, heterogeneous P/E cores) keeping all logical processors avoids starving P-core SMT +// execution slots and forcing critical threads onto low-clock E-cores. Under Wine / Proton the Linux kernel schedules +// the threads, and there the Steam Deck measured one processor per core as a loss (platform.h): the default keeps +// every logical processor, as the Linux build does. void plat_cpu_placement(void) { DWORD_PTR all, sys, one = 0; if (!GetProcessAffinityMask(GetCurrentProcess(), &all, &sys)) return; @@ -446,18 +452,28 @@ void plat_cpu_placement(void) { DWORD len = 0; GetLogicalProcessorInformationEx(RelationProcessorCore, NULL, &len); char *buf = len ? malloc(len) : NULL; + BYTE min_eff = 255, max_eff = 0; if (buf && GetLogicalProcessorInformationEx(RelationProcessorCore, (void *)buf, &len)) for (DWORD o = 0; o < len;) { SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *e = (void *)(buf + o); DWORD_PTR m = e->Processor.GroupMask[0].Group == 0 ? e->Processor.GroupMask[0].Mask & all : 0; - if (m) cores++, one |= m & -m; // (the core's first logical processor) + if (m) { + cores++; + one |= m & -m; // (the core's first logical processor) + BYTE eff = e->Processor.EfficiencyClass; + if (eff < min_eff) min_eff = eff; + if (eff > max_eff) max_eff = eff; + } o += e->Size; } free(buf); + bool hybrid = (cores > 0 && min_eff != max_eff); const char *x = getenv("SAVAGEWIND_ONE_PER_CORE"); - bool on = one && (x ? atoi(x) != 0 : !wine && plat_one_per_core_default(cores, logical)); - fprintf(stderr, "[cpu] %d cores, %d logical processors: %s%s\n", cores, logical, - on ? "one logical processor per core" : "all logical processors", wine && !x ? " (Wine)" : ""); + bool on = one && (x ? atoi(x) != 0 : !wine && !hybrid && plat_one_per_core_default(cores, logical)); + fprintf(stderr, "[cpu] %d cores%s, %d logical processors: %s%s\n", cores, + hybrid ? " (hybrid P/E)" : "", logical, + on ? "one logical processor per core" : "all logical processors", + wine && !x ? " (Wine)" : hybrid && !x ? " (hybrid architecture)" : ""); if (on) SetProcessAffinityMask(GetCurrentProcess(), one); } diff --git a/runtime/services/fs.c b/runtime/services/fs.c index a005da6fe..07f803768 100644 --- a/runtime/services/fs.c +++ b/runtime/services/fs.c @@ -980,9 +980,10 @@ static void hud_letters_patch(const uint8_t *fmeta, uint64_t foff, uint64_t fsz) // (Savage Wind+) Video > Haze: the air's haze. BOTW's outdoor haze is its atmospheric scattering, set per climate in // Pack/TitleBG.pack's WorldMgr/normal.bwinfo (AAMP, 20 climates): CalcMie and CalcRayleigh (the white and the blue of // the air: lower, clearer; at 0.6x the sky darkens and turns teal) and CalcSfParamNear (0 or below: the haze close by, -// least at 0). The setting's share k of the game's haze gives those 0.7 + 0.3 k times theirs (0.85 at 50 %, where far -// mountains keep their colour and the sky its blue; seen from Hebra's tower at noon, clear sky) and k times the near -// one. The file is read at the start: one patch over its bytes, the same size. +// least at 0). The setting's share k of the game's haze gives those 0.7 + 0.3 k times theirs and k times the near one. +// k stays at 75 % or more (HAZE_MIN): at 50 % (0.85x) the sky, the far mountains and the ground already turn +// green-teal on the Great Plateau at day, so 0-50 are left out. The file is read at the start: one patch over its +// bytes, the same size. static uint32_t crc32_str(const char *s) { return (uint32_t)crc32(0, (const uint8_t *)s, (uInt)strlen(s)); } static size_t haze_done[512]; // (the value offsets changed so far) static void haze_walk_list(uint8_t *d, size_t n, size_t o, const uint32_t h[3], const float f[3], int *changed, int depth) { @@ -1019,7 +1020,7 @@ static void haze_walk_list(uint8_t *d, size_t n, size_t o, const uint32_t h[3], // names that this scaling turned teal) } static void haze_patch(void) { - int pct = g_settings.haze; + int pct = g_settings.haze < HAZE_MIN ? HAZE_MIN : g_settings.haze; if (pct >= 100 || R != &images[0] || R->npatches >= 16) return; static const char pack_path[] = "Pack/TitleBG.pack", name[] = "WorldMgr/normal.bwinfo"; int k = 0; diff --git a/runtime/settings.c b/runtime/settings.c index 986d58ae6..22b335041 100644 --- a/runtime/settings.c +++ b/runtime/settings.c @@ -356,7 +356,10 @@ void settings_load(void) { else if (!strcmp(key, "one_hit_kill")) g_settings.one_hit_kill = atoi(val) != 0; else if (!strcmp(key, "damage_taken")) g_settings.damage_taken = atoi(val); // (percent) else if (!strcmp(key, "damage_dealt")) g_settings.damage_dealt = atoi(val); - else if (!strcmp(key, "haze")) { int v = atoi(val); g_settings.haze = v < 0 ? 0 : v > 100 ? 100 : v; } // (percent) + else if (!strcmp(key, "haze")) { // (percent; an older ini's 0-50 reads as 75: HAZE_MIN) + int v = atoi(val); + g_settings.haze = v < HAZE_MIN ? HAZE_MIN : v > 100 ? 100 : v; + } else if (!strcmp(key, "bloom")) g_settings.bloom = atoi(val) != 0; else if (!strcmp(key, "depth_of_field")) g_settings.depth_of_field = atoi(val) != 0; else if (!strcmp(key, "dynamic_resolution")) g_settings.dynamic_res = atoi(val) != 0; diff --git a/runtime/settings.h b/runtime/settings.h index cf642be1b..7a460cf6b 100644 --- a/runtime/settings.h +++ b/runtime/settings.h @@ -187,7 +187,8 @@ typedef struct { #define STICK_CAM_MAX 600 #define STICK_CAM_DEFAULT 200 #define STICK_DEADZONE_DEFAULT 0.10f // (the Switch's own input service has one: the game expects 0 at rest) -#define HAZE_CHOICES {0, 25, 50, 75, 100} // (percent of the game's haze) +#define HAZE_CHOICES {75, 90, 100} // (percent of the game's haze: below 75 the whole picture turns teal) +#define HAZE_MIN 75 enum { DRAWDIST_ORIGINAL, DRAWDIST_MEDIUM, DRAWDIST_HIGH, DRAWDIST_POTATO, DRAWDIST_COUNT }; // (Original: the game's own // distances; Potato: nearer) float draw_distance_factor(void); // the setting's factor on the game's distances (1: Original) diff --git a/runtime/ui/i18n/de.inc b/runtime/ui/i18n/de.inc index e7d8b23f9..181ce402b 100644 --- a/runtime/ui/i18n/de.inc +++ b/runtime/ui/i18n/de.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "Ein Screenshot") T("Latest save", "Letzter Spielstand") T("Loading picture", "Ladebild") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Zeigt dieses Bild, während das Spiel lädt. Aus: Das Fenster bleibt bis zum Titelbildschirm schwarz; das Laden dauert genauso lange.") +T("Folder picker failed to open", "Ordnerauswahl konnte nicht geöffnet werden") +T("Type or paste the folder path below instead.", "Geben Sie stattdessen unten den Ordnerpfad ein oder fügen Sie ihn ein.") +T("Folder path", "Ordnerpfad") +T("Type or paste path...", "Pfad eingeben oder einfügen...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Geben Sie den Pfad zu Ihrem Ordner mit den entpackten Spieldateien direkt ein, falls sich die System-Ordnerauswahl nicht öffnet.") diff --git a/runtime/ui/i18n/es.inc b/runtime/ui/i18n/es.inc index 093ccffc1..19ceea54f 100644 --- a/runtime/ui/i18n/es.inc +++ b/runtime/ui/i18n/es.inc @@ -1002,3 +1002,8 @@ T("A screenshot", "Una captura") T("Latest save", "Última partida") T("Loading picture", "Imagen de carga") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Muestra esa imagen mientras carga el juego. Desactivada, la ventana se queda en negro hasta la pantalla de título del juego: la carga tarda lo mismo.") +T("Folder picker failed to open", "No se pudo abrir el selector de carpetas") +T("Type or paste the folder path below instead.", "Escriba o pegue la ruta de la carpeta abajo.") +T("Folder path", "Ruta de la carpeta") +T("Type or paste path...", "Escriba o pegue la ruta...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Introduzca directamente la ruta a la carpeta con los archivos extraídos del juego si el selector del sistema no se abre.") diff --git a/runtime/ui/i18n/fr.inc b/runtime/ui/i18n/fr.inc index c874740ee..c17574392 100644 --- a/runtime/ui/i18n/fr.inc +++ b/runtime/ui/i18n/fr.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "Une capture") T("Latest save", "Dernière sauvegarde") T("Loading picture", "Image de chargement") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Affiche cette image pendant le chargement du jeu. Désactivé, la fenêtre reste noire jusqu'à l'écran titre : le chargement dure autant.") +T("Folder picker failed to open", "Impossible d’ouvrir le sélecteur de dossier") +T("Type or paste the folder path below instead.", "Saisissez ou collez plutôt le chemin du dossier ci-dessous.") +T("Folder path", "Chemin du dossier") +T("Type or paste path...", "Saisir ou coller le chemin...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Saisissez directement le chemin vers le dossier de vos fichiers de jeu extraits si le sélecteur de dossier système ne s’ouvre pas.") diff --git a/runtime/ui/i18n/he.inc b/runtime/ui/i18n/he.inc index 4838a179e..3071dadd5 100644 --- a/runtime/ui/i18n/he.inc +++ b/runtime/ui/i18n/he.inc @@ -1002,3 +1002,8 @@ T("A screenshot", "צילום מסך") T("Latest save", "שמירה אחרונה") T("Loading picture", "תמונת טעינה") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "מציג את התמונה הזו בזמן שהמשחק נטען. כשכבוי, החלון נשאר שחור עד מסך הכותרת של המשחק: הטעינה נמשכת אותו זמן.") +T("Folder picker failed to open", "פתיחת בורר התיקיות נכשלה") +T("Type or paste the folder path below instead.", "הקלידו או הדביקו את נתיב התיקייה למטה במקום זאת.") +T("Folder path", "נתיב התיקייה") +T("Type or paste path...", "הקלידו או הדביקו נתיב...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "הזינו ישירות את הנתיב לתיקיית קובצי המשחק המחולצים אם בורר התיקיות של המערכת אינו נפתח.") diff --git a/runtime/ui/i18n/it.inc b/runtime/ui/i18n/it.inc index 6d3b17162..42ef4019f 100644 --- a/runtime/ui/i18n/it.inc +++ b/runtime/ui/i18n/it.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "Uno screenshot") T("Latest save", "Ultimo salvataggio") T("Loading picture", "Immagine di caricamento") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Mostra quell'immagine durante il caricamento del gioco. Disattivata, la finestra resta nera fino alla schermata del titolo: il caricamento dura lo stesso.") +T("Folder picker failed to open", "Impossibile aprire il selettore di cartelle") +T("Type or paste the folder path below instead.", "Digita o incolla invece il percorso della cartella qui sotto.") +T("Folder path", "Percorso cartella") +T("Type or paste path...", "Digita o incolla il percorso...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Inserisci direttamente il percorso della cartella con i file di gioco estratti se il selettore di sistema non si apre.") diff --git a/runtime/ui/i18n/ja.inc b/runtime/ui/i18n/ja.inc index 69183327d..ebeace9ea 100644 --- a/runtime/ui/i18n/ja.inc +++ b/runtime/ui/i18n/ja.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "スクリーンショット") T("Latest save", "最新のセーブ") T("Loading picture", "読み込み中の画像") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "ゲームの読み込み中にその画像を表示します。オフにすると、タイトル画面まで画面は黒いままです。読み込み時間は変わりません。") +T("Folder picker failed to open", "フォルダー選択を開けませんでした") +T("Type or paste the folder path below instead.", "代わりに下の欄へフォルダーのパスを入力または貼り付けてください。") +T("Folder path", "フォルダーのパス") +T("Type or paste path...", "パスを入力または貼り付け...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "システムのフォルダー選択が開かない場合は、展開済みのゲームファイルがあるフォルダーのパスを直接入力してください。") diff --git a/runtime/ui/i18n/ko.inc b/runtime/ui/i18n/ko.inc index f9903bb08..98aee2a78 100644 --- a/runtime/ui/i18n/ko.inc +++ b/runtime/ui/i18n/ko.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "스크린샷") T("Latest save", "최근 세이브") T("Loading picture", "로딩 이미지") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "게임을 불러오는 동안 그 이미지를 보여 줍니다. 끄면 타이틀 화면까지 창이 검은색으로 유지됩니다. 로딩 시간은 같습니다.") +T("Folder picker failed to open", "폴더 선택기를 열지 못했습니다") +T("Type or paste the folder path below instead.", "대신 아래에 폴더 경로를 입력하거나 붙여 넣으세요.") +T("Folder path", "폴더 경로") +T("Type or paste path...", "경로 입력 또는 붙여넣기...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "시스템 폴더 선택기가 열리지 않으면 추출된 게임 파일 폴더의 경로를 직접 입력하세요.") diff --git a/runtime/ui/i18n/nl.inc b/runtime/ui/i18n/nl.inc index 408bee9f8..895257aba 100644 --- a/runtime/ui/i18n/nl.inc +++ b/runtime/ui/i18n/nl.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "Een screenshot") T("Latest save", "Laatste opslag") T("Loading picture", "Laadafbeelding") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Toont die afbeelding tijdens het laden van het spel. Uitgeschakeld blijft het venster zwart tot het titelscherm: laden duurt even lang.") +T("Folder picker failed to open", "Kan mapkiezer niet openen") +T("Type or paste the folder path below instead.", "Typ of plak in plaats daarvan het mappad hieronder.") +T("Folder path", "Mappad") +T("Type or paste path...", "Typ of plak pad...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Voer rechtstreeks het pad naar uw map met uitgepakte gamebestanden in als de systeemmapkiezer niet opent.") diff --git a/runtime/ui/i18n/pt.inc b/runtime/ui/i18n/pt.inc index 63118efc0..3529d797c 100644 --- a/runtime/ui/i18n/pt.inc +++ b/runtime/ui/i18n/pt.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "Uma captura") T("Latest save", "Último save") T("Loading picture", "Imagem de carregamento") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Mostra essa imagem enquanto o jogo carrega. Desativada, a janela fica preta até a tela de título: o carregamento leva o mesmo tempo.") +T("Folder picker failed to open", "Não foi possível abrir o seletor de pastas") +T("Type or paste the folder path below instead.", "Digite ou cole o caminho da pasta abaixo.") +T("Folder path", "Caminho da pasta") +T("Type or paste path...", "Digite ou cole o caminho...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Insira diretamente o caminho da pasta com os arquivos extraídos do jogo caso o seletor do sistema não abra.") diff --git a/runtime/ui/i18n/ru.inc b/runtime/ui/i18n/ru.inc index 80f649d6f..08f3f4474 100644 --- a/runtime/ui/i18n/ru.inc +++ b/runtime/ui/i18n/ru.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "Скриншот") T("Latest save", "Последнее сохранение") T("Loading picture", "Картинка загрузки") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "Показывает эту картинку, пока загружается игра. Если выключено, окно остаётся чёрным до титульного экрана: загрузка длится столько же.") +T("Folder picker failed to open", "Не удалось открыть выбор папки") +T("Type or paste the folder path below instead.", "Введите или вставьте путь к папке ниже.") +T("Folder path", "Путь к папке") +T("Type or paste path...", "Введите или вставьте путь...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "Укажите путь к папке с распакованными файлами игры напрямую, если системный выбор папки не открывается.") diff --git a/runtime/ui/i18n/th.inc b/runtime/ui/i18n/th.inc index 7871ad0fd..cd34fb3d2 100644 --- a/runtime/ui/i18n/th.inc +++ b/runtime/ui/i18n/th.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "ภาพหน้าจอ") T("Latest save", "เซฟล่าสุด") T("Loading picture", "ภาพขณะโหลด") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "แสดงภาพนั้นขณะโหลดเกม หากปิดไว้ หน้าต่างจะเป็นสีดำจนถึงหน้าจอชื่อเกม โดยใช้เวลาโหลดเท่าเดิม") +T("Folder picker failed to open", "ไม่สามารถเปิดหน้าต่างเลือกโฟลเดอร์ได้") +T("Type or paste the folder path below instead.", "พิมพ์หรือวางเส้นทางโฟลเดอร์ด้านล่างแทน") +T("Folder path", "เส้นทางโฟลเดอร์") +T("Type or paste path...", "พิมพ์หรือวางเส้นทาง...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "ป้อนเส้นทางไปยังโฟลเดอร์ไฟล์เกมที่แตกไว้โดยตรงหากหน้าต่างเลือกโฟลเดอร์ของระบบไม่เปิดขึ้น") diff --git a/runtime/ui/i18n/zh-Hans.inc b/runtime/ui/i18n/zh-Hans.inc index f50e19ce7..2ae2584bb 100644 --- a/runtime/ui/i18n/zh-Hans.inc +++ b/runtime/ui/i18n/zh-Hans.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "一张截图") T("Latest save", "最新存档") T("Loading picture", "加载图片") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "游戏加载时显示该图片。关闭后,在游戏标题画面出现前窗口保持黑屏:加载时间不变。") +T("Folder picker failed to open", "无法打开文件夹选择器") +T("Type or paste the folder path below instead.", "请改在下方输入或粘贴文件夹路径。") +T("Folder path", "文件夹路径") +T("Type or paste path...", "输入或粘贴路径...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "如果系统文件夹选择器无法打开,请直接输入已提取游戏文件所在文件夹的路径。") diff --git a/runtime/ui/i18n/zh-Hant.inc b/runtime/ui/i18n/zh-Hant.inc index b8e54d7ac..a47da8983 100644 --- a/runtime/ui/i18n/zh-Hant.inc +++ b/runtime/ui/i18n/zh-Hant.inc @@ -1003,3 +1003,8 @@ T("A screenshot", "一張截圖") T("Latest save", "最新存檔") T("Loading picture", "載入圖片") T("Shows that picture while the game loads. Turned off, the window stays black until the game's title screen: loading takes just as long.", "遊戲載入時顯示該圖片。關閉後,在遊戲標題畫面出現前視窗維持黑色:載入時間不變。") +T("Folder picker failed to open", "無法開啟資料夾選擇器") +T("Type or paste the folder path below instead.", "請改在下方輸入或貼上資料夾路徑。") +T("Folder path", "資料夾路徑") +T("Type or paste path...", "輸入或貼上路徑...") +T("Enter the path to your extracted game files folder directly if the system folder picker does not open.", "如果系統資料夾選擇器無法開啟,請直接輸入已擷取遊戲檔案所在資料夾的路徑。") diff --git a/runtime/ui/launcher.mm b/runtime/ui/launcher.mm index b6fe310a1..6984a14f8 100644 --- a/runtime/ui/launcher.mm +++ b/runtime/ui/launcher.mm @@ -896,8 +896,23 @@ static bool path_inside(const std::string &path, const std::string &folder) { } // ------------------------------------------------------------------ folder dialog (SDL calls back on any thread) +static std::string trim_folder_path(const char *s) { + std::string p = s ? s : ""; + while (!p.empty() && (p.front() == ' ' || p.front() == '\t' || p.front() == '\r' || p.front() == '\n')) p.erase(p.begin()); + while (!p.empty() && (p.back() == ' ' || p.back() == '\t' || p.back() == '\r' || p.back() == '\n')) p.pop_back(); + if (p.size() >= 2 && ((p.front() == '"' && p.back() == '"') || (p.front() == '\'' && p.back() == '\''))) + p = p.substr(1, p.size() - 2); + return p; +} + static void SDLCALL picked(void *, const char *const *files, int) { - if (!files || !files[0]) return; + if (!files) { + const char *err = SDL_GetError(); + if (err && err[0]) fprintf(stderr, "[launcher] folder dialog error: %s\n", err); + set_job("Folder picker failed to open", true, "Type or paste the folder path below instead."); + return; + } + if (!files[0]) return; pthread_mutex_lock(&g_lock); g_src = files[0]; pthread_mutex_unlock(&g_lock); @@ -1968,6 +1983,24 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { if (opt_action("Game files folder", src_v.c_str(), src_d.c_str(), true)) SDL_ShowOpenFolderDialog(picked, NULL, win, NULL, false); if (!src.empty()) check_left_of_value(src_v); + if (busy) opt_disable_next(); + { + static char path_buf[1024]; + static std::string last_synced_src; + if (src != last_synced_src) { + snprintf(path_buf, sizeof path_buf, "%s", src.c_str()); + last_synced_src = src; + } + if (opt_text("Folder path", path_buf, sizeof path_buf, "Type or paste path...", + "Enter the path to your extracted game files folder directly if the system folder picker does not open.")) { + std::string p = trim_folder_path(path_buf); + pthread_mutex_lock(&g_lock); + g_src = p; + pthread_mutex_unlock(&g_lock); + last_synced_src = p; + snprintf(path_buf, sizeof path_buf, "%s", p.c_str()); + } + } if (!ready) { first_row(); opt_section("Set up"); diff --git a/runtime/ui/menu.mm b/runtime/ui/menu.mm index 53d3dc48b..ce3676f57 100644 --- a/runtime/ui/menu.mm +++ b/runtime/ui/menu.mm @@ -2056,7 +2056,7 @@ void menu_render(void *cmd, uint32_t target_w, uint32_t target_h) { ImGui::NewFrame(); if(pointer_hover&&!open&&!kbd&&!sizes) { - float s=fminf(io.DisplaySize.x/1280.f,io.DisplaySize.y/720.f); + float s=fminf(io.DisplaySize.x/1280.f,io.DisplaySize.y/(720.f+2*output_ui_extra_y())); ImVec2 a(io.DisplaySize.x*.5f+pointer_box[0]*s,io.DisplaySize.y*.5f-pointer_box[3]*s); ImVec2 b(io.DisplaySize.x*.5f+pointer_box[2]*s,io.DisplaySize.y*.5f-pointer_box[1]*s); bool pressed=pc_cursor_hover_pressed(); diff --git a/runtime/ui_layout.c b/runtime/ui_layout.c new file mode 100644 index 000000000..b7b6a4155 --- /dev/null +++ b/runtime/ui_layout.c @@ -0,0 +1,108 @@ +#include +#include +#include +#include "ui_layout.h" +#include "game_sites.h" +#include "hle.h" +#include "kernel.h" +#include "settings.h" +#include "framepace.h" +#include "nvn/nvn.h" + +static bool ui_range(uint64_t p, uint64_t n) { + return p >= GUEST_LO && p < GUEST_HI && n <= GUEST_HI - p; +} + +// MiniMap's native animation chooses the map presentation before pause state catches up. +// Frame zero is the full map; its end frame is the minimap, also while opening the inventory. +int ui_layout_map_mode(uint64_t screen) { + if (strcmp(g_game_version, "1.9.0") || !ui_range(screen, 0x3648)) return -1; + uint64_t animation = *(uint64_t *)(uintptr_t)(screen + 0x3640); + if (!ui_range(animation, 0x24)) return -1; + uint64_t resource = *(uint64_t *)(uintptr_t)(animation + 0x18); + if (!ui_range(resource, 0xa)) return -1; + unsigned end = *(uint16_t *)(uintptr_t)(resource + 8); + float frame = *(float *)(uintptr_t)(animation + 0x20); + if (!end || !isfinite(frame)) return -1; + return frame == 0 ? 1 : frame == end ? 0 : -1; +} + +static _Thread_local unsigned pane_draw_depth; +RT_ON_RESET(ui_layout_reset) { pane_draw_depth = 0; } + +bool rt_ui_layout_pane_draw(Cpu *c, void (*native)(Cpu *)) { +#ifdef __APPLE__ + return false; +#else + uint64_t pane = c->x[0]; + if (pane_draw_depth || !native || (!g_settings.hud_edges && g_settings.hud_size == 100) || + strcmp(g_game_version, "1.9.0") || !g_site.screen_mgr || !ui_range(pane, 0xf8) || + memcmp((const void *)(uintptr_t)(pane + 0xb8), "Pa_QuestName_00", sizeof "Pa_QuestName_00")) return false; + uint64_t manager = *(uint64_t *)(uintptr_t)g_site.screen_mgr; + if (!ui_range(manager, 0x38)) return false; + uint32_t count = *(uint32_t *)(uintptr_t)(manager + 0x28); + uint64_t screens = *(uint64_t *)(uintptr_t)(manager + 0x30); + if (count <= 0x25 || count > 256 || !ui_range(screens, count * 8)) return false; + uint64_t hud = *(uint64_t *)(uintptr_t)(screens + 8 * 0x25); + if (!ui_range(hud, 0x3cc8)) return false; + uint64_t quest = *(uint64_t *)(uintptr_t)(hud + 0x3cc0); + if (!quest || *(uint64_t *)(uintptr_t)(pane + 0xf0) != quest) return false; + // MainScreen embeds this notification part: its glyph origins and window centers fall + // into different HUD anchor zones. Keep the complete subtree in its native layout. + uint64_t wrapper = c->x[2]; + if (!ui_range(wrapper, 0xb8)) return false; + uint64_t commands = *(uint64_t *)(uintptr_t)(wrapper + 0xb0); + if (!nvn_ui_scope(commands, UI_LAYOUT_DIALOGUE)) return false; + pane_draw_depth++; + native(c); // the entry gate re-enters once, then draws the original subtree normally + pane_draw_depth--; + nvn_ui_scope(commands, UI_LAYOUT_NONE); + return true; +#endif +} + +uint64_t ui_layout_begin(Cpu *c) { +#ifdef __APPLE__ + return 0; +#else + if ((!g_settings.hud_edges && g_settings.hud_size == 100) || !g_site.screen_mgr || strcmp(g_game_version, "1.9.0")) return 0; + uint64_t manager = *(uint64_t *)(uintptr_t)g_site.screen_mgr; + if (!ui_range(manager, 0x38)) return 0; + uint32_t count = *(uint32_t *)(uintptr_t)(manager + 0x28); + uint64_t screens = *(uint64_t *)(uintptr_t)(manager + 0x30), screen = c->x[0]; + if (count <= 0x4c || count > 256 || !ui_range(screens, count * 8)) return 0; + const uint64_t *slots = (const uint64_t *)(uintptr_t)screens; + unsigned kind = screen == slots[0x25] || screen == slots[0x2] || screen == slots[0x1c] ? UI_LAYOUT_HUD : screen == slots[0xc] ? UI_LAYOUT_CONTEXT : + screen == slots[0xb] || screen == slots[0x11] || screen == slots[0x27] || + screen == slots[0x2d] || screen == slots[0x4a] || screen == slots[0x4c] ? UI_LAYOUT_DIALOGUE : UI_LAYOUT_NONE; + // AppMap renders the minimap in play and the full map in pause. Keep their policies separate. + if (screen == slots[0x2a]) { + int map = ui_layout_map_mode(screen); + kind = (map < 0 ? framepace_menu_ui() : map) ? UI_LAYOUT_MENU : UI_LAYOUT_HUD; + } + if (screen == slots[0x4a]) kind = UI_LAYOUT_TALK; + if (!kind || !ui_range(screen, 0x103)) return 0; + const uint8_t *state = (const uint8_t *)(uintptr_t)screen; + // The native draw returns here before the render context is required to be initialized. + if (!state[0x100] || state[0x102] || !state[0xfe] || state[0xff] == 2) return 0; + uint64_t context = c->x[1]; + if (!kind || !ui_range(context, 0x28)) return 0; + uint64_t commands = *(uint64_t *)(uintptr_t)(context + 0x20); + if (!ui_range(commands, 0xc0)) return 0; + // Layout/pane draw receives nn::gfx's wrapper at +8; its NVN object is the pointer at wrapper+0xb0. + commands = *(uint64_t *)(uintptr_t)(commands + 0xb8); + if (!ui_range(commands, 8)) return 0; + return nvn_ui_scope(commands, kind) ? commands : 0; +#endif +} + +void ui_layout_end(Cpu *c, uint64_t commands) { + (void)c; + if (commands) nvn_ui_scope(commands, UI_LAYOUT_NONE); +} + +void rt_ui_layout_draw(Cpu *c, void (*native)(Cpu *)) { + uint64_t commands = ui_layout_begin(c); + native(c); + ui_layout_end(c, commands); +} diff --git a/runtime/ui_layout.h b/runtime/ui_layout.h new file mode 100644 index 000000000..ed6d2c8c8 --- /dev/null +++ b/runtime/ui_layout.h @@ -0,0 +1,12 @@ +#pragma once +#include +#include "cpu.h" + +// Layout ownership travels with deferred NVN commands, rather than the live event manager. +enum { UI_LAYOUT_NONE, UI_LAYOUT_HUD, UI_LAYOUT_DIALOGUE, UI_LAYOUT_CONTEXT, UI_LAYOUT_MENU, UI_LAYOUT_TALK }; +// -1 unsupported/uninitialized; 0 minimap; 1 full map (including transitions). +int ui_layout_map_mode(uint64_t screen); +uint64_t ui_layout_begin(Cpu *c); +void ui_layout_end(Cpu *c, uint64_t commands); +void rt_ui_layout_draw(Cpu *c, void (*native)(Cpu *)); +bool rt_ui_layout_pane_draw(Cpu *c, void (*native)(Cpu *)); diff --git a/runtime/vibration.h b/runtime/vibration.h index 49ea15bf8..6f8ec336a 100644 --- a/runtime/vibration.h +++ b/runtime/vibration.h @@ -12,3 +12,5 @@ void vibration_permit(bool permitted); bool vibration_permitted(void); void vibration_clear(void); void vibration_update(SDL_Gamepad *pad, bool focused); +void vibration_pad_closed(SDL_Gamepad *pad); +void vibration_flush(void); diff --git a/runtime/window_size.c b/runtime/window_size.c index e5f69ea5c..9fa9031bf 100644 --- a/runtime/window_size.c +++ b/runtime/window_size.c @@ -272,6 +272,19 @@ static SDL_DisplayID target_display(void) { unsigned winsize_start_display(void) { return (unsigned)target_display(); } +// The display's mode of that size with the highest refresh rate (NULL: none) +static bool find_mode(SDL_DisplayID d, WinSize s, SDL_DisplayMode *out) { + int count = 0; + SDL_DisplayMode **ms = SDL_GetFullscreenDisplayModes(d, &count); + bool found = false; + for (int i = 0; ms && i < count; i++) { + WinSize m = {(int)lroundf(ms[i]->w * ms[i]->pixel_density), (int)lroundf(ms[i]->h * ms[i]->pixel_density)}; + if (same(m, s) && (!found || ms[i]->refresh_rate > out->refresh_rate)) *out = *ms[i], found = true; + } + SDL_free(ms); + return found; +} + // Read display d (its desktop size, modes, refresh rate) when it isn't the one read last (0: the primary) static void refresh_display(SDL_DisplayID d) { if (!d) d = SDL_GetPrimaryDisplay(); @@ -281,6 +294,13 @@ static void refresh_display(SDL_DisplayID d) { WinSize desk = {(int)lroundf(dm->w * density), (int)lroundf(dm->h * density)}; const SDL_DisplayMode *cur = SDL_GetCurrentDisplayMode(d); // (exclusive fullscreen: the mode in use) float hz = cur && cur->refresh_rate > 0 ? cur->refresh_rate : dm->refresh_rate; + SDL_DisplayMode max_mode; + if (find_mode(d, desk, &max_mode) && max_mode.refresh_rate > hz) { + // If the monitor supports a higher refresh rate for its desktop resolution + // (e.g. Windows 11 Dynamic Refresh Rate / power savings reporting 60 Hz while the panel is 165 Hz), + // adopt the true panel refresh rate unless locked in exclusive fullscreen at another rate. + if (!cur || cur == dm) hz = max_mode.refresh_rate; + } settings_fps_for_display(hz); // (Frame rate > Match display) pthread_mutex_lock(&g_m); g_hz = hz; @@ -315,19 +335,6 @@ void winsize_refresh(void *win) { refresh_display(win ? SDL_GetDisplayForWindow((SDL_Window *)win) : target_display()); } -// The display's mode of that size with the highest refresh rate (NULL: none) -static bool find_mode(SDL_DisplayID d, WinSize s, SDL_DisplayMode *out) { - int count = 0; - SDL_DisplayMode **ms = SDL_GetFullscreenDisplayModes(d, &count); - bool found = false; - for (int i = 0; ms && i < count; i++) { - WinSize m = {(int)lroundf(ms[i]->w * ms[i]->pixel_density), (int)lroundf(ms[i]->h * ms[i]->pixel_density)}; - if (same(m, s) && (!found || ms[i]->refresh_rate > out->refresh_rate)) *out = *ms[i], found = true; - } - SDL_free(ms); - return found; -} - void winsize_apply(void *win) { SDL_Window *w = (SDL_Window *)win; if (!w) return; @@ -368,13 +375,24 @@ void winsize_apply(void *win) { // (Exclusive), or for none (Borderless: another size is the image scaled to the screen) int fm = g_settings.fullscreen_mode; SDL_DisplayMode mode; - bool want_mode = fm == FSMODE_EXCLUSIVE || (fm != FSMODE_BORDERLESS && !same(s, desk)); - bool exclusive = want_mode && find_mode(d, s, &mode); + bool has_mode = find_mode(d, s, &mode); + const SDL_DisplayMode *dm = d ? SDL_GetDesktopDisplayMode(d) : NULL; + bool higher_hz = has_mode && dm && (mode.refresh_rate > dm->refresh_rate + 1.0f); + bool want_mode = fm == FSMODE_EXCLUSIVE || (fm != FSMODE_BORDERLESS && (!same(s, desk) || higher_hz)); + bool exclusive = want_mode && has_mode; if (!same(s, desk) && !exclusive) virt = s; SDL_SetWindowFullscreenMode(w, exclusive ? &mode : NULL); // (NULL: borderless, the desktop's size) SDL_SetWindowFullscreen(w, true); - if (exclusive) LOG("[window] fullscreen %dx%d (display mode, %.2f Hz)\n", s.w, s.h, mode.refresh_rate); - else LOG("[window] fullscreen %dx%d (%s)\n", s.w, s.h, virt.w ? "borderless, image scaled to the screen" : "borderless"); + if (exclusive) { + float mode_hz = mode.refresh_rate > 0 ? mode.refresh_rate : winsize_refresh_rate(); + pthread_mutex_lock(&g_m); + g_hz = mode_hz; + pthread_mutex_unlock(&g_m); + settings_fps_for_display(mode_hz); + LOG("[window] fullscreen %dx%d (display mode, %.2f Hz)\n", s.w, s.h, mode.refresh_rate); + } else { + LOG("[window] fullscreen %dx%d (%s)\n", s.w, s.h, virt.w ? "borderless, image scaled to the screen" : "borderless"); + } } else { SDL_SetWindowFullscreen(w, false); if (!keep_size) { diff --git a/tests/test_cursor_math.c b/tests/test_cursor_math.c index d7a9f746c..6f24fa8be 100644 --- a/tests/test_cursor_math.c +++ b/tests/test_cursor_math.c @@ -5,15 +5,23 @@ int main(void) { int sizes[][2]={{1280,720},{1920,1080},{2560,1440},{3840,2160},{2560,1080},{1280,1024},{1920,1200}}; for(unsigned i=0;i #include "../runtime/nvn/output_scale.c" Settings g_settings = {.wide_view = true, .fov = 100, .render_scale = RSCALE_100}; -static bool title, loading, map; +static bool title, loading, map, pause; +bool framepace_menu_ui(void) { return pause; } bool framepace_map_ui(void) { return map; } bool framepace_title_ui(void) { return title; } bool framepace_loading_ui(void) { return loading; } @@ -27,32 +28,66 @@ int main(void) { near(o.vx, 0); near(o.vy, 0); near(1920 * o.sx, 1280); near(1080 * o.sy, 800); + pause = true; + g_settings.hud_edges = true; +#ifndef __APPLE__ + assert(fabsf(output_pause_extra_y() - 40) < .001f); + assert(fabsf(output_ui_extra_y() - 40) < .001f); + g_settings.hud_edges = false; + near(output_pause_extra_y(), 0); + g_settings.hud_edges = true; + map = true; + near(output_pause_extra_y(), 0); + map = false; +#endif + pause = false; + near(output_pause_extra_y(), 0); output_scale(1280, 800, false, &o); near(o.shape, 1); near(o.vh, 720); near(o.vy, 40); title = true; output_scale(1280, 800, true, &o); - near(o.shape, 1); near(o.vh, 720); +#ifdef __APPLE__ + near(o.shape, 1); near(o.vh, 720); near(o.vy, 40); +#else + near(o.shape, .9); near(o.vh, 800); near(o.vy, 0); +#endif + output_scale(2560, 1080, true, &o); + near(o.shape, 1); near(o.vw, 1920); near(o.vx, 320); title = false; loading = true; output_scale(1280, 800, true, &o); + near(o.shape, .9); near(o.vh, 800); near(o.vy, 0); + near(1920 * o.sx, 1280); near(1080 * o.sy, 800); + output_scale(1280, 800, false, &o); near(o.shape, 1); near(o.vh, 720); + output_scale(2560, 1080, true, &o); + near(o.shape, 1); near(o.vw, 1920); near(o.vx, 320); loading = false; output_scale(1920, 1200, true, &o); near(o.shape, .9); near(o.vh, 1200); - // Clip the map's overscan without changing its targets, projection or pointer mapping. + // A full-height map reveals more terrain within the original pixel scale. map = true; output_scale(1280, 800, true, &o); - near(o.shape, .9); near(o.vw, 1280); near(o.vh, 720); near(o.vy, 40); - near(o.crop[1], .05); near(o.crop[3], .9); +#ifdef __APPLE__ + near(o.shape, .9); near(o.vh, 720); near(o.vy, 40); + near(output_map_extra_y(), 0); + output_scale(1024, 768, true, &o); + near(o.vh, 576); near(o.vy, 96); near(output_map_extra_y(), 0); +#else + near(o.shape, .9); near(o.vw, 1280); near(o.vh, 800); near(o.vy, 0); + near(o.crop[1], 0); near(o.crop[3], 1); + near(output_map_extra_y(), 40); near(1920 * o.sx, 1280); near(1080 * o.sy, 800); - // One source pixel still maps to one window pixel: cropping must not stretch the map. - near(1080 * o.sy * o.crop[3], o.vh); output_scale(1024, 768, true, &o); - near(o.vh, 576); near(o.vy, 96); near(o.crop[3], .75); - near(1080 * o.sy * o.crop[3], o.vh); + near(o.vh, 768); near(o.vy, 0); near(o.crop[3], 1); + near(output_map_extra_y(), 120); +#endif + output_scale(1280, 1024, true, &o); + near(o.vh, 720); near(o.vy, 152); + near(output_map_extra_y(), 0); output_scale(1280, 800, false, &o); - near(o.vh, 720); near(o.crop[3], 1); + near(o.vh, 720); near(o.crop[3], 1); near(output_map_extra_y(), 0); output_scale(1920, 1080, true, &o); near(o.vh, 1080); near(o.crop[3], 1); output_scale(2560, 1080, true, &o); @@ -60,5 +95,5 @@ int main(void) { map = false; output_scale(1280, 800, true, &o); near(o.vh, 800); near(o.crop[3], 1); - puts("PASS: map overscan clipped at 16:10 and 4:3; gameplay, disabled fill, title, loading, 16:9 and ultrawide unchanged"); + puts("PASS: taller map viewport, 16:9 fallback, disabled fill, title, loading and ultrawide"); } diff --git a/tests/test_pc_controls.c b/tests/test_pc_controls.c index 382694307..4837cc493 100644 --- a/tests/test_pc_controls.c +++ b/tests/test_pc_controls.c @@ -31,6 +31,7 @@ bool menu_input_captured(void) { return captured; } bool prof_toggle(void) { return false; } bool menu_cursor_free(void) { return freed; } void vibration_update(SDL_Gamepad *p, bool focused) { (void)p; (void)focused; } +void vibration_pad_closed(SDL_Gamepad *p) { (void)p; } void motion_tilt_held(bool held) { motion_tilt = held; } bool pc_gyro_keyboard_active(void) { return gyro_active; } void motion_keyboard(int p,int r,int y,bool reset) { gyro_pitch=p;gyro_roll=r;gyro_yaw=y;gyro_reset=reset; } diff --git a/tests/test_ui_layout.c b/tests/test_ui_layout.c new file mode 100644 index 000000000..d9df6502f --- /dev/null +++ b/tests/test_ui_layout.c @@ -0,0 +1,182 @@ +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include "../runtime/ui_layout.c" +#include "../runtime/nvn/cmdbuf.c" +#include "../runtime/nvn/hud_scale.h" + +GameSites g_site; +const char *g_game_version = "1.9.0"; +Settings g_settings = {.hud_edges = true, .hud_size = 100}; +void kmutex_lock(KMutex *m) { assert(!pthread_mutex_lock(&m->pm)); } +void kmutex_unlock(KMutex *m) { assert(!pthread_mutex_unlock(&m->pm)); } +uint64_t renderer_present_count(void) { return 1; } +uint32_t kernel_current_thread_handle(void) { return 1; } +uint64_t plat_now_ns(void) { return 1; } +bool nvn_timeline(void) { return false; } +void rt_fatal_trace(void) { abort(); } +void guest_call(Cpu *c, uint64_t address) { (void)c; (void)address; assert(!"unexpected guest callback"); } + +static bool pause_menu; +bool framepace_menu_ui(void) { return pause_menu; } +static unsigned calls; +static void native_draw(Cpu *c) { calls++; c->x[5] = 123; } + +static void native_pane(Cpu *c) { + if (rt_ui_layout_pane_draw(c, native_pane)) return; + calls++; c->x[5] = 456; +} + +static unsigned scope_at(uint64_t at) { + CmdRec *r = (CmdRec *)(uintptr_t)at; + if (r->op == CMD_JUMP) r = (CmdRec *)(uintptr_t)r->x[0]; + assert(r->op == CMD_UI_SCOPE); + return r->x[0]; +} + +int main(void) { + // Unsupported versions and disabled options must not inspect version-specific guest fields. + Cpu unsupported = {0};g_site.screen_mgr=1;g_game_version="unknown"; + assert(!ui_layout_begin(&unsupported)); + g_game_version="1.9.0";g_settings.hud_edges=false; + assert(!ui_layout_begin(&unsupported)); + g_site.screen_mgr=0;g_settings.hud_edges=true; + float crop[27] = {0};crop[23] = 1.8359375f;crop[24] = .440625f;crop[25] = .17777778f; + assert(hud_capture_crop(crop, .9f, -.1f)); + assert(fabsf((.5f+crop[23]*crop[25])*800-675)<.001f); + assert(fabsf(crop[25]-.16f)<.00001f); + crop[22]=.3f;crop[23]=1.1f;crop[25]=.2f;crop[26]=.6f; + float u0=.5f+crop[24]*(cosf(crop[26])*crop[22]-sinf(crop[26])*crop[23]); + float v0=.5f+crop[25]*(sinf(crop[26])*crop[22]+cosf(crop[26])*crop[23]); + assert(hud_capture_crop(crop,.9f,-.1f)); + float u1=.5f+crop[24]*(cosf(crop[26])*crop[22]-sinf(crop[26])*crop[23]); + float v1=.5f+crop[25]*(sinf(crop[26])*crop[22]+cosf(crop[26])*crop[23]); + assert(fabsf(u1-u0)<1e-6f&&fabsf(v1-(.5f+.9f*(v0-.5f)+.05f))<1e-6f); + crop[25]=0;assert(!hud_capture_crop(crop,.9f,-.1f)); + uint64_t base = HEAP_BASE; +#ifdef _WIN32 + assert(VirtualAlloc((void *)(uintptr_t)base, 0x10000, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE) == (void *)(uintptr_t)base); +#else + assert(mmap((void *)(uintptr_t)base, 0x10000, PROT_READ|PROT_WRITE, + MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE, -1, 0) != MAP_FAILED); +#endif + uint64_t manager = base + 0x100, slots = base + 0x200, screen = base + 0x1000; + uint64_t context = base + 0x2000, wrapper = base + 0x3000, commands = base + 0x4000; + g_site.screen_mgr = base; + ST64(base, manager); ST32(manager+0x28, 99); ST64(manager+0x30, slots); + ST64(slots+8*0x25, screen); ST64(context+0x20, wrapper); + ST64(wrapper+8, 0x11); ST64(wrapper+0xb8, commands); + Cpu c = {0}; c.x[0] = screen; c.x[1] = context; + // Inactive layouts must return before touching an unusable render context. + c.x[1] = 0; assert(!ui_layout_begin(&c)); + rt_ui_layout_draw(&c, native_draw); assert(calls == 1); calls = 0; + ST8(screen+0x100, 1); ST8(screen+0xfe, 2); c.x[1] = context; + for (unsigned i = 0; i < 4; i++) { + ST8(screen+0x100, i == 0 ? 0 : 1); ST8(screen+0x102, i == 1); + ST8(screen+0xfe, i == 2 ? 0 : 3); ST8(screen+0xff, i == 3 ? 2 : 0); + c.x[1] = 0; assert(!ui_layout_begin(&c)); + } + ST8(screen+0x100, 1); ST8(screen+0x102, 0); ST8(screen+0xfe, 3); ST8(screen+0xff, 0); + c.x[1] = context; + ST64(commands, 0x11); // the previously crashing non-NVN object is rejected without dereference + assert(!ui_layout_begin(&c)); + Cpu init = {0}; init.x[0] = commands; hle_nvnCommandBufferInitialize(&init); + assert(!ui_layout_begin(&c)); // initialized but not recording + cb_of(commands)->recording = true; + assert(!ui_layout_begin(&c)); // no initial host storage; must not call the guest allocator + cb_of(commands)->recording = false; + init.x[0] = commands; hle_nvnCommandBufferBeginRecording(&init); + NvnCmdBuf *cb = cb_of(commands); + cb->gused = cb->gsize + 16; cb->callback = 123; + uint64_t guest_used = cb->gused; + Cpu original = c; rt_ui_layout_draw(&c, native_draw); + original.x[5] = 123; + assert(!memcmp(&c, &original, sizeof c) && calls == 1 && cb->gused == guest_used); + CmdRec *begin = (CmdRec *)(uintptr_t)(cb->start + sizeof(CmdRec)); + CmdRec *end = (CmdRec *)((char *)begin + begin->size); + assert(begin->op == CMD_UI_SCOPE && begin->x[0] == UI_LAYOUT_HUD); + assert(end->op == CMD_UI_SCOPE && end->x[0] == UI_LAYOUT_NONE); + // MainScreen3D and Time use the same stable HUD policy as the flat HUD. + ST64(slots+8*0x25, 0); ST64(slots+8*0x2, screen); + uint64_t at = cb->mem + cb->used; + rt_ui_layout_draw(&c, native_draw); + assert(scope_at(at) == UI_LAYOUT_HUD); + ST64(slots+8*0x2, 0); ST64(slots+8*0x1c, screen); + at = cb->mem + cb->used; rt_ui_layout_draw(&c, native_draw); + assert(scope_at(at) == UI_LAYOUT_HUD); + ST64(slots+8*0x1c, 0); ST64(slots+8*0x2a, screen); + for (unsigned paused = 0; paused < 2; paused++) { + pause_menu = paused; at = cb->mem + cb->used; + rt_ui_layout_draw(&c, native_draw); + assert(scope_at(at) == (paused ? UI_LAYOUT_MENU : UI_LAYOUT_HUD)); + } + // Native MiniMap endpoints, not the global pause state, choose the presentation. + uint64_t animation = base + 0x6000, resource = base + 0x7000; + ST64(screen+0x3640, animation); ST64(animation+0x18, resource); ST16(resource+8, 1); + float map_frame = 0; memcpy((void *)(uintptr_t)(animation+0x20), &map_frame, 4); + pause_menu = false; assert(ui_layout_map_mode(screen) == 1); + at = cb->mem + cb->used; rt_ui_layout_draw(&c, native_draw); assert(scope_at(at) == UI_LAYOUT_MENU); + map_frame = 1; memcpy((void *)(uintptr_t)(animation+0x20), &map_frame, 4); + pause_menu = true; assert(ui_layout_map_mode(screen) == 0); + at = cb->mem + cb->used; rt_ui_layout_draw(&c, native_draw); assert(scope_at(at) == UI_LAYOUT_HUD); + map_frame = NAN; memcpy((void *)(uintptr_t)(animation+0x20), &map_frame, 4); + assert(ui_layout_map_mode(screen) == -1); + ST64(animation+0x18, GUEST_HI-4); assert(ui_layout_map_mode(screen) == -1); + ST64(screen+0x3640, 0); assert(ui_layout_map_mode(screen) == -1); + ST64(slots+8*0x2a, 0); + // Quest notifications, item cards and complete quick selectors retain native geometry. + const unsigned native_slots[] = {0xb, 0x27, 0x2d}; + for (unsigned i = 0; i < 3; i++) { + ST64(slots+8*native_slots[i], screen); at = cb->mem + cb->used; + rt_ui_layout_draw(&c, native_draw); assert(scope_at(at) == UI_LAYOUT_DIALOGUE); + ST64(slots+8*native_slots[i], 0); + } + ST64(slots+8*0x4a, screen); + at = cb->mem + cb->used; rt_ui_layout_draw(&c, native_draw); + assert(scope_at(at) == UI_LAYOUT_TALK); + // The quest title is a part inside MainScreen, not the separate ChallengeWin screen. + uint64_t pane = base + 0x8000, pane_wrapper = base + 0x9000, controller = base + 0xa000; + ST64(slots+8*0x25, screen); ST64(screen+0x3cc0, controller); + memcpy((void *)(uintptr_t)(pane+0xb8), "Pa_QuestName_00", sizeof "Pa_QuestName_00"); + ST64(pane+0xf0, controller); ST64(pane_wrapper+0xb0, commands); + Cpu part = {0}; part.x[0] = pane; part.x[2] = pane_wrapper; + assert(nvn_ui_scope(commands, UI_LAYOUT_HUD)); + unsigned previous_calls = calls; Cpu expected = part; expected.x[5] = 456; + at = cb->mem + cb->used; + assert(rt_ui_layout_pane_draw(&part, native_pane)); + assert(calls == previous_calls+1 && !memcmp(&part, &expected, sizeof part)); + CmdRec *part_begin = (CmdRec *)(uintptr_t)at; + if (part_begin->op == CMD_JUMP) part_begin = (CmdRec *)(uintptr_t)part_begin->x[0]; + CmdRec *part_end = (CmdRec *)((char *)part_begin+part_begin->size); + assert(part_begin->op == CMD_UI_SCOPE && part_begin->x[0] == UI_LAYOUT_DIALOGUE); + assert(part_end->op == CMD_UI_SCOPE && part_end->x[0] == UI_LAYOUT_NONE); + assert(rt_ui_layout_pane_draw(&part, native_pane) && calls == previous_calls+2); + ST64(pane+0xf0, controller+8); assert(!rt_ui_layout_pane_draw(&part, native_pane)); + ST64(pane+0xf0, controller); part.x[2] = 0; assert(!rt_ui_layout_pane_draw(&part, native_pane)); + assert(nvn_ui_scope(commands, UI_LAYOUT_NONE)); + // Nested cached lists restore the executing owner, including bounded overflow. + HudScope scope = {0}; + hud_scope_enter(&scope, UI_LAYOUT_HUD); hud_scope_enter(&scope, UI_LAYOUT_DIALOGUE); + assert(scope.kind == UI_LAYOUT_DIALOGUE); + hud_scope_leave(&scope); assert(scope.kind == UI_LAYOUT_HUD); + for (int i = 0; i < 40; i++) hud_scope_enter(&scope, UI_LAYOUT_CONTEXT); + for (int i = 0; i < 40; i++) hud_scope_leave(&scope); + assert(scope.kind == UI_LAYOUT_HUD); + hud_scope_leave(&scope); assert(!scope.kind && !scope.depth && !scope.overflow); + cb->gused = 0; cb->callback = 0; + init.x[0] = commands; hle_nvnCommandBufferEndRecording(&init); + init.x[0] = commands; hle_nvnCommandBufferFinalize(&init); + assert(!ui_layout_begin(&c) && !g_command_buffers); + cmdbuf_shadow_reset(); + assert(!g_command_buffers); +#ifdef _WIN32 + VirtualFree((void *)(uintptr_t)base, 0, MEM_RELEASE); +#else + munmap((void *)(uintptr_t)base, 0x10000); +#endif + puts("PASS: native eligibility, invalid/stopped NVN contexts, balanced deferred scopes, zero guest cost, CPU preservation and lifetime reset"); +} diff --git a/tools/game_sites.py b/tools/game_sites.py index 0ab35d908..7f59f0aea 100644 --- a/tools/game_sites.py +++ b/tools/game_sites.py @@ -216,6 +216,8 @@ Site('cam_stick', 'code', 'd100c3ff fd000be8 f90017f3 a901fbfd 910063fd aa0003f3 f900001f 52800060', 0), # (the end of the camera's stick input, with the stick's value written: tools/patches.py _cam_stick_end) Site('cam_stick_end', 'code', 'f9409408 910023e0 f90007e8 94000000/fc000000 360000c0 fd400be8 f94017f3', 5), + # CameraHorse's return address after calling the camera stick input (rt_cam_stick's lr, runtime/hle/input.c) + Site('horse_cam_lr', 'code', 'bd401ba0 1e202008 39416a68 54000001/ff00001f bd401fa0 1e202008 54000001/ff00001f 37180008/fff8001f', 0), Site('cam_pitch_chase', 'code', '1e208803 1e202008 bd41ce80 1e23cc2b bd41d281 1e212000 54000001/ff00001f ' '52800039', 0), Site('cam_pitch_surf', 'code', '1e208803 1e202008 bd430260 1e23cc2d bd430661 1e212000 54000001/ff00001f ' @@ -363,6 +365,10 @@ Site('pouch_item_get', 'code', 'd10243ff a9037bfd a9046ffc a90567fa a9065ff8 a90757f6 a9084ff4 9100c3fd f90003e3', 0), Site('pouch_mgr', 'got', '90000017/9f00001f aa0003f5 f94002f7/ffc003ff 910003e0 f94002f6 94000000/fc000000 2a0003e2 ' 'aa1603e0', 2), + # Generic layout draw thunk and its native eligibility checks (runtime/ui_layout.c). + Site('ui_layout_draw', 'code', '14000000/fc000000 f9013001 b4000001/ff00001f d10403ff a90a7bfd a90b6ffc a90c67fa a90d5ff8', 0), + Site('ui_layout_native', 'code', '39440008 7100011f 39440809 3943f80a 3943fc0b 7a401920 7a400944 7a421964', 0), + Site('ui_layout_pane', 'code', '39416008 52801029 6a28013f 54000001/ff00001f a9bd7bfd a90157f6 a9024ff4 910003fd', 0), Site('main_data', 'data', '', 0), Site('main_end', 'end', '', 0), ] @@ -373,6 +379,7 @@ # Without them the mouse turns the camera through the right stick, as before (runtime/hle/input.c); without the # second group it turns it without the game's camera inversion options. OPTIONAL_GROUPS = [ + ('ui_layout_draw', 'ui_layout_native', 'ui_layout_pane'), ('quick_drop_tick', 'quick_drop_actor_call', 'player_drop_forbidden', 'actor_info_lookup', 'actor_info_has_tag', 'pouch_discard', 'player_equipment', 'pouch_default_name', 'player_schedule_equip', 'pouch_equipped_snapshot', 'actor_index_assign', 'actor_index_resolve', @@ -413,11 +420,15 @@ ('stamina_store',), ('tp_gate',), # (a far teleport of the control endpoint: without it a long jump freezes the world) ('item_tick', 'pouch_item_get', 'pouch_mgr'), + ('horse_cam_lr',), ] OPTIONAL = {n for g in OPTIONAL_GROUPS for n in g} KNOWN = { '1.9.0': { + 'ui_layout_draw': 0x70013ee084, + 'ui_layout_native': 0x7000f6f690, + 'ui_layout_pane': 0x7000027d30, 'quick_drop_tick': 0x7000e68168, 'quick_drop_actor_call': 0x7001223f50, 'player_drop_forbidden': 0x7000cc0334, @@ -540,6 +551,7 @@ 'world_mgr': 0x7001e57580, 'cam_stick': 0x7000d57fe0, 'cam_stick_end': 0x7000d5801c, + 'horse_cam_lr': 0x7000c29000, 'cam_pitch_chase': 0x7000bf5334, 'cam_pitch_surf': 0x7000c1a52c, 'cam_pitch_wakeboard': 0x7000c22104, diff --git a/tools/patches.py b/tools/patches.py index 49de02ccc..dd89dff71 100644 --- a/tools/patches.py +++ b/tools/patches.py @@ -19,6 +19,28 @@ def _word(gen, a): return struct.unpack_from('x[8] = LD8(c->x[0] + 0x58); }}') + + def _quick_sort_enter(gen, a): # Menu::enter: sample held X before the selector initializes its list. assert _word(gen, a) == 0xfc1d0fe8, hex(_word(gen, a)) # str d8, [sp, #-0x30]! @@ -933,6 +955,8 @@ def _tp_gate(gen, a): PATCHES = { + 'ui_layout_draw': _ui_layout_draw, + 'ui_layout_pane': _ui_layout_pane, 'quick_drop_tick': _quick_drop_tick, 'quick_drop_actor_call': _quick_drop_actor_call, 'quick_sort_enter': _quick_sort_enter, diff --git a/tools/test_gyro_bindings.c b/tools/test_gyro_bindings.c index 4537742dc..f1ec26ecc 100644 --- a/tools/test_gyro_bindings.c +++ b/tools/test_gyro_bindings.c @@ -22,6 +22,7 @@ void plat_accessibility_shortcuts(bool allow) { (void)allow; } GameSites g_site; // (no game: runtime/hle/bindings.c finds no HUD prompt) Cpu *kernel_current_cpu(void){abort();} void vibration_update(SDL_Gamepad *p,bool f){(void)p;(void)f;abort();} +void vibration_pad_closed(SDL_Gamepad *p){(void)p;} bool menu_cursor_free(void){return false;} void motion_pad_opened(SDL_Gamepad*p){(void)p;abort();} void motion_pad_closed(void){abort();} diff --git a/tools/test_input_focus.c b/tools/test_input_focus.c index 239f8ec62..0d94d2122 100644 --- a/tools/test_input_focus.c +++ b/tools/test_input_focus.c @@ -14,6 +14,7 @@ uint64_t quick_drop_action_filter_buttons(uint64_t b) { return b; } #include "test_pointer_disabled.h" int bind_pad_family(int type, int vendor, int product, const char *name, bool first) { (void)type, (void)vendor, (void)product, (void)name, (void)first; return 0; } +GameSites g_site; Settings g_settings; int16_t g_bind_key[BIND_KEY_COUNT], g_bind_pad[BIND_KEY_COUNT]; uint64_t g_watch_lo, g_watch_hi; @@ -29,8 +30,10 @@ void motion_pad_opened(SDL_Gamepad *p) { (void)p; } void motion_pad_closed(void) {} void motion_sensor_event(const SDL_Event *e) { (void)e; sensor_events++; } void vibration_update(SDL_Gamepad *p, bool focused) { (void)p; vibrating = focused; } +void vibration_pad_closed(SDL_Gamepad *p) { (void)p; } uint64_t renderer_present_count(void) { return 0; } -uint64_t plat_now_ns(void) { return 0; } +static uint64_t test_now_ns; +uint64_t plat_now_ns(void) { return test_now_ns; } void plat_accessibility_shortcuts(bool allow) { (void)allow; } // PE linkers also keep exported helpers from input.c. These paths are outside this harness. @@ -61,6 +64,7 @@ void freecam_pad(float lx, float ly, float rx, float ry, float up, float down, b (void)lx; (void)ly; (void)rx; (void)ry; (void)up; (void)down; (void)fast; (void)slow; } void control_input_frame(uint64_t frame) { (void)frame; } +void photo_pad(uint32_t buttons) { (void)buttons; } void control_input_apply(uint64_t *b, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) { (void)b; (void)lx; (void)ly; (void)rx; (void)ry; } bool pc_gyro_keyboard_active(void) { return false; } void pc_gyro_scene_tick(void) {} @@ -106,6 +110,25 @@ static void sample_raw(uint64_t buttons, bool tilted, uint64_t raw) { } static void sample(uint64_t buttons, bool tilted) { sample_raw(buttons, tilted, buttons); } +static void steering_axes(int32_t key_x, int32_t key_y, int32_t pad_y, bool riding, + int32_t expected_x, int32_t expected_y) { + key_lx = key_x; + key_ly = key_y; + pad_lx = 0; + pad_ly = pad_y; + script_lx = script_ly = 0; + g_site.horse_cam_lr = 0x1234; + horse_cam_ns = riding ? test_now_ns : 0; + + uint64_t state[5] = {0}; + uint32_t id = 0; + Cpu c = {0}; + c.x[0] = (uintptr_t)state; + c.x[1] = (uintptr_t)&id; + fill_state(&c); + int32_t *sticks = (int32_t *)((uint8_t *)state + 16); + assert(sticks[0] == expected_x && sticks[1] == expected_y); +} static void controls(SDL_Joystick *joy, bool held) { assert(SDL_SetJoystickVirtualButton(joy, SDL_GAMEPAD_BUTTON_EAST, held)); @@ -225,8 +248,24 @@ int main(void) { pump(); sample(0, false); SDL_CloseJoystick(joy); + + // While mounted, keyboard forward is suppressed when steering; other input sources stay unchanged. + focus(true); + test_now_ns = 1000000000; + g_site.horse_cam_lr = 0; + horse_cam_ns = test_now_ns; + cam_caller(0x1234, test_now_ns); + assert(!horse_riding()); + g_site.horse_cam_lr = 0x1234; + cam_caller(0x1234, test_now_ns); + assert(horse_riding()); + steering_axes(32767, 32767, 0, true, 32767, 0); + steering_axes(-32767, 32767, 0, true, -32767, 0); + steering_axes(0, 32767, 0, true, 0, 32767); + steering_axes(-32767, 0, 0, true, -32767, 0); + steering_axes(32767, 32767, 5000, true, 32767, 5000); + steering_axes(32767, 32767, 0, false, 32767, 32767); + SDL_Quit(); puts("input focus checks passed"); } - -void photo_pad(uint32_t buttons) { (void)buttons; } diff --git a/tools/test_ui_layout_codegen.py b/tools/test_ui_layout_codegen.py new file mode 100644 index 000000000..9b7a8f62d --- /dev/null +++ b/tools/test_ui_layout_codegen.py @@ -0,0 +1,48 @@ +"""Synthetic tests for the independently resolved UI draw thunk; no game data required.""" +import struct +from types import SimpleNamespace +import game_sites +import patches + +base, thunk, native = 0x7100000000, 0x7100000080, 0x7100000020 +gates = (0x39440008, 0x7100011f, 0x39440809, 0x3943f80a, + 0x3943fc0b, 0x7a401920, 0x7a400944, 0x7a421964) +image = bytearray(0x100) +branch = 0x14000000 | (((native - thunk) // 4) & 0x3ffffff) +struct.pack_into('sp' not in code and 'c->x[' not in code +assert patches.table(g.sites)[thunk] is patches._ui_layout_draw +assert ('ui_layout_draw', 'ui_layout_native', 'ui_layout_pane') in game_sites.OPTIONAL_GROUPS +for at, wrong in [(thunk, branch | 0x80000000), (thunk, branch + 1), + *[(native + 4*i, word ^ 1) for i, word in enumerate(gates)]]: + saved = struct.unpack_from('x[8] = LD8(c->x[0] + 0x58);' in code +assert patches.table(g.sites)[pane] is patches._ui_layout_pane +struct.pack_into(' SDL checks, with no game files or physical controller. make test-vibration #include #include +#include #include "../runtime/hle/vibration.c" #include "../runtime/services/hid_set.c" @@ -10,12 +11,27 @@ static uint64_t now; static unsigned calls; static uint16_t motor_low, motor_high; static uint32_t duration; +static int rumble_delay_ms; +static void sleep_ms(int ms) { + struct timespec ts = {.tv_sec = ms / 1000, .tv_nsec = (long)(ms % 1000) * 1000000L}; + nanosleep(&ts, NULL); +} +static double mono_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000.0 + ts.tv_nsec / 1000000.0; +} Uint64 SDL_GetTicks(void) { return now; } bool SDL_RumbleGamepad(SDL_Gamepad *pad, Uint16 low, Uint16 high, Uint32 ms) { assert(pad); + if (rumble_delay_ms > 0) sleep_ms(rumble_delay_ms); motor_low = low; motor_high = high; duration = ms; calls++; return true; } +static void update_sync(SDL_Gamepad *pad, bool focused) { + vibration_update(pad, focused); + vibration_flush(); +} const char *SDL_GetError(void) { return "test"; } // Unrelated HID / settings dependencies. Keep the returned vibration object callable. @@ -57,11 +73,11 @@ int main(void) { VibrationValue value = {.25f, 160, .5f, 320}; memcpy(packet, &left, 4); memcpy(packet + 4, &value, sizeof value); command(201, packet, sizeof packet); - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 16384 && motor_high == 32768 && duration == 100); unsigned before = calls; - now = 49; vibration_update(pad, true); assert(calls == before); - now = 50; vibration_update(pad, true); assert(calls == before + 1); + now = 49; update_sync(pad, true); assert(calls == before); + now = 50; update_sync(pad, true); assert(calls == before + 1); resp = command(202, packet, 16); assert(resp.data_size == sizeof value && memcmp(resp.data, &value, sizeof value) == 0); command(201, packet, 4); // truncated: leave the current effect alone @@ -72,7 +88,7 @@ int main(void) { IpcReq req = {.cmd = 206, .nx = 2, .x = { {(uintptr_t)handles, sizeof handles}, {(uintptr_t)batch, sizeof batch}}}; resp = (IpcResp){0}; hid(NULL, &req, &resp); - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 49151 && motor_high == 58982); // Bound iteration by the shorter buffer; an incomplete trailing value must not be read. batch[0].low_amplitude = .6f; req.x[1].size = sizeof(VibrationValue) + 1; @@ -81,54 +97,72 @@ int main(void) { // The player's toggle stops active motors without changing the game's HID permission. g_settings.rumble = false; - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 0 && motor_high == 0 && vibration_permitted()); command(201, packet, sizeof packet); assert(vibration_get(left).low_amplitude == 0); vibration_reset(); assert(!g_settings.rumble); // returning to the title screen preserves the preference g_settings.rumble = true; - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 0 && motor_high == 0); // no stale effect after re-enabling command(201, packet, sizeof packet); - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 16384 && motor_high == 32768); // Rumble strength scales the motor output proportionally. g_settings.rumble_strength = 50; - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 8192 && motor_high == 16384); g_settings.rumble_strength = 100; - vibration_update(pad, true); + update_sync(pad, true); assert(motor_low == 16384 && motor_high == 32768); uint8_t allow = 0; command(204, &allow, 1); - vibration_update(pad, true); assert(motor_low == 0 && motor_high == 0); + update_sync(pad, true); assert(motor_low == 0 && motor_high == 0); command(201, packet, sizeof packet); assert(vibration_get(left).low_amplitude == 0); allow = 1; command(204, &allow, 1); - vibration_update(pad, true); assert(motor_low == 0); // do not resume an old effect + update_sync(pad, true); assert(motor_low == 0); // do not resume an old effect value = (VibrationValue){NAN, 160, INFINITY, 320}; - vibration_send(left, &value); vibration_update(pad, true); + vibration_send(left, &value); update_sync(pad, true); assert(motor_low == 0 && motor_high == 0); value = (VibrationValue){-1, 160, 2, 320}; - vibration_send(left, &value); vibration_update(pad, true); + vibration_send(left, &value); update_sync(pad, true); assert(motor_low == 0 && motor_high == 65535); value = (VibrationValue){1, 160, 1, 320}; vibration_send(0x00000103, &value); // player 2: must not drive player 1 assert(vibration_get(left).low_amplitude == 0); vibration_send(0, &value); assert(vibration_get(left).low_amplitude == 0); - vibration_update(pad, false); assert(motor_high == 0); - vibration_update(pad, true); assert(motor_high == 0); + update_sync(pad, false); assert(motor_high == 0); + update_sync(pad, true); assert(motor_high == 0); vibration_send(0x00002003, &value); // handheld aliases the same physical controller - vibration_update(pad, true); assert(motor_low == 65535); - vibration_update(NULL, false); - vibration_update(pad, true); assert(vibration_get(left).low_amplitude == 0); + update_sync(pad, true); assert(motor_low == 65535); + update_sync(NULL, false); + update_sync(pad, true); assert(vibration_get(left).low_amplitude == 0); vibration_send(left, &value); command(210, NULL, 0); - vibration_update(pad, true); assert(motor_low == 0); + update_sync(pad, true); assert(motor_low == 0); vibration_send(left, &value); vibration_reset(); - vibration_update(pad, true); assert(motor_low == 0 && vibration_permitted()); - puts("vibration: HID packets, batching, motors, focus, disconnect and reboot checks passed"); + update_sync(pad, true); assert(motor_low == 0 && vibration_permitted()); + + // Slow blocking SDL_RumbleGamepad (e.g. Bluetooth DualSense on Windows) must not block vibration_update, + // and rapid updates while in flight must coalesce to the latest request. + rumble_delay_ms = 40; + unsigned before_slow = calls; + double t0 = mono_ms(); + for (int step = 1; step <= 10; step++) { + value = (VibrationValue){step * 0.1f, 160, 0, 320}; + vibration_send(left, &value); + vibration_update(pad, true); + } + double elapsed = mono_ms() - t0; + assert(elapsed < 20.0); + vibration_flush(); + assert(motor_low == 65535 && calls - before_slow < 10); + vibration_pad_closed(pad); + rumble_delay_ms = 0; + + puts("vibration: HID packets, batching, motors, focus, disconnect, async rumble and reboot checks passed"); return 0; } From 73ef7c2c48e444f9a5a3d2a384bdebc39a8852d6 Mon Sep 17 00:00:00 2001 From: guill Date: Fri, 13 Nov 2026 16:14:52 -0500 Subject: [PATCH 04/18] Vulkan: less CPU per draw (PRs #762, #763) Two per-draw shortcuts in the render thread, measured clean at about +2% fps where the CPU is the limit (720p) and +1% at 1080p: - gw_check is skipped when no vertex/uniform buffer and no GPU-written range changed since the last clean check, and snapshot invalidation only walks populated slots (#762). - resolve_feedback is skipped while the render targets and textures stay the same and the last draw had no feedback, and vertex streams are bound by bit-scan over the used ones (#763). Co-authored-by: jfpaardoo Co-Authored-By: Claude Opus 5.5 --- runtime/nvn/vulkan/exec.c | 65 ++++++++++++++++++++++++++++++++------- 1 file changed, 54 insertions(+), 11 deletions(-) diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index 3360e87e5..4ba556efc 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -1361,8 +1361,16 @@ const char *renderer_stats(void) { return stats_text; } +static uint64_t vbuf_gen = 1; +static uint64_t ubuf_gen[6] = {1, 1, 1, 1, 1, 1}; +static uint64_t rt_gen = 1, tex_gen[6] = {1, 1, 1, 1, 1, 1}; + static void st_defaults(void) { memset(&st, 0, sizeof st); + vbuf_gen++; + for (int i = 0; i < 6; i++) ubuf_gen[i]++; + rt_gen++; + for (int i = 0; i < 6; i++) tex_gen[i]++; for (int i = 0; i < 16; i++) { st.viewport[i][2] = 1280; st.viewport[i][3] = 720; st.scissor[i][2] = 16384; st.scissor[i][3] = 16384; @@ -3960,12 +3968,15 @@ static const char *snap_reason = "?"; // A snapshot of texture object t, or of its image through another object (BOTW reaches some targets through more than // one), is stale once t is written. SAVAGEWIND_VK_SNAP_BY_OBJECT=1: by object only, as before. static uint64_t snap_wpass[8]; // (the pass the latest write into the slot's target was in, since its snapshot; 0: none) +static uint8_t snap_mask; static uint64_t snap_pass_now(void); static void snapshots_invalidate(NvnTexture *t) { + if (!snap_mask) return; static int by_obj = -1; if (by_obj < 0) by_obj = getenv("SAVAGEWIND_VK_SNAP_BY_OBJECT") ? atoi(getenv("SAVAGEWIND_VK_SNAP_BY_OBJECT")) != 0 : !g_vk.is_mali; TexBackend *be = t && !by_obj ? (TexBackend *)t->backend : NULL; - for (int i = 0; i < 8; i++) { + for (uint32_t m = snap_mask; m; m &= m - 1) { + int i = __builtin_ctz(m); if (!(!t || snap_tex[i] == t || (be && snap_be[i] == be))) continue; if (t) snap_wpass[i] = snap_pass_now(); if (snap_ok[i]) { snap_ok[i] = false; snap_why[i] = snap_reason; } @@ -4194,6 +4205,10 @@ static void resolve_feedback(Prog *pr) { static int off = -1; if (off < 0) off = getenv("SAVAGEWIND_NO_FEEDBACK") != NULL; if (off) return; + static struct { const ShaderInfo *vi, *fi; const void *tpool; uint64_t rt_gen, tgen0, tgen1; } rf_clean; + if (rf_clean.vi == pr->vi && rf_clean.fi == pr->fi && rf_clean.tpool == st.tpool && + rf_clean.rt_gen == rt_gen && rf_clean.tgen0 == tex_gen[0] && rf_clean.tgen1 == tex_gen[1]) + return; ShaderInfo *infos[2] = {pr->vi, pr->fi}; for (int sg = 0; sg < 2; sg++) for (int i = 0; i < infos[sg]->ntex; i++) { @@ -4525,6 +4540,7 @@ static void resolve_feedback(Prog *pr) { feedback_any_type[nfeedback] = false; feedback_view[nfeedback++] = vk_image_view(dst, VK_IMAGE_VIEW_TYPE_2D, src->format, 0, 1, 0, 1, id, sa); if (si < 0) { static int rr; si = rr++ & 7; snap_tex[si] = t; } + snap_mask |= (uint8_t)(1u << si); snap_ok[si] = true; snap_cleared[si] = false; snap_wpass[si] = 0; @@ -4533,6 +4549,10 @@ static void resolve_feedback(Prog *pr) { snap_pass[si] = pass_serial + 1; // (the pass that begins next, after this one ends) st.rt_dirty = true; } + if (!nfeedback && !draw_feedback) + rf_clean = (__typeof__(rf_clean)){pr->vi, pr->fi, st.tpool, rt_gen, tex_gen[0], tex_gen[1]}; + else + rf_clean.vi = NULL; } // ================================================================== resource binding @@ -5913,16 +5933,34 @@ static bool gw_ubo_copied(int stage, uint32_t cbuf_mask) { // a constant buffer // cbufs[stage]: the constant buffers each stage reads (ShaderInfo.cbuf_mask; 0: none). static void gw_check(const uint32_t cbufs[6], bool vertices, uint64_t iaddr, uint64_t isize) { if (!ngw) return; + static uint64_t chk_vbuf_gen, chk_vbuf_gw, chk_ubuf_gen[6], chk_ubuf_gw[6], chk_ubuf_gc[6]; + static uint32_t chk_cbuf_mask[6]; + uint64_t gc = __atomic_load_n(&gcopy_gen, __ATOMIC_RELAXED); bool wait = false; - for (int s = 0; s < 6 && !wait; s++) - if (cbufs[s]) wait = gw_ubo_copied(s, cbufs[s]); + for (int s = 0; s < 6 && !wait; s++) { + uint32_t m = cbufs[s]; + if (!m) continue; + if (chk_ubuf_gen[s] == ubuf_gen[s] && chk_ubuf_gw[s] == gw_gen && chk_ubuf_gc[s] == gc && (chk_cbuf_mask[s] & m) == m) + continue; + wait = gw_ubo_copied(s, m); + if (!wait) { + if (chk_ubuf_gen[s] != ubuf_gen[s] || chk_ubuf_gw[s] != gw_gen || chk_ubuf_gc[s] != gc) { + chk_ubuf_gen[s] = ubuf_gen[s]; chk_ubuf_gw[s] = gw_gen; chk_ubuf_gc[s] = gc; chk_cbuf_mask[s] = m; + } else { + chk_cbuf_mask[s] |= m; + } + } + } VkBuffer b; VkDeviceSize off; // (the overlap first: it is rarely there, and guest_direct is the dearer of the two) - for (int i = 0; i < 16 && vertices && !wait; i++) { - Range v = st.vbuf[i]; - uint64_t n = v.size ? v.size : 256; - if (v.addr && gw_overlaps(v.addr, v.addr + n)) wait = !guest_direct(v.addr, n, &b, &off); + if (vertices && !wait && (chk_vbuf_gen != vbuf_gen || chk_vbuf_gw != gw_gen)) { + for (int i = 0; i < 16 && !wait; i++) { + Range v = st.vbuf[i]; + uint64_t n = v.size ? v.size : 256; + if (v.addr && gw_overlaps(v.addr, v.addr + n)) wait = !guest_direct(v.addr, n, &b, &off); + } + if (!wait) { chk_vbuf_gen = vbuf_gen; chk_vbuf_gw = gw_gen; } } if (iaddr && !wait && gw_overlaps(iaddr, iaddr + isize)) wait = !guest_direct(iaddr, isize, &b, &off); if (!wait) return; @@ -8762,8 +8800,8 @@ static void draw_(CmdRec *r, bool indexed) { } // ---- vertex streams: the range this draw can read, copied once per submission - for (int s = 0; s < 17; s++) { - if (!(pipe_memo.k.s.used_streams & (1u << s))) continue; + for (uint32_t sm = pipe_memo.k.s.used_streams & ((1u << 17) - 1); sm; sm &= sm - 1) { + int s = __builtin_ctz(sm); VkSpan sp; if (s == ZERO_BINDING) { static const float zero[4] = {0, 0, 0, 1}; @@ -10935,6 +10973,7 @@ void vk_list_stats_frame(void) { // (device.c, each present) static void exec_list(uint64_t handle, int depth) { uint64_t p = handle; + if (depth == 0) { tex_gen[0]++; tex_gen[1]++; } if (lst_on < 0) lst_on = getenv("SAVAGEWIND_VK_LIST_STATS") != NULL; if (lst_on) lst_begin(depth); for (int guard = 0; guard < 10000000; guard++) { @@ -10994,10 +11033,12 @@ static void exec_list(uint64_t handle, int depth) { break; case CMD_BIND_VERTEX_BUFFERS: for (uint64_t i = 0; i < r->x[1] && r->x[0] + i < 16; i++) memcpy(&st.vbuf[r->x[0] + i], (uint8_t *)x + i * 16, 16); + vbuf_gen++; break; case CMD_BIND_UNIFORM_BUFFERS: for (uint64_t i = 0; i < r->x[2] && r->x[1] + i < 18 && r->x[0] < 6; i++) memcpy(&st.ubuf[r->x[0]][r->x[1] + i], (uint8_t *)x + i * 16, 16); + if (r->x[0] < 6) ubuf_gen[r->x[0]]++; if (g_debug_frame && getenv("SAVAGEWIND_LOG_BINDS")) { LOG("[bind] ubuf stage %llu slots %llu+%llu:", (unsigned long long)r->x[0], (unsigned long long)r->x[1], (unsigned long long)r->x[2]); @@ -11015,6 +11056,7 @@ static void exec_list(uint64_t handle, int depth) { case CMD_BIND_TEXTURES: for (uint64_t i = 0; i < r->x[2] && r->x[1] + i < 32 && r->x[0] < 6; i++) memcpy(&st.tex[r->x[0]][r->x[1] + i], (uint8_t *)x + i * 8, 8); + if (r->x[0] < 6) tex_gen[r->x[0]]++; if (g_debug_frame && getenv("SAVAGEWIND_LOG_BINDS")) { LOG("[bind] stage %llu slots %llu+%llu:", (unsigned long long)r->x[0], (unsigned long long)r->x[1], (unsigned long long)r->x[2]); @@ -11033,12 +11075,13 @@ static void exec_list(uint64_t handle, int depth) { if (r->x[3] >= GUEST_LO && r->x[3] + r->x[2] * 8 <= GUEST_HI) for (uint64_t i = 0; i < r->x[2] && r->x[1] + i < 32 && r->x[0] < 6; i++) memcpy(&st.tex[r->x[0]][r->x[1] + i], (const uint8_t *)(uintptr_t)r->x[3] + i * 8, 8); + if (r->x[0] < 6) tex_gen[r->x[0]]++; break; case CMD_BIND_IMAGES: for (uint64_t i = 0; i < r->x[2] && r->x[1] + i < 8 && r->x[0] < 6; i++) memcpy(&st.img[r->x[0]][r->x[1] + i], (uint8_t *)x + i * 8, 8); break; - case CMD_SET_TEXTURE_POOL: st.tpool = (NvnDescPool *)(uintptr_t)r->x[0]; break; + case CMD_SET_TEXTURE_POOL: st.tpool = (NvnDescPool *)(uintptr_t)r->x[0]; tex_gen[0]++; tex_gen[1]++; break; case CMD_SET_SAMPLER_POOL: st.spool = (NvnDescPool *)(uintptr_t)r->x[0]; break; case CMD_SET_RENDER_TARGETS: { const struct { uint64_t tex[8]; NvnTextureView views[8]; uint8_t has_view[8]; uint64_t depth; @@ -11056,7 +11099,7 @@ static void exec_list(uint64_t handle, int depth) { st.rt.has_dview = rt->has_dview; static int always = -1; if (always < 0) always = getenv("SAVAGEWIND_VK_PASS_RESTART") != NULL; - if (always || memcmp(&prev, &st.rt, sizeof prev)) st.rt_dirty = true; + if (always || memcmp(&prev, &st.rt, sizeof prev)) { st.rt_dirty = true; rt_gen++; } if (nfbrun && memcmp(&prev, &st.rt, sizeof prev)) fbdump_flush(); if (logfb > 0 && !fbskip && memcmp(&prev, &st.rt, sizeof prev)) LOG("[feedback] targets %d (%ux%u fmt %#x) depth %d after %u draws\n", st.rt.ncolor, st.rt.ncolor && st.rt.color[0] ? st.rt.color[0]->width : 0, From d9801320d5500058cfd61d6a9a546656fcbbce1f Mon Sep 17 00:00:00 2001 From: Revivedx <82332536+Revivedx@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:02:16 -0500 Subject: [PATCH 05/18] Fixes of 2026-11-13: intro walk at high frame rates (#364), particles with external frame limiters (#629), AMD sky (#359) - Cutscene rail walks: the rail's point waits at the console's distance, so Link reaches the cliff after the first shrine at any frame rate (#364). - GPU overlap: a deferred frame reaches the driver before the game goes on, so an external limiter (RivaTuner, Radeon Chill) no longer lets the game rewrite particle data the GPU still reads (#629, #620, #683, #776). - AMD sky: 3D textures aren't cleared when they're made; AMD's Windows driver kept part of that clear in the sky table, which made the sky grey or black everywhere since Alpha 4 (#359, #665). Co-Authored-By: Claude Opus 5.5 --- docs/SAVAGE-WIND.md | 21 ++++- runtime/hle/framepace.c | 35 ++++++-- runtime/launch_flags_table.c | 8 +- runtime/nvn/vulkan/device.c | 18 ++++ runtime/nvn/vulkan/exec.c | 155 ++++++++++++++++++++++++++++++++++ runtime/nvn/vulkan/textures.c | 11 +++ tools/game_sites.py | 5 ++ tools/patches.py | 14 +++ 8 files changed, 259 insertions(+), 8 deletions(-) diff --git a/docs/SAVAGE-WIND.md b/docs/SAVAGE-WIND.md index 1d1ece02e..51e9309eb 100644 --- a/docs/SAVAGE-WIND.md +++ b/docs/SAVAGE-WIND.md @@ -920,7 +920,9 @@ Pendiente: `SAVAGEWIND_LOG_OPTIONS=1` registra cada valor que se guarda desde la pantalla de opciones, con la hora; `SAVAGEWIND_LOG_SCREENS=1` el estado de pausa y las pantallas de interfaz que existen; `SAVAGEWIND_DUMP_DATA_AT=` vuelca `.data` y `.bss` de main a `build/data_.bin` (para comparar - estados del juego). + estados del juego); `SAVAGEWIND_DEBUG_FIXED_STEP=` da al juego siempre el paso de esa frecuencia, sea cual + sea la real: su lógica corre como a esos FPS, más lenta o más rápida que el tiempo real (así se reprodujo a 180 FPS + en este PC, que no llega a ellos en esa escena, la salida del Santuario de la Vida de #364). - 60 FPS estables en el mundo abierto (2026-10-20). Dónde se iba el frame (perfilador de muestreo y `SAVAGEWIND_TIMELINE`): el hilo principal (0x101) graba ~30 de las ~62 listas del frame y hace el cálculo; dos hilos de trabajo graban el resto; el hilo de render (sead, 0x7000d81100) entrega UNA lista por frame @@ -976,7 +978,16 @@ Pendiente: es completa. Medido con 2+2 pasadas alternas (Kakariko, establo y Hateno, sin límite de FPS, 1280x720): 40,1 → 54,0, 47,8 → 63,6 y 51,5 → 59,0 fps; la GPU ocupada del 74-83 % al 98-99 %. Sin saltos de brillo en 60 capturas seguidas de día, de noche, con lluvia y dentro de Vah Ruta, y la foto de la cámara correcta. - `SAVAGEWIND_GPU_OVERLAP=0` lo quita. + `SAVAGEWIND_GPU_OVERLAP=0` lo quita. Eso cuenta con que el frame aplazado ya está en manos del driver: desde + Alpha 5 presenta el hilo grabador, y un limitador de FPS externo (RivaTuner, Radeon Chill), que duerme dentro de + `vkQueuePresentKHR`, lo dejaba ahí con ese frame sin entregar mientras el juego escribía el siguiente encima. + Las partículas de lluvia y antorchas (vértices que escriben la CPU y los shaders, leídos en su sitio) salían + estiradas un frame (#620, #629, #683, #717, #776). Ahora aplazar un fence espera a que su envío llegue al driver + (`deferred_handed_over`): con el limitador imitado en la lluvia fuerte de Lanayru, lo que la CPU reescribía antes + del envío pasa de ~20 % de las muestras a 0 y no se ven partículas estiradas; sin limitador cuesta ~1 % (123,0 + frente a 124,4 fps, 4+4 pasadas alternas, RTX 3060). `SAVAGEWIND_VK_OVERLAP_HANDOVER=0` lo quita; + `SAVAGEWIND_DEBUG_PRESENT_LIMIT=` imita un limitador así y `SAVAGEWIND_VK_RACE_PROBE=1` mide la memoria que + el juego lee en su sitio y cambia entre la traducción y el envío o la espera (líneas `[race]`). Además: - Copias de constant buffers: se comparten en toda la lista (antes, solo dentro de cada trozo de ~300 draws que va a la GPU) y `UpdateUniformBuffer` (~450 por frame en el mundo, sobre solo ~40 rangos pequeños) invalida solo @@ -1548,6 +1559,12 @@ Pendiente: `SAVAGEWIND_DEBUG_TEXDUMP_LEVEL=` el nivel (estirado al tamaño del 0) y `SAVAGEWIND_DEBUG_TEXDUMP_DRAW=` el draw (numerado como en `[pick]`; cambia entre corridas) en vez del primero; `SAVAGEWIND_DEBUG_TEXDUMP_NTH=`, el n-ésimo draw de ese shader en el frame (el cielo de BOTW: 1 es el del cubemap, 2 el de la vista). + Las texturas 3D se leen de la GPU tal cual (`build/gpu3d__xx_f.raw`, texels en bruto: x, + luego y, luego z) y se comparan con lo subido (`SAVAGEWIND_DUMP_TEX3D=1`: `build/tex3d_*.raw`). El log también + trae las constantes del compilador (`vcb1` / `fcb1`, en hex). Así se encontró el cielo gris o negro de AMD en + Windows (#359): la tabla del cielo (256x32x16 RGBA16F, fs 3fe42f9951190955) subía bien, pero el driver de AMD + guardaba parte del borrado a cero que la precedía (40 % de la tabla mal); las imágenes 3D ya no se borran al + crearse (`SAVAGEWIND_VK_CLEAR_3D=1`: se borran como antes). - `SAVAGEWIND_LOG_FS_CB=:::`: en cada frame, esos floats del uniform buffer `c[k]` del fragment shader (el `fcb` del frame de depuración) en su primer draw; sigue un parámetro a lo largo de un recorrido con guion (así apareció la paleta de 60 s). En el frame de depuración, el log `[draw]` termina con diff --git a/runtime/hle/framepace.c b/runtime/hle/framepace.c index c512ed4a5..eca192541 100644 --- a/runtime/hle/framepace.c +++ b/runtime/hle/framepace.c @@ -498,11 +498,11 @@ int rt_phys_ticked(uint64_t solver_info) { // A player demo move's arrival (tools/patches.py _demo_move_arrive, #364): the move that walks Link in a cutscene ends // when the distance left is under the body's speed, given in metres per console frame: one console frame of walking. -// Leaving the Shrine of Resurrection, the rail move's point runs about 0.15 m ahead of Link; above ~100 fps a frame's step -// is short enough for Link to come within 0.185 m of an intermediate point (0.169 at 120 fps, measured), and the walk -// ended halfway, Link standing still for the rest of the scene. The game's other end test (2 x speed x delta frame) -// already follows the step; this one now does too: one frame of walking at the frame's length, at most a console frame's, -// so 30 fps (and slower) keeps the game's test. SAVAGEWIND_DEMO_ARRIVE=0: the game's own. +// Leaving the Shrine of Resurrection above ~100 fps, Link came within 0.185 m of the rail's point at its first node +// (0.169 at 120 fps, measured; rt_rail_point_radius has why the point was that close), and the walk ended halfway, Link +// standing still for the rest of the scene. The game's other end test (2 x speed x delta frame) already follows the step; +// this one now does too: one frame of walking at the frame's length, at most a console frame's, so 30 fps (and slower) +// keeps the game's test. SAVAGEWIND_DEMO_ARRIVE=0: the game's own. float rt_demo_move_arrive(float speed, float delta_frame) { static int on = -1; if (on < 0) on = env_int("SAVAGEWIND_DEMO_ARRIVE", 1) != 0; @@ -510,6 +510,21 @@ float rt_demo_move_arrive(float speed, float delta_frame) { return speed * delta_frame; } +// A player rail move's point (tools/patches.py _rail_point_radius, #364). Link walks to a point on the rail +// (PlayerRailMove, 1.9.0 0x7000c89cec), and the point moves on by half a radius whenever Link is within the radius of it. +// The radius is the delta frame the player stored that frame, in metres: 1 at 30 fps, 0.17 at 180. At a rail node the +// point starts along the next segment from rest and speeds up in the rail's own time, so the smaller the radius, the +// closer Link came to it before it got away: 0.72 x the radius at 60 fps, 0.49 at 100, and at 180 (the game's step held +// at 180 fps) 0.03 m, under the move's own end test (the distance growing again within two frames of walking), and the +// walk out of the Shrine of Resurrection ended at the rail's first node, Link standing still for the rest of the scene. +// The radius is at least the console's 1 m, so the point waits at the distance it does at 30 fps; slower than 30 fps +// keeps the game's larger one. SAVAGEWIND_RAIL_RADIUS=0: the game's own. +float rt_rail_point_radius(float radius) { + static int on = -1; + if (on < 0) on = env_int("SAVAGEWIND_RAIL_RADIUS", 1) != 0; + return on && radius < 1.0f ? 1.0f : radius; +} + // The sound system's frame (tools/patches.py _snd_frame_floor, #145): the game gives it the delta frame, at least 0.5 // (a 60 fps frame), and every sound timer and fade steps by it: above 60 fps the sound's clock ran ahead of the game's // (x1.6 at ~95 fps, x2 at 120), and the field battle music started each segment while the last one still played. The @@ -652,6 +667,16 @@ void rt_vfr_update(uint64_t vfr) { last_step = step; ratio = (float)(step * 30); } + { // (testing) SAVAGEWIND_DEBUG_FIXED_STEP=: the game's step is always that frame rate's, whatever the real + // one: its logic runs as at that rate (slower or faster than real time), for frame-rate bugs a PC can't reach + static double fixed = -1; + if (fixed < 0) { + const char *e = getenv("SAVAGEWIND_DEBUG_FIXED_STEP"); + fixed = e && atof(e) > 0 ? atof(e) : 0; + if (fixed > 0) LOG("[framepace] the game's step fixed at %.1f fps (testing)\n", fixed); + } + if (fixed > 0 && !paused) ratio = (float)(30.0 / fixed); + } bool held = VF(uint8_t, vfr, VFR_OVERRIDE) && ratio > 1; // (stage loading: the game asks for single steps) if (held) ratio = 1; extern bool freecam_active(void); diff --git a/runtime/launch_flags_table.c b/runtime/launch_flags_table.c index c853ca618..771aee289 100644 --- a/runtime/launch_flags_table.c +++ b/runtime/launch_flags_table.c @@ -40,6 +40,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_DBG_VS", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_DATA", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_DEPTHCOPY", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, + {"SAVAGEWIND_DEBUG_FIXED_STEP", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_FRAME", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_FRAMES", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_GSNAP", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, @@ -52,6 +53,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_DEBUG_PICK", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_PICK_RT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_POINT_SIZE", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, + {"SAVAGEWIND_DEBUG_PRESENT_LIMIT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_TEXDUMP", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_TEXDUMP_ALL", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_DEBUG_TEXDUMP_DRAW", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, @@ -307,6 +309,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_PSO_ANY_VERSION", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_PSO_SLOW_MS", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_QUEUE_AHEAD", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_RAIL_RADIUS", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_REBOOT_AT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_REEXEC", LF_KIND_TEXT, LF_GROUP_INTERNAL, "", "Counter for the automatic restart that finds free memory for the game."}, {"SAVAGEWIND_REVERB_TOGGLE", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, @@ -380,6 +383,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_VK_BLOCK_AFBC", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_BLOCK_ALL", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_CHECKPOINTS", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, + {"SAVAGEWIND_VK_CLEAR_3D", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_COPY_VERTICES", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_COUNTER", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_VK_DEDUP_ATTACHMENTS", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, @@ -437,6 +441,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_VK_ONCE_STRICT_FMT", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_OPT", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_VK_OPT_FS", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, + {"SAVAGEWIND_VK_OVERLAP_HANDOVER", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_OVERLAP_SYNC_QUERIES", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_PASS_RESTART", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_PRESENT", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, @@ -446,6 +451,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_VK_PROF", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_VK_PROVOKING_LAST", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_PUBLISH_KB", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_VK_RACE_PROBE", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_VK_RECORDER", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_RECORDER_MB", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_RECORDER_SPIN", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, @@ -486,4 +492,4 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_XLATE_VERIFY", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_YAZ0", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, }; -const int LF_TABLE_N = 482; +const int LF_TABLE_N = 488; diff --git a/runtime/nvn/vulkan/device.c b/runtime/nvn/vulkan/device.c index 3e7ac88ed..478e880a5 100644 --- a/runtime/nvn/vulkan/device.c +++ b/runtime/nvn/vulkan/device.c @@ -1726,8 +1726,26 @@ static void *pt_waiter(void *arg) { } } +// (testing) SAVAGEWIND_DEBUG_PRESENT_LIMIT=: each present held until 1/fps after the last one, inside the present +// call, as an external frame limiter does (RivaTuner hooks vkQueuePresentKHR, Radeon Chill holds it in the driver): +// the thread that presents waits there, not the game +static void external_limiter(void) { + static double iv = -1; + static uint64_t next; + if (iv < 0) { + const char *e = getenv("SAVAGEWIND_DEBUG_PRESENT_LIMIT"); + iv = e && atof(e) > 0 ? 1e9 / atof(e) : 0; + if (iv > 0) LOG("[vk] presents held to %.1f fps inside the present (an external limiter, testing)\n", 1e9 / iv); + } + if (iv <= 0) return; + uint64_t now = SDL_GetTicksNS(); + if (next > now) SDL_DelayPrecise(next - now), now = next; + next = next && now - next < (uint64_t)iv ? next + (uint64_t)iv : now + (uint64_t)iv; +} + // vkQueuePresentKHR, timed and given a present id for the waiter when SAVAGEWIND_LOG_PRESENT asks static VkResult queue_present(VkQueue q, const VkPresentInfoKHR *info) { + external_limiter(); if (pt_every < 0) { const char *e = getenv("SAVAGEWIND_LOG_PRESENT"); pt_every = e ? atoi(e) : 0; diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index 4ba556efc..503f146c4 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -53,6 +53,8 @@ static uint64_t stat_uub, stat_uub_same, stat_gcopy_hit, stat_gcopy_miss, stat_g static uint64_t stat_ubo_direct, stat_chain_barriers; // constant buffers bound in place (ubo_direct) static void ubo_check_done(bool report); static void vdyn_check(uint64_t seq); +static void race_probe_check(uint64_t seq); +static void race_probe_submit(uint64_t seq); static void vdyn_reset(void); static void ubo_check_submit(uint64_t seq); static uint64_t stat_feedback_live; // depth attachments sampled as they are (read-only feedback, no copy) @@ -669,6 +671,7 @@ void vk_submit_extra(VkSemaphore wait, VkSemaphore signal, VkCommandBuffer extra SW_ACC("submit"); dl_note("submit %llu", (unsigned long long)submit_seq + 1); ubo_check_submit(submit_seq + 1); + race_probe_submit(submit_seq + 1); rec_QueueSubmit2(&si, submit_seq + 1); // (the recorder: in order with the commands) PROF_ADD(prof_submit); } @@ -805,6 +808,24 @@ static bool oneshot_queries(void) { return on; } +// (GPU overlap) A fence the game is told is done before the GPU is: its submission is at least in the driver's hands. +// The overlap counts on the GPU working on that frame while the game writes its next frame's data, double-buffered, into +// the memory the frame before it used. Since Alpha 5 plain presents are made by the recorder thread (device.c +// present_on_recorder): an external frame limiter (RivaTuner, Radeon Chill) that sleeps inside vkQueuePresentKHR held +// the recorder there, and the frame the game was told was done had not even been submitted when the game wrote into +// what it reads. Rain and torch particles (vertex data both the CPU and storing shaders write, read in place, which +// vdyn can't copy) came out stretched across the screen for a frame (#620, #629, #683, #717, #776; reproduced with +// SAVAGEWIND_DEBUG_PRESENT_LIMIT=60 on an RTX 3060, and gone with the recorder off or presents on a thread of their own). +// Measured with SAVAGEWIND_VK_RACE_PROBE=1 in Lanayru's heavy rain: ~20% of that vertex data was written by the CPU +// between its translation and its submission with the limiter, ~0% without. Waiting here for the submission costs +// nothing without such a limiter (the recorder is done with it by then), and with one, the game waits in its own frame +// fence, as it did with presents on the translating thread. SAVAGEWIND_VK_OVERLAP_HANDOVER=0: not waited for. +static void deferred_handed_over(uint64_t seq) { + static int on = -1; + if (on < 0) on = !getenv("SAVAGEWIND_VK_OVERLAP_HANDOVER") || atoi(getenv("SAVAGEWIND_VK_OVERLAP_HANDOVER")); + if (on && rec_on() && seq > rec_submitted()) rec_wait_submitted(seq); +} + void renderer_wait_seq(uint64_t seq) { if (!seq) return; pthread_mutex_lock(&seq_lock); @@ -820,6 +841,7 @@ void renderer_wait_seq(uint64_t seq) { uint64_t prev = deferred_seq, need = full ? seq : oneshot_seq > prev ? oneshot_seq : prev; deferred_seq = need >= seq ? 0 : seq; pthread_mutex_unlock(&seq_lock); + if (need < seq) deferred_handed_over(seq); static int nlog; if (nlog < 20) { nlog++; @@ -828,12 +850,14 @@ void renderer_wait_seq(uint64_t seq) { } vk_wait_seq(need); vdyn_check(need); + race_probe_check(need); return; } if (gpu_overlap()) { if (vk_completed_seq() >= seq) { if (seq >= deferred_seq) deferred_seq = 0; // (in order: the older one is done too) pthread_mutex_unlock(&seq_lock); + race_probe_check(seq); readbacks_apply(); return; } @@ -841,6 +865,7 @@ void renderer_wait_seq(uint64_t seq) { if (seq > prev) { // a newer fence: the deferred one is waited for now, this one at the next call deferred_seq = seq; pthread_mutex_unlock(&seq_lock); + deferred_handed_over(seq); if (!prev) return; seq = prev; } else { // the deferred fence again, or an older one: a real wait on it @@ -849,11 +874,13 @@ void renderer_wait_seq(uint64_t seq) { } vk_wait_seq(seq); vdyn_check(seq); + race_probe_check(seq); return; } pthread_mutex_unlock(&seq_lock); vk_wait_seq(seq); vdyn_check(seq); + race_probe_check(seq); } // A call per set costs the driver a lock, a free-list walk and a handle write (~0.25 ms a frame at ~3000 new sets). Sets @@ -6496,6 +6523,95 @@ static void vdyn_check(uint64_t seq) { pthread_mutex_unlock(&vdyn_lock); } +// (testing) SAVAGEWIND_VK_RACE_PROBE=1: what the GPU reads of guest memory in place (or through the heap copy, which +// the GPU fills when it gets to the list) changing between translation and the real wait on its submission, by kind +// and size, whatever vdyn does: one fetch in 8 of every size up to 256 KB hashed when recorded and again after the +// wait. A "[race]" line every 600 checks: samples, changes, and the biggest changed fetches. +enum { RP_VTX_S, RP_VTX_L, RP_IDX_S, RP_IDX_L, RP_GW_VTX, RP_GW_IDX, RP_KINDS }; +static const char *const rp_kind_name[RP_KINDS] = {"vertex<=4K", "vertex>4K", "index<=4K", "index>4K", "gpu-written vertex", + "gpu-written index"}; +#define RP_N 16384 +#define RP_MAX (256u << 10) +static int rp_on = -1; +static struct { uint64_t addr, size, hash, seq; int kind; } rp_chk[RP_N]; +static _Atomic uint64_t rp_sub_cpu[RP_KINDS]; // (of those: the CPU wrote the pages since translation - write watch) +static _Atomic uint64_t rp_w, rp_r, rp_s; // (written by the render thread; read after the wait / in the recorder's turn) +static uint64_t rp_tick, rp_samples[RP_KINDS], rp_changed[RP_KINDS], rp_checks; +static _Atomic uint64_t rp_sub_samples[RP_KINDS], rp_sub_changed[RP_KINDS]; // (changed before the GPU had the submission) +static uint64_t rp_big_addr, rp_big_size; +static pthread_mutex_t rp_lock = PTHREAD_MUTEX_INITIALIZER; +static void race_probe_note(uint64_t addr, uint64_t size, bool index) { + if (rp_on < 0) { + rp_on = getenv("SAVAGEWIND_VK_RACE_PROBE") && atoi(getenv("SAVAGEWIND_VK_RACE_PROBE")); + if (rp_on) LOG("[race] probe on: in-place vertex / index fetches hashed at translation and after their wait\n"); + } + if (!rp_on || !size || size > RP_MAX || addr < HEAP_BASE || addr + size > HEAP_BASE + HEAP_MAX || (++rp_tick & 7)) return; + bool gw = gw_overlaps(addr, addr + size); // (GPU-written: may change by the GPU's own writes too) + uint64_t w = atomic_load_explicit(&rp_w, memory_order_relaxed), r = atomic_load_explicit(&rp_r, memory_order_acquire), + rs = atomic_load_explicit(&rp_s, memory_order_acquire); + if (w - (r < rs ? r : rs) >= RP_N) return; + __typeof__(rp_chk[0]) *c = &rp_chk[w % RP_N]; + c->addr = addr, c->size = size, c->seq = vk_pending_seq(); + c->kind = gw ? (index ? RP_GW_IDX : RP_GW_VTX) : (index ? RP_IDX_S : RP_VTX_S) + (size > VDYN_SAMPLE_MAX); + if (gw) { // (the CPU's writes from here on, apart from the GPU's: write watch, reset now; the GPU's don't count there) + uint64_t pages[64]; + plat_written_pages(addr & ~0xFFFull, ((addr + size + 0xFFF) & ~0xFFFull) - (addr & ~0xFFFull), pages, 64); + } + c->hash = hash_words(0x9E3779B97F4A7C15ull, (const void *)(uintptr_t)addr, size & ~3ull); + atomic_store_explicit(&rp_w, w + 1, memory_order_release); +} +static void race_probe_check(uint64_t seq) { + if (rp_on <= 0 || pthread_mutex_trylock(&rp_lock)) return; + uint64_t r = atomic_load_explicit(&rp_r, memory_order_relaxed), w = atomic_load_explicit(&rp_w, memory_order_acquire); + for (; r < w && rp_chk[r % RP_N].seq <= seq; r++) { + __typeof__(rp_chk[0]) *c = &rp_chk[r % RP_N]; + rp_samples[c->kind]++; + if (hash_words(0x9E3779B97F4A7C15ull, (const void *)(uintptr_t)c->addr, c->size & ~3ull) == c->hash) continue; + rp_changed[c->kind]++; + if (c->size > rp_big_size) rp_big_size = c->size, rp_big_addr = c->addr; + } + atomic_store_explicit(&rp_r, r, memory_order_release); + if (++rp_checks % 600 == 0) { + char line[512]; + int n = 0; + for (int k = 0; k < RP_KINDS; k++) + n += snprintf(line + n, sizeof line - n, " %s %llu/%llu", rp_kind_name[k], (unsigned long long)rp_changed[k], + (unsigned long long)rp_samples[k]); + LOG("[race] changed while read (of sampled):%s; biggest %llu bytes at %llx\n", line, (unsigned long long)rp_big_size, + (unsigned long long)rp_big_addr); + n = 0; + for (int k = 0; k < RP_KINDS; k++) + n += snprintf(line + n, sizeof line - n, " %s %llu/%llu (CPU %llu)", rp_kind_name[k], + (unsigned long long)atomic_exchange(&rp_sub_changed[k], 0), (unsigned long long)atomic_exchange(&rp_sub_samples[k], 0), + (unsigned long long)atomic_exchange(&rp_sub_cpu[k], 0)); + LOG("[race] changed before the GPU had the submission:%s\n", line); + memset(rp_samples, 0, sizeof rp_samples); + memset(rp_changed, 0, sizeof rp_changed); + rp_big_size = rp_big_addr = 0; + } + pthread_mutex_unlock(&rp_lock); +} + +// (recorder's turn, right before submission seq goes to the driver) the samples recorded into it, hashed again: a change +// here was made after translation and before the GPU could read it +static void race_probe_submit_run(void *arg) { + uint64_t seq = (uint64_t)(uintptr_t)arg; + uint64_t s = atomic_load_explicit(&rp_s, memory_order_relaxed), w = atomic_load_explicit(&rp_w, memory_order_acquire); + for (; s < w && rp_chk[s % RP_N].seq <= seq; s++) { + __typeof__(rp_chk[0]) *c = &rp_chk[s % RP_N]; + atomic_fetch_add_explicit(&rp_sub_samples[c->kind], 1, memory_order_relaxed); + if (hash_words(0x9E3779B97F4A7C15ull, (const void *)(uintptr_t)c->addr, c->size & ~3ull) != c->hash) { + atomic_fetch_add_explicit(&rp_sub_changed[c->kind], 1, memory_order_relaxed); + if (plat_any_written(c->addr, c->size) == 1) atomic_fetch_add_explicit(&rp_sub_cpu[c->kind], 1, memory_order_relaxed); + } + } + atomic_store_explicit(&rp_s, s, memory_order_release); +} +static void race_probe_submit(uint64_t seq) { + if (rp_on > 0) rec_custom(race_probe_submit_run, (void *)(uintptr_t)seq); + else if (rp_on == 0) atomic_store_explicit(&rp_s, atomic_load_explicit(&rp_w, memory_order_relaxed), memory_order_relaxed); +} + static void vdyn_reset(void) { // (vk_exec_reset, the GPU idle: another boot, other buffers) pthread_mutex_lock(&vdyn_lock); for (size_t i = 0; i < sizeof vdyn; i++) atomic_store_explicit(&vdyn[i], 0, memory_order_relaxed); @@ -8762,6 +8878,7 @@ static void draw_(CmdRec *r, bool indexed) { icount = count; if (iaddr % isz == 0 && guest_fetch(iaddr, (uint64_t)count * isz, &ib.buf, &ib.off)) { if (profd) prof_index_direct++; + race_probe_note(iaddr, (uint64_t)count * isz, true); scan_src = src; scan_isz = isz; scan_restart = restart; // max_index only if a stream gets copied } else { if (profd) prof_index_copy++; @@ -8812,6 +8929,7 @@ static void draw_(CmdRec *r, bool indexed) { VkDeviceSize doff; if (v.addr && v.size && guest_fetch(v.addr, v.size, &dbuf, &doff)) { if (profd) prof_vertex_direct++; + race_probe_note(v.addr, v.size, false); if (dc.vbuf[s] != dbuf || dc.voff[s] != doff) { rec_CmdBindVertexBuffers(cb, (uint32_t)s, 1, &dbuf, &doff); dc.vbuf[s] = dbuf; dc.voff[s] = doff; @@ -8892,6 +9010,7 @@ static void draw_(CmdRec *r, bool indexed) { } static void debug_save_channels(TexBackend *b, const char *path); +static void debug_save_3d(TexBackend *b, const char *path); static void debug_draw(Prog *pr, CmdRec *r, bool indexed) { LOG("[draw] %s inst %llu mode %llu count %llu prog vs=%llx fs=%llx | vs cb %#x fs cb %#x | rt %d", indexed ? "e" : "a", @@ -9032,6 +9151,12 @@ static void debug_draw(Prog *pr, CmdRec *r, bool indexed) { snprintf(path, sizeof path, "build/dtex_%016llx_%d.%s", (unsigned long long)g_cur_fs_hash, i, b->aspect & VK_IMAGE_ASPECT_DEPTH_BIT ? "pgm" : "png"); vk_end_pass(); + if (b->base_type == VK_IMAGE_VIEW_TYPE_3D) { + snprintf(path, sizeof path, "build/gpu3d_%llu_%ux%ux%u_f%x.raw", (unsigned long long)t->debug_id, b->width, + b->height, b->depth, t->format); + debug_save_3d(b, path); + continue; + } if (b->aspect & VK_IMAGE_ASPECT_DEPTH_BIT) debug_save_depth(b, path); else debug_save_channels(b, path); LOG("[draw] tex%d saved as %s\n", i, path); @@ -9114,6 +9239,14 @@ static void debug_draw(Prog *pr, CmdRec *r, bool indexed) { LOG("%s%.6g", k % 16 == 0 ? "\n[draw] " : k % 4 ? " " : " | ", f[k]); LOG("\n"); } + for (int sg = 0; sg < 2; sg++) { // the compiler constants (c1) of either stage, exact + const NvnShaderStage *ss = &st.program->stages[sg]; + if (!ss->code_addr || !ss->const_size) continue; + const uint32_t *u = (const uint32_t *)(uintptr_t)(ss->code_addr + ss->const_offset); + LOG("[draw] %ccb1 size %u:", sg ? 'f' : 'v', ss->const_size); + for (uint32_t k = 0; k < 256 && k * 4 < ss->const_size; k++) LOG(" %08x", u[k]); + LOG("\n"); + } } } } @@ -10857,6 +10990,28 @@ static void save_view_png(TexBackend *b, VkImageView src, const char *path) { vmaDestroyImage(g_vk.vma, img, mem); } +// (debugging) A 3D image's level 0 as the GPU holds it, raw texels (x, then y, then z), for comparing with what was +// uploaded (SAVAGEWIND_DUMP_TEX3D). debug_save_channels can't show 3D images. +static void debug_save_3d(TexBackend *b, const char *path) { + uint32_t bpp = b->format == VK_FORMAT_R16G16B16A16_SFLOAT ? 8 : b->format == VK_FORMAT_R32G32B32A32_SFLOAT ? 16 + : b->format == VK_FORMAT_R8_UNORM ? 1 : b->format == VK_FORMAT_R16_SFLOAT || b->format == VK_FORMAT_R8G8_UNORM ? 2 : 4; + uint64_t size = (uint64_t)b->width * b->height * b->depth * bpp; + vk_end_pass(); + VkCommandBuffer cb = vk_cmd(); + vk_full_barrier(cb); + VkSpan out = vk_readback(size); + VkBufferImageCopy c = {.bufferOffset = out.off, .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {b->width, b->height, b->depth}}; + rec_CmdCopyImageToBuffer(cb, b->image, VK_IMAGE_LAYOUT_GENERAL, out.buf, 1, &c); + vk_full_barrier(cb); + renderer_flush(); + vk_readback_sync(); + FILE *f = fopen(path, "wb"); + if (f) fwrite(out.ptr, 1, size, f), fclose(f); + LOG("[vk] 3D image %ux%ux%u vk format %d (%u bytes a texel) read back from the GPU: %s\n", b->width, b->height, b->depth, + b->format, bpp, f ? path : "(not saved)"); +} + // ================================================================== executor (renderer.m exec_list) // (measuring) SAVAGEWIND_VK_LIST_STATS=1: how self-contained the command lists a frame calls are (whether each could be // translated on its own): per list, the state its draws use that it did not set itself, and UpdateUniformBuffer writes diff --git a/runtime/nvn/vulkan/textures.c b/runtime/nvn/vulkan/textures.c index 263726404..d2e94f943 100644 --- a/runtime/nvn/vulkan/textures.c +++ b/runtime/nvn/vulkan/textures.c @@ -691,6 +691,17 @@ static void create_image(NvnTexture *t, TexBackend *b) { // first contents into the 1x1 colours the CPU reads back (exec.c readbacks_apply): a NaN there stayed for good and // washed the picture out (white, or neon green and yellow), about every other time at 2560 x 1440. bool float_rt = (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) && format_is_float(vf); + // Not 3D images: BOTW's sky table (256x32x16 RGBA16F, the atmosphere's scattering) is one, filled from the CPU right + // after this clear. AMD's Windows driver (RX 6600, 26.6.2) kept part of the clear through that copy: read back from + // the GPU, 40% of the table was wrong (whole rows empty), the sky came out grey or black everywhere, from Alpha 4 on + // (#359, #665); not cleared, the table read back whole and the sky was right. On NVIDIA it reads back whole either + // way. 3D targets the game draws into start as they did before Alpha 4. SAVAGEWIND_VK_CLEAR_3D=1: cleared too. + static int clear_3d = -1; + if (clear_3d < 0) { + clear_3d = getenv("SAVAGEWIND_VK_CLEAR_3D") ? atoi(getenv("SAVAGEWIND_VK_CLEAR_3D")) != 0 : 0; + if (clear_3d) LOG("[vk] new 3D images cleared too (SAVAGEWIND_VK_CLEAR_3D)\n"); + } + if (type == VK_IMAGE_TYPE_3D && !clear_3d) float_rt = false; if ((b->scalable || float_rt) && !depthfmt) { // (scalable: made again at a new scale, no stale memory in what frames keep) VkCommandBuffer cb = vk_upload_cmd(); VkClearColorValue zero = {{0}}; diff --git a/tools/game_sites.py b/tools/game_sites.py index 7f59f0aea..0913a71c0 100644 --- a/tools/game_sites.py +++ b/tools/game_sites.py @@ -185,6 +185,9 @@ # in console frames, fcmp s8, s9 Site('demo_move_arrive', 'code', 'bd60bd09 94000000/fc000000 f9400668 5282fe09 38696908 34000008/ff00001f 1e292100 ' '54000004/ff00001f 90000008/9f00001f bd404261 bd425102 1e222821 1e282020 54000005/ff00001f 1e292921 1e200820', 6), + # the radius within which a player rail move's point goes on along the rail (tools/patches.py _rail_point_radius): + # its load from the player, ldr s0, [x8, #0x20f0] + Site('rail_point_radius', 'code', 'bd60f100 1e202020 54000005/ff00001f 1e2c1001 f9403668 aa1403e0 aa1f03e1 aa1f03e2', 0), Site('kf_angle', 'code', '0e612800 0e0e3c08 0e040d00 0f3f5400 0ea0a800 6e180400 4e221c00 6e211c00 3c9983a0 ' '94000000/fc000000 3cd883a6 1e2008c0', 9), # the sound system's frame (tools/patches.py _snd_frame_floor): the delta frame, at least 0.5, its timers' step @@ -396,6 +399,7 @@ ('quick_menu_capture_alpha',), ('kf_angle',), ('demo_move_arrive',), + ('rail_point_radius',), ('phys_tick', 'phys_tick_mt', 'phys_motion_tick', 'phys_motion_tick_c'), ('yaz0_stream', 'yaz0_stream_ret'), ('pc_map_focus', 'pc_map_focus_target', 'pc_map_focus_now'), @@ -528,6 +532,7 @@ 'stale_actor_target': 0x7000dea400, 'phys_solver_steps': 0x700156f930, 'demo_move_arrive': 0x7000c711dc, + 'rail_point_radius': 0x7000c89d4c, 'kf_angle': 0x70012d57fc, 'phys_tick': 0x70000f5e20, 'phys_tick_mt': 0x700012644c, diff --git a/tools/patches.py b/tools/patches.py index dd89dff71..cc0f5b634 100644 --- a/tools/patches.py +++ b/tools/patches.py @@ -421,6 +421,19 @@ def _demo_move_arrive(gen, a): f' /* {a:#x}: fcmp s8, s9 (player demo move: arrived within a frame of walking) */') +# A player rail move's point (runtime/hle/framepace.c rt_rail_point_radius, #364): PlayerRailMove's update (1.9.0 +# 0x7000c89cec) moves the point Link walks to along the rail by half a radius whenever Link is within the radius of it, +# and the radius is the delta frame the player stored that frame (+0x20f0), in metres. Above 30 fps the point waited for +# Link at a rail node until he was within a fraction of a metre (0.17 at 180 fps), and the move's arrival tests ended the +# walk there. The radius is at least 1, the console's. + +def _rail_point_radius(gen, a): + assert _word(gen, a) == 0xbd60f100, hex(_word(gen, a)) # ldr s0, [x8, #0x20f0] + return ('{ extern float rt_rail_point_radius(float); union { uint32_t u; float f; } r = { .u = (uint32_t)LD32(c->x[8] + 0x20f0) }; ' + 'r.f = rt_rail_point_radius(r.f); c->v[0] = r.u; }' + f' /* {a:#x}: ldr s0, [x8, #0x20f0] (player rail move: the radius its point moves on within) */') + + def _kf_angle(gen, a): assert _word(gen, a) >> 26 == 0x25, hex(_word(gen, a)) # bl (getAngle) target = sext(_word(gen, a) & 0x3ffffff, 26) * 4 + a @@ -1008,6 +1021,7 @@ def _tp_gate(gen, a): 'phys_solver_steps': _solver_steps, 'kf_angle': _kf_angle, 'demo_move_arrive': _demo_move_arrive, + 'rail_point_radius': _rail_point_radius, 'phys_tick': _phys_tick, 'phys_tick_mt': _phys_tick, 'phys_motion_tick': _phys_motion_tick, From 086bc687c1e57c7de820b1922028985e03536ad6 Mon Sep 17 00:00:00 2001 From: guill Date: Fri, 13 Nov 2026 17:34:37 -0500 Subject: [PATCH 06/18] Controls and 1366x768 (PRs #642, #802) - Controls: rebinding a "Menu: ..." row no longer moves the gameplay A/B/X/Y buttons. In play, those four come from the action bindings (Attack, Jump, Interact, Sprint/Cancel); script, console, cursor and auto-continue buttons are left untouched (PR #642, fixes #608). - Output scale: near-16:9 integer sizes like 1366x768 render 1:1 instead of 1365 px wide with a sub-pixel offset, which made them blurrier than 1280x720 (PR #802, fixes #770). Checked: output scale, PC controls, input focus and action tests; a hidden 1366x768 run; a visible playtest from a 100% save. Co-authored-by: jfpaardoo Co-Authored-By: Claude Opus 5.5 --- runtime/hle/bindings.c | 101 +++++++++++++++++++++++-------------- runtime/hle/input.c | 9 +++- runtime/input_bind.h | 1 + runtime/nvn/output_scale.c | 11 ++-- tests/test_output_scale.c | 8 +++ tests/test_pc_controls.c | 19 +++++++ tools/test_input_focus.c | 1 + 7 files changed, 107 insertions(+), 43 deletions(-) diff --git a/runtime/hle/bindings.c b/runtime/hle/bindings.c index 8deaee6d6..39ffb4a2b 100644 --- a/runtime/hle/bindings.c +++ b/runtime/hle/bindings.c @@ -149,6 +149,7 @@ int bind_label_family(void) { static void result(int kind, int dev, int slot, int other); static int act_default(int dev, int id); +static void act_refresh(void); void bind_reset(int dev) { if (dev == BIND_DEV_PAD) memcpy(g_bind_pad, k_def_pad, sizeof g_bind_pad); @@ -167,6 +168,7 @@ void bind_reset_slot(int slot) { if (slot < 0 || slot >= BIND_KEY_COUNT) return; g_bind_key[slot] = k_def_key[slot]; if (bind_pad_slot(slot)) g_bind_pad[slot] = k_def_pad[slot]; + act_refresh(); } bool bind_is_default(int dev) { @@ -247,6 +249,7 @@ static void assign(int dev, int slot, int host) { other >= 0 ? k_names[other] : "", other >= 0 ? ")" : ""); if (other >= 0) LOG("[input] %s -> %s\n", k_names[other], dev == BIND_DEV_PAD ? bind_pad_label(t[other], 0) : bind_key_label(t[other])); result(other >= 0 ? 2 : 1, dev, slot, other); + act_refresh(); } bool bind_capture_event(const SDL_Event *e) { @@ -325,6 +328,7 @@ bool bind_settings_load(const char *key, const char *val) { } if (i < BIND_PAD_COUNT) act_migrate(pad ? BIND_DEV_PAD : BIND_DEV_KEY, i); } + act_refresh(); return true; } @@ -369,6 +373,43 @@ static const char *const k_act_names[ACT_COUNT] = { const char *act_name(int id) { return id >= 0 && id < ACT_COUNT ? k_act_names[id] : NULL; } bool act_hidden(int id) { return id >= 0 && id < ACT_COUNT && (ACT_HIDDEN_MASK >> id & 1); } +// The game's mask bits are sead's pad indices (open-ead: PadIdx), not the Switch's nn::hid bits. +static int mask_button(uint32_t m) { + switch (m) { + case 0x1: return BIND_A; + case 0x2: return BIND_B; + case 0x4: return BIND_ZL; + case 0x8: return BIND_X; + case 0x10: return BIND_Y; + case 0x20: return BIND_ZR; + case 0x40: return BIND_RSTICK; + case 0x80: return BIND_LSTICK; + case 0x2000: return BIND_L; + case 0x4000: return BIND_R; + case 0x10000: return BIND_UP; + case 0x20000: return BIND_DOWN; + default: return -1; + } +} + +// The game's table for 1.9.0 (all 41 masks): factory defaults and legacy migration always use this fixed table. +// act_switch_button also uses it before the game has supplied its live table. +static const uint32_t k_masks_190[ACT_COUNT] = { + 0x1, 0x2, 0x8, 0x10, 0x8, 0x1, 0x8, 0x2, 0x8, 0x2, 0x8, 0x8, 0x2, 0x4, 0x2, 0x40, 0x1, 0x80, 0x20, 0x8, 0x2, + 0x10000, 0x20000, 0x10000, 0x20000, 0x2, 0x1, 0x2000, 0x4000, 0x4, 0x2, 0x4000, 0x4000, 0x2000, 0x1, 0x20000, + 0x10, 0x20000, 0x1, 0x2, 0x2000}; + +int act_switch_button(int id) { + if (id < 0 || id >= ACT_COUNT) return -1; + return mask_button((k_masks ? k_masks : k_masks_190)[id]); +} + +static int act_default(int dev, int id) { + int b = mask_button(k_masks_190[id]); + if (b < 0) return ACT_NONE; + return dev == BIND_DEV_PAD ? k_def_pad[b] : k_def_key[b]; +} + bool act_is_default(int id) { return id < 0 || id >= ACT_COUNT || (g_act_key[id] == act_default(BIND_DEV_KEY, id) && g_act_pad[id] == act_default(BIND_DEV_PAD, id)); @@ -406,38 +447,9 @@ void act_reset(void) { // Initialized before settings or either Controls page can read the public arrays (also in standalone tests). __attribute__((constructor)) static void act_init(void) { act_reset(); } -void act_masks(const uint32_t *table) { k_masks = table; } - -// The game's mask bits are sead's pad indices (open-ead: PadIdx), not the Switch's nn::hid bits. -static int mask_button(uint32_t m) { - switch (m) { - case 0x1: return BIND_A; - case 0x2: return BIND_B; - case 0x4: return BIND_ZL; - case 0x8: return BIND_X; - case 0x10: return BIND_Y; - case 0x20: return BIND_ZR; - case 0x40: return BIND_RSTICK; - case 0x80: return BIND_LSTICK; - case 0x2000: return BIND_L; - case 0x4000: return BIND_R; - case 0x10000: return BIND_UP; - case 0x20000: return BIND_DOWN; - default: return -1; - } -} - -// The game's table for 1.9.0 (all 41 masks): factory defaults and legacy migration always use this fixed table. -// act_switch_button also uses it before the game has supplied its live table. -static const uint32_t k_masks_190[ACT_COUNT] = { - 0x1, 0x2, 0x8, 0x10, 0x8, 0x1, 0x8, 0x2, 0x8, 0x2, 0x8, 0x8, 0x2, 0x4, 0x2, 0x40, 0x1, 0x80, 0x20, 0x8, 0x2, - 0x10000, 0x20000, 0x10000, 0x20000, 0x2, 0x1, 0x2000, 0x4000, 0x4, 0x2, 0x4000, 0x4000, 0x2000, 0x1, 0x20000, - 0x10, 0x20000, 0x1, 0x2, 0x2000}; - -static int act_default(int dev, int id) { - int b = mask_button(k_masks_190[id]); - if (b < 0) return ACT_NONE; - return dev == BIND_DEV_PAD ? k_def_pad[b] : k_def_key[b]; +void act_masks(const uint32_t *table) { + k_masks = table; + act_refresh(); } // Applied while reading legacy ini lines, independent of line order and independently for each device. @@ -452,11 +464,6 @@ static void act_migrate(int dev, int slot) { act_refresh(); } -int act_switch_button(int id) { - if (id < 0 || id >= ACT_COUNT) return -1; - return mask_button((k_masks ? k_masks : k_masks_190)[id]); -} - uint64_t act_scan_keys(uint64_t key_buttons, int (*held)(int scancode)) { (void)key_buttons; // kept for callers; actions read host inputs, never the live Switch layout uint64_t out = 0, custom = a_custom; @@ -479,6 +486,24 @@ uint64_t act_scan_pad(uint64_t pad_buttons, uint32_t host_buttons) { return out; } +static bool act_held_host(int id, int (*held)(int scancode), uint32_t host) { + if (id < 0 || id >= ACT_COUNT) return false; + int k = g_act_key[id], p = g_act_pad[id]; + return (k > 0 && held && held(k)) || (p >= 0 && p < PADB_HOST_COUNT && (host >> p & 1)); +} + +// During gameplay, decouple in-game action buttons (Y/X/A/B) from raw menu rebinds +// so that rebinding a menu slot (e.g. "Menu: sort / sensor") never hijacks actions in play. +// Only the raw keyboard/pad mask is rewritten; script/console/cursor/auto-continue bits stay untouched. +uint64_t act_gameplay_buttons(uint64_t raw, int (*held)(int scancode), uint32_t host) { + raw &= ~((1ull << BIND_Y) | (1ull << BIND_X) | (1ull << BIND_A) | (1ull << BIND_B)); + if (act_held_host(3, held, host) || act_held_host(36, held, host)) raw |= 1ull << BIND_Y; + if (act_held_host(2, held, host)) raw |= 1ull << BIND_X; + if (act_held_host(0, held, host)) raw |= 1ull << BIND_A; + if (act_held_host(12, held, host) || act_held_host(14, held, host)) raw |= 1ull << BIND_B; + return raw; +} + // Each side publishes its own half (the keyboard and the controller change at different times) void act_publish(uint64_t keys, uint64_t pads) { if (keys != ~0ull) a_keys = keys; @@ -656,7 +681,7 @@ void act_poll(bool live) { } int rt_act_query(int kind, uint64_t pad, uint64_t id, uint64_t lr, uint64_t masks) { - if (!k_masks && masks) k_masks = (const uint32_t *)(uintptr_t)masks; + if (!k_masks && masks) { k_masks = (const uint32_t *)(uintptr_t)masks; act_refresh(); } bool custom = id < ACT_COUNT && (a_custom >> id & 1); if (act_log_on()) act_log_query(kind, pad, (unsigned)id, lr, custom && a_live); if (id >= ACT_COUNT || !a_live || !custom) return -1; diff --git a/runtime/hle/input.c b/runtime/hle/input.c index d40c62abe..a6d579c16 100644 --- a/runtime/hle/input.c +++ b/runtime/hle/input.c @@ -1025,7 +1025,10 @@ void input_frame(uint64_t frame) { // Buttons held right now (keyboard, gamepad, test script), independent of whether the game polls (movies). uint64_t input_buttons_now(void) { bool muted = (!win_focused && !host_test) || menu_input_captured(); - uint64_t b = (muted ? 0 : key_buttons | pad_buttons | escape_buttons) | script_buttons; + uint64_t raw = muted ? 0 : key_buttons | pad_buttons; + if (!muted && !framepace_title_ui() && !framepace_menu_ui() && !pc_cursor_active()) + raw = act_gameplay_buttons(raw, game_key, host_buttons); + uint64_t b = raw | (muted ? 0 : escape_buttons) | script_buttons; control_input_apply(&b, NULL, NULL, NULL, NULL); return b; } @@ -1057,7 +1060,9 @@ static void fill_state(Cpu *c) { // the window unfocused or the overlay up, use the Switch layer, so no binding can lock the player out. act_poll(!menu && !framepace_title_ui() && !framepace_menu_ui()); uint64_t bow = pc_bow_sample(); - uint64_t b = menu ? script_buttons : key_buttons | pad_buttons | escape_buttons | bow | script_buttons; + bool in_menu = menu || framepace_title_ui() || framepace_menu_ui(); + uint64_t raw = menu ? 0 : (in_menu ? (key_buttons | pad_buttons) : act_gameplay_buttons(key_buttons | pad_buttons, game_key, host_buttons)); + uint64_t b = raw | (menu ? 0 : escape_buttons | bow) | script_buttons; if (!menu) b |= auto_continue_buttons(b); // (not while the overlay has the controls) b=pc_cursor_buttons(b); { // injected Plus: held for ~10 presented frames (the game polls several times per frame) diff --git a/runtime/input_bind.h b/runtime/input_bind.h index 45c7b6861..25bb64a70 100644 --- a/runtime/input_bind.h +++ b/runtime/input_bind.h @@ -113,6 +113,7 @@ void act_reset(void); // every action back to the defaul // Host state in, from runtime/hle/input.c. Main thread, on every key / button event: uint64_t act_scan_keys(uint64_t key_buttons, int (*held)(int scancode)); // actions the keyboard side holds uint64_t act_scan_pad(uint64_t pad_buttons, uint32_t host_buttons); // ... the controller side holds +uint64_t act_gameplay_buttons(uint64_t raw, int (*held)(int scancode), uint32_t host_buttons); // gameplay A/B/X/Y from action bindings void act_publish(uint64_t keys, uint64_t pads); // (bit per action) // The controller poll (game thread, once per GetNpadStates): freezes the held / pressed sets the game's queries see. // live = false in the game's menus, with the window unfocused or the overlay up: the Switch layer answers then. diff --git a/runtime/nvn/output_scale.c b/runtime/nvn/output_scale.c index f9b708c94..00b5ce5c2 100644 --- a/runtime/nvn/output_scale.c +++ b/runtime/nvn/output_scale.c @@ -133,9 +133,14 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { static const double ss_f[RSCALE_COUNT] = {0.5, 0.75, 1.0, 1.25, 1.5, 2.0}; int rsi = g_settings.render_scale; double ss = rsi >= 0 && rsi < RSCALE_COUNT ? ss_f[rsi] : 1.0; + // Near-16:9 integer resolutions like 1366x768 (768 * 16/9 = 1365.33) would otherwise render 1365px wide and + // resample at a sub-pixel horizontal offset into the 1366px window (#770); snap <2px rounding to exact 1:1. + bool near_fit = !reshape && forced <= 0 && wide_test <= 0 && + fabs(dw - 1920.0 * fit) < 2.0 && fabs(dh - 1080.0 * fit) < 2.0; double h = forced > 0 ? forced : (reshape ? dh / 1080.0 : fit) / out_div * ss; h = fmax(h, 0.1); // (a tiny window) - double sx = h * shape, sy = h; + double sx = near_fit ? fmax((dw / 1920.0) / out_div * ss, 0.1) : h * shape; + double sy = near_fit ? fmax((dh / 1080.0) / out_div * ss, 0.1) : h; double cap = fmin(MAX_TEX / (1920.0 * sx), MAX_TEX / (1080.0 * sy)); if (cap < 1.0) { sx *= cap; sy *= cap; } o->sx = sx; o->sy = sy; o->shape = shape; @@ -145,8 +150,8 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { o->scene_sx = sx * k; o->scene_sy = sy * k; double scap = fmin(MAX_TEX / (1920.0 * o->scene_sx), MAX_TEX / (1080.0 * o->scene_sy)); if (scap < 1.0) { o->scene_sx *= scap; o->scene_sy *= scap; } - // where the image goes in the window: fills it when reshaped, else a fitted 16:9 box - if (reshape) { o->vw = dw; o->vh = dh; } + // where the image goes in the window: fills it when reshaped (or near-16:9 snapped), else a fitted 16:9 box + if (reshape || near_fit) { o->vw = dw; o->vh = dh; } else { o->vw = 1920.0 * fit; o->vh = 1080.0 * fit; } if (wide_test > 0) { double f2 = fmin(dw / (1920.0 * wide_test), dh / 1080.0); diff --git a/tests/test_output_scale.c b/tests/test_output_scale.c index f69af6b42..78920dff1 100644 --- a/tests/test_output_scale.c +++ b/tests/test_output_scale.c @@ -95,5 +95,13 @@ int main(void) { map = false; output_scale(1280, 800, true, &o); near(o.vh, 800); near(o.crop[3], 1); + + // Near-16:9 integer resolutions (1366x768) snap 1:1 instead of rendering 1365px wide (#770). + for (int wide = 0; wide <= 1; wide++) { + output_scale(1366, 768, wide != 0, &o); + near(1920 * o.sx, 1366); near(1080 * o.sy, 768); + near(1600 * o.scene_sx, 1366); near(900 * o.scene_sy, 768); + near(o.vw, 1366); near(o.vh, 768); near(o.vx, 0); near(o.vy, 0); + } puts("PASS: taller map viewport, 16:9 fallback, disabled fill, title, loading and ultrawide"); } diff --git a/tests/test_pc_controls.c b/tests/test_pc_controls.c index 4837cc493..45bd203a3 100644 --- a/tests/test_pc_controls.c +++ b/tests/test_pc_controls.c @@ -125,6 +125,25 @@ int main(void) { e.type=SDL_EVENT_MOUSE_BUTTON_DOWN;e.button.button=SDL_BUTTON_LEFT; input_handle_event(&e);assert(input_buttons_now()&(1ull< Date: Fri, 13 Nov 2026 18:17:20 -0500 Subject: [PATCH 07/18] FSR 3 / TAA rework, shadows follow the upscaler, frame generation pacing - FSR 3, FSR 4 and TAA cost the CPU much less: motion vectors are worked out on a thread of their own, every scene draw uses one motion program, FSR 3 is dispatched by the recorder thread. FSR 3 / 4 upscaling stays held back for now (SAVAGEWIND_FSR3=1 offers it). - TAA is a single pass (about 0.5 ms of GPU time at 1440p instead of 2.5 ms); SAVAGEWIND_TAA=full is the old one. - Frame generation with no frame limit no longer lowers the frame rate: its presents are paced on a thread of their own, on the game's queue. RTX 3060 + Ryzen 5 5600X, 1440p, Savage preset at 100 %, presented fps without it / before / now: Great Plateau 102 / 47 / 125, Kakariko 88 / 48 / 116, Korok Forest 40 / 29 / 66. SAVAGEWIND_VK_FG_PACER=0: as before. - Shadow maps above the console's size follow a temporal upscaler's factor (Savage at Quality: 5440 instead of 8192). Korok Forest, FSR 3 Quality: 41 to 67 fps (native 40). SAVAGEWIND_SHADOW_FOLLOW=0: the setting's size. - Ultra Performance with FSR 3 / 4 or DLSS is offered on a 4K window only; below that it runs as Performance. Checked: hidden runs at the Great Plateau, Kakariko and Korok Forest (native, TAA, every FSR 3 mode, with and without frame generation); a visible playtest of the branch. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 22 ++ runtime/launch_flags_table.c | 8 +- runtime/nvn/maxwell/shader.h | 9 +- runtime/nvn/maxwell/translate.c | 11 +- runtime/nvn/output_scale.c | 35 ++- runtime/nvn/output_scale.h | 2 + runtime/nvn/vulkan/device.c | 37 +++- runtime/nvn/vulkan/exec.c | 186 +++++++++++----- runtime/nvn/vulkan/mvec.c | 374 +++++++++++++++++++++++++------- runtime/nvn/vulkan/mvec.h | 70 +++--- runtime/nvn/vulkan/precompile.c | 4 +- runtime/nvn/vulkan/record.c | 22 ++ runtime/nvn/vulkan/record.h | 5 + runtime/nvn/vulkan/shaders.c | 95 +++++++- runtime/nvn/vulkan/vk.h | 3 + runtime/ui/game_options.mm | 4 +- runtime/ui/menu.mm | 4 +- 17 files changed, 698 insertions(+), 193 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef418ec8e..b4fc44c95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ What changed in each Savage Wind release. The `test` branch holds what the next ## Next (on the `test` branch) +### Performance + +- **FSR 3, FSR 4 and TAA cost the CPU much less:** their motion vectors are worked out on a thread of their own + instead of the thread that translates the game's drawing, every scene draw uses one motion program, and FSR 3 is + dispatched by the recorder thread. RTX 3060 and a Ryzen 5 5600X, Great Plateau, uncapped, 1440p, where the CPU is + the limit: FSR 3 Quality went from 101 to 119 fps (native 130). CPUs with fewer than 6 logical processors keep + the work on the translating thread. +- **TAA is a single pass:** about 0.5 ms of GPU time at 1440p instead of 2.5 ms (same PC: 104 to 122 fps at 1440p; + with the Savage preset, 150% render scale, 54 to 71 fps, SMAA 77). The image is a little softer in motion than + before; `SAVAGEWIND_TAA=full` brings the old seven passes back. +- **Frame generation with no frame limit** no longer lowers the frame rate: its two presents per game frame are + paced on a thread of their own instead of holding the thread that translates the game's drawing. Same PC, Savage + preset at 100% render scale, 1440p, presented frames per second without frame generation / with it before / with it + now: Great Plateau 102 / 47 / 125, Kakariko 88 / 48 / 116, Korok Forest 40 / 29 / 66. +- **Shadow resolution follows FSR 3, FSR 4 and DLSS:** with one of them on, shadow maps above the console's size are + made smaller by the upscaler mode's factor (Savage at Quality: 5440 instead of 8192), the same shadow detail per + rendered pixel. Where shadows were most of the frame the upscaler gained nothing (Korok Forest, FSR 3 Quality: + 41 to 67 fps, native 40). `SAVAGEWIND_SHADOW_FOLLOW=0` keeps the setting's size. +- **Ultra Performance with FSR 3, FSR 4 or DLSS needs a 4K window:** below that it rendered a third of the window on + each side (853 x 480 at 1440p) and the whole image came out blurred. It is greyed there, and a stored Ultra + Performance runs as Performance. FSR 1 keeps it at any size. + ### Fixes - **Water** drawn transparent where a new image was read before its clear finished diff --git a/runtime/launch_flags_table.c b/runtime/launch_flags_table.c index 771aee289..8b6aedc9d 100644 --- a/runtime/launch_flags_table.c +++ b/runtime/launch_flags_table.c @@ -235,7 +235,9 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_MVEC_MATCH", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_MVEC_MATCH_LIMIT", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_MVEC_SHOW_UNMATCHED", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_MVEC_SPIN", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_MVEC_STILL", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_MVEC_THREAD", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_MVEC_VIEW", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_NEAR_MAX", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_NEAR_MIN", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, @@ -337,6 +339,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_SHADER_DUMP", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_SHADER_SALT", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_SHADOW_AT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, + {"SAVAGEWIND_SHADOW_FOLLOW", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_SHOT_AT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_SHOT_PATH", LF_KIND_SWITCH, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_SIZE_PICK", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, @@ -350,6 +353,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_SYNC_FLUSH", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_SYNC_SHADERS", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_SYNC_SUBMIT", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_TAA", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_TAA_VIEW", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_TEST_ACQUIRE_TIMEOUT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_TEST_FLAGS", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, @@ -374,6 +378,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_TWO_BUTTON_LABEL_TEST", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_TWO_BUTTON_ROWS", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_UNIT_HEAP_SCALE", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_UPSCALE_ANY", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_UPSCALE_AT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_VIBRATION", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_ADDR_REPORT", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, @@ -398,6 +403,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_VK_FEEDBACK_LAYOUT", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_FEEDBACK_LOOP", LF_KIND_SWITCH, LF_GROUP_PLAY, "1", "Turns feedback loops on where they are held back for your graphics card."}, {"SAVAGEWIND_VK_FEEDBACK_ONCE", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, + {"SAVAGEWIND_VK_FG_PACER", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_FLIP_WINDING", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_FULL_PASS_BARRIER", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_VK_GATHER_BIAS", LF_KIND_TEXT, LF_GROUP_OTHER, "", ""}, @@ -492,4 +498,4 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_XLATE_VERIFY", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_YAZ0", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, }; -const int LF_TABLE_N = 488; +const int LF_TABLE_N = 494; diff --git a/runtime/nvn/maxwell/shader.h b/runtime/nvn/maxwell/shader.h index 239c3baa8..128752c1e 100644 --- a/runtime/nvn/maxwell/shader.h +++ b/runtime/nvn/maxwell/shader.h @@ -45,12 +45,13 @@ typedef struct { bool flip_y; // lower-left window origin uint8_t mvec; // vertex (GLSL): also the previous frame's position, from the motion history (vulkan/mvec.c): // the body run first with its constant buffers read from the history buffer, both clip - // positions to mv_cur / mv_prev (locations 30, 31) + // positions to mv_cur / mv_prev (locations 30, 31); only when the push constants' mflag + // says the draw moved (else mv_prev is zero, and so is the vector) uint8_t mvec_rt; // fragment (GLSL): 1 + the color location the motion vector goes to (0: none), from mv_cur / // mv_prev: the NDC distance from the previous position; with 0x80: the reactive mask instead // (.z: how much this blended effect covers the pixel, its alpha; no vector); with 0x40: zero - // (a draw whose inputs did not change: the camera's motion, vulkan/mvec.c mvec_still) (in the - // padding: the key's size and layout are unchanged) + // (the camera's motion: what a scene draw writes until its motion program is built, + // exec.c draw_) (in the padding: the key's size and layout are unchanged) uint32_t vs_out_mask; // fragment: varyings the vertex shader provides uint8_t glsl; // emit Vulkan GLSL (see the contract above) instead of MSL uint8_t point_size; // vertex, GLSL: the draw is a point list; a shader that writes no point size writes 1.0 @@ -71,7 +72,7 @@ typedef struct { uint32_t cbuf_mask; // hardware constant buffers read uint32_t cbuf_size[18]; uint32_t cbuf_dynamic; // cbufs indexed with a register of unknown value: bind the whole buffer - uint64_t cbuf_rows[18][4]; // the vec4s of each cbuf read at constant offsets (the first 256; vulkan/mvec.c mvec_still) + uint64_t cbuf_rows[18][4]; // the vec4s of each cbuf read at constant offsets (the first 256; vulkan/mvec.c cb_hash) uint32_t cbuf_rows_all; // cbufs read at an index, or past vec4 255: any of their vec4s may be read int ntex; ShaderTexture tex[64]; diff --git a/runtime/nvn/maxwell/translate.c b/runtime/nvn/maxwell/translate.c index 478e7b647..53cfceeab 100644 --- a/runtime/nvn/maxwell/translate.c +++ b/runtime/nvn/maxwell/translate.c @@ -2338,7 +2338,7 @@ static ShaderInfo *glsl_finish(Ctx *c, bool any_branch, bool dbg) { if (mvec) { // the history: the previous frame's copies of the game's constant buffers (mvec.c), at pb[cb - 3] sp(&s, "layout(std430, set = 0, binding = 63) readonly buffer MvHist { uvec4 ph[]; };\n"); // (std430: uint arrays 4 bytes apart, as mvec.c packs them; a push constant block is std140 by default) - sp(&s, "layout(push_constant, std430) uniform MvPush { uint pb[14]; uint pbn[14]; };\n"); + sp(&s, "layout(push_constant, std430) uniform MvPush { uint mflag; uint pb[14]; uint pbn[14]; };\n"); sp(&s, "#define pcbr(n, off) ph[pb[n] + min((off) >> 4, pbn[n] - 1u)][((off) >> 2) & 3u]\n"); sp(&s, "layout(location = 30) out vec4 mv_cur;\nlayout(location = 31) out vec4 mv_prev;\n"); } @@ -2376,7 +2376,9 @@ static ShaderInfo *glsl_finish(Ctx *c, bool any_branch, bool dbg) { } } if (mvec) { // the previous frame's position first, in a block of its own (its registers start at 0 as well) - sp(&s, " vec4 ppos = vec4(0, 0, 0, 1); vec4 pvd = vec4(0); float pps = 0.0f;\n {\n"); + // (only when the draw moved, mflag: whether it did is known after the draw is translated, vulkan/mvec.c, so one + // program serves both, and a still draw's vertices are not shaded twice) + sp(&s, " vec4 ppos = vec4(0, 0, 0, 1); vec4 pvd = vec4(0); float pps = 0.0f;\n if (mflag != 0u) {\n"); glsl_body(c, &s, pbody.buf ? pbody.buf : "", any_branch, false); sp(&s, " }\n"); } @@ -2389,7 +2391,7 @@ static ShaderInfo *glsl_finish(Ctx *c, bool any_branch, bool dbg) { if (mvec) { if (key->flip_y) sp(&s, " ppos.y = -ppos.y;\n"); if (key->depth_minus_one) sp(&s, " ppos.z = (ppos.z + ppos.w) * 0.5f;\n"); - sp(&s, " mv_cur = gl_Position; mv_prev = ppos;\n"); + sp(&s, " mv_cur = gl_Position; mv_prev = mflag != 0u ? ppos : vec4(0.0f);\n"); } } else if (stage == STAGE_FRAGMENT) { int r = 0; @@ -2433,7 +2435,8 @@ static ShaderInfo *glsl_finish(Ctx *c, bool any_branch, bool dbg) { } else if (mvec_still) { sp(&s, " mv_out = vec4(0.0f);\n"); } else if (mvec_rt >= 0) { // NDC from the previous frame's position to this one's (both after the y flip) - sp(&s, " mv_out = vec4(mv_cur.xy / mv_cur.w - mv_prev.xy / mv_prev.w, 0.0f, 1.0f);\n"); + // (mv_prev all zero: a draw that stood still or has no match, mflag 0: zero, the camera's motion, mvec_fill) + sp(&s, " mv_out = mv_prev.w == 0.0f ? vec4(0.0f) : vec4(mv_cur.xy / mv_cur.w - mv_prev.xy / mv_prev.w, 0.0f, 1.0f);\n"); } } sp(&s, "}\n"); diff --git a/runtime/nvn/output_scale.c b/runtime/nvn/output_scale.c index 00b5ce5c2..32af03f2e 100644 --- a/runtime/nvn/output_scale.c +++ b/runtime/nvn/output_scale.c @@ -93,10 +93,28 @@ bool upscale_modes_available(void) { return on; } +// Ultra Performance renders a third of the window's size on each side. A temporal upscaler (FSR 3 / 4, DLSS) is made to +// bring that to 2160 lines or more; at 1440 the scene is 853 x 480 and the whole image comes out blurred, for hardly +// more frames than Performance where the CPU is the limit. So it is offered from a 4K window on, and below that a +// stored Ultra Performance runs as Performance (the setting is kept: it comes back on a 4K window). FSR 1 keeps it at +// any size. SAVAGEWIND_UPSCALE_ANY=1: offered at any size, as before. +static volatile int g_out_lines; // the window's height (output_scale; 0: not known yet) +bool upscale_mode_offered(int q) { + static int any = -1; + if (any < 0) any = getenv("SAVAGEWIND_UPSCALE_ANY") && atoi(getenv("SAVAGEWIND_UPSCALE_ANY")) != 0; + if (q != UPQ_ULTRA_PERFORMANCE || any || !(rt_fsr3() || rt_dlss())) return true; + return !g_out_lines || g_out_lines >= 2160; +} + +int upscale_quality_now(void) { + int q = g_settings.upscale_quality; + return upscale_mode_offered(q) ? q : UPQ_PERFORMANCE; +} + double upscale_factor(void) { int u = g_settings.upscaler; return u != UPSCALE_OFF && upscaler_available(u) && upscale_modes_available() - ? upscale_mode_factor(g_settings.upscale_quality) : 1.0; + ? upscale_mode_factor(upscale_quality_now()) : 1.0; } // The window's shape over 16:9 while the game's views are widened to fill it, else 1; the field of view's factor in @@ -105,6 +123,7 @@ static volatile float g_view_shape = 1, g_fov = 1, g_map_extra_y; static uint32_t g_world_proj[4]; // tan(fovy / 2), aspect, near, far of the world camera's last matrix (rt_persp), float bits void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { + g_out_lines = (int)dh; double fit = fmin(dw / 1920.0, dh / 1080.0); static double forced = -1, wide_test = -1; if (forced < 0) forced = getenv("SAVAGEWIND_SCALE") ? atof(getenv("SAVAGEWIND_SCALE")) : 0; @@ -451,5 +470,17 @@ unsigned shadow_map_size(unsigned long long frame) { unsigned r = g_settings.shadow_res >= 0 && g_settings.shadow_res < SHADOW_COUNT ? size[g_settings.shadow_res] : 0; for (int i = 0; i < n; i++) if (frame >= at[i]) r = w[i]; - return r > 8192 ? 8192 : r; + if (r > 8192) r = 8192; + // With a temporal upscaler (FSR 3 / 4, DLSS) the scene is drawn smaller by the quality mode's factor, and the + // cascades above the console's size follow it: as many shadow texels per drawn pixel as without the upscaler + // (Extreme at Quality: 5440 instead of 8192). The cascades cost the same at any scene resolution otherwise, and + // where they are most of the frame the upscaler gained nothing. Never under the console's own 896. + // SAVAGEWIND_SHADOW_FOLLOW=0: the setting's size, as before. + static int follow = -1; + if (follow < 0) follow = !getenv("SAVAGEWIND_SHADOW_FOLLOW") || atoi(getenv("SAVAGEWIND_SHADOW_FOLLOW")) != 0; + if (follow && r > 896 && (rt_fsr3() || rt_dlss())) { + r = (unsigned)(r / upscale_factor() / 64.0 + 0.5) * 64; + if (r < 896) r = 896; + } + return r; } diff --git a/runtime/nvn/output_scale.h b/runtime/nvn/output_scale.h index a6401d4e4..3bad9e51b 100644 --- a/runtime/nvn/output_scale.h +++ b/runtime/nvn/output_scale.h @@ -35,6 +35,8 @@ void rt_jitter_set_phases(uint32_t n); // (FSR 3: the jitter sequence's length, bool upscale_modes_available(void); // (rendering below the window's size: needs render-target scaling) double upscale_mode_factor(int q); double upscale_factor(void); +bool upscale_mode_offered(int q); // mode q can be chosen now (Ultra Performance with FSR 3 / 4 or DLSS: a 4K window) +int upscale_quality_now(void); // the mode in use: the setting, or Performance where it is not offered // Video > Shadow resolution: the width the game's shadow maps are made at from presented frame `frame` on (0: their // own size; vulkan/textures.c RS_SHADOW) unsigned shadow_map_size(unsigned long long frame); diff --git a/runtime/nvn/vulkan/device.c b/runtime/nvn/vulkan/device.c index 478e880a5..4fa9587b2 100644 --- a/runtime/nvn/vulkan/device.c +++ b/runtime/nvn/vulkan/device.c @@ -1805,6 +1805,7 @@ static void recreate_swapchain(void) { // one frame at a time otherwise, as before); a swapchain change and teardown wait for them all. // Only with SAVAGEWIND_VK_PRESENT_THREAD=1 now (create_device: one queue by default, #36, #293); otherwise presents on // the calling thread. +pthread_mutex_t g_vk_queue_lock = PTHREAD_MUTEX_INITIALIZER; // (vk.h) static pthread_mutex_t pres_m = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t pres_cv = PTHREAD_COND_INITIALIZER; static pthread_mutex_t sc_lock = PTHREAD_MUTEX_INITIALIZER; @@ -1863,7 +1864,9 @@ static void *present_thread(void *arg) { .swapchainCount = 1, .pSwapchains = &q.sc, .pImageIndices = &q.img}; pthread_mutex_lock(&sc_lock); uint64_t tq = SDL_GetTicksNS(); + pthread_mutex_lock(&g_vk_queue_lock); // (one queue: the recorder submits on it meanwhile) VkResult r = queue_present(g_vk.present_queue, &pi); + pthread_mutex_unlock(&g_vk_queue_lock); tq = SDL_GetTicksNS() - tq; pthread_mutex_unlock(&sc_lock); if (tq > 200000000ull) { // (#224: a present the driver held on to) @@ -1891,6 +1894,25 @@ static bool present_threaded(void) { return on; } +// Frame generation's pair with one queue (the default): each of the two is presented once the GPU has drawn it, the +// game's frame half an interval after the generated one (present_wait_turn). The translating thread did those waits +// itself: it stood still for the GPU's whole frame and then for half the interval it had just made longer, so the game +// drew at a quarter of its rate with the GPU half idle (RTX 3060, 1440p, no frame limit, Great Plateau: 101 fps +// without frame generation, 47 presented with it). The present thread makes them instead, on the same queue +// (g_vk_queue_lock), and the translating thread goes on to the next frame; present_wait_room still holds it at two +// pairs ahead. Plain presents stay with the recorder, except while the thread still has some to make (their order). +// SAVAGEWIND_VK_FG_PACER=0: on the calling thread, as before. +static bool fg_pacer(void) { + static int on = -1; + if (on < 0) { + const char *e = getenv("SAVAGEWIND_VK_FG_PACER"); + on = !(e && !strcmp(e, "0")); + if (on) { pthread_t t; pthread_create(&t, NULL, present_thread, NULL); } + LOG("[vk] frame generation's presents made by %s\n", on ? "the present thread, on the game's queue" : "the calling thread"); + } + return on; +} + void vk_present_idle(void) { pthread_mutex_lock(&pres_m); while (presq_n) pthread_cond_wait(&pres_cv, &pres_m); @@ -1967,7 +1989,9 @@ static void rec_present_run(void *arg) { VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, .pWaitSemaphores = &q->sem, .swapchainCount = 1, .pSwapchains = &q->sc, .pImageIndices = &q->img}; pthread_mutex_lock(&sc_lock); + pthread_mutex_lock(&g_vk_queue_lock); VkResult r = queue_present(g_vk.queue, &pi); + pthread_mutex_unlock(&g_vk_queue_lock); pthread_mutex_unlock(&sc_lock); if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) atomic_store(&rec_present_stale, 1); } @@ -1984,18 +2008,27 @@ static bool present_on_recorder(void) { // Present window image img once sem is signalled (kind, seq: frame generation's pair and the frame's submission, see // present_wait_turn). Returns false when the swapchain must be made again. static bool present_image(uint32_t img, VkSemaphore sem, int kind, uint64_t seq) { - if (!present_threaded() && kind == PRES_PLAIN && present_on_recorder()) { + bool threaded = present_threaded(); + if (!threaded) { + pthread_mutex_lock(&pres_m); + bool queued = presq_n != 0; + pthread_mutex_unlock(&pres_m); + threaded = (kind != PRES_PLAIN || queued) && fg_pacer(); + } + if (!threaded && kind == PRES_PLAIN && present_on_recorder()) { __typeof__(recp[0]) *q = &recp[recp_n++ % RECP_N]; *q = (__typeof__(recp[0])){g_vk.swapchain, sem, img}; rec_custom(rec_present_run, q); return !atomic_exchange(&rec_present_stale, 0); } - if (!present_threaded()) { + if (!threaded) { VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, .pWaitSemaphores = &sem, .swapchainCount = 1, .pSwapchains = &g_vk.swapchain, .pImageIndices = &img}; rec_wait_submitted(seq); // (as present_thread) present_wait_turn(kind, seq); + pthread_mutex_lock(&g_vk_queue_lock); VkResult r = queue_present(g_vk.queue, &pi); + pthread_mutex_unlock(&g_vk_queue_lock); return !(r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR); } pthread_mutex_lock(&pres_m); diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index 503f146c4..79f97de24 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -464,6 +464,7 @@ static void gpp_mark(VkCommandBuffer cb, const char *label) { static void gp_mark(VkCommandBuffer cb, const char *fmt, ...) { bool legacy = g_gpuprof_frame && gp_n < GP_MAX - 1; if (!legacy && !prof_enabled()) return; + if (rec_on_recorder()) return; // (FSR 3's passes when the recorder dispatches it, fsr3_run: a mark is queued commands) char buf[160]; va_list ap; va_start(ap, fmt); @@ -1063,7 +1064,8 @@ static uint64_t gcopy_gen = 1; static struct { uint64_t lo, hi, serial; } uubt[UUB_MAX]; // ranges UpdateUniformBuffer wrote, with the last update's count static int nuub; static uint64_t uub_serial; -static void guest_copy_flush(void) { __atomic_fetch_add(&gcopy_gen, 1, __ATOMIC_RELAXED); } +// (mvec_sync: the motion vector thread reads guest memory after the draw that handed it the ranges, mvec.c) +static void guest_copy_flush(void) { mvec_sync(); __atomic_fetch_add(&gcopy_gen, 1, __ATOMIC_RELAXED); } // UpdateUniformBuffer wrote [lo, hi) static void uub_note(uint64_t lo, uint64_t hi) { @@ -2743,6 +2745,10 @@ typedef struct { bool vs_uses_vid; uint8_t fs_gather; // (up_fix) the fragment stage's first gathered texture: 0 not looked yet, 1 none, 2 + its slot _Atomic int state; // 0 building, 1 ready, 2 failed + // Its motion vector variants once they are built (draw_, mvec.c), by the pass's motion target slot: [0] the motion + // program, [1] the reactive mask's. (Looked up through get_program for every scene draw, their keys made anew + // each time, they cost the translating thread ~0.2 ms a frame.) + void *mv[2][8]; } Prog; // The push constants of a motion vector program (mvec.c MVEC_PUSH: the history offsets of the previous frame's @@ -5416,7 +5422,9 @@ static bool gmem_sparse_refresh(uint64_t size) { .pBufferBinds = &buffer_bind, .signalSemaphoreCount = 1, .pSignalSemaphores = &gmem_sparse_timeline}; + pthread_mutex_lock(&g_vk_queue_lock); VkResult r = vkQueueBindSparse(g_vk.queue, 1, &bind_info, VK_NULL_HANDLE); + pthread_mutex_unlock(&g_vk_queue_lock); if (r != VK_SUCCESS) { LOG("[vk] sparse guest heap batch binding failed (%d)\n", r); goto fail; @@ -8396,60 +8404,78 @@ static void draw_(CmdRec *r, bool indexed) { // ---- motion vectors (mvec.c): an opaque draw of a pass with the motion target is recorded (its identity and the // vertex shader's inputs, for the next frame); matched with one of the previous frame, it is drawn with its motion // program: the vertex shader also run on the previous frame's inputs, the fragment shader also writing the distance - uint32_t mvec_pc[MVEC_PUSH / 4]; + uint32_t mvec_seq = 0; bool mvec_draw = false; // Full-screen triangles and quads that write depth (BOTW fills the scene's depth with several: sky, far plane) // keep no vector: drawn after the geometry, their camera-independent positions would cover it with zeros (they get // the camera's motion in the fallback). bool fullscreen = r->x[2] <= 6 && st.viewport[0][2] >= pass_w * 0.9f / pass_sx && st.viewport[0][3] >= pass_h * 0.9f / pass_sy; - if (pass_mvec >= 0 && st.ds[0] && st.ds[1]) { - MvecDrawIn md; // (its streams and buffers past nstream and ncb are not read: zeroing all of it, ~1 KB a draw, was not free) - memset(&md, 0, offsetof(MvecDrawIn, stream)); - md.vs_streams = 0, md.ncb = 0; - md.frame = renderer_present_count(); - md.gen = __atomic_load_n(&gcopy_gen, __ATOMIC_RELAXED); - md.vs = st.program->stages[0].code_addr; - md.fs = st.program->stages[1].code_addr; - md.count = (uint32_t)r->x[2]; + MvecDrawIn *mdp = pass_mvec >= 0 && st.ds[0] && st.ds[1] ? mvec_draw_begin(renderer_present_count()) : NULL; + if (mdp) { +#define md (*mdp) // (mvec.c's place for the draw being described: only what the head counts is handed on) + md.h.iaddr = 0, md.h.first = 0, md.h.base_vertex = 0; + md.h.ncb = 0, md.h.ninst = 0, md.h.skey = 0; + md.h.gen = __atomic_load_n(&gcopy_gen, __ATOMIC_RELAXED); + md.h.pkey = mvec_mix(st.program->stages[0].code_addr, st.program->stages[1].code_addr); + md.h.vi = pr->vi; + md.h.count = (uint32_t)r->x[2]; if (indexed) { - md.iaddr = r->x[3]; md.base_vertex = (int32_t)r->x[4]; md.base_inst = (uint32_t)r->x[5]; - md.inst = (uint32_t)r->x[6] ? (uint32_t)r->x[6] : 1; + md.h.iaddr = r->x[3]; md.h.base_vertex = (int32_t)r->x[4]; md.h.base_inst = (uint32_t)r->x[5]; + md.h.inst = (uint32_t)r->x[6] ? (uint32_t)r->x[6] : 1; } else { - md.first = (uint32_t)r->x[1]; md.base_inst = (uint32_t)r->x[3]; md.inst = (uint32_t)r->x[4] ? (uint32_t)r->x[4] : 1; + md.h.first = (uint32_t)r->x[1]; md.h.base_inst = (uint32_t)r->x[3]; md.h.inst = (uint32_t)r->x[4] ? (uint32_t)r->x[4] : 1; } - md.nstream = st.nstream; - for (int s = 0; s < st.nstream && s < 16; s++) - md.stream[s] = (MvecStream){st.vbuf[s].addr, st.vbuf[s].size, st.stream[s][0], st.stream[s][1]}; + // the streams the vertex shader's attributes read: per-vertex ones are part of the draw's identity (their + // addresses), instanced ones are inputs (copied by mvec.c) + uint32_t vs_streams = 0; for (int a = 0; a < 16 && a < st.nattrib; a++) - if ((pr->vi->attr_mask >> a) & 1) md.vs_streams |= 1u << ((st.attrib[a] >> 8) & 0x1F); - for (int k = 3; k < 17 && md.ncb < MVEC_CB; k++) { // (the game's buffers: cbuf_info's k >= 3) + if ((pr->vi->attr_mask >> a) & 1) vs_streams |= 1u << ((st.attrib[a] >> 8) & 0x1F); + for (uint32_t m = vs_streams & 0xFFFF; m; m &= m - 1) { + int s = __builtin_ctz(m); + if (s >= st.nstream || !st.vbuf[s].addr) continue; + if (!st.stream[s][1]) md.h.skey = mvec_mix(md.h.skey, st.vbuf[s].addr); + else if (md.h.ninst < MVEC_INST) + md.in[md.h.ninst++] = (MvecInst){st.vbuf[s].addr, st.vbuf[s].size, st.stream[s][0], st.stream[s][1], (uint32_t)s, 0}; + } + for (int k = 3; k < 17 && md.h.ncb < MVEC_CB; k++) { // (the game's buffers: cbuf_info's k >= 3) Range u = st.ubuf[0][k - 3]; if (!((pr->vi->cbuf_mask >> k) & 1) || !u.addr) continue; uint64_t size = pr->vi->cbuf_size[k] ? pr->vi->cbuf_size[k] : 256; if ((pr->vi->cbuf_dynamic & (1u << k)) && u.size) size = u.size > 0x10000 ? 0x10000 : u.size; if (size > u.size && u.size) size = u.size; - md.cb[md.ncb].rows = (pr->vi->cbuf_rows_all >> k) & 1 ? NULL : pr->vi->cbuf_rows[k]; - md.cb[md.ncb].slot = (uint8_t)k; md.cb[md.ncb].addr = u.addr; md.cb[md.ncb++].size = size; - } - int rec = mvec_record(&md); - // a draw that stood still (mvec_still) or got no vector of its own writes zero, the camera's motion (mvec_fill), - // over what a draw behind it wrote - bool still = rec >= 0 && !fullscreen && mvec_still(rec); - bool pushed = !still && rec >= 0 && !fullscreen && mvec_push(rec, mvec_pc); - if (rec >= 0 && !fullscreen) { - ShaderKey mvk = {0}, mfk = {0}; - mvk.glsl = mfk.glsl = 1; - mvk.flip_y = mfk.flip_y = origin == 0; - mvk.depth_minus_one = dmode == 0; - for (int i = 0; i < st.nattrib; i++) mvk.attr_kind[i] = (uint8_t)attr_kind(st.attrib[i] & 0xFF); - for (int i = 0; i < st.rt.ncolor; i++) if (st.rt.color[i]) mfk.rt_kind[i] = (uint8_t)rt_kind(st.rt.color[i]->format); - mvk.mvec = pushed; - mfk.mvec_rt = (uint8_t)((pushed ? 0 : 0x40) | (pass_mvec + 1)); - Prog *mp = get_program(st.program, &mvk, &mfk); - if (mp && atomic_load(&mp->state) == 1) { // (else built later) + md.cb[md.h.ncb++] = (MvecCb){u.addr, (uint32_t)size, (uint8_t)k, {0}}; + } +#undef md + mvec_seq = mvec_draw_commit(); + // Its motion program: the vertex shader also run on the previous frame's inputs when the draw moved, which + // mvec.c's thread tells the recorder (the push constants' mflag, rec_CmdPushConstantsMvec); a draw that stood + // still or got no match writes zero, the camera's motion (mvec_fill), over what a draw behind it wrote. + // Until that program is built, or when it can't be (its varyings 30 / 31 taken): the still variant, zero. + if (!fullscreen) { + Prog *mp = pr->mv[0][pass_mvec]; + if (mp) { pr = mp; - mvec_draw = pushed || still; - if (pushed) mvec_drawn(); + mvec_draw = true; + } else { + ShaderKey mvk = {0}, mfk = {0}; + mvk.glsl = mfk.glsl = 1; + mvk.flip_y = mfk.flip_y = origin == 0; + mvk.depth_minus_one = dmode == 0; + for (int i = 0; i < st.nattrib; i++) mvk.attr_kind[i] = (uint8_t)attr_kind(st.attrib[i] & 0xFF); + for (int i = 0; i < st.rt.ncolor; i++) if (st.rt.color[i]) mfk.rt_kind[i] = (uint8_t)rt_kind(st.rt.color[i]->format); + mvk.mvec = 1; + mfk.mvec_rt = (uint8_t)(pass_mvec + 1); + mp = get_program(st.program, &mvk, &mfk); + if (mp && atomic_load(&mp->state) == 1) { // (else built later) + pr->mv[0][pass_mvec] = mp; + pr = mp; + mvec_draw = true; + } else { + mvk.mvec = 0; + mfk.mvec_rt = (uint8_t)(0x40 | (pass_mvec + 1)); + mp = get_program(st.program, &mvk, &mfk); + if (mp && atomic_load(&mp->state) == 1) pr = mp; + } } } } @@ -8462,15 +8488,20 @@ static void draw_(CmdRec *r, bool indexed) { static int show_unmatched = -1; if (show_unmatched < 0) show_unmatched = getenv("SAVAGEWIND_MVEC_SHOW_UNMATCHED") != NULL; if (pass_mvec >= 0 && ((!(st.ds[0] && st.ds[1]) && (st.color_state[0] & 1)) || (show_unmatched && st.ds[0] && st.ds[1] && !mvec_draw)) && !fullscreen) { - ShaderKey mvk = {0}, mfk = {0}; - mvk.glsl = mfk.glsl = 1; - mvk.flip_y = mfk.flip_y = origin == 0; - mvk.depth_minus_one = dmode == 0; - for (int i = 0; i < st.nattrib; i++) mvk.attr_kind[i] = (uint8_t)attr_kind(st.attrib[i] & 0xFF); - for (int i = 0; i < st.rt.ncolor; i++) if (st.rt.color[i]) mfk.rt_kind[i] = (uint8_t)rt_kind(st.rt.color[i]->format); - mfk.mvec_rt = (uint8_t)(0x80 | (pass_mvec + 1)); - Prog *mp = get_program(st.program, &mvk, &mfk); - if (mp && atomic_load(&mp->state) == 1) pr = mp, mvec_masked(); // (else built for the next frames) + Prog *mp = pr->mv[1][pass_mvec]; + if (!mp) { + ShaderKey mvk = {0}, mfk = {0}; + mvk.glsl = mfk.glsl = 1; + mvk.flip_y = mfk.flip_y = origin == 0; + mvk.depth_minus_one = dmode == 0; + for (int i = 0; i < st.nattrib; i++) mvk.attr_kind[i] = (uint8_t)attr_kind(st.attrib[i] & 0xFF); + for (int i = 0; i < st.rt.ncolor; i++) if (st.rt.color[i]) mfk.rt_kind[i] = (uint8_t)rt_kind(st.rt.color[i]->format); + mfk.mvec_rt = (uint8_t)(0x80 | (pass_mvec + 1)); + mp = get_program(st.program, &mvk, &mfk); + if (mp && atomic_load(&mp->state) != 1) mp = NULL; // (built for the next frames) + if (mp) pr->mv[1][pass_mvec] = mp; + } + if (mp) pr = mp, mvec_masked(); } if (st.rt.depth && !depth_read_only()) pass_ds_written = true; for (int i = 0; i < st.rt.ncolor && i < 8; i++) @@ -8842,7 +8873,7 @@ static void draw_(CmdRec *r, bool indexed) { dc.ndyn = (uint32_t)ndyn; memcpy(dc.dyn, dyn, (size_t)ndyn * 4); } - if (mvec_draw) rec_CmdPushConstants(cb, pr->layout, VK_SHADER_STAGE_VERTEX_BIT, 0, MVEC_PUSH, mvec_pc); + if (mvec_draw) rec_CmdPushConstantsMvec(cb, pr->layout, mvec_seq); uint64_t prof_t2_ = profd ? SDL_GetTicksNS() : 0; ProfZone pz7 = PZ_NOW(); @@ -10610,7 +10641,7 @@ static TexBackend *dlss_scene(VkCommandBuffer cb, TexBackend *color, uint32_t ow if (md && !strcmp(md, "off")) jx = jy = 0; else if (md && strlen(md) == 2) jx *= md[0] == 'n' ? -1 : 1, jy *= md[1] == 'n' ? -1 : 1; } - bool ok = vk_dlss_apply(cb, color, db, mv, o, (unsigned)g_settings.upscale_quality, jx, jy, sx, sy, reset); + bool ok = vk_dlss_apply(cb, color, db, mv, o, (unsigned)upscale_quality_now(), jx, jy, sx, sy, reset); // (the next frames' jitter sequence: 8 x the upscale's area, NVIDIA's recommended length) float area = (float)ow * (float)oh / ((float)w * (float)h); rt_jitter_set_phases((uint32_t)ceilf(8.0f * (area > 1 ? area : 1))); @@ -10732,6 +10763,30 @@ static TexBackend *mvec_taa(VkCommandBuffer cb, TexBackend *b, uint64_t frame) { n ^= 1; const VkImageUsageFlags S = VK_IMAGE_USAGE_STORAGE_BIT; const VkFormat F16 = VK_FORMAT_R16G16B16A16_SFLOAT, R8 = VK_FORMAT_R8_UNORM; + // The light TAA, one pass (shaders.c taa_lite), unless SAVAGEWIND_TAA=full: the seven passes below, FSR 3.1's + // whole reconstruction, cost the GPU ~2.5 ms at 1440p and ~6 ms at 4K on an RTX 3060 (TAA took 20-30 fps off) + static int full = -1; + if (full < 0) full = getenv("SAVAGEWIND_TAA") && !strcmp(getenv("SAVAGEWIND_TAA"), "full"); + if (!full) { + TexBackend *hist[2] = {post_image_ex(11, w, h, F16, S), post_image_ex(12, w, h, F16, S)}; + TexBackend *out = post_image_ex(31, w, h, F16, S); + static const VkComponentMapping id = {0}; + float flip = nvn_window_origin() == 0 ? -1.0f : 1.0f; + float pc[16] = {(float)w, (float)h, 1.0f / (float)w, 1.0f / (float)h, jit[0] * (float)w * 0.5f, + -jit[1] * flip * (float)h * 0.5f, 0, 0, 0, 0, 0, 0, valid ? 1.0f : 0.0f, 8.0f, 0, 0}; + VkImageView in[] = {vk_image_view(b, VK_IMAGE_VIEW_TYPE_2D, b->format, 0, 1, 0, 1, id, VK_IMAGE_ASPECT_COLOR_BIT), + post_view(mvec_vectors_img), + vk_image_view(db, VK_IMAGE_VIEW_TYPE_2D, db->format, 0, 1, 0, 1, id, VK_IMAGE_ASPECT_DEPTH_BIT), + post_view(hist[p])}; + TexBackend *o[] = {hist[c], out}; + vk_full_barrier(cb); + cpost_pass(cb, "taa_lite.comp", in, 4, o, 2, pc, w, h); + vk_full_barrier(cb); + gp_mark(cb, "post taa end"); + last = frame; + lw = w, lh = h; + return out; + } uint32_t w2 = (w + 1) / 2, h2 = (h + 1) / 2, w4 = (w2 + 1) / 2, h4 = (h2 + 1) / 2, w8 = (w4 + 1) / 2, h8 = (h4 + 1) / 2; TexBackend *dil = post_image_ex(16, w, h, VK_FORMAT_R32G32B32A32_SFLOAT, S); TexBackend *luma[2] = {post_image_ex(17, w, h, VK_FORMAT_R16_SFLOAT, S), post_image_ex(18, w, h, VK_FORMAT_R16_SFLOAT, S)}; @@ -10823,6 +10878,17 @@ static TexBackend *mvec_taa(VkCommandBuffer cb, TexBackend *b, uint64_t frame) { // clip-space NDC differences (y up, the image's y down: mvec_fill.frag), FSR wants the UV offset to where the pixel was: // (-x / 2, y / 2), its motion vector scale over the render size. Its jitter is in render pixels, y down. NULL when an // input is missing (no camera yet, sizes that differ) or FSR failed: the scene goes on without it. +typedef struct { Fsr3Dispatch d; int api; } FsrJob; +static _Atomic int fsr3_failed; +// The recorder thread: AMD's DLLs when asked for (their failing, logged there and remembered by fsr_api_usable: the +// built-in FSR 3.1 in their place, from this frame on, without the history of the other upscaler), else the built-in one +static void fsr3_run(void *arg) { + FsrJob *j = arg; + bool amd_ok = j->api && fsr_api_dispatch(&j->d, j->api); + if (j->api && !amd_ok) j->d.reset = true; + if (!amd_ok && !(fsr3_available() && fsr3_dispatch(&j->d))) atomic_store(&fsr3_failed, 1); +} + static TexBackend *fsr3_scene(VkCommandBuffer cb, TexBackend *b, uint32_t ow, uint32_t oh) { uint64_t frame = renderer_present_count(); TexBackend *v = mvec_vectors_img, *db = mvec_depth ? vk_tex(mvec_depth, false) : NULL; @@ -10873,12 +10939,16 @@ static TexBackend *fsr3_scene(VkCommandBuffer cb, TexBackend *b, uint32_t ow, ui if (api != last_api) d.reset = true; last_api = api; gp_mark(cb, api == 4 ? "FSR 4 upscaler" : "FSR 3 upscaler"); - rec_drain(); // (FidelityFX records into cb itself, and may wait for the device: what was queued before goes first) - // (AMD's failing, logged there: the built-in FSR 3.1 in its place, from this frame on, without the history of the - // other upscaler) - bool amd_ok = api && fsr_api_dispatch(&d, api); - if (api && !amd_ok) d.reset = true, api = 0, last_api = 0; - if (!amd_ok && !(fsr3_available() && fsr3_dispatch(&d))) return NULL; + // FidelityFX records into cb itself, and may wait for the device: the recorder thread makes the call, in its turn + // (fsr3_run; with the recorder off, here and now). Waiting for the recorder and dispatching here cost this thread + // ~0.18 ms a frame (RTX 3060, 1440p Quality), where it limits the frame rate. Whether it worked is known a frame + // late: a failure leaves this frame's output undefined and the scene goes on without FSR from the next. + if (atomic_load(&fsr3_failed)) return NULL; + static FsrJob jobs[8]; // (the recorder is never 8 frames behind: a submission a frame waits for it) + static unsigned nj; + FsrJob *j = &jobs[nj++ & 7]; + j->d = d, j->api = api; + rec_custom(fsr3_run, j); gp_mark(cb, api == 4 ? "after FSR 4" : "after FSR 3"); last = frame; vk_dyn_forget(); // (FSR's own pipelines and sets were bound) @@ -11360,6 +11430,7 @@ static void exec_list(uint64_t handle, int depth) { stat_uub++; // The same bytes again (~1 update in 5 in the open world): the copies over the range stay good. if (!memcmp((void *)(uintptr_t)(r->x[0] + r->x[2]), x, r->x[3])) { stat_uub_same++; break; } + mvec_guest_write(r->x[0] + r->x[2], r->x[0] + r->x[2] + r->x[3]); // (mvec.c: a draw its thread has not read yet) memcpy((void *)(uintptr_t)(r->x[0] + r->x[2]), x, r->x[3]); hc_cpu_wrote(r->x[0] + r->x[2], r->x[3]); uub_note(r->x[0] + r->x[2], r->x[0] + r->x[2] + r->x[3]); // (the shared copies over it are stale now) @@ -11452,6 +11523,7 @@ void backend_execute(uint64_t handle) { guest_copy_flush(); // (a new list: the game may have written the memory of the last one's copies since) hc_list_begin(); exec_list(handle, 0); + mvec_sync(); // (the game may write the list's memory from here on) } in_execute = false; PROF_ADD(prof_exec); diff --git a/runtime/nvn/vulkan/mvec.c b/runtime/nvn/vulkan/mvec.c index 6dd42c3ea..7977c966d 100644 --- a/runtime/nvn/vulkan/mvec.c +++ b/runtime/nvn/vulkan/mvec.c @@ -16,14 +16,33 @@ // remaining draws get no motion) and the slot is grown before its next use. // On with Video > Anti-aliasing TAA (mvec_enabled; SAVAGEWIND_MVEC=1 / 0 whatever the setting). // SAVAGEWIND_MVEC_LOG=: statistics every that many frames (default: none). +// +// Threads. The thread that translates the game's command lists (T, exec.c draw_) only describes each scene draw +// (mvec_draw_begin / mvec_draw_commit: 64-byte cells of a ring, two for most draws) and goes on; a thread of its own (W, w_run) does the work: +// the copies, the hashes, the matching, and the draw's push constants, which the recorder thread (record.c) asks for +// when it records the draw (mvec_resolve: by then W is usually done; it waits otherwise). Done on T, all of it cost +// ~1.2 ms a frame of the thread that limits the frame rate (RTX 3060, 1440p: native 130 fps, FSR 3 Quality 104, TAA +// 106). What each thread owns: +// T cur, prev, cur_frame; a slot's buffer, capacity, growth and seq; the cameras; the ring's written end (tq) +// W w_cur, w_prev; a slot's records and used bytes; the tables (dedupe, indices, sorted keys), camc, mstat +// T reads or resets W's state only after mvec_sync (W has done everything handed on and is idle): at a new frame, for +// the cameras at the composite. W reads guest memory after T handed the draw on, so T also syncs before it changes +// memory a pending draw reads (mvec_guest_write, exec.c guest_copy_flush) and at the end of each command list. +// SAVAGEWIND_MVEC_THREAD=0 (or fewer than 6 logical processors): no thread, the work is done at the commit. #include +#include +#include #include #include +#include "../../platform.h" +#include "../../prof.h" #include "../../rt.h" #include "../../settings.h" +#include "../maxwell/shader.h" #include "../output_scale.h" #include "mvec.h" +#include "record.h" #define MVEC_SLOTS 5 #define HIST_START (2ull << 20) // (the Great Plateau uses ~0.3 MB a frame; a fuller frame grows it, losing one frame's motion) @@ -47,7 +66,8 @@ typedef struct { } Slot; static Slot slots[MVEC_SLOTS]; -static int cur = -1, prev = -1; // slots of the frame being recorded and of the one before it +static int cur = -1, prev = -1; // (T) slots of the frame being recorded and of the one before it +static int w_cur = -1, w_prev = -1; // (W) the same, of the frame whose draws it is doing static uint64_t cur_frame = ~0ull; static Dedupe dedupe[DEDUPE]; static Index prev_index[INDEX], ord_index[INDEX]; @@ -223,10 +243,7 @@ bool mvec_enabled(void) { return on; } -static uint64_t mix(uint64_t h, uint64_t v) { - h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); - return h * 0xff51afd7ed558ccdull; -} +static uint64_t mix(uint64_t h, uint64_t v) { return mvec_mix(h, v); } static uint32_t slot_hash(uint64_t key, uint32_t ord) { return (uint32_t)(mix(key, ord) >> 32) & (INDEX - 1); } @@ -303,8 +320,178 @@ static bool match_by_order(void) { static int32_t prev_match(MvecRec *r); -// A new presented frame: the slot it records into, the previous frame's index +// ---- the ring of draws (T writes, W reads) and of their results (W writes, the recorder reads) +// The ring is 64-byte cells: a draw is its head, then its constant buffers four to a cell, then its instanced streams +// two to a cell; a new frame is a head alone. Each thread's counters sit in a cache line of their own, and T looks at +// W's only when its own copy says the ring is full or a draw is pending: with q_head and q_done in one line, and a +// field of the slot written by T for every draw next to the ones W writes, the line went from core to core twice a draw. +#define MQ 8192 // cells T may be ahead of W (a draw: 2-3) +#define RES 16384 // results kept: draws T may be ahead of the recorder (mvec_draw_commit drains it before that) +#if defined(__x86_64__) || defined(__i386__) +#define RELAX() __builtin_ia32_pause() +#elif defined(__aarch64__) +#define RELAX() __asm__ volatile("yield") +#else +#define RELAX() ((void)0) +#endif +typedef union { MvecHead h; MvecCb cb[4]; MvecInst in[2]; } Cell; +static Cell *mq; +static uint32_t (*res)[MVEC_PUSH / 4]; +static _Alignas(64) struct { _Atomic uint32_t v; char pad[60]; } q_head; // cells published by T +static _Alignas(64) struct { _Atomic uint32_t cells, draws; char pad[56]; } q_done; // done by W +static _Alignas(64) struct { _Atomic uint32_t v; char pad[60]; } r_seen; // the last draw the recorder resolved +static _Alignas(64) struct { // T's own + uint32_t w; // cells handed on so far + uint32_t dw; // draws handed on so far: the next one's number + uint32_t done; // q_done.cells when T last looked + uint64_t seq; // the submission the frame's slots were last marked with (mvec_draw_commit) + MvecDrawIn in; // the draw being described (mvec_draw_begin) + char pad[64]; +} tq; +static uint32_t w_dseq; // (W) draws done so far +static int threaded = -1; // 1: W does the work, 0: T at the commit +static pthread_mutex_t q_mu = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t q_cv = PTHREAD_COND_INITIALIZER; +static _Atomic int q_asleep; +// W spins this long for the next draw before it sleeps (T hands one on every ~2 us in a scene pass, and a sleeping W +// costs T a wake-up syscall) +static uint64_t q_spin_ns = 200000; + +static uint32_t cells_of(const MvecHead *h) { return 1u + (h->ncb + 3u) / 4 + (h->ninst + 1u) / 2; } + +static void w_frame(const MvecHead *h); +static void w_draw(const MvecDrawIn *d, uint32_t *pc); +// W: the entry at cell c; how many cells it is +static uint32_t w_process(uint32_t c) { + const MvecHead *h = &mq[c & (MQ - 1)].h; + if (h->kind) { w_frame(h); return 1; } + MvecDrawIn d; + d.h = *h; + uint32_t n = 1; + for (uint32_t k = 0; k < d.h.ncb; k += 4, n++) memcpy(&d.cb[k], &mq[(c + n) & (MQ - 1)], sizeof(Cell)); + for (uint32_t k = 0; k < d.h.ninst; k += 2, n++) memcpy(&d.in[k], &mq[(c + n) & (MQ - 1)], sizeof(Cell)); + w_draw(&d, res[w_dseq & (RES - 1)]); + w_dseq++; + return n; +} + +static void *w_run(void *arg) { + (void)arg; + prof_thread_name("mvec"); + uint32_t t = 0; + for (;;) { + uint32_t h = atomic_load_explicit(&q_head.v, memory_order_acquire); + if (h == t) { + uint64_t t0 = plat_now_ns(); + for (unsigned i = 1; h == t; i++) { + RELAX(); + h = atomic_load_explicit(&q_head.v, memory_order_acquire); + if (!(i & 63) && plat_now_ns() - t0 > q_spin_ns) break; + } + } + if (h == t) { + pthread_mutex_lock(&q_mu); + atomic_store_explicit(&q_asleep, 1, memory_order_seq_cst); + while ((h = atomic_load_explicit(&q_head.v, memory_order_seq_cst)) == t) pthread_cond_wait(&q_cv, &q_mu); + atomic_store_explicit(&q_asleep, 0, memory_order_relaxed); + pthread_mutex_unlock(&q_mu); + } + while (t != h) { + t += w_process(t); + atomic_store_explicit(&q_done.draws, w_dseq, memory_order_release); + atomic_store_explicit(&q_done.cells, t, memory_order_release); + } + } + return NULL; +} + +static void q_init(void) { + mq = calloc(MQ, sizeof *mq); + res = calloc(RES, sizeof *res); + if (!mq || !res) FATAL("[mvec] out of memory\n"); + if (getenv("SAVAGEWIND_MVEC_SPIN")) q_spin_ns = (uint64_t)atol(getenv("SAVAGEWIND_MVEC_SPIN")) * 1000; + const char *e = getenv("SAVAGEWIND_MVEC_THREAD"); + threaded = 0; + if (e ? atoi(e) != 0 : plat_cpu_count() >= 6) { + pthread_t th; + int rc = pthread_create(&th, NULL, w_run, NULL); + if (rc) LOG("[mvec] thread: could not start (error %d): the work stays on the queue thread\n", rc); + else pthread_detach(th), threaded = 1; + } + LOG("[mvec] motion vectors: %s\n", threaded ? "on a thread of their own" : "on the queue thread"); +} + +// T: hands tq.in on (its head, and the buffers and streams it counts) +static void q_put(void) { + if (threaded < 0) q_init(); + const MvecDrawIn *d = &tq.in; + uint32_t n = cells_of(&d->h); + while (tq.w + n - tq.done > MQ) { // (W is behind by the whole ring: a short wait) + tq.done = atomic_load_explicit(&q_done.cells, memory_order_acquire); + if (tq.w + n - tq.done > MQ) RELAX(); + } + uint32_t c = tq.w; + mq[c++ & (MQ - 1)].h = d->h; + for (uint32_t k = 0; k < d->h.ncb; k += 4) memcpy(&mq[c++ & (MQ - 1)], &d->cb[k], sizeof(Cell)); + for (uint32_t k = 0; k < d->h.ninst; k += 2) memcpy(&mq[c++ & (MQ - 1)], &d->in[k], sizeof(Cell)); + if (!threaded) { + tq.w += w_process(tq.w); + tq.done = tq.w; + atomic_store_explicit(&q_done.draws, w_dseq, memory_order_release); + atomic_store_explicit(&q_done.cells, tq.w, memory_order_release); + return; + } + tq.w = c; + atomic_store_explicit(&q_head.v, c, memory_order_seq_cst); + if (atomic_load_explicit(&q_asleep, memory_order_seq_cst)) { + pthread_mutex_lock(&q_mu); + pthread_cond_signal(&q_cv); + pthread_mutex_unlock(&q_mu); + } +} + +void mvec_sync(void) { + if (threaded <= 0 || tq.done == tq.w) return; + if ((tq.done = atomic_load_explicit(&q_done.cells, memory_order_acquire)) == tq.w) return; + SW_ZONE("mvec sync"); + while (atomic_load_explicit(&q_done.cells, memory_order_acquire) != tq.w) RELAX(); + tq.done = tq.w; +} + +void mvec_guest_write(uint64_t lo, uint64_t hi) { + if (threaded <= 0 || tq.done == tq.w) return; + tq.done = atomic_load_explicit(&q_done.cells, memory_order_acquire); + for (uint32_t i = tq.done; i != tq.w;) { + const MvecHead *h = &mq[i & (MQ - 1)].h; + uint32_t c = i + 1; + i += cells_of(h); + if (h->kind) continue; + bool hit = false; + for (uint32_t k = 0; k < h->ncb && !hit; k++) { + const MvecCb *b = &mq[(c + k / 4) & (MQ - 1)].cb[k & 3]; + hit = b->addr < hi && lo < b->addr + b->size; + } + c += (h->ncb + 3u) / 4; + for (uint32_t k = 0; k < h->ninst && !hit; k++) { + const MvecInst *m = &mq[(c + k / 2) & (MQ - 1)].in[k & 1]; + hit = m->addr < hi && lo < m->addr + (m->size ? m->size : 8ull << 20); + } + if (hit) { mvec_sync(); return; } + } +} + +void mvec_resolve(uint32_t seq, uint32_t pc[MVEC_PUSH / 4]) { + if ((int32_t)(atomic_load_explicit(&q_done.draws, memory_order_acquire) - seq) <= 0) { + SW_ZONE("mvec resolve wait"); + while ((int32_t)(atomic_load_explicit(&q_done.draws, memory_order_acquire) - seq) <= 0) RELAX(); + } + memcpy(pc, res[seq & (RES - 1)], MVEC_PUSH); + atomic_store_explicit(&r_seen.v, seq, memory_order_relaxed); +} + +// T: a new presented frame: the slot it records into (W idle: its state of the last frame is read and reset here) static void frame_begin(uint64_t frame) { + mvec_sync(); if (cur >= 0) camera_finish(&slots[cur]); if (cur >= 0) { if (slots[cur].used > mstat.max_used) mstat.max_used = slots[cur].used; @@ -321,20 +508,28 @@ static void frame_begin(uint64_t frame) { s->full = false; s->frame = frame; prev = last >= 0 && slots[last].frame + 1 == frame ? last : -1; + tq.seq = ~0ull; + tq.in.h = (MvecHead){.kind = 1, .inst = (uint32_t)cur, .base_inst = (uint32_t)prev}; + q_put(); +} + +// W: the new frame's index of the previous frame's records +static void w_frame(const MvecHead *h) { + w_cur = (int)h->inst, w_prev = (int)h->base_inst; if (++epoch == 0) { // (wrapped: entries 2^32 frames old would look current) memset(dedupe, 0, sizeof dedupe), memset(prev_index, 0, sizeof prev_index), memset(ord_index, 0, sizeof ord_index); if (krange) memset(krange, 0, (krange_mask + 1) * sizeof *krange); epoch = 1; } - if (prev < 0) return; + if (w_prev < 0) return; if (match_by_order() || log_every() > 0) // (key, ordinal) -> record: draw-order matching and its statistics only - for (int i = 0; i < slots[prev].nrec; i++) { - const MvecRec *r = &slots[prev].rec[i]; + for (int i = 0; i < slots[w_prev].nrec; i++) { + const MvecRec *r = &slots[w_prev].rec[i]; uint32_t h = slot_hash(r->key, r->ord); while (prev_index[h].epoch == epoch) h = (h + 1) & (INDEX - 1); prev_index[h] = (Index){r->key, r->ord, epoch, i}; } - npk = slots[prev].nrec; // (by key: each key's candidates together, in draw order) + npk = slots[w_prev].nrec; // (by key: each key's candidates together, in draw order) if (npk > cap_pk) { cap_pk = npk * 2; pkeys = realloc(pkeys, (size_t)cap_pk * sizeof *pkeys); @@ -346,7 +541,7 @@ static void frame_begin(uint64_t frame) { ksort = realloc(ksort, (size_t)cap_pk * sizeof *ksort); ksort2 = realloc(ksort2, (size_t)cap_pk * sizeof *ksort2); } - sort_prev_by(&slots[prev], false, pkeys, pidx); + sort_prev_by(&slots[w_prev], false, pkeys, pidx); uint32_t want = 1024; while (want < 2u * (uint32_t)npk) want *= 2; if (want > krange_mask + 1) { @@ -363,7 +558,7 @@ static void frame_begin(uint64_t frame) { i = j; } memset(ptaken, 0, (size_t)npk * sizeof *ptaken); - sort_prev_by(&slots[prev], true, pkeys2, pidx2); + sort_prev_by(&slots[w_prev], true, pkeys2, pidx2); memset(rtaken, 0, (size_t)npk * sizeof *rtaken); } @@ -389,7 +584,7 @@ static float fingerprint_distance(const MvecRec *a, const MvecRec *b) { // draw), and stops at an identical fingerprint (a still object, the most common case). #define MATCH_WINDOW 24 static int32_t prev_match(MvecRec *r) { - if (prev < 0 || !npk) return -1; + if (w_prev < 0 || !npk) return -1; uint32_t h = (uint32_t)(r->key >> 40) & krange_mask; while (krange[h].epoch == epoch && krange[h].key != r->key) h = (h + 1) & krange_mask; if (krange[h].epoch != epoch) return -1; @@ -402,8 +597,8 @@ static int32_t prev_match(MvecRec *r) { for (int k = 0; k <= 2 * MATCH_WINDOW && bd > 0; k++) { // (at, at + 1, at - 1, at + 2, ...) int i = at + (k & 1 ? (k + 1) / 2 : -(k / 2)); if (i < lo || i >= end || ptaken[i] || rtaken[pidx[i]]) continue; - if (slots[prev].rec[pidx[i]].ninst != r->ninst) continue; - float d = fingerprint_distance(r, &slots[prev].rec[pidx[i]]); + if (slots[w_prev].rec[pidx[i]].ninst != r->ninst) continue; + float d = fingerprint_distance(r, &slots[w_prev].rec[pidx[i]]); if (d < bd) bd = d, best = i; } if (best < 0) return -1; @@ -427,14 +622,14 @@ static int32_t prev_match(MvecRec *r) { // camera's motion alone, not their swaying (temporal anti-aliasing smeared them, a shimmer on every distant tree). // Their vertices hold where they are; the motion is in the constants, which any of them gives the same. static int32_t prev_match_loose(MvecRec *r) { - if (prev < 0 || !npk) return -1; + if (w_prev < 0 || !npk) return -1; int lo = 0, hi = npk; while (lo < hi) { int m = (lo + hi) / 2; if (pkeys2[m] < r->key2) lo = m + 1; else hi = m; } int best = -1; float bd = 0.01f; for (int i = lo, n = 0; i < npk && pkeys2[i] == r->key2 && n < 64 && bd > 0; i++, n++) { if (rtaken[pidx2[i]]) continue; - float d = fingerprint_distance(r, &slots[prev].rec[pidx2[i]]); + float d = fingerprint_distance(r, &slots[w_prev].rec[pidx2[i]]); if (d < bd) bd = d, best = i; } if (best < 0) return -1; @@ -445,7 +640,7 @@ static int32_t prev_match_loose(MvecRec *r) { } static int32_t prev_lookup(uint64_t key, uint32_t ord) { - if (prev < 0) return -1; + if (w_prev < 0) return -1; for (uint32_t h = slot_hash(key, ord);; h = (h + 1) & (INDEX - 1)) { if (prev_index[h].epoch != epoch) return -1; if (prev_index[h].key == key && prev_index[h].ord == ord) return prev_index[h].rec; @@ -460,7 +655,7 @@ static uint32_t next_ordinal(uint64_t key) { } } -// A hash of n bytes (mvec_still: equal inputs) +// A hash of n bytes (w_draw: equal inputs, a draw that stood still) static uint64_t content_hash(const uint8_t *p, uint64_t n) { uint64_t h = n * 0x9e3779b97f4a7c15ull, v; for (; n >= 8; p += 8, n -= 8) memcpy(&v, p, 8), h = (h ^ v) * 0xff51afd7ed558ccdull, h ^= h >> 32; @@ -489,7 +684,7 @@ static uint64_t cb_hash(const uint8_t *p, uint64_t size, const uint64_t *rows, b // Copies [addr, addr + size) of guest memory into the current slot (shared with an earlier copy of the same range in // the same generation); UINT32_MAX when the slot is full. *hash: cb_hash's. static uint32_t copy_in(uint64_t addr, uint64_t size, uint64_t gen, bool share, const uint64_t *rows, bool camera, uint64_t *hash) { - Slot *s = &slots[cur]; + Slot *s = &slots[w_cur]; uint32_t h = (uint32_t)(mix(mix(addr, size), gen) >> 40) & (DEDUPE - 1); if (share && dedupe[h].epoch == epoch && dedupe[h].addr == addr && dedupe[h].size == size && dedupe[h].gen == gen) { mstat.dedupe_hits++; @@ -513,43 +708,74 @@ static uint32_t copy_in(uint64_t addr, uint64_t size, uint64_t gen, bool share, return (uint32_t)off; } -int mvec_record(const MvecDrawIn *d) { - if (!mvec_enabled()) return -1; - if (d->frame != cur_frame) frame_begin(d->frame); - Slot *s = &slots[cur]; +MvecDrawIn *mvec_draw_begin(uint64_t frame) { + if (!mvec_enabled()) return NULL; + if (frame != cur_frame) frame_begin(frame); + tq.in.h.kind = 0; + return &tq.in; +} + +uint32_t mvec_draw_commit(void) { + // (the history of both frames is read by this frame's draws: kept until their submission is done) + uint64_t sq = vk_pending_seq(); + if (sq != tq.seq) { + tq.seq = sq; + slots[cur].seq = sq; + if (prev >= 0) slots[prev].seq = sq; + } + // the recorder still has to read the results of draws up to RES back: never in practice (it is a few hundred + // draws behind), but a result overwritten would be another draw's history offsets (looked at now and then: the + // recorder writes that line for every draw) + if (!(tq.dw & 255) && tq.dw - atomic_load_explicit(&r_seen.v, memory_order_relaxed) > RES - 512) { + rec_drain(); + atomic_store_explicit(&r_seen.v, tq.dw, memory_order_relaxed); + } + uint32_t seq = tq.dw++; + q_put(); + return seq; +} + +// W: one draw: its record, its copies, its match, and its push constants (pc: mflag, then the match's constant buffer +// copies in the previous frame's history; all zero: no vector of its own) +static void w_draw(const MvecDrawIn *d, uint32_t *pc) { + memset(pc, 0, MVEC_PUSH); + if (w_cur < 0) return; + Slot *s = &slots[w_cur]; mstat.draws++; - if (s->full) { mstat.dropped++; return -1; } + if (s->full) { mstat.dropped++; return; } if (s->nrec == s->cap_rec) { s->cap_rec = s->cap_rec ? s->cap_rec * 2 : 4096; s->rec = realloc(s->rec, (size_t)s->cap_rec * sizeof *s->rec); } MvecRec *r = &s->rec[s->nrec]; memset(r, 0, sizeof *r); - uint64_t key = mix(mix(mix(d->vs, d->fs), d->iaddr), ((uint64_t)d->count << 32) | d->first); - key = mix(key, (uint32_t)d->base_vertex); - uint64_t key2 = mix(mix(d->vs, d->fs), ~0ull); + const ShaderInfo *vi = d->h.vi; + uint64_t key = mix(mix(d->h.pkey, d->h.iaddr), ((uint64_t)d->h.count << 32) | d->h.first); + key = mix(mix(key, (uint32_t)d->h.base_vertex), d->h.skey); + uint64_t key2 = mix(mix(d->h.pkey, ~0ull), d->h.skey); uint64_t used_before = s->used; - for (int i = 0; i < d->nstream && i < 16; i++) { - const MvecStream *m = &d->stream[i]; - if (!((d->vs_streams >> i) & 1) || !m->addr) continue; - if (!m->divisor) { key = mix(key, m->addr), key2 = mix(key2, m->addr); continue; } - if (r->ninst == MVEC_INST) continue; - uint64_t n = (d->base_inst + d->inst + m->divisor - 1) / m->divisor, size = n * m->stride; + const MvecInst *inst0 = NULL; // (the first instanced stream copied) + for (int i = 0; i < d->h.ninst && i < MVEC_INST; i++) { + const MvecInst *m = &d->in[i]; + uint64_t n = (d->h.base_inst + d->h.inst + m->divisor - 1) / m->divisor, size = n * m->stride; if (size > m->size && m->size) size = m->size; if (!size || size > (8u << 20)) continue; uint64_t ch; - uint32_t off = copy_in(m->addr, size, d->gen, false, NULL, false, &ch); // (rewritten in place: never shared across draws) + uint32_t off = copy_in(m->addr, size, d->h.gen, false, NULL, false, &ch); // (rewritten in place: never shared across draws) if (off == UINT32_MAX) goto full; r->hash = mix(r->hash, ch); - r->inst_stream[r->ninst] = (uint8_t)i; + if (!inst0) inst0 = m; + r->inst_stream[r->ninst] = (uint8_t)m->index; r->inst_off[r->ninst] = off; r->inst_size[r->ninst++] = (uint32_t)size; mstat.inst_bytes += size; } - for (int k = 0; k < d->ncb && r->ncb < MVEC_CB; k++) { + for (int k = 0; k < d->h.ncb && r->ncb < MVEC_CB; k++) { if (!d->cb[k].addr || !d->cb[k].size) continue; uint64_t ch; - uint32_t off = copy_in(d->cb[k].addr, d->cb[k].size, d->gen, true, d->cb[k].rows, d->cb[k].slot == 3, &ch); + int sl = d->cb[k].slot; // (the vec4s the vertex shader reads of it; NULL: any) + const uint64_t *rows = (vi->cbuf_rows_all >> sl) & 1 ? NULL : vi->cbuf_rows[sl]; + uint32_t off = copy_in(d->cb[k].addr, d->cb[k].size, d->h.gen, true, rows, sl == 3, &ch); if (off == UINT32_MAX) goto full; r->hash = mix(r->hash, mix(d->cb[k].slot, ch)); if (d->cb[k].slot == 3) { // (camera block candidates: camera_finish) @@ -566,14 +792,14 @@ int mvec_record(const MvecDrawIn *d) { // the fingerprint, from guest memory as it is now; not from the camera block (slot 3), which the scene's draws share: // it tells no draw apart, and as the camera moves no draw's fingerprint was equal to its match's any more, so the // search never stopped early (0.9 ms a frame of matching) - for (int k = 0; k < d->ncb && r->nfeat + 12 <= MVEC_FEAT; k++) { + for (int k = 0; k < d->h.ncb && r->nfeat + 12 <= MVEC_FEAT; k++) { if (!d->cb[k].addr || d->cb[k].size < 48 || d->cb[k].slot == 3) continue; memcpy(&r->feat[r->nfeat], (const void *)(uintptr_t)d->cb[k].addr, 48); r->nfeat += 12; } if (r->ninst > 0 && r->nfeat + 4 <= MVEC_FEAT) { - const MvecStream *m = &d->stream[r->inst_stream[0]]; - uint64_t ioff = m->divisor ? (uint64_t)(d->base_inst / m->divisor) * m->stride : 0; + const MvecInst *m = inst0; + uint64_t ioff = m->divisor ? (uint64_t)(d->h.base_inst / m->divisor) * m->stride : 0; if (m->addr && ioff + 16 <= r->inst_size[0]) { uint64_t avail = r->inst_size[0] - ioff; int nf = (int)(avail / 4); @@ -597,7 +823,7 @@ int mvec_record(const MvecDrawIn *d) { mstat.moved_checked++; const float *t = &r->feat[0]; for (int m = 0; m < 2; m++) { - const MvecRec *q = &slots[prev].rec[m ? pf : po]; + const MvecRec *q = &slots[w_prev].rec[m ? pf : po]; if (q->nfeat < 12) continue; float dx = t[3] - q->feat[3], dy = t[7] - q->feat[7], dz = t[11] - q->feat[11]; if (dx * dx + dy * dy + dz * dz > 1e-4f) { if (m) mstat.moved_fp++; else mstat.moved_order++; } @@ -608,45 +834,32 @@ int mvec_record(const MvecDrawIn *d) { if (r->ord) mstat.repeated++; if (r->prev >= 0) mstat.matched++; else mstat.unmatched++; - s->seq = vk_pending_seq(); - return s->nrec++; + s->nrec++; + if (r->prev < 0) return; + const MvecRec *p = &slots[w_prev].rec[r->prev]; + // its inputs are its match's (the hash): it stood still, and the camera's motion is its vector (most of the world + // stands still, and a vertex shader run twice costs the GPU: ~5% fps when every matched draw did) + static int still = -1; // SAVAGEWIND_MVEC_STILL=0: (testing) every matched draw runs its vertex shader twice + if (still < 0) still = !getenv("SAVAGEWIND_MVEC_STILL") || atoi(getenv("SAVAGEWIND_MVEC_STILL")) != 0; + if (still && p->hash == r->hash) { mstat.still++; return; } + for (int k = 0; k < r->ncb; k++) { + int j = -1; + for (int m = 0; m < p->ncb; m++) if (p->cb_slot[m] == r->cb_slot[k]) j = m; + if (j < 0) { memset(pc, 0, MVEC_PUSH); return; } // (the match lacks a buffer this draw reads) + int sl = r->cb_slot[k] - 3; + pc[1 + sl] = p->cb_off[j] / 16; + pc[15 + sl] = (p->cb_size[j] + 15) / 16; + } + pc[0] = 1; + mstat.motion++; + return; full: s->used = used_before; mstat.dropped++; - return -1; } -void mvec_drawn(void) { mstat.motion++; } - -bool mvec_still(int rec) { - static int on = -1; // SAVAGEWIND_MVEC_STILL=0: (testing) every matched draw with its motion program - if (on < 0) on = !getenv("SAVAGEWIND_MVEC_STILL") || atoi(getenv("SAVAGEWIND_MVEC_STILL")) != 0; - if (!on || cur < 0 || prev < 0 || rec < 0 || rec >= slots[cur].nrec) return false; - const MvecRec *r = &slots[cur].rec[rec]; - if (r->prev < 0 || slots[prev].rec[r->prev].hash != r->hash) return false; - mstat.still++; - return true; -} void mvec_masked(void) { mstat.masked++; } -bool mvec_push(int rec, uint32_t pc[MVEC_PUSH / 4]) { - if (cur < 0 || prev < 0 || rec < 0 || rec >= slots[cur].nrec) return false; - const MvecRec *r = &slots[cur].rec[rec]; - if (r->prev < 0) return false; - const MvecRec *p = &slots[prev].rec[r->prev]; - memset(pc, 0, MVEC_PUSH); - for (int k = 0; k < r->ncb; k++) { - int j = -1; - for (int m = 0; m < p->ncb; m++) if (p->cb_slot[m] == r->cb_slot[k]) j = m; - if (j < 0) return false; - int s = r->cb_slot[k] - 3; - pc[s] = p->cb_off[j] / 16; - pc[14 + s] = (p->cb_size[j] + 15) / 16; - } - slots[prev].seq = vk_pending_seq(); // (read by this frame's draws too: kept until they are done) - return true; -} - VkDescriptorBufferInfo mvec_history_info(void) { int i = prev >= 0 ? prev : cur; return (VkDescriptorBufferInfo){i >= 0 ? slots[i].buf : VK_NULL_HANDLE, 0, VK_WHOLE_SIZE}; @@ -671,6 +884,7 @@ float mvec_view_enabled(void) { bool mvec_reprojection(float m[16], float jitter[2]) { if (cur < 0 || prev < 0 || !slots[prev].cam.valid) return false; + mvec_sync(); // (the frame's camera block copies: W's) MvecCamera now; if (!camera_compute(&slots[cur], &now)) return false; // prev proj * (prev view * inverse of this view) * inverse of this proj, in double: the views hold the camera's @@ -705,7 +919,9 @@ bool mvec_reprojection(float m[16], float jitter[2]) { bool mvec_camera_now(float jitter[2], float *near_, float *far_, float *fov_y) { MvecCamera now; - if (cur < 0 || !camera_compute(&slots[cur], &now)) return false; + if (cur < 0) return false; + mvec_sync(); + if (!camera_compute(&slots[cur], &now)) return false; jitter[0] = -now.proj[2], jitter[1] = -now.proj[6]; // (OpenGL-style rows: [2][2] = -(f + n) / (f - n), [2][3] = -2fn / (f - n), [1][1] = 1 / tan(fovy / 2)) float a = now.proj[10], b = now.proj[11]; @@ -718,11 +934,3 @@ const MvecCamera *mvec_camera(bool previous) { if (!previous && prev >= 0) i = (prev + MVEC_SLOTS - 1) % MVEC_SLOTS; return i >= 0 && slots[i].cam.valid ? &slots[i].cam : NULL; } - -const MvecRec *mvec_records(bool previous, int *n, VkBuffer *history) { - int i = previous ? prev : cur; - if (i < 0) { *n = 0; *history = VK_NULL_HANDLE; return NULL; } - *n = slots[i].nrec; - *history = slots[i].buf; - return slots[i].rec; -} diff --git a/runtime/nvn/vulkan/mvec.h b/runtime/nvn/vulkan/mvec.h index eff9bf8f0..b457e80f6 100644 --- a/runtime/nvn/vulkan/mvec.h +++ b/runtime/nvn/vulkan/mvec.h @@ -11,28 +11,35 @@ #define MVEC_INST 4 // instanced streams copied per draw #define MVEC_FEAT 48 // a draw's fingerprint: the first 12 floats of each of its first 4 constant buffers // A motion program's inputs (maxwell/translate.c, ShaderKey mvec): the previous frame's history buffer at this binding -// of the vertex set, and push constants: uint pb[14] (where each constant buffer slot 3..16 starts, in 16-byte units) -// then uint pbn[14] (its size, in 16-byte units) +// of the vertex set, and push constants: uint mflag (1: the draw moved, its vertex shader also runs on the previous +// frame's inputs; 0: it stood still or has no match, the camera's motion is its vector), uint pb[14] (where each +// constant buffer slot 3..16 starts, in 16-byte units) then uint pbn[14] (its size, in 16-byte units) #define MVEC_HISTORY_BINDING 63 -#define MVEC_PUSH 112 +#define MVEC_PUSH 116 -typedef struct { uint64_t addr, size; uint32_t stride, divisor; } MvecStream; - -// A scene draw as draw_ sees it (exec.c): what identifies it and where its vertex shader's inputs are in guest memory +// A scene draw as draw_ sees it (exec.c): what identifies it and where its vertex shader's inputs are in guest memory. +// Packed: the translating thread writes one for every scene draw and the motion vector thread reads it, so every cache +// line of it crosses from one core to the other (a draw is 2 lines in the ring, mvec.c; at 900 bytes a draw with the +// two threads' counters in one line it cost the translating thread ~0.2 us a draw, 0.5 ms a frame). +typedef struct { uint64_t addr; uint32_t size; uint8_t slot, pad[3]; } MvecCb; // a constant buffer the vertex shader reads +typedef struct { uint64_t addr, size; uint32_t stride, divisor, index, pad; } MvecInst; // an instanced stream it reads typedef struct { - uint64_t frame; // presented frames so far (renderer_present_count) + uint8_t kind; // (mvec.c: 0 a draw, 1 a new frame: inst, base_inst = its slot and the previous frame's) + uint8_t ncb, ninst, pad; + int32_t base_vertex; uint64_t gen; // guest copy generation (exec.c gcopy_gen): equal ranges of one generation hold equal bytes - uint64_t vs, fs; // shader code addresses - uint64_t iaddr; // index buffer (0: not indexed) + uint64_t pkey; // mvec_mix(vertex shader code address, fragment shader code address) + uint64_t skey; // the non-instanced streams the vertex shader reads: their addresses, mvec_mix'ed in stream order + uint64_t iaddr; // index buffer (0: not indexed) + const void *vi; // the vertex shader's ShaderInfo: the vec4s it reads of each buffer (cbuf_rows) uint32_t count, first, inst, base_inst; - int32_t base_vertex; - int nstream; - MvecStream stream[16]; - uint32_t vs_streams; // streams the vertex shader's attributes read - int ncb; - // rows: the vec4s the vertex shader reads of it (ShaderInfo cbuf_rows; NULL: any) - struct { uint8_t slot; uint64_t addr, size; const uint64_t *rows; } cb[MVEC_CB]; -} MvecDrawIn; +} MvecHead; +typedef struct { MvecHead h; MvecCb cb[16]; MvecInst in[MVEC_INST]; } MvecDrawIn; // (cb: MVEC_CB used) +_Static_assert(sizeof(MvecHead) == 64 && sizeof(MvecCb) == 16 && sizeof(MvecInst) == 32, "mvec ring cells"); +static inline uint64_t mvec_mix(uint64_t h, uint64_t v) { + h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); + return h * 0xff51afd7ed558ccdull; +} // One recorded draw: its identity, its match in the previous frame and its copied inputs (offsets in its frame's // history buffer, mvec_records) @@ -54,9 +61,20 @@ typedef struct { bool mvec_enabled(void); // Video > Anti-aliasing TAA, or SAVAGEWIND_MVEC=1 bool mvec_for_framegen(void); // frame generation takes them: SAVAGEWIND_FG_OBJECT_VECTORS=1 (default: the camera's) -// Records a scene draw of the current frame: its index among the frame's records, -1 when not recorded (off, or the -// history buffer is full: grown for the next frame). -int mvec_record(const MvecDrawIn *d); +// A scene draw of the current frame, recorded in two steps by the thread that translates the game's command lists: +// mvec_draw_begin gives the place to describe it in (NULL: off), mvec_draw_commit hands it on and returns its number. +// The work itself - copying the vertex shader's inputs into the history, matching the draw with one of the previous +// frame, telling whether it moved - is done by a thread of its own (mvec.c), while the translating thread goes on: +// it cost that thread ~1.2 ms a frame, and where it is the limit FSR 3 and TAA ran slower than native. The draw's +// push constants (MVEC_PUSH bytes) are therefore not known when it is translated: mvec_resolve gives them, waiting +// for the work if need be, to the thread that records the command (record.c rec_CmdPushConstantsMvec). +MvecDrawIn *mvec_draw_begin(uint64_t frame); +uint32_t mvec_draw_commit(void); +void mvec_resolve(uint32_t seq, uint32_t pc[MVEC_PUSH / 4]); +// Every draw handed on so far is done (the translating thread): before guest memory the draws may read changes +// (mvec_guest_write: only when a draw not done yet reads [lo, hi)), at the end of a command list. +void mvec_sync(void); +void mvec_guest_write(uint64_t lo, uint64_t hi); // A frame's camera, from its scene camera block (the constant buffer at slot 3 that most scene draws share; the scene // shaders make clip = proj * view * position): the view (rows 0-2, a rigid 3x4) and the projection (rows 7-10, an // OpenGL-style 4x4, its near plane moving with the camera's distance), row-major as the shaders read them; vp = proj * @@ -76,17 +94,7 @@ bool mvec_camera_now(float jitter[2], float *near_, float *far_, float *fov_y); // object vector, the camera vector minus it (zero on still geometry when both are right) int mvec_camera_only(void); -// The current and the previous frame's records and history buffers (NULL / 0 when there is no previous frame) -const MvecRec *mvec_records(bool previous, int *n, VkBuffer *history); -// The push constants of the current frame's record `rec` (mvec_record's index): its match's constant buffer copies in -// the previous frame's history. false: no match, or the match lacks a buffer this draw reads (no motion program). -bool mvec_push(int rec, uint32_t pc[MVEC_PUSH / 4]); -// Whether the current frame's record `rec` read the same inputs as its match (its hash): it stood still, and the -// camera's motion is its vector (exec.c draws it with the still variant, ShaderKey mvec_rt 0x40, not its motion -// program: most of the world stands still, and the motion programs, their vertex shaders run twice, cost ~5% fps) -bool mvec_still(int rec); -void mvec_drawn(void); -void mvec_masked(void); // a blended effect was drawn with its reactive mask program (statistics) // a recorded draw was drawn with its motion program (statistics) +void mvec_masked(void); // a blended effect was drawn with its reactive mask program (statistics) // The previous frame's history buffer, for MVEC_HISTORY_BINDING (any valid buffer before there is one) VkDescriptorBufferInfo mvec_history_info(void); // SAVAGEWIND_MVEC_VIEW=: the vectors drawn over the scene (exec.c mvec_scene_view), full colour at that length diff --git a/runtime/nvn/vulkan/precompile.c b/runtime/nvn/vulkan/precompile.c index 14a69f84b..face4168f 100644 --- a/runtime/nvn/vulkan/precompile.c +++ b/runtime/nvn/vulkan/precompile.c @@ -17,8 +17,8 @@ // vectors on, a pass with the internal-resolution scene depth gets the motion target appended after its color targets // (slot = the pass's color target count, exec.c begin_pass), and in it // - a depth-writing draw (not full-screen) uses its program's motion variant: vertex key + mvec 1 and fragment key + -// mvec_rt (slot + 1) when it has a match in the previous frame, else the vertex key as is and fragment mvec_rt -// 0x40 | (slot + 1) (still: zero motion); +// mvec_rt (slot + 1), whether it moved or not (the push constants say); until that is built, the vertex key as +// is and fragment mvec_rt 0x40 | (slot + 1) (still: zero motion); // - a blended draw that writes no depth: fragment mvec_rt 0x80 | (slot + 1) (the reactive mask), vertex key as is. // The keys are otherwise those of the draw without motion vectors (in the key log of 2026-10-28 all 522 motion keys // were a logged key plus these fields). Which shaders: BOTW's motion passes are the G-buffer (6 color targets: slot 6; diff --git a/runtime/nvn/vulkan/record.c b/runtime/nvn/vulkan/record.c index 6f6dfa31f..910d1cc26 100644 --- a/runtime/nvn/vulkan/record.c +++ b/runtime/nvn/vulkan/record.c @@ -30,6 +30,7 @@ // stats RecStats: T's fields plain, R's and the waits' _Atomic relaxed adds; read by T // profiling the profiler's markers (runtime/prof.h): the recorder thread's batches and submits, T's waits on it #include "record.h" +#include "mvec.h" #include "../../prof.h" #include @@ -63,6 +64,8 @@ static _Atomic uint64_t r_busy_ns, r_wakeups, r_submit_ns; static _Atomic uint64_t a_seq_waits, a_seq_wait_ns; // (waits from any thread) bool rec_on(void) { return on > 0; } +static __thread bool is_recorder; +bool rec_on_recorder(void) { return is_recorder; } #define NOW() plat_now_ns() #define ADD(v, x) atomic_fetch_add_explicit(&(v), (x), memory_order_relaxed) @@ -180,6 +183,7 @@ static uint64_t spin_for_work(uint64_t t) { // the published end once it moves static void *run(void *arg) { (void)arg; + is_recorder = true; prof_thread_name("vk-record"); plat_thread_elevate(); extern void control_prof_thread(const char *name); // runtime/control_prof.c (`threads`) @@ -397,7 +401,9 @@ static void submit_run(const void *p) { .waitSemaphoreInfoCount = a->nwait, .pWaitSemaphoreInfos = a->wait}; SW_ZONE("vkQueueSubmit2"); uint64_t t0 = NOW(); + pthread_mutex_lock(&g_vk_queue_lock); VkResult r = vkQueueSubmit2(g_vk.queue, 1, &si, VK_NULL_HANDLE); + pthread_mutex_unlock(&g_vk_queue_lock); uint64_t dt = NOW() - t0; if (prof) ADD(r_submit_ns, dt); if (dt > 50000000) { // (a driver stall: a slow wait on the recorder shows where it was) @@ -622,6 +628,22 @@ void rec_CmdPushConstants(VkCommandBuffer cb, VkPipelineLayout layout, VkShaderS ENQ_END(); } +CMD_ARGS(CmdPushConstantsMvec, VkPipelineLayout layout; uint32_t seq;) +static void push_mvec(VkCommandBuffer cb, VkPipelineLayout layout, uint32_t seq) { + uint32_t pc[MVEC_PUSH / 4]; + mvec_resolve(seq, pc); + vkCmdPushConstants(cb, layout, VK_SHADER_STAGE_VERTEX_BIT, 0, MVEC_PUSH, pc); +} +static void CmdPushConstantsMvec_run(const void *p) { const CmdPushConstantsMvecArgs *a = p; push_mvec(a->cb, a->layout, a->seq); } +void rec_CmdPushConstantsMvec(VkCommandBuffer cb, VkPipelineLayout layout, uint32_t seq) { + if (on <= 0) { push_mvec(cb, layout, seq); return; } + ENQ_T0(); + CmdPushConstantsMvecArgs *a = push(CmdPushConstantsMvec_run, sizeof *a, 0); + *a = (CmdPushConstantsMvecArgs){cb, layout, seq}; + commit(); + ENQ_END(); +} + CMD_ARGS(CmdSetViewport, uint32_t first, n;) // then VkViewport[n] static void CmdSetViewport_run(const void *p) { const CmdSetViewportArgs *a = p; vkCmdSetViewport(a->cb, a->first, a->n, after(a, sizeof *a)); } void rec_CmdSetViewport(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkViewport *v) { diff --git a/runtime/nvn/vulkan/record.h b/runtime/nvn/vulkan/record.h index b67df4333..6fdf934f1 100644 --- a/runtime/nvn/vulkan/record.h +++ b/runtime/nvn/vulkan/record.h @@ -14,6 +14,7 @@ // ---- start / mode (exec.c vk_exec_init, before any command) void rec_init(void); bool rec_on(void); // commands go through the recorder thread +bool rec_on_recorder(void); // the calling thread is the recorder (inside a rec_custom call): it must queue nothing // ---- command buffers, submissions void rec_BeginCommandBuffer(VkCommandBuffer cb); // ONE_TIME_SUBMIT @@ -52,6 +53,10 @@ void rec_CmdBindVertexBuffers(VkCommandBuffer cb, uint32_t first, uint32_t n, co void rec_CmdBindIndexBuffer(VkCommandBuffer cb, VkBuffer buf, VkDeviceSize off, VkIndexType type); void rec_CmdPushConstants(VkCommandBuffer cb, VkPipelineLayout layout, VkShaderStageFlags stages, uint32_t off, uint32_t size, const void *data); +// A motion program's push constants (mvec.h MVEC_PUSH, the vertex stage's) for the scene draw mvec_draw_commit numbered +// seq: asked of mvec_resolve when the command is recorded, not when it is queued (the thread that works them out may +// not be done yet) +void rec_CmdPushConstantsMvec(VkCommandBuffer cb, VkPipelineLayout layout, uint32_t seq); void rec_CmdDraw(VkCommandBuffer cb, uint32_t count, uint32_t inst, uint32_t first, uint32_t first_inst); void rec_CmdDrawIndexed(VkCommandBuffer cb, uint32_t count, uint32_t inst, uint32_t first, int32_t base, uint32_t first_inst); void rec_CmdDispatch(VkCommandBuffer cb, uint32_t x, uint32_t y, uint32_t z); diff --git a/runtime/nvn/vulkan/shaders.c b/runtime/nvn/vulkan/shaders.c index cbcfc0aa2..0a67b9c71 100644 --- a/runtime/nvn/vulkan/shaders.c +++ b/runtime/nvn/vulkan/shaders.c @@ -941,6 +941,93 @@ static const char taa_instability[] = " imageStore(hist_i, p, h);\n" " imageStore(instab_i, p, vec4(instab));\n" "}\n"; +// The light TAA (exec.c mvec_taa, the default; SAVAGEWIND_TAA=full: the seven passes above): one pass. The vector of +// the nearest surface among the pixel and its 4 diagonal neighbours (edges move with what is in front); the history +// there (Catmull-Rom, 5 bilinear taps), clipped in YCoCg to the 3x3's mean +- 1.5 standard deviations (0.9 with +// motion) and its extremes; the new sample a Lanczos 2 of the 3x3 at their jittered distances, deringed to the 3x3. +// The history's .a counts the frames accumulated (/ 16): the blend is 1 / count down to 0.08 on a still pixel (0.3 +// in fast motion), more where the reactive mask (the vectors' .z: blended effects) is set (a plain blend: weighting +// the samples by 1 / (1 + luma) darkened the scene, whose values are not display-range). No disocclusion or shading-change detection, no thin-feature locks: the +// clipping alone drops stale history. The seven passes cost the GPU ~2.5 ms at 1440p (RTX 3060), this one ~0.5. +static const char taa_lite[] = + "layout(set = 0, binding = 0) uniform sampler2D color_t;\n" + "layout(set = 0, binding = 1) uniform sampler2D vec_t;\n" + "layout(set = 0, binding = 2) uniform sampler2D depth_t;\n" + "layout(set = 0, binding = 3) uniform sampler2D hist_t;\n" + "layout(set = 0, binding = 8, rgba16f) uniform writeonly image2D hist_i;\n" + "layout(set = 0, binding = 9, rgba16f) uniform writeonly image2D out_i;\n" + "float lanczos2_sq(float x2) {\n" + " x2 = min(x2, 4.0);\n" + " float a = 0.4 * x2 - 1.0, b = 0.25 * x2 - 1.0;\n" + " return (25.0 / 16.0 * a * a - 9.0 / 16.0) * (b * b);\n" + "}\n" + "vec4 history(vec2 uv) {\n" + " vec2 sp = uv * pc.size.xy, tc = floor(sp - 0.5) + 0.5, f = sp - tc;\n" + " vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f));\n" + " vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f);\n" + " vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f));\n" + " vec2 w3 = f * f * (-0.5 + 0.5 * f);\n" + " vec2 w12 = w1 + w2;\n" + " vec2 t0 = (tc - 1.0) * pc.size.zw, t3 = (tc + 2.0) * pc.size.zw, t12 = (tc + w2 / w12) * pc.size.zw;\n" + " float a = w12.x * w0.y, b = w0.x * w12.y, c = w12.x * w12.y, d = w3.x * w12.y, e = w12.x * w3.y;\n" + " vec4 s = textureLod(hist_t, vec2(t12.x, t0.y), 0.0) * a + textureLod(hist_t, vec2(t0.x, t12.y), 0.0) * b +\n" + " textureLod(hist_t, t12, 0.0) * c + textureLod(hist_t, vec2(t3.x, t12.y), 0.0) * d +\n" + " textureLod(hist_t, vec2(t12.x, t3.y), 0.0) * e;\n" + " return s / (a + b + c + d + e);\n" + "}\n" + "void main() {\n" + " ivec2 p = pixel();\n" + " if (!onscreen(p)) return;\n" + " vec2 uv = (vec2(p) + 0.5) * pc.size.zw, J = pc.jit.xy;\n" + " float dn = texelFetch(depth_t, p, 0).r;\n" + " ivec2 pn = p;\n" + " for (int i = 0; i < 4; i++) {\n" + " ivec2 q = clampp(p + ivec2((i & 1) * 2 - 1, (i >> 1) * 2 - 1));\n" + " float d = texelFetch(depth_t, q, 0).r;\n" + " if (d < dn) { dn = d; pn = q; }\n" + " }\n" + " vec4 v = texelFetch(vec_t, pn, 0);\n" + " bool has = v.a >= 0.25;\n" + " vec2 mv = has ? vec2(-0.5 * v.x, 0.5 * v.y) : vec2(0.0);\n" + " vec2 ruv = uv + mv;\n" + " bool fresh = pc.st.x < 0.5 || !has || !inside(ruv);\n" + " vec4 c4 = texelFetch(color_t, p, 0);\n" + " vec3 up = vec3(0.0), mu = vec3(0.0), m2 = vec3(0.0), lo = vec3(65504.0), hi = vec3(-65504.0);\n" + " float uw = 0.0, n = 0.0;\n" + " for (int y = -1; y <= 1; y++)\n" + " for (int x = -1; x <= 1; x++) {\n" + " ivec2 q = p + ivec2(x, y);\n" + " if (!onscreen(q)) continue;\n" + " vec3 s = ycocg(max(texelFetch(color_t, q, 0).rgb, vec3(0.0)));\n" + " vec2 o = vec2(x, y) - J;\n" + " float w = lanczos2_sq(dot(o, o));\n" + " up += s * w; uw += w;\n" + " mu += s; m2 += s * s; n += 1.0;\n" + " lo = min(lo, s); hi = max(hi, s);\n" + " }\n" + " mu /= n;\n" + " vec3 sigma = sqrt(max(m2 / n - mu * mu, vec3(0.0)));\n" + " up = uw > FP16_MIN ? clamp(up / uw, lo, hi) : ycocg(max(c4.rgb, vec3(0.0)));\n" + " vec3 res = up;\n" + " float cnt = 1.0;\n" + " if (!fresh) {\n" + " vec4 h = history(ruv);\n" + " vec3 hc = ycocg(max(h.rgb, vec3(0.0)));\n" + " float prevn = clamp(h.a, 0.0, 1.0) * 16.0, vel = v4k(mv), react = clamp(v.z, 0.0, 1.0);\n" + " float g = mix(1.5, 0.9, clamp(vel / 8.0, 0.0, 1.0));\n" + " vec3 bmin = max(mu - g * sigma, lo), bmax = min(mu + g * sigma, hi);\n" + " vec3 ctr = 0.5 * (bmin + bmax), ext = 0.5 * (bmax - bmin) + 1e-5, dl = hc - ctr, u3 = abs(dl / ext);\n" + " float mx = max(u3.x, max(u3.y, u3.z));\n" + " if (mx > 1.0) hc = ctr + dl / mx;\n" + " float alpha = max(1.0 / (prevn + 1.0), mix(0.08, 0.3, clamp(vel / 16.0, 0.0, 1.0)));\n" + " alpha = max(alpha, 0.5 * react);\n" + " res = mix(hc, up, alpha);\n" + " cnt = min(prevn + 1.0, 16.0);\n" + " }\n" + " vec3 o = max(rgb(res), vec3(0.0));\n" + " imageStore(hist_i, p, vec4(o, cnt / 16.0));\n" + " imageStore(out_i, p, vec4(o, c4.a));\n" + "}\n"; static const char taa_resolve[] = "layout(set = 0, binding = 0) uniform sampler2D color_t;\n" "layout(set = 0, binding = 1) uniform sampler2D dil_t;\n" @@ -1332,11 +1419,11 @@ static const char *builtin_src(const char *name, int *stage) { } if (!strncmp(name, "taa_", 4)) { static const char *const names[] = {"taa_prepare.comp", "taa_shade_src.comp", "taa_shade_down.comp", "taa_shade.comp", - "taa_reactivity.comp", "taa_instability.comp", "taa_resolve.comp"}; + "taa_reactivity.comp", "taa_instability.comp", "taa_resolve.comp", "taa_lite.comp"}; static const char *const bodies[] = {taa_prepare, taa_shade_src, taa_shade_down, taa_shade, taa_reactivity, - taa_instability, taa_resolve}; - static char *src[7]; - for (int i = 0; i < 7; i++) { + taa_instability, taa_resolve, taa_lite}; + static char *src[8]; + for (int i = 0; i < 8; i++) { if (strcmp(name, names[i])) continue; if (!src[i]) { size_t a = strlen(taa_common), b = strlen(bodies[i]); diff --git a/runtime/nvn/vulkan/vk.h b/runtime/nvn/vulkan/vk.h index 2902010c7..30ea919bd 100644 --- a/runtime/nvn/vulkan/vk.h +++ b/runtime/nvn/vulkan/vk.h @@ -70,6 +70,9 @@ typedef struct { VkImageView sc_views[8]; } VkG; extern VkG g_vk; +// g_vk.queue from more than one thread: the recorder's submissions (record.c), frame generation's presents (device.c +// present_thread) and the sparse binds (exec.c) +extern pthread_mutex_t g_vk_queue_lock; // ---- submissions (exec.c) // Work is recorded into the current command buffer; uploads go into a separate one that runs first. diff --git a/runtime/ui/game_options.mm b/runtime/ui/game_options.mm index 125355a93..dd1474e0e 100644 --- a/runtime/ui/game_options.mm +++ b/runtime/ui/game_options.mm @@ -540,7 +540,9 @@ void build_items(void) { if (g_settings.upscaler != UPSCALE_OFF) g_settings.upscale_quality = x; }, UPQ_QUALITY); - mode.value_off = [](const Item &, int) { return !upscale_modes_available() || g_settings.upscaler == UPSCALE_OFF; }; + mode.value_off = [](const Item &, int x) { + return !upscale_modes_available() || g_settings.upscaler == UPSCALE_OFF || !upscale_mode_offered(x); + }; mode.reset = [](const Item &) { g_settings.upscale_quality = UPQ_QUALITY; }; // (also while Off) mode.desc_fn = [](const Item &) { // (one line: the game's description pane is one English line wide) diff --git a/runtime/ui/menu.mm b/runtime/ui/menu.mm index ce3676f57..d17d101cb 100644 --- a/runtime/ui/menu.mm +++ b/runtime/ui/menu.mm @@ -965,7 +965,7 @@ static void tab_display(void) { for (int i = 0; i < UPQ_COUNT; i++) { mode_names[i] = modes_ok ? tr(modes[i]) : std::string(tr(modes[i])) + " " + tr("(coming soon)"); mn[i] = mode_names[i].c_str(); - mavail[i] = modes_ok; + mavail[i] = modes_ok && upscale_mode_offered(i); } float sx, sy; // the 3D scene's size (BOTW docked: 1600 x 900 times its scale) renderer_get_scene_scale(&sx, &sy); @@ -1560,7 +1560,7 @@ const ImVec4 gpu_c(0.55f, 0.83f, 0.31f, 1), cpu_c(0.18f, 0.59f, 0.80f, 1), ram_c case UPSCALE_FSR4: line += tr("FSR 4"); break; default: line += tr("Off"); } - int q = g_settings.upscale_quality; + int q = upscale_quality_now(); if (up != UPSCALE_OFF && upscale_factor() > 1.0) { char f[16]; snprintf(f, sizeof f, "%.1f", upscale_factor()); From ceef1ef8d3027d943c4849ebcfb4a0f3059d2c18 Mon Sep 17 00:00:00 2001 From: Revivedx <82332536+Revivedx@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:22:17 -0500 Subject: [PATCH 08/18] AMD FSR 3 and FSR 4 upscaling offered again They were held back since 0.5.0 because they ran slower than native where the CPU was the limit. With the motion vectors on a thread of their own and the shadow maps following the upscaler's factor they gain: RTX 3060 + Ryzen 5 5600X, 1440p, Savage preset at 100 %, FSR 3 Quality over native at the Great Plateau 106 / 102 fps, Kakariko 106 / 88, Korok Forest 67 / 40. SAVAGEWIND_FSR3=0 hides them (a settings file with fsr3 or fsr4 then loads as FSR 1, as before). Checked: a visible playtest with FSR 3; hidden runs with fsr3 in the settings file, with and without the variable. FSR 4 not run here (needs an AMD Radeon). Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 ++++ docs/SAVAGE-WIND.md | 6 ++++-- runtime/launch_flags_table.c | 2 +- runtime/nvn/output_scale.c | 15 ++++++++------- runtime/nvn/output_scale.h | 2 +- runtime/settings.c | 4 ++-- tools/launch_flags_curated.txt | 2 +- 7 files changed, 21 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4fc44c95..670d85545 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ What changed in each Savage Wind release. The `test` branch holds what the next ### Performance +- **AMD FSR 3 and FSR 4 upscaling are back** in Video > Upscaler. They were held back in Alpha 5 because they ran + slower than native where the CPU was the limit; with the changes below they gain. RTX 3060 and a Ryzen 5 5600X, + 1440p, Savage preset at 100% render scale, FSR 3 Quality over native: Great Plateau 106 / 102 fps, Kakariko + 106 / 88, Korok Forest 67 / 40. `SAVAGEWIND_FSR3=0` hides them. - **FSR 3, FSR 4 and TAA cost the CPU much less:** their motion vectors are worked out on a thread of their own instead of the thread that translates the game's drawing, every scene draw uses one motion program, and FSR 3 is dispatched by the recorder thread. RTX 3060 and a Ryzen 5 5600X, Great Plateau, uncapped, 1440p, where the CPU is diff --git a/docs/SAVAGE-WIND.md b/docs/SAVAGE-WIND.md index 51e9309eb..04a61bcb1 100644 --- a/docs/SAVAGE-WIND.md +++ b/docs/SAVAGE-WIND.md @@ -1813,8 +1813,10 @@ It comes back with the redesign of the motion vectors planned for Alpha 6: recor 1.2 ms a frame for 2969 draws, spread out (constant buffers 0.35, matching 0.24, frame start 0.16, program 0.15, per-draw setup 0.13, push 0.10), with no single defect. FSR itself costs next to nothing there (2026-11-09, 1440p Quality: 130 fps native, 104 with FSR 3, 130 with FSR 3 and `SAVAGEWIND_MVEC=0`). That work has to leave the render thread. -Until then `SAVAGEWIND_FSR3=1` offers it for tests, and a settings file with `upscaler = fsr3` loads as AMD FSR 1 with -the same quality mode. TAA (Video > Anti-aliasing) and frame generation stay available. +Offered again since 2026-11-13: the vectors are worked out on a thread of their own (`runtime/nvn/vulkan/mvec.c`) and +the shadow cascades follow the upscaler's factor (same PC, Savage preset, 1440p, FSR 3 Quality over native: Great +Plateau 106 / 102, Kakariko 106 / 88, Korok Forest 67 / 40). `SAVAGEWIND_FSR3=0` hides FSR 3 and FSR 4 again; a +settings file with `upscaler = fsr3` then loads as AMD FSR 1 with the same quality mode. ## Frame generation (AMD FSR 3) diff --git a/runtime/launch_flags_table.c b/runtime/launch_flags_table.c index 8b6aedc9d..1f18aa937 100644 --- a/runtime/launch_flags_table.c +++ b/runtime/launch_flags_table.c @@ -114,7 +114,7 @@ const LfInfo LF_TABLE[] = { {"SAVAGEWIND_FRAME_CLEAR", LF_KIND_SWITCH, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_FRAME_LOG", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_FREECAM_TEST", LF_KIND_NUMBER, LF_GROUP_DEV, "", ""}, - {"SAVAGEWIND_FSR3", LF_KIND_NUMBER, LF_GROUP_PLAY, "1", "Offers AMD FSR 3 upscaling in the Video menu (builds that include it)."}, + {"SAVAGEWIND_FSR3", LF_KIND_NUMBER, LF_GROUP_PLAY, "0", "Hides AMD FSR 3 and FSR 4 upscaling in the Video menu (0: they load as AMD FSR 1)."}, {"SAVAGEWIND_FSR3_API", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, {"SAVAGEWIND_FSR3_DEBUG", LF_KIND_TEXT, LF_GROUP_DEV, "", ""}, {"SAVAGEWIND_FSR3_REACTIVE", LF_KIND_NUMBER, LF_GROUP_OTHER, "", ""}, diff --git a/runtime/nvn/output_scale.c b/runtime/nvn/output_scale.c index 32af03f2e..13e565f1a 100644 --- a/runtime/nvn/output_scale.c +++ b/runtime/nvn/output_scale.c @@ -37,14 +37,15 @@ extern bool vk_dlss_available(void); bool fsr3_available(void); // (vulkan/fsr3.h: built in) bool fsr4_available(void); // (vulkan/fsr_api.h: AMD's DLLs, on an AMD Radeon) #endif -// FSR 3 and FSR 4 upscaling are held back until the motion vectors are redesigned (Alpha 6). FSR itself costs the CPU -// next to nothing; recording the vectors on the render thread costs 1.2 ms a frame, spread over many small steps, with -// no single defect to fix (2026-11-09, RTX 3060, 1440p Quality: 130 fps native, 104 with FSR 3, 130 with FSR 3 and no -// vectors), so FSR runs slower than native where that thread is the limit. That work has to leave the render thread. -// SAVAGEWIND_FSR3=1 offers it anyway (tests); TAA and frame generation stay as they are. +// FSR 3 and FSR 4 upscaling were held back from 0.5.0 until the motion vectors left the render thread (recording them +// there cost 1.2 ms a frame: RTX 3060, 1440p Quality, 130 fps native, 104 with FSR 3). Offered again since they are +// worked out on a thread of their own (vulkan/mvec.c) and the shadow cascades follow the upscaler's factor +// (shadow_map_size): same PC, Savage preset, 1440p, FSR 3 Quality over native at the Great Plateau 106 / 102, +// Kakariko 106 / 88, Korok Forest 67 / 40. SAVAGEWIND_FSR3=0 hides them again (a settings file with fsr3 or fsr4 then +// loads as FSR 1 with the same mode). bool fsr3_upscaler_enabled(void) { static int on = -1; - if (on < 0) on = getenv("SAVAGEWIND_FSR3") && atoi(getenv("SAVAGEWIND_FSR3")) != 0; + if (on < 0) on = !getenv("SAVAGEWIND_FSR3") || atoi(getenv("SAVAGEWIND_FSR3")) != 0; return on; } @@ -53,7 +54,7 @@ bool upscaler_available(int u) { return u == UPSCALE_OFF || u == UPSCALE_METALFX; #else return u == UPSCALE_OFF || u == UPSCALE_FSR1 || (u == UPSCALE_FSR3 && fsr3_available() && fsr3_upscaler_enabled()) - || (u == UPSCALE_FSR4 && fsr4_available() && fsr3_upscaler_enabled()) // (FSR 4: the same hold-back as FSR 3) + || (u == UPSCALE_FSR4 && fsr4_available() && fsr3_upscaler_enabled()) // (FSR 4: the same switch as FSR 3) || (u == UPSCALE_DLSS && vk_dlss_available()); #endif } diff --git a/runtime/nvn/output_scale.h b/runtime/nvn/output_scale.h index 3bad9e51b..62748f846 100644 --- a/runtime/nvn/output_scale.h +++ b/runtime/nvn/output_scale.h @@ -19,7 +19,7 @@ void output_scale_screen(double sw, double sh, int iw, int ih, OutScale *o); // = window / factor per axis), and the factor in use (1: Off) bool upscaler_available(int u); bool fsr4_offered(void); // AMD FSR 4 usable on this PC (an AMD Radeon and AMD's DLLs; held back or not) -bool fsr3_upscaler_enabled(void); // FSR 3 upscaling offered (held back for now; SAVAGEWIND_FSR3=1) +bool fsr3_upscaler_enabled(void); // FSR 3 / 4 upscaling offered (SAVAGEWIND_FSR3=0: hidden) // The world camera's projection as last made (rt_persp, game thread): tan(fovy / 2), aspect, near, far; zeros before void rt_world_projection(float out[4]); // The scene's render size in pixels (vulkan/exec.c: its motion target), for the jitter's sub-pixel offsets diff --git a/runtime/settings.c b/runtime/settings.c index 22b335041..d1c7bf26b 100644 --- a/runtime/settings.c +++ b/runtime/settings.c @@ -11,7 +11,7 @@ #include "language.h" #include "handheld.h" -bool fsr3_upscaler_enabled(void); // (nvn/output_scale.c: FSR 3 upscaling held back for now) +bool fsr3_upscaler_enabled(void); // (nvn/output_scale.c: SAVAGEWIND_FSR3=0 hides FSR 3 / 4) #define SETTINGS_FILE settings_file() @@ -241,7 +241,7 @@ void settings_load(void) { else if (!strcmp(key, "settings_version")) version = atoi(val); else if (!strcmp(key, "resolution")) snprintf(old_res, sizeof old_res, "%s", val); // (version 1) else if (!strcmp(key, "upscaler")) // (metalfx / fsr1: this OS's spatial upscaler; dlss: NGX; fsr3, fsr4: Vulkan, - // held back for now: FSR 1 with the same quality mode, nvn/output_scale.c fsr3_upscaler_enabled) + // hidden with SAVAGEWIND_FSR3=0: FSR 1 with the same quality mode, nvn/output_scale.c fsr3_upscaler_enabled) g_settings.upscaler = !strcmp(val, "dlss") ? UPSCALE_DLSS : !strcmp(val, "fsr1") || !strcmp(val, "metalfx") ? UPSCALE_SPATIAL : !strcmp(val, "fsr3") ? (fsr3_upscaler_enabled() ? UPSCALE_FSR3_OR_SPATIAL : UPSCALE_SPATIAL) diff --git a/tools/launch_flags_curated.txt b/tools/launch_flags_curated.txt index 4c4b3cc71..ed06dd353 100644 --- a/tools/launch_flags_curated.txt +++ b/tools/launch_flags_curated.txt @@ -42,7 +42,7 @@ launcher SAVAGEWIND_LAUNCHER_SHOT | | Test hook of the start screen. build SAVAGEWIND_GEN | | The program that builds the game code. build SAVAGEWIND_CC | | The compiler that builds the game code. -play SAVAGEWIND_FSR3 | 1 | Offers AMD FSR 3 upscaling in the Video menu (builds that include it). +play SAVAGEWIND_FSR3 | 0 | Hides AMD FSR 3 and FSR 4 upscaling in the Video menu (0: they load as AMD FSR 1). play SAVAGEWIND_VK_NO_FEEDBACK_LOOP | 1 | Draws with copies instead of feedback loops. Fixes a wrong picture on some graphics cards, slower on others. play SAVAGEWIND_VK_FEEDBACK_LOOP | 1 | Turns feedback loops on where they are held back for your graphics card. play SAVAGEWIND_VK_GPL | 1 | Turns pipeline libraries on where they are held back for your graphics driver. From da6a9cbd2e67878324be4445760e48eeac7b5f68 Mon Sep 17 00:00:00 2001 From: guill Date: Fri, 13 Nov 2026 19:09:26 -0500 Subject: [PATCH 09/18] Ultrawide start and loading screens (#805) - Start screen: the frames before it first comes up keep 16:9 too. The game makes its layout projection once, in those frames; widened to the window there, it kept the window's aspect and the 16:9 start screen drew its artwork 1/shape as wide (a narrow strip on 32:9). - Loading screen: the status icons over the tip (hearts, stamina, counters, figures) are drawn at their 16:9 places. They used a layout projection widened in play and came out squeezed toward the middle. Checked: output scale test; hidden runs at 21:9, 32:9 and 16:9 (start screen, loading screen, world, pouch); a visible 32:9 window test. Co-Authored-By: Claude Opus 5.5 --- runtime/nvn/output_scale.c | 10 +++++++++- runtime/nvn/output_scale.h | 2 ++ runtime/nvn/vulkan/exec.c | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/runtime/nvn/output_scale.c b/runtime/nvn/output_scale.c index 13e565f1a..d448b9130 100644 --- a/runtime/nvn/output_scale.c +++ b/runtime/nvn/output_scale.c @@ -121,6 +121,7 @@ double upscale_factor(void) { // The window's shape over 16:9 while the game's views are widened to fill it, else 1; the field of view's factor in // use (rt_persp) static volatile float g_view_shape = 1, g_fov = 1, g_map_extra_y; +static volatile float g_window_shape = 1; // the window's shape over 16:9, widened or not (output_window_shape) static uint32_t g_world_proj[4]; // tan(fovy / 2), aspect, near, far of the world camera's last matrix (rt_persp), float bits void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { @@ -130,11 +131,17 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { if (forced < 0) forced = getenv("SAVAGEWIND_SCALE") ? atof(getenv("SAVAGEWIND_SCALE")) : 0; if (wide_test < 0) wide_test = getenv("SAVAGEWIND_WIDE_TEST") ? atof(getenv("SAVAGEWIND_WIDE_TEST")) : 0; double shape = wide_test > 0 ? wide_test : (dw / dh) / (16.0 / 9.0); + g_window_shape = (float)shape; // A wider window (21:9, 32:9) sees more to the sides, a taller one (16:10, 4:3: shape < 1) more above and below // (#125); the HUD keeps its 16:9 layout in the middle either way. Taller title screens fill the window too. // Fit wider title/loading layouts to keep their artwork and text aligned (#98). Taller views keep their shape // through the loading overlay so the world doesn't change aspect while fading out or back in. - bool title_fit = framepace_title_ui(); + // The frames before the start screen first comes up count as it too (#805): the game makes its layout projection + // there, once, and widened then (rt_persp) it kept the window's aspect on the 16:9 start screen, whose artwork came + // out 1/shape as wide (a strip in the middle on 32:9). + static bool title_seen; + if (framepace_title_ui()) title_seen = true; + bool title_fit = framepace_title_ui() || !title_seen; #ifndef __APPLE__ title_fit = title_fit && shape >= 1; // Vulkan cover-crops the artwork on taller title screens. #endif @@ -211,6 +218,7 @@ void output_scale(double dw, double dh, bool reshape_allowed, OutScale *o) { } float output_view_shape(void) { return g_view_shape; } +float output_window_shape(void) { return g_window_shape; } float output_map_extra_y(void) { return g_map_extra_y; } float output_pause_extra_y(void) { diff --git a/runtime/nvn/output_scale.h b/runtime/nvn/output_scale.h index 62748f846..feea10516 100644 --- a/runtime/nvn/output_scale.h +++ b/runtime/nvn/output_scale.h @@ -47,6 +47,8 @@ void output_world_proj_set(float t, float a, float n, float f); bool output_world_proj(WorldProj *p); float output_view_shape(void); +// The window's shape over 16:9 whether or not the view is widened to it (the loading screen keeps 16:9) +float output_window_shape(void); bool output_tall_map(float shape); // Extra layout space above and below the visible world map, in native 1280x720 units. float output_map_extra_y(void); diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index 79f97de24..e822a90c0 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -4821,6 +4821,20 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) } } if (!tb || tb->rs_group != RS_OUT) return false; + // The loading screen on a wider window shows at 16:9 (output_scale, #98), but the status icons it draws over its + // tip (hearts, stamina, rupees, the figures) use a layout projection the game made in play, widened to the window + // (rt_persp): they came out squeezed toward the middle, 1/shape as wide (#805). Back to 16:9 here. + if (shape == 1 && size >= 64 && g[0] > 0 && g[5] != 0 && framepace_loading_ui()) { // (text: m11 < 0) + float ws = output_window_shape(); + if (ws > 1.005f && fabsf(fabsf(g[5]) / g[0] - 16.0f / 9.0f * ws) < 0.002f * ws) { + static float lbuf[0x10000 / 4]; + uint64_t n = size > sizeof lbuf ? sizeof lbuf : size; + memcpy(lbuf, g, n); + for (int k = 0; k < 4; k++) lbuf[k] *= ws; // (clip x: the whole row, a text pane's position too) + *out = ubo_span(vk_transient_copy(lbuf, n, 256), n); + return true; + } + } float hud_s = hud_scale_now(); if (shape == 1 && hud_s == 1) return false; int edge_mode = hud_edges_now(shape); From a348e5331ec999ef223a8b529ddc048364d779b0 Mon Sep 17 00:00:00 2001 From: guill Date: Sat, 14 Nov 2026 18:19:16 -0500 Subject: [PATCH 10/18] Pause menu on ultrawide: cut at the 16:9 screen's sides (#805) The pause menu's layouts are made to be cut by the console's 16:9 screen: frames run on past its sides and the next page's panels and labels wait there. On a wider window (32:9 most of all) they showed: loose frame ends, dark bands ending mid-screen, the next page's text at the window's edges. Frame ends caught while the menu opens also stayed in the picture the game blurs for the menu's background. Menu panes, text and frame ends are now scissored to the 16:9 band on windows wider than 16:9. Panes stretched over the whole window (the blurred background, fades) are left as they are. 16:9 and taller windows are unchanged. Co-Authored-By: Claude Opus 5.5 --- runtime/nvn/vulkan/exec.c | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index e822a90c0..c1aee56db 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -1450,6 +1450,7 @@ void renderer_save_texture_tex(TexBackend *b, const char *path); static float pass_sx = 1, pass_sy = 1; static bool pass_out; // the pass draws into the game's final image (RS_OUT: the HUD and menus draw there) static bool hud_clip; // the draw in progress is a 16:9 layout's pane wholly off a 16:9 screen: not drawn (hud_patch) +static bool hud_cut; // a pause menu pane across a 16:9 screen's side: cut there, as the console's screen does (hud_patch) // Snapshot shared state once per presented frame. Ownership is recorded alongside the actual UI draw. extern bool framepace_quick_ui(void); static HudScope hud_scope; @@ -2523,6 +2524,14 @@ static VkRect2D scissor_rect(void) { x = (int)x0; y = (int)y0; sw = (int)(x1 - x0); sh = (int)(y1 - y0); } if (hud_clip && pass_out) sw = sh = 0; // (a pane wholly off a 16:9 screen: see hud_patch) + if (hud_cut && pass_out && shape > 1) { // (a pause menu pane across a 16:9 screen's side: see hud_patch) + double c = w / 2.0, half = w / 2.0 / shape; + int bx0 = (int)floor(c - half), bx1 = (int)ceil(c + half); + int x1 = x + sw; + if (x < bx0) x = bx0; + if (x1 > bx1) x1 = bx1; + sw = x1 > x ? x1 - x : 0; + } if (x < 0) { sw += x; x = 0; } if (y < 0) { sh += y; y = 0; } if (w > (int)pass_w) w = (int)pass_w; @@ -4821,6 +4830,12 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) } } if (!tb || tb->rs_group != RS_OUT) return false; + // A pause menu's panes are laid out to be cut by the console's 16:9 screen: a frame running on past its side, the + // next page's panels and labels waiting there, a frame's ends while the menu opens (the game then takes the + // picture it blurs for the menu's background, and they stayed in it). On a wider window they are cut at the 16:9 + // screen's sides too (hud_cut, scissor_rect), but not the panes stretched over the whole window (the blurred + // picture of the game, a fade). + bool menu_cut = shape > 1 && !off && framepace_menu_ui() && !framepace_map_ui(); // The loading screen on a wider window shows at 16:9 (output_scale, #98), but the status icons it draws over its // tip (hearts, stamina, rupees, the figures) use a layout projection the game made in play, widened to the window // (rt_persp): they came out squeezed toward the middle, 1/shape as wide (#805). Back to 16:9 here. @@ -4855,6 +4870,7 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) float text_matrix[32]; memcpy(text_matrix, g, sizeof text_matrix); for (int k = 0; k < 4; k++) text_matrix[k] /= shape; + hud_cut = menu_cut; float tx = text_matrix[3] / text_matrix[15], ty = text_matrix[7] / text_matrix[15]; if (hud_s != 1 && !hud_context_native(shape, tx, ty, edge_x, edge_y) && !(hud_quick && hud_quick_keeps(tx, ty, edge_x, edge_y))) @@ -4866,6 +4882,7 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) // Keep their projection and apply the same HUD placement as their captured shadow or button plate. float combined_scale[2]; if (hud_combined_shape(g, size, shape, combined_scale)) { + hud_cut = menu_cut; static float buf[0x10000 / 4]; uint64_t n = size > sizeof buf ? sizeof buf : size; memcpy(buf, g, n); @@ -4906,9 +4923,13 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) return true; } if (!(g[0] > 0 && g[5] > 0 && g[14] == -1 && !g[1] && !g[2] && !g[3] && !g[4] && !g[6] && !g[7] && !g[8] && !g[9] && - !g[12] && !g[13] && !g[15])) + !g[12] && !g[13] && !g[15])) { + // (ui2d text whose projection and position are combined and already wide: the next page's labels) + if (size == 128 && g[0] > 0 && g[5] < 0 && g[14] == -1 && g[15] > 0) hud_cut = menu_cut; return false; + } bool tall = shape < 1; // (a taller window: the view widened vertically, m11 x shape) + hud_cut = menu_cut; float ratio = g[5] / g[0], flat = 16.0f / 9.0f, wide = flat * shape; bool is_flat = fabsf(ratio - flat) < 0.002f, is_wide = fabsf(ratio - wide) < 0.002f * fmaxf(shape, 1.0f); if (!is_flat && !is_wide) return false; @@ -4955,12 +4976,15 @@ static bool hud_patch(uint64_t addr, uint64_t size, VkDescriptorBufferInfo *out) bool frame_end = !tall && hud_frame_end(g, mv, rc, m00, shape); // Taller map views are cropped to their 16:9 frame at presentation (output_scale.c). // Stretching a scrollable pane here separates its pan/zoom from the icons over it. + bool stretched = false; if (lo < 1e8f && (tall ? lo <= -edge + 0.01f && hi >= edge - 0.01f && lo >= -over && hi <= over : (hi - lo >= 2 / shape - 0.02f && hi - lo <= 2 * over) || frame_end) && !(tall && framepace_map_ui())) { if (tall) m11 /= shape; else m00 *= shape; + stretched = true; } + if (stretched && !frame_end) hud_cut = false; // (a frame's ends: cut, see above) float clip_edge = tall_map ? 1 : edge; if (lo < 1e8f && (hi <= -clip_edge || lo >= clip_edge)) hud_clip = true; // (wholly off the view) } @@ -8735,7 +8759,7 @@ static void draw_(CmdRec *r, bool indexed) { PZ_SPAN("exec/draw/dyn", pz2, pz3); uint32_t dyn[64]; int ndyn = 0; - hud_clip = false; // (hud_patch, while the vertex stage's constant buffers are bound) + hud_clip = hud_cut = false; // (hud_patch, while the vertex stage's constant buffers are bound) VkDescriptorSet vset = stage_set(pr, pr->set_layout[0], 0, 0, pr->vi, NULL, NULL, 0, 0, 0, NULL, dyn, &ndyn); PROFD_ADD(prof_sets); ProfZone pz4 = PZ_NOW(); From fbbdb17821b11b88daf3beb3c706c89239f8eb81 Mon Sep 17 00:00:00 2001 From: guill Date: Sat, 14 Nov 2026 19:09:34 -0500 Subject: [PATCH 11/18] Vulkan: stop the particle fix from copying a whole region after a fast travel (#815) 0.5.3 copies vertex data the CPU rewrites while the GPU still reads it (the stretched rain and torch particles). It learns which 1 MB heap regions race by hashing some small fetches again after their wait, and copied every fetch in a marked region for the rest of the session. A fast travel's load reuses freed memory for new meshes once, and marked about 30 regions in one go. From then on every fetch in them went through the copy: upload 200 -> 1200 MB per 2 s and 60 -> 54 fps on a GTX 1070, until the game was closed (#815, #794). A region is now marked only once it changed in 3 different frames, each within a second of the last, and never on a loading screen; the ring that races is rewritten every frame and is still marked in a few frames. In a marked region only fetches up to 64 KB are copied (the ring's are 129 B - 2 KB), not the meshes around it. Checked: the same two particle regions are marked as before (hidden runs with 8 and 10 tower teleports); a 22 min visible run with teleports stayed at 3 marked regions and normal upload. Co-Authored-By: Claude Opus 5.5 --- runtime/nvn/vulkan/exec.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/runtime/nvn/vulkan/exec.c b/runtime/nvn/vulkan/exec.c index c1aee56db..dd7e6aaa4 100644 --- a/runtime/nvn/vulkan/exec.c +++ b/runtime/nvn/vulkan/exec.c @@ -6508,13 +6508,22 @@ static void hc_list_begin(void) { // The samples go to the waiting thread through a ring the render thread never waits on (one in 4 under a lock cost // 4% of the frame rate). In the rain the ring was learned in its first second, and nothing the CPU wrote changed while // read after that; 150.9 -> 149.5 fps (4 runs each, interleaved). +// A region is marked only once it changed while read in VDYN_HITS different frames, each within a second of the last, +// and not on a loading screen: a fast travel reuses freed memory for new meshes once, and its load marked ~30 regions in +// one go; every fetch in them then went through the copy for the rest of the session (upload 200 -> 1200 MB per 2 s, +// 60 -> 54 fps on a GTX 1070, #815). The ring that races is rewritten every frame, and is still marked in a few frames. +// In a marked region only fetches up to VDYN_COPY_MAX are copied (the ring's are 129 B - 2 KB), not the meshes around it. // SAVAGEWIND_VK_VDYN=0: off; =2: every fetch up to 4 KB copied (no learning, the cost above). #define VDYN_N 4096 #define VDYN_SAMPLE_MAX 4096 #define VDYN_SHIFT 20 // (a region: 1 MB; 64 KB ones took 10 marks to cover the ring instead of 2) #define VDYN_SMASK 31 // (one small fetch in 32 sampled) +#define VDYN_HITS 3 +#define VDYN_COPY_MAX (64u << 10) static int vdyn_mode = -1; -static _Atomic uint8_t vdyn[HEAP_MAX >> VDYN_SHIFT]; // (a region: 1 once seen rewritten while read) +static _Atomic uint8_t vdyn[HEAP_MAX >> VDYN_SHIFT]; // (a region: 1 once marked, see above) +static uint8_t vdyn_hits[HEAP_MAX >> VDYN_SHIFT]; // (vdyn_lock: frames it changed in, in a row) +static uint64_t vdyn_last[HEAP_MAX >> VDYN_SHIFT]; // (vdyn_lock: the frame of the last change) static struct { uint64_t addr, size, hash, seq; } vdyn_chk[VDYN_N]; static _Atomic uint64_t vdyn_w, vdyn_r; // (written by the render thread / read by a waiting thread) static uint64_t vdyn_tick; @@ -6542,7 +6551,7 @@ static bool vdyn_hit(uint64_t addr, uint64_t size) { static bool vdyn_fetch(uint64_t addr, uint64_t size) { if (!size || !vdyn_on() || gw_overlaps(addr, addr + size)) return true; if (vdyn_mode == 2 && size <= VDYN_SAMPLE_MAX) return false; - if (vdyn_hit(addr, size)) return false; + if (size <= VDYN_COPY_MAX && vdyn_hit(addr, size)) return false; if (size > VDYN_SAMPLE_MAX || addr < HEAP_BASE || addr + size > HEAP_BASE + HEAP_MAX || (++vdyn_tick & VDYN_SMASK)) return true; uint64_t w = atomic_load_explicit(&vdyn_w, memory_order_relaxed); if (w - atomic_load_explicit(&vdyn_r, memory_order_acquire) >= VDYN_N) return true; // (full: no sample) @@ -6553,6 +6562,7 @@ static bool vdyn_fetch(uint64_t addr, uint64_t size) { return true; } +extern bool framepace_loading_ui(void); // (renderer_wait_seq, right after a real wait on submission seq) the samples recorded up to it, hashed again static void vdyn_check(uint64_t seq) { if (vdyn_mode != 1 || pthread_mutex_trylock(&vdyn_lock)) return; @@ -6560,7 +6570,12 @@ static void vdyn_check(uint64_t seq) { for (; r < w && vdyn_chk[r % VDYN_N].seq <= seq; r++) { __typeof__(vdyn_chk[0]) *c = &vdyn_chk[r % VDYN_N]; if (hash_words(0x9E3779B97F4A7C15ull, (const void *)(uintptr_t)c->addr, c->size & ~3ull) == c->hash) continue; - if (atomic_exchange_explicit(&vdyn[(c->addr - HEAP_BASE) >> VDYN_SHIFT], 1, memory_order_relaxed)) continue; + uint64_t reg = (c->addr - HEAP_BASE) >> VDYN_SHIFT, frame = renderer_present_count(); + if (framepace_loading_ui() || frame == vdyn_last[reg]) continue; + vdyn_hits[reg] = frame - vdyn_last[reg] <= 60 && vdyn_hits[reg] < 255 ? vdyn_hits[reg] + 1 : 1; + vdyn_last[reg] = frame; + if (vdyn_hits[reg] < VDYN_HITS) continue; + if (atomic_exchange_explicit(&vdyn[reg], 1, memory_order_relaxed)) continue; int n = atomic_fetch_add_explicit(&vdyn_marked, 1, memory_order_relaxed); if (n < 32) LOG("[vk] vertex data rewritten while read at %llx (%llu bytes): the %u KB around it copied from now on\n", (unsigned long long)c->addr, (unsigned long long)c->size, 1u << (VDYN_SHIFT - 10)); @@ -6661,6 +6676,8 @@ static void race_probe_submit(uint64_t seq) { static void vdyn_reset(void) { // (vk_exec_reset, the GPU idle: another boot, other buffers) pthread_mutex_lock(&vdyn_lock); for (size_t i = 0; i < sizeof vdyn; i++) atomic_store_explicit(&vdyn[i], 0, memory_order_relaxed); + memset(vdyn_hits, 0, sizeof vdyn_hits); + memset(vdyn_last, 0, sizeof vdyn_last); atomic_store(&vdyn_marked, 0); atomic_store(&vdyn_r, atomic_load(&vdyn_w)); pthread_mutex_unlock(&vdyn_lock); From 7bc800846576d7703c2a7567d704e1372fbfb4b1 Mon Sep 17 00:00:00 2001 From: guill Date: Sat, 14 Nov 2026 19:14:00 -0500 Subject: [PATCH 12/18] CI: triage the crash reports RecompLauncher opens by itself The bug report check only ran on issues with the bug label, which the issue form adds. RecompLauncher opens "Crash: closed with code ..." issues without the form, so they had no label, were never checked and never got needs-info when the log was missing (#748, #775, #778, #800). Those issues are now checked too and get the bug label. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/triage.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/triage.yml b/.github/workflows/triage.yml index f16c15ab8..e1c0bf246 100644 --- a/.github/workflows/triage.yml +++ b/.github/workflows/triage.yml @@ -3,6 +3,8 @@ # its author replies with what was missing, it takes them away again. stale.yml closes needs-info issues after 7 days. # A maintainer can label an issue triage-ok to keep the check off it. Only reads the issue's text: no code from the # issue or the repository runs here. +# Crash reports that a third-party launcher opens by itself ("Crash: closed with code ...", RecompLauncher) don't use the +# issue form, so they come without the bug label: they are checked too, and get the label. name: Bug report triage on: @@ -18,7 +20,8 @@ jobs: triage: if: >- !github.event.issue.pull_request && - contains(github.event.issue.labels.*.name, 'bug') && + (contains(github.event.issue.labels.*.name, 'bug') || + startsWith(github.event.issue.title, 'Crash: closed with code')) && !contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.issue.author_association) runs-on: ubuntu-latest steps: @@ -34,6 +37,8 @@ jobs: // triage-ok (the information came some other way). if (new Date(issue.created_at) < new Date('2026-10-26T00:00:00Z')) return; if (issue.labels.some(l => l.name === 'triage-ok')) return; + if (!issue.labels.some(l => l.name === 'bug')) + await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: ['bug'] }); // The issue form's answers: "###