diff --git a/docs/building.md b/docs/building.md index fc4a706a..fa437580 100644 --- a/docs/building.md +++ b/docs/building.md @@ -489,6 +489,13 @@ and end a sprint, ZL, the button kept from the game only during play (the bottom Link the player does not control, and the set switched off with the button off but never over a start that kept it off. No game files. +A change to the text speed (`runtime/text_speed.c`, the set `text_speed` of `recomp/patches-v111.txt`, its call in +`runtime/ov_input.c` `npad_states`) passes `python tests\text_speed_check.py`, which lifts the set's replacement words +with `recomp/lifter.py` and runs them with `text_speed.c` against a stand-in message window and typewriter: the page +words each setting writes and the set it switches, the skip site's decide bit and typewriter word for a message the +player may skip and one the game keeps from skipping, the speed site's factor for that typewriter and no other, the +registers and flags both sites leave alone, and a start that kept the set off. No game files. + A change to the mouse camera (`runtime/mouse_direct.c`, the mouse path of `runtime/input.c`, the set `mouse_direct` of `recomp/patches-v111.txt` or `patches-v143.txt`) passes `python tests\mouse_direct_check.py --cc --deps \include`, which builds `mouse_direct.c`, and `input.c` with `--deps`, with the rest of the runtime stubbed and diff --git a/nx2navi.ini.example b/nx2navi.ini.example index 2376a6a8..ac90f29e 100644 --- a/nx2navi.ini.example +++ b/nx2navi.ini.example @@ -757,6 +757,12 @@ # lang = en-US # System mode reported to the game: docked or handheld. # operation_mode = docked +# Speed of the game's message windows (game 1.1.1; live): normal (the game's), fast (three times as fast; the +# pauses the text holds stay as long) or instant (each page shows at once, as the game shows it when you press the +# button that turns the page while it types). +# Messages the game does not let you hurry, such as text timed against a cutscene or a voice, keep their speed. +# Needs a game built with this version (the launcher's Rebuild the Game); the menu row shows once it is. +# text_speed = normal # Language of the settings menu and the overlay: en, ru, pt-BR or zh-Hans. Default: the Windows display language, English if # it is none of them. # menu_lang = en diff --git a/recomp/patches-v111.txt b/recomp/patches-v111.txt index b4eee4ca..77726d15 100644 --- a/recomp/patches-v111.txt +++ b/recomp/patches-v111.txt @@ -251,3 +251,26 @@ site occlusion_off main 11b82f4 39400008 2a1f03e8 # its update's store set sprint NX2NAVI_SPRINT_BUTTON_PATCH 1 site sprint main 4ae798 f940014a f940014a 9527c9ea # ldr x10, [x10] -> ldr x10, [x10]; bl page+0xf40 site sprint main c07f3c 39400108 39400108 950a63fd # ldrb w8, [x8] -> ldrb w8, [x8]; bl page+0xf30 + +# Text speed (runtime/text_speed.c). The message window (its update main+0x774b00) shows its text through a typewriter +# object at window +0x2b0 (its step main+0xafe140): each frame the step adds speed (+0x4c) times the frame's step (s0) +# to a reveal position (+0x60) and shows every character whose extent that position passed. The message's tags (group 1, +# main+0xafdff0) hold the script: type 0 waits a number of frames (+0x58, the reveal stops until it has run out), type 1 +# sets the speed to the base (+0x50) times its value, type 2 shows the rest at once, type 3 starts a timer (+0x5c) after +# which the window turns the page by itself. A press of the decide button while the text types (window +0x348) shows the +# page at once, ignoring the waits (typewriter +0x72 = 2), unless the window marked the message unskippable (+0x34a): +# a message with a type 3 tag, and some window types (main+0x76eb40), are, so text timed against a cutscene, a voice or +# a sound is never hurried. Both sites keep to that rule. +# Instant: where the update tests the decide press for that (main+0x774b74, tbz w20), the page's byte +0x20c is ORed in, +# so the game's own skip runs on the first frame of every page it lets the player skip; the test of +0x34a after it is +# the game's. The same site stores the typewriter (x8, loaded at main+0x774b48) at page +0x200 while the message may be +# skipped, 0 otherwise: x10 = [x19 +0x34a] - 1 is all ones for 0 and 0 for 1. x9 and x10 are written before they are +# read again on every path from the site, and no word writes the flags. +# Fast: where the step loads the speed (main+0xafe1d8), s1 becomes s1 + s1 * eq * (page +0x208), eq being 1 when the +# typewriter (x19) is the one at page +0x200 (clz of the difference is 64 only for equal values) and +0x208 the +# factor less one, so only a skippable message window types faster; its waits keep their length. x22, x27, s2 and s8 +# are written by the next words of the step before anything reads them (d8 is saved by its prologue), and no word +# writes the flags. The set runs only while text_speed is not normal. +set text_speed NX2NAVI_TEXT_SPEED_PATCH 1 +site text_speed main 774b74 36000074 @page:x9 394d2a6a d100054a 8a0a010a f901012a 39483129 2a140129 36000069 # tbz w20, #0, #0x774b80 -> adrp x9, page; ldrb w10, [x19, #0x34a]; sub x10, x10, #1; and x10, x8, x10; str x10, [x9, #0x200]; ldrb w9, [x9, #0x20c]; orr w9, w9, w20; tbz w9, #0, #0x774b80 +site text_speed main afe1d8 bd404e61 bd404e61 @page:x22 f94102db cb13037b dac0137b d346ff7b 9e220362 bd420ac8 1e280842 1f020421 # ldr s1, [x19, #0x4c]; adrp x22, page; ldr x27, [x22, #0x200]; sub x27, x27, x19; clz x27, x27; lsr x27, x27, #6; scvtf s2, x27; ldr s8, [x22, #0x208]; fmul s2, s2, s8; fmadd s1, s1, s2, s1 diff --git a/runtime/cfg.c b/runtime/cfg.c index 6c57c5e6..3dca35bb 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -55,7 +55,7 @@ static const char *const known[] = { "HDR_HIGHLIGHTS", "HDR_HUE", "HDR_HUE_CLIP", "HDR_MATCH_SLOPE", "HDR_MIDGRAY", "HDR_SATURATION", "HDR_SHADOWS", "HDR_TONEMAP", "HDR_TONE_SLOPE", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "BIG_BUILD_FREE_MB", "BIG_BUILD_MAX_MB", "BUILD_FREE_MB", "BUILD_RESERVE_MB", "LIB_PREBUILD_BIG", "LIB_PREBUILD_BIG_BG", "COMPUTE_WARM_REUSE", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIB_WARM", "LINE_WIDTH", "POOL_SHOWN_FIRST", "POOL_DATA_FIRST", "TEX_REUSE_NAMED", "TEX_OVERWRITTEN_USED", "PIPE_LINK_MS", "FRAME_HOLD_MS", "PACE_SMOOTH", "OQ_BATCH", "CLEAR_SMALL_CPU", "GATE_WAIT_MS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MEM_CENSUS", "MEM_NEED_MB", "MENU_LANG", "MENU_SOUND_VOLUME", "MENU_TEST", - "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_CLICK", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MICROPHONE", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MONITOR", "MOTION", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOUSE_TRACE", "MOVIE_HOST", "MOVIE_PACE", "MOVIE_CLOCK", "TEST_HITCH", "SPRINT_BUTTON", "SPRINT_MODE", "SPRINT_BUTTON_PATCH", + "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_CLICK", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MICROPHONE", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MONITOR", "MOTION", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOUSE_TRACE", "MOVIE_HOST", "MOVIE_PACE", "MOVIE_CLOCK", "TEST_HITCH", "SPRINT_BUTTON", "SPRINT_MODE", "SPRINT_BUTTON_PATCH", "TEXT_SPEED", "TEXT_SPEED_PATCH", "MOTION_GUARD_DEGREES", "MOTION_POLICY_TRACE", "SELECTIVE_MOTION", "SELECTIVE_MOTION_RAW", // motion_owner.c, vk_fg_pose.inc "SKIN_MOTION", // vk_skin_motion.inc "MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK", @@ -122,7 +122,7 @@ static const struct { const char *key, *section; } sections[] = { {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"}, {"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"}, - {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, + {"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"}, {"TEXT_SPEED", "language"}, {"VOLUME", "audio"}, {"AUDIO_CHANNELS", "audio"}, {"AUDIO_DEVICE", "audio"}, {"MICROPHONE", "audio"}, {"MENU_SOUND_VOLUME", "audio"}, {"AUDIO_RAMP", "audio"}, {"AUDIO_CATCHUP", "audio"}, {"MOTION", "input"}, {"SPRINT_BUTTON", "input"}, {"SPRINT_MODE", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"}, {"RUMBLE_HD", "input"}, {"DS3", "input"}, @@ -244,6 +244,7 @@ static const CfgMeta metas[] = { {"HIGHFPS_FIX", "1", "0|1", RESTART}, {"LANG", "", "ja|en-US|fr|de|it|es|zh-CN|ko|nl|pt|ru|zh-TW|en-GB|fr-CA|es-419|zh-Hans|zh-Hant|pt-BR|pl", RESTART}, {"OPERATION_MODE", "docked", "docked|handheld", LIVE}, + {"TEXT_SPEED", "normal", "normal|fast|instant", LIVE}, // text_speed.c: the message window's typing {"ASSUME_FOCUS", "1", "0|1", LIVE}, // read on every focus change (ov_system.c) // Sound, Controls, Menu {"VOLUME", "100", "0..100", LIVE}, {"MENU_SOUND_VOLUME", "80", "0..100", LIVE}, {"AUDIO_CHANNELS", "stereo", "auto|stereo|5.1", LIVE}, // audio_mixer.c audio_channels_live diff --git a/runtime/ov_input.c b/runtime/ov_input.c index a8c72960..8ce6eed0 100644 --- a/runtime/ov_input.c +++ b/runtime/ov_input.c @@ -19,6 +19,7 @@ #include "ov.h" #include "platform/platform.h" #include "sprint.h" +#include "text_speed.h" typedef struct { int64_t sampling; uint64_t buttons; int32_t lx, ly, rx, ry; uint32_t attributes, pad; } NpadState; typedef struct { int64_t sampling; int32_t x, y, dx, dy, wx, wy; uint32_t buttons, attributes; } MouseState; @@ -103,6 +104,7 @@ static void npad_states(Cpu *c, uint32_t want) { dbg_tick(c); // the debug menu's changes to the game, between two of its frames (debug_tools.c) if (live) dbg_pad(&s.buttons, &s.lx, &s.ly, &s.rx, &s.ry); // its free camera takes the sticks while it flies if (live) sprint_pad(&s.buttons); // the sprint button's presses, kept from the game during gameplay (sprint.c) + if (live) text_speed_poll(); // the text_speed setting onto the patch page (text_speed.c) *out = s; ret_x(c, 1); } diff --git a/runtime/text_speed.c b/runtime/text_speed.c new file mode 100644 index 00000000..41f6ab64 --- /dev/null +++ b/runtime/text_speed.c @@ -0,0 +1,63 @@ +// Text speed for Ocarina of Time 1.1.1 (the patch set text_speed, recomp/patches-v111.txt). The message window shows +// its text through a typewriter whose speed and waits the message's own tags set, and a press of the decide button +// while it types shows the page at once, unless the window marked the message unskippable (a message that turns its +// page by itself on a timer, and some window types). The set's two sites read the patch page words this file writes: +// +// +0x200 the typewriter of the message window while its message may be skipped, 0 otherwise (written by the game's +// code at the first site, read at the second) +// +0x208 the fast factor less one, as a float: 0 leaves the speed as it is +// +0x20c 1 for instant: the window's skip runs on the first frame of each page, as if the button were pressed +// +// Setting text_speed (live): normal (the game's, and the set off), fast (the skippable messages type +// TEXT_SPEED_FAST_FACTOR times as fast, their scripted waits as long as before) or instant (the skippable messages +// show each page at once, as the game's skip does). Unskippable messages keep the game's speed under both. +#include +#include +#include + +#include "cfg.h" +#include "host.h" +#include "text_speed.h" + +enum { SPEED_NORMAL, SPEED_FAST, SPEED_INSTANT }; +static const char *const speed_names[] = {"normal", "fast", "instant"}; + +#define PAGE_FACTOR 0x208 +#define PAGE_INSTANT 0x20c + +static int setting_speed(void) { + const char *v = cfg_value("NX2NAVI_TEXT_SPEED"); + for (int i = 0; i < (int)(sizeof speed_names / sizeof *speed_names); i++) + if (v && !strcmp(v, speed_names[i])) return i; + return SPEED_NORMAL; +} + +// Whether the set may run at all is read once, after the start: NX2NAVI_TEXT_SPEED_PATCH=0, or a mod whose code +// patches the same sites (mods.c mods_exefs_switch), leaves it off then, and switching it on later must not undo that. +static _Atomic int allowed = -1; +static int speed_set(void) { return rt_patch_set("text_speed"); } +int text_speed_available(void) { + int a = atomic_load(&allowed); + if (a < 0) { + a = rt_patch_enabled(speed_set()) && rt_patch_page() != NULL; + atomic_store(&allowed, a); + } + return a; +} + +void text_speed_poll(void) { + if (!text_speed_available()) return; + int s = setting_speed(), set = speed_set(); + uint8_t *page = rt_patch_page(); + float factor = s == SPEED_FAST ? TEXT_SPEED_FAST_FACTOR - 1.0f : 0.0f; + uint32_t bits; + memcpy(&bits, &factor, sizeof bits); + __atomic_store_n((uint32_t *)(page + PAGE_FACTOR), bits, __ATOMIC_RELAXED); + __atomic_store_n(page + PAGE_INSTANT, (uint8_t)(s == SPEED_INSTANT), __ATOMIC_RELAXED); + static int logged = -1; + if (s != logged) { + logged = s; + rt_log("text speed: %s", speed_names[s]); + } + if (rt_patch_enabled(set) != (s != SPEED_NORMAL)) rt_patch_switch(set, s != SPEED_NORMAL); +} diff --git a/runtime/text_speed.h b/runtime/text_speed.h new file mode 100644 index 00000000..bd2f112e --- /dev/null +++ b/runtime/text_speed.h @@ -0,0 +1,11 @@ +// Text speed (text_speed.c): the patch set text_speed's page words and switch. +#pragma once + +// Called at every controller poll the game makes (ov_input.c npad_states): puts the text_speed setting on the patch +// page and switches the set, so a change in the menu reaches the text that types next. +void text_speed_poll(void); +// 1 when the game version has the patch set text_speed and nothing keeps it off (NX2NAVI_TEXT_SPEED_PATCH=0, a mod +// patching its sites): the Game tab shows the row then. The set itself runs only while the setting is not normal. +int text_speed_available(void); +// The factor the fast setting multiplies the message window's typing speed by. +#define TEXT_SPEED_FAST_FACTOR 3.0f diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 3ce1a069..1efbd736 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -56,6 +56,7 @@ extern "C" { #include "save_share.h" #include "sprint.h" #include "sysinfo.h" +#include "text_speed.h" #include "ui/menu.h" #include "ui_text.h" #include "vk_dlssg.h" @@ -1480,6 +1481,12 @@ static void tab_game(float scale) { static const UiTextId mode[] = {UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD}; opt_choice("NX2NAVI_OPERATION_MODE", UI_MENU_OPERATION_MODE, mode, 2, UI_MENU_OPERATION_MODE_DESC); opt_toggle("NX2NAVI_ASSUME_FOCUS", UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC); + // The message window's typing speed (text_speed.c), where the game version has the patch set text_speed; live. The + // names follow the values in their cfg.c order. + if (text_speed_available()) { + static const UiTextId speed[] = {UI_MENU_TEXT_SPEED_NORMAL, UI_MENU_TEXT_SPEED_FAST, UI_MENU_TEXT_SPEED_INSTANT}; + opt_choice("NX2NAVI_TEXT_SPEED", UI_MENU_TEXT_SPEED, speed, 3, UI_MENU_TEXT_SPEED_DESC); + } // discord_rpc.c reads the setting on its own thread and connects or clears the status within half a second opt_toggle("NX2NAVI_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC); rows_saves(); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index 3435abcd..1a32a62e 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -297,6 +297,12 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_MODE_DOCKED] = "Docked", [UI_MENU_MODE_HANDHELD] = "Handheld", [UI_MENU_ASSUME_FOCUS] = "Keep running out of focus", [UI_MENU_ASSUME_FOCUS_DESC] = "Keeps the game running when you switch to another window.", + [UI_MENU_TEXT_SPEED] = "Text speed", + [UI_MENU_TEXT_SPEED_DESC] = "How fast the game's message windows show their text. Fast types three times as fast; " + "instant shows each page at once. Text the game does not let you hurry, such as " + "lines timed to a cutscene or a voice, keeps its speed.", + [UI_MENU_TEXT_SPEED_NORMAL] = "Normal", [UI_MENU_TEXT_SPEED_FAST] = "Fast", + [UI_MENU_TEXT_SPEED_INSTANT] = "Instant", [UI_MENU_MODS_BUILTIN] = "Built into the port", [UI_MENU_MODS_INSTALLED] = "Installed mods", [UI_MENU_MODS_NONE] = "No mods yet. Unpack a mod into the mods folder, one folder per mod with its romfs folder " @@ -1071,6 +1077,12 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_MODE_DOCKED] = "В док-станции", [UI_MENU_MODE_HANDHELD] = "Портативный", [UI_MENU_ASSUME_FOCUS] = "Работать без фокуса", [UI_MENU_ASSUME_FOCUS_DESC] = "Игра продолжает работать, когда вы переключаетесь на другое окно.", + [UI_MENU_TEXT_SPEED] = "Скорость текста", + [UI_MENU_TEXT_SPEED_DESC] = "Как быстро окна сообщений игры показывают текст. Быстро: в три раза быстрее; " + "мгновенно: каждая страница сразу целиком. Текст, который игра не даёт ускорить, " + "например реплики в такт сценке или голосу, идёт с обычной скоростью.", + [UI_MENU_TEXT_SPEED_NORMAL] = "Обычная", [UI_MENU_TEXT_SPEED_FAST] = "Быстро", + [UI_MENU_TEXT_SPEED_INSTANT] = "Мгновенно", [UI_MENU_MODS_BUILTIN] = "Встроенные в порт", [UI_MENU_MODS_INSTALLED] = "Установленные моды", [UI_MENU_MODS_NONE] = "Модов пока нет. Распакуйте мод в папку mods, каждый мод в свою папку с папкой romfs внутри, и " @@ -1691,6 +1703,12 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_FPS_60] = "60 FPS", [UI_MENU_FPS_90] = "90 FPS", [UI_MENU_FPS_120] = "120 FPS", [UI_MENU_FPS_144] = "144 FPS", [UI_MENU_ASSUME_FOCUS] = "Continuar rodando fora de foco", [UI_MENU_ASSUME_FOCUS_DESC] = "Mantém o jogo rodando quando você troca de janela.", + [UI_MENU_TEXT_SPEED] = "Velocidade do texto", + [UI_MENU_TEXT_SPEED_DESC] = "A rapidez com que as janelas de mensagem do jogo mostram o texto. Rápida escreve três " + "vezes mais rápido; instantânea mostra cada página de uma vez. Textos que o jogo não " + "deixa apressar, como falas sincronizadas com uma cena ou uma voz, mantêm a velocidade.", + [UI_MENU_TEXT_SPEED_NORMAL] = "Normal", [UI_MENU_TEXT_SPEED_FAST] = "Rápida", + [UI_MENU_TEXT_SPEED_INSTANT] = "Instantânea", [UI_MENU_FPS_DISPLAY] = "Taxa do monitor", [UI_MENU_FPS_DISPLAY_HZ] = "Taxa do monitor (%.0f Hz)", [UI_MENU_FPS_UNLIMITED] = "Sem limite", [UI_MENU_FPS_RTSS] = "limitado pelo RivaTuner Statistics Server", @@ -2464,6 +2482,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_MODE_HANDHELD] = "掌机模式", [UI_MENU_ASSUME_FOCUS] = "后台保持运行", [UI_MENU_ASSUME_FOCUS_DESC] = "切换到其他窗口时游戏继续运行。", + [UI_MENU_TEXT_SPEED] = "文字速度", + [UI_MENU_TEXT_SPEED_DESC] = "游戏对话框显示文字的速度。快速为三倍速度;即时则每页立即全部显示。" + "游戏不允许加快的文字(例如与过场动画或语音同步的台词)保持原速。", + [UI_MENU_TEXT_SPEED_NORMAL] = "正常", [UI_MENU_TEXT_SPEED_FAST] = "快速", + [UI_MENU_TEXT_SPEED_INSTANT] = "即时", [UI_MENU_VOLUME] = "音量", [UI_MENU_MENU_SOUNDS] = "菜单音效", [UI_MENU_MENU_SOUNDS_DESC] = "本菜单的音效音量。", [UI_MENU_VOLUME_DESC] = "游戏总音量。", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 32b4183c..cee46d55 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -80,6 +80,8 @@ typedef enum { UI_MENU_GAME_LANG, UI_MENU_GAME_LANG_DESC, UI_MENU_GAME_LANG_AUTO, UI_MENU_OPERATION_MODE, UI_MENU_OPERATION_MODE_DESC, UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD, UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC, + UI_MENU_TEXT_SPEED, UI_MENU_TEXT_SPEED_DESC, UI_MENU_TEXT_SPEED_NORMAL, UI_MENU_TEXT_SPEED_FAST, + UI_MENU_TEXT_SPEED_INSTANT, // Mods: the port's own patches and the player's mods folder (mods.c) UI_MENU_MODS_BUILTIN, UI_MENU_MODS_INSTALLED, diff --git a/tests/text_speed_check.c b/tests/text_speed_check.c new file mode 100644 index 00000000..905e37ed --- /dev/null +++ b/tests/text_speed_check.c @@ -0,0 +1,140 @@ +// The text_speed setting (runtime/text_speed.c) and the patch set text_speed's lifted replacement words against a +// stand-in message window and typewriter: what each setting puts on the patch page and how it switches the set; the +// skip site's typewriter word and decide bit, for a message the window lets the player skip and one it does not; the +// speed site's scaled speed for the window's typewriter and for any other; and that both sites change nothing else. +// Built by tests/text_speed_check.py, which lifts the words into sites.c. With the argument kept-off the set starts +// off (NX2NAVI_TEXT_SPEED_PATCH=0 or a mod on its sites), and no setting may switch it on or touch the page. +#include +#include +#include +#include +#include + +#include "text_speed.c" + +void site_skip(Cpu *c); // main+0x774b74 without its adrp (x9 = the page) and its last tbz w9, #0 +void site_speed(Cpu *c); // main+0xafe1d8 without its adrp (x22 = the page) + +static const char *speed = "normal"; +const char *cfg_value(const char *key) { return strcmp(key, "NX2NAVI_TEXT_SPEED") ? "" : speed; } +static int set_on = 1; // the patch set text_speed, on at the start as its default +int rt_patch_set(const char *name) { return strcmp(name, "text_speed") ? -1 : 7; } +int rt_patch_enabled(int set) { return set == 7 && set_on; } +void rt_patch_switch(int set, int on) { assert(set == 7); set_on = on != 0; } +static _Alignas(4096) uint8_t page[4096]; +void *rt_patch_page(void) { return page; } +void rt_log(const char *fmt, ...) { (void)fmt; } + +static uint8_t window[0x400]; // the message window: +0x34a 1 when its message may not be skipped +static _Alignas(16) uint8_t typewriter[0x80], other[0x80]; // typewriters: +0x4c the speed + +static float page_float(int off) { float f; memcpy(&f, page + off, 4); return f; } +static uint64_t page_word(int off) { uint64_t v; memcpy(&v, page + off, 8); return v; } +static float lane(const Cpu *c, int v) { float f; memcpy(&f, &c->v[v], 4); return f; } + +static void fill(Cpu *c, unsigned seed) { + uint8_t *p = (uint8_t *)c; + for (size_t i = 0; i < sizeof *c; i++) p[i] = (uint8_t)(seed * 131u + i * 7u); + c->nzcv = (uint64_t)(seed & 15) << 28; +} + +// The skip site for the window and its typewriter: returns the decide bit the site's tbz tests, and checks that only +// x9, x10 and the page's typewriter word changed. +static int run_skip(int unskippable, int pressed, unsigned seed) { + Cpu c, before; + fill(&c, seed); + window[0x34a] = (uint8_t)unskippable; + c.x[19] = (uintptr_t)window; + c.x[8] = (uintptr_t)typewriter; + c.x[20] = (c.x[20] & ~1ull) | (uint64_t)pressed; + c.x[9] = (uintptr_t)page; // the site's adrp + before = c; + site_skip(&c); + assert(page_word(0x200) == (unskippable ? 0 : (uint64_t)(uintptr_t)typewriter)); + for (int r = 0; r < 31; r++) + if (r != 9 && r != 10) assert(c.x[r] == before.x[r]); + assert(c.nzcv == before.nzcv && c.sp == before.sp); + assert(!memcmp(c.v, before.v, sizeof c.v)); + return (int)(c.x[9] & 1); +} + +// The speed site for a typewriter: returns the speed it loads into s1, and checks that only x27, s1, s2 and s8 changed. +static float run_speed(uint8_t *tw, float base, unsigned seed) { + Cpu c, before; + fill(&c, seed); + memcpy(tw + 0x4c, &base, 4); + c.x[19] = (uintptr_t)tw; + c.x[22] = (uintptr_t)page; // the site's adrp + before = c; + site_speed(&c); + for (int r = 0; r < 31; r++) + if (r != 27) assert(c.x[r] == before.x[r]); + assert(c.nzcv == before.nzcv && c.sp == before.sp); + for (int v = 0; v < 32; v++) + if (v != 1 && v != 2 && v != 8) assert(!memcmp(&c.v[v], &before.v[v], sizeof c.v[v])); + return lane(&c, 1); +} + +static void kept_off(void) { + set_on = 0; + memset(page, 0xa5, sizeof page); + const char *all[] = {"normal", "fast", "instant", "normal"}; + for (int i = 0; i < 4; i++) { + speed = all[i]; + text_speed_poll(); + assert(!set_on && !text_speed_available()); + for (size_t k = 0; k < sizeof page; k++) assert(page[k] == 0xa5); + } + printf("text_speed_check: a set kept off stays off and the page untouched\n"); +} + +int main(int argc, char **argv) { + if (argc > 1 && !strcmp(argv[1], "kept-off")) { + kept_off(); + return 0; + } + // normal: the set goes off, the page holds no factor and no skip + speed = "normal"; + text_speed_poll(); + assert(text_speed_available() && !set_on && page_float(0x208) == 0.0f && page[0x20c] == 0); + // An unknown value reads as normal. + speed = "turbo"; + text_speed_poll(); + assert(!set_on && page_float(0x208) == 0.0f && page[0x20c] == 0); + + // fast: the set on, the factor less one on the page, no skip + speed = "fast"; + text_speed_poll(); + assert(set_on && page_float(0x208) == TEXT_SPEED_FAST_FACTOR - 1.0f && page[0x20c] == 0); + for (unsigned seed = 1; seed < 40; seed++) { + int pressed = seed & 1; + // a message the player may skip: the window's typewriter goes on the page and types faster; the decide bit + // is the player's own + assert(run_skip(0, pressed, seed) == pressed); + float base = 0.25f * (float)(seed % 9 + 1); + assert(fabsf(run_speed(typewriter, base, seed) - base * TEXT_SPEED_FAST_FACTOR) < 1e-5f); + // any other typewriter keeps its speed + assert(run_speed(other, base, seed) == base); + // a message the window does not let the player skip: no typewriter on the page, the game's speed + assert(run_skip(1, pressed, seed) == pressed); + assert(run_speed(typewriter, base, seed) == base); + } + + // instant: the set on, no factor, the decide bit set for the skip test (whose +0x34a test is the game's own) + speed = "instant"; + text_speed_poll(); + assert(set_on && page_float(0x208) == 0.0f && page[0x20c] == 1); + for (unsigned seed = 1; seed < 40; seed++) { + assert(run_skip(0, seed & 1, seed) == 1); + assert(run_speed(typewriter, 1.5f, seed) == 1.5f); + assert(run_skip(1, seed & 1, seed) == 1); + assert(run_speed(typewriter, 1.5f, seed) == 1.5f); + } + + // back to normal: the set off again (the sites run the original instructions), the page cleared + speed = "normal"; + text_speed_poll(); + assert(!set_on && page_float(0x208) == 0.0f && page[0x20c] == 0); + printf("text_speed_check: settings, page words and both sites as expected\n"); + return 0; +} diff --git a/tests/text_speed_check.py b/tests/text_speed_check.py new file mode 100644 index 00000000..5389bdea --- /dev/null +++ b/tests/text_speed_check.py @@ -0,0 +1,82 @@ +"""Build and run tests/text_speed_check.c: the text_speed setting (runtime/text_speed.c) and the replacement words of +the patch set text_speed (recomp/patches-v111.txt), lifted by recomp/lifter.py as the generator lifts them, against a +stand-in message window and typewriter. No game files: the lifted words go to the test's build folder. + +Usage: text_speed_check.py +""" +import os +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'recomp')] +from lifter import Lifter # noqa: E402 +from patches import load # noqa: E402 +from tools.check_content import GENERATED_MARKER # noqa: E402 + +MSYS_BIN = Path(r'C:\msys64\ucrt64\bin') +MAIN = 0x7000000000 +SKIP_SITE, SPEED_SITE = 0x774b74, 0xafe1d8 + + +def compiler(): + if os.environ.get('CC'): + return os.environ['CC'] + if os.name == 'nt' and (MSYS_BIN / 'clang.exe').exists(): + return str(MSYS_BIN / 'clang.exe') + return shutil.which('clang') or 'clang' + + +def site_words(table, site, original): + """The set's replacement words at a site, after checking the site has only them and the original word.""" + alternatives = table.sites['main'][site] + assert len(alternatives) == 1, hex(site) + key, words, have = alternatives[0] + assert table.sets[key] == ('text_speed', 'NX2NAVI_TEXT_SPEED_PATCH', 1), table.sets[key] + assert have == original, (hex(site), hex(have)) + return words + + +def lifted(name, site, words, page_reg, last_branch): + """A C function running the words at the site: the adrp of the patch page is left to the caller, who puts the + page's address in that register, and a last conditional branch is left to the caller too, who reads its register.""" + body = [] + for j, word in enumerate(words): + if isinstance(word, tuple): + assert word == ('page', page_reg) and j == (1 if site == SPEED_SITE else 0), (hex(site), word) + continue + insn = Lifter(0, simd='c').lift(word, MAIN + site) + if j == len(words) - 1 and last_branch: + assert insn.kind != 'op' and word == 0x36000069, hex(word) # tbz w9, #0, the original's target + continue + assert insn.kind == 'op', (hex(site), hex(word), insn.kind) + body.append(' ' + insn.code) + return f'void {name}(Cpu *c) {{\n' + '\n'.join(body) + '\n}\n' + + +def main(): + table = load(ROOT / 'recomp/patches-v111.txt', [('main', MAIN, 0x4ea0000)]) + skip = site_words(table, SKIP_SITE, 0x36000074) # tbz w20, #0, #0x774b80 + speed = site_words(table, SPEED_SITE, 0xbd404e61) # ldr s1, [x19, #0x4c] + work = ROOT / 'build' / 'test' / 'text_speed' + work.mkdir(parents=True, exist_ok=True) + sites = work / 'sites.c' + sites.write_text(f'// {GENERATED_MARKER}: the patch set text_speed lifted by tests/text_speed_check.py.\n' + '#include "cpu.h"\n#include "simd.h"\n\n' + + lifted('site_skip', SKIP_SITE, skip, 9, True) + '\n' + + lifted('site_speed', SPEED_SITE, speed, 22, False)) + exe = work / ('text_speed_check.exe' if os.name == 'nt' else 'text_speed_check') + env = dict(os.environ) + if os.name == 'nt' and MSYS_BIN.exists(): + env['PATH'] = str(MSYS_BIN) + os.pathsep + env.get('PATH', '') + subprocess.check_call([compiler(), '-O1', '-Wall', '-Wno-unused-function', '-Wno-unused-variable', + '-fno-strict-aliasing', '-I', str(ROOT / 'runtime'), + str(ROOT / 'tests' / 'text_speed_check.c'), str(sites), '-o', str(exe), '-lm'], env=env) + rc = subprocess.run([str(exe)], env=env).returncode + return subprocess.run([str(exe), 'kept-off'], env=env).returncode or rc + + +if __name__ == '__main__': + sys.exit(main())