From d1b5bdf0f97bae85c1e90c7faf78a3eaf7ca33ae Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 29 Oct 2026 12:55:16 -0700 Subject: [PATCH 01/85] Switch: read the on-screen keyboard and type on it with feedback Games open the Switch's own keyboard for names (e.g. BDSP's player name). keyboard_enter_code() types on it blind from an assumed starting key, so it can't recover from a press the keyboard ignored while sliding in, or start from wherever the keyboard left its cursor. SystemKeyboardDetector recognizes the keyboard (OK blue, or grey while the field is empty), find_system_keyboard_cursor() reads the key under the cursor, and system_keyboard_field_has_text() says whether the field is empty. Unit tests cover all three on six reference screenshots (CommandLineTests, NintendoSwitch/SystemKeyboardDetector). type_on_system_keyboard() in FastCodeEntry reads the cursor before each key and moves it with keyboard_get_path(), now declared in the header, over KEYBOARD_POSITIONS, so it shares the key grid and the wrap-around moves with blind code entry and also supports AZERTY. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../NintendoSwitch_SystemKeyboardDetector.cpp | 141 ++++++++++++++++++ .../NintendoSwitch_SystemKeyboardDetector.h | 66 ++++++++ .../NintendoSwitch_KeyboardCodeEntry.h | 9 ++ .../NintendoSwitch_SystemKeyboardTyping.cpp | 108 ++++++++++++++ .../NintendoSwitch_SystemKeyboardTyping.h | 39 +++++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 7 files changed, 369 insertions(+) create mode 100644 SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp create mode 100644 SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h create mode 100644 SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp create mode 100644 SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 75af30e3e6..e4cc0a7488 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -25,6 +25,7 @@ #include "NintendoSwitch/Inference/NintendoSwitch_CheckOnlineDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_FailedToConnectDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h" #include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" @@ -59,6 +60,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Kernels::add_tests(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); + NintendoSwitch::add_tests_SystemKeyboardDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); NintendoSwitch::Typewriter::add_tests_TypewriterTextMapping(ret); NintendoSwitch::PokemonFRLG::add_tests(ret); diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp new file mode 100644 index 0000000000..428abbafa3 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp @@ -0,0 +1,141 @@ +/* System Keyboard Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_SystemKeyboardDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +// Centres of the four rows of character keys, and of the first column and the +// spacing between columns, as fractions of the screen. +static constexpr double KEY_ROW_Y[] = {0.500, 0.593, 0.681, 0.770}; +static constexpr double KEY_COL_X0 = 0.077; +static constexpr double KEY_COL_STEP = 0.075; + + +SystemKeyboardDetector::SystemKeyboardDetector(Color color) + : m_color(color) + , m_key_panel(0.15, 0.555, 0.65, 0.020) + , m_bottom_bar(0.10, 0.935, 0.35, 0.030) + , m_ok_button(0.875, 0.760, 0.045, 0.020) +{} +void SystemKeyboardDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_key_panel); + items.add(m_color, m_bottom_bar); + items.add(m_color, m_ok_button); +} +bool SystemKeyboardDetector::detect(const ImageViewRGB32& screen){ + if (!is_white(extract_box_reference(screen, m_key_panel)) || + !is_white(extract_box_reference(screen, m_bottom_bar)) + ){ + return false; + } + // OK is blue, or flat grey while the field is empty (disabled). + const ImageStats ok = image_stats(extract_box_reference(screen, m_ok_button)); + return is_solid(ok, {0.172, 0.276, 0.552}) || is_grey(ok, 600, 690); +} + + +bool find_system_keyboard_cursor(const ImageViewRGB32& screen, int& row, int& col){ + // The cursor is a cyan border around one key. Neighbouring keys overlap that border, + // so take the centroid of all cyan pixels and map it to the nearest key. + const ImageFloatBox area(0.02, 0.44, 0.84, 0.38); + ImageViewRGB32 keys = extract_box_reference(screen, area); + double count = 0, sum_x = 0, sum_y = 0; + for (size_t y = 0; y < keys.height(); y++){ + for (size_t x = 0; x < keys.width(); x++){ + const uint32_t pixel = keys.pixel(x, y); + const int red = (pixel >> 16) & 0xff; + const int green = (pixel >> 8) & 0xff; + const int blue = pixel & 0xff; + if (red < 150 && green > 200 && blue > 190){ + count++; + sum_x += (double)x; + sum_y += (double)y; + } + } + } + // The border is about 0.15% of the screen; a few stray pixels are not a cursor. + if (count < 0.0005 * screen.width() * screen.height()){ + return false; + } + const double cx = area.x + sum_x / count / keys.width() * area.width; + const double cy = area.y + sum_y / count / keys.height() * area.height; + col = (int)std::lround((cx - KEY_COL_X0) / KEY_COL_STEP); + row = 0; + for (int r = 1; r < 4; r++){ + if (std::abs(KEY_ROW_Y[r] - cy) < std::abs(KEY_ROW_Y[row] - cy)){ + row = r; + } + } + return 0 <= col && col < 11; +} + +bool system_keyboard_field_has_text(const ImageViewRGB32& screen){ + // Left part of the field, after the caret's position on an empty field. + const ImageStats stats = image_stats(extract_box_reference(screen, ImageFloatBox(0.11, 0.235, 0.19, 0.030))); + return stats.stddev.sum() > 30; +} + + +// One screenshot and what each function should read from it. +class Test_SystemKeyboardDetector : public UnitTest{ +public: + // cursor_row/col: -1 for a screen without the keyboard. + Test_SystemKeyboardDetector(const std::string& image, bool keyboard, int cursor_row, int cursor_col, bool has_text) + : UnitTest("NintendoSwitch::SystemKeyboardDetector - " + image) + , m_image(UNIT_TEST_RESOURCE_PATH() + image) + , m_keyboard(keyboard) + , m_cursor_row(cursor_row) + , m_cursor_col(cursor_col) + , m_has_text(has_text) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + ImageRGB32 image(m_image); + if (SystemKeyboardDetector().detect(image) != m_keyboard){ + return false; + } + if (!m_keyboard){ + return true; + } + int row = -1; + int col = -1; + return find_system_keyboard_cursor(image, row, col) + && row == m_cursor_row && col == m_cursor_col + && system_keyboard_field_has_text(image) == m_has_text; + } + +private: + std::string m_image; + bool m_keyboard; + int m_cursor_row; + int m_cursor_col; + bool m_has_text; +}; + + +void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ + const std::string folder = "NintendoSwitch/SystemKeyboardDetector/"; + // The OK button is blue with text in the field and grey without. + database.add(folder + "BDSP-PlayerName-Empty.png", true, 0, 0, false); + database.add(folder + "BDSP-FriendName-Typed.png", true, 0, 0, true); + database.add(folder + "BDSP-Dialog.png", false, -1, -1, false); + database.add(folder + "HomeMenu.png", false, -1, -1, false); + database.add(folder + "HomeMenu-OnlineLicensePopup.png", false, -1, -1, false); + database.add(folder + "UserSelect.png", false, -1, -1, false); +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h new file mode 100644 index 0000000000..7a2952a2ce --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h @@ -0,0 +1,66 @@ +/* System Keyboard Detector + * + * From: https://github.com/PokemonAutomation/ + * + * The Switch's own on-screen keyboard, which games open for names (e.g. the + * player's name in BDSP): detect it, find the key under its cursor, and tell + * whether its text field is empty. Typing with it is in + * Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h. + * + * Measured on 1920x1080 captures of the QWERTY layout. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SystemKeyboardDetector_H +#define PokemonAutomation_NintendoSwitch_SystemKeyboardDetector_H + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// White key panel and bottom bar, and the OK button (blue, or grey while the +// field is empty). +class SystemKeyboardDetector : public StaticScreenDetector{ +public: + SystemKeyboardDetector(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_key_panel; + ImageFloatBox m_bottom_bar; + ImageFloatBox m_ok_button; +}; +class SystemKeyboardWatcher : public DetectorToFinder{ +public: + SystemKeyboardWatcher(Color color = COLOR_CYAN) + : DetectorToFinder("SystemKeyboardWatcher", std::chrono::milliseconds(250), color) + {} +}; + + +// The key under the cursor, as row (0: digits .. 3: "zxcv") and column (0..10). +// The keyboard remembers the cursor between uses, so read it, don't assume it. +// Returns false if no cursor border is visible. +bool find_system_keyboard_cursor(const ImageViewRGB32& screen, int& row, int& col); + +// Whether the text field holds any text. Pressing B on an empty field closes the +// keyboard, so delete only while this is true. +bool system_keyboard_field_has_text(const ImageViewRGB32& screen); + + + +void add_tests_SystemKeyboardDetector(UnitTestDatabase& database); + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h index 7048582ea0..38f4f4d841 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h @@ -8,10 +8,12 @@ #define PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H #include +#include #include "Controllers/StandardHid/StandardHid_Keyboard.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardEntryMappings.h" +#include "NintendoSwitch_CodeEntryTools.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -19,6 +21,13 @@ namespace FastCodeEntry{ +// The D-pad moves from "source" to "destination" on the on-screen keyboard, +// wrapping around the sides when that is shorter, then ENTER_CHAR. +std::vector keyboard_get_path( + KeyboardEntryPosition source, + KeyboardEntryPosition destination +); + // Automatically select between keyboard or pro controller depending on the // controller type. void keyboard_enter_code( diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp new file mode 100644 index 0000000000..43a3329df5 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp @@ -0,0 +1,108 @@ +/* System Keyboard Typing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h" +#include "NintendoSwitch_KeyboardCodeEntry.h" +#include "NintendoSwitch_SystemKeyboardTyping.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + +using namespace std::chrono_literals; + + +namespace{ + +constexpr Milliseconds MOVE_HOLD = 100ms; // One key per press, without auto-repeat. +constexpr Milliseconds MOVE_RELEASE = 200ms; +constexpr Milliseconds WRAP_RELEASE = 400ms; // Wrapping around a side animates for longer. +constexpr Milliseconds SETTLE = 300ms; // Before reading the cursor after moving it. +constexpr Milliseconds KEY_HOLD = 80ms; +constexpr Milliseconds KEY_RELEASE = 300ms; + +// A press made while the keyboard is still sliding in is ignored, so the +// cursor is read again after each try until it is on the target. +constexpr size_t MAX_MOVE_TRIES = 10; + + +bool read_cursor(VideoStream& stream, ProControllerContext& context, KeyboardEntryPosition& position){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int row = -1; + int col = -1; + if (!screen || !find_system_keyboard_cursor(screen, row, col)){ + return false; + } + position = {(uint8_t)row, (uint8_t)col}; + return true; +} + +void move_cursor(VideoStream& stream, ProControllerContext& context, KeyboardEntryPosition target, char ch){ + for (size_t attempt = 0; attempt < MAX_MOVE_TRIES; attempt++){ + KeyboardEntryPosition cursor; + if (!read_cursor(stream, context, cursor)){ + pbf_wait(context, SETTLE); + continue; + } + if (cursor.row == target.row && cursor.col == target.col){ + return; + } + for (CodeEntryAction action : keyboard_get_path(cursor, target)){ + if (!is_move(action)){ + continue; + } + const bool wrap = ((uint8_t)action & 0x80) != 0; + const DpadPosition direction = (DpadPosition)((uint8_t)action & 0x7f); + pbf_press_dpad(context, direction, MOVE_HOLD, wrap ? WRAP_RELEASE : MOVE_RELEASE); + } + pbf_wait(context, SETTLE); + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::string("System keyboard: the cursor did not reach '") + ch + "'.", + stream + ); +} + +} + + + +void type_on_system_keyboard( + VideoStream& stream, ProControllerContext& context, + const std::string& text, + KeyboardLayout layout +){ + const std::map& positions = KEYBOARD_POSITIONS(layout); + for (char ch : text){ + // Letters are listed under their uppercase key. + auto iter = positions.find((char)std::toupper((unsigned char)ch)); + if (iter == positions.end()){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::string("System keyboard: no key for '") + ch + "'.", + stream + ); + } + move_cursor(stream, context, iter->second, ch); + if (std::isupper((unsigned char)ch)){ + pbf_press_button(context, BUTTON_LCLICK, 100ms, 250ms); + } + pbf_press_button(context, BUTTON_A, KEY_HOLD, KEY_RELEASE); + } + context.wait_for_all_requests(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h new file mode 100644 index 0000000000..b0ec331111 --- /dev/null +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h @@ -0,0 +1,39 @@ +/* System Keyboard Typing + * + * From: https://github.com/PokemonAutomation/ + * + * Types text on the Switch's on-screen keyboard with a Pro Controller, reading + * the cursor from the video before each key. Unlike keyboard_enter_code(), + * which moves blind from an assumed starting key, it works wherever the + * keyboard left its cursor and catches presses the keyboard ignored. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SystemKeyboardTyping_H +#define PokemonAutomation_NintendoSwitch_SystemKeyboardTyping_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch_KeyboardEntryMappings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + +// Types `text` (letters, digits and the symbols on the keyboard's first page) +// on the open keyboard. An uppercase letter is typed with Shift (left stick +// click). Throws, with a screenshot, for a character that has no key, or if +// the cursor can't be read or doesn't reach a key. +void type_on_system_keyboard( + VideoStream& stream, ProControllerContext& context, + const std::string& text, + KeyboardLayout layout = KeyboardLayout::QWERTY +); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 39c48d531e..f82e61647b 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1323,6 +1323,8 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp @@ -1374,6 +1376,8 @@ file(GLOB LIBRARY_SOURCES Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp From 110d05e6a28a791f5fb19f4c8ffb10302384a36c Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 12:51:38 -0800 Subject: [PATCH 02/85] Pokemon AutoStory: share SV's checkpoint retry and save counting Move the game-agnostic part of SV's checkpoint_reattempt_loop and checkpoint_save into Pokemon/AutoStory/Pokemon_CheckpointRetry: the retry policy, reset counter and StoryLog lines, with the game's run, report, reset and give-up as callables. SV keeps its saves and messages and its historical counts (102 attempts, report on the 11th failure). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../AutoStory/Pokemon_CheckpointRetry.cpp | 57 +++++ .../AutoStory/Pokemon_CheckpointRetry.h | 78 ++++++ .../Pokemon_CheckpointRetry_Tests.cpp | 225 ++++++++++++++++++ .../AutoStory/Pokemon_CheckpointRetry_Tests.h | 23 ++ .../AutoStory/PokemonSV_AutoStoryTools.cpp | 206 ++++++++-------- SerialPrograms/cmake/SourceFiles.cmake | 4 + 7 files changed, 492 insertions(+), 103 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 5502b147a4..58dfaaf8cb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -15,6 +15,7 @@ #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" +#include "Pokemon_CheckpointRetry_Tests.h" #include "Pokemon_StoryLog_Tests.h" namespace PokemonAutomation{ @@ -25,6 +26,7 @@ namespace Pokemon{ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); add_tests_AutoStoryStats(database); + add_tests_CheckpointRetry(database); add_tests_StoryLog(database); add_tests_StoryRangeOptions(database); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp new file mode 100644 index 0000000000..87d9317d07 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp @@ -0,0 +1,57 @@ +/* Checkpoint Retry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryLog.h" +#include "Pokemon_CheckpointRetry.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +size_t run_checkpoint_with_retries( + std::string_view checkpoint, + const CheckpointRetryPolicy& policy, + const CheckpointRetryActions& actions, + AutoStoryStats& stats +){ + actions.log(checkpoint_start_line(checkpoint)); + for (size_t attempt = 1;; attempt++){ + try{ + actions.log(checkpoint_attempt_line(checkpoint, attempt, policy.max_attempts)); + actions.run(attempt); + actions.log(checkpoint_pass_line(checkpoint, attempt)); + return attempt; + }catch (OperationFailedException& e){ + if (attempt == policy.report_at_failure){ + actions.report(e); + } + if (attempt >= policy.max_attempts){ + actions.give_up(e); + throw; + } + actions.log(checkpoint_reset_line(checkpoint, attempt + 1)); + actions.reset(); + stats.m_reset++; + actions.update_stats(); + } + } +} + + +void record_checkpoint_saved( + AutoStoryStats& stats, + const std::function& update_stats, + const std::function& notify +){ + stats.m_checkpoint++; + update_stats(); + notify(CHECKPOINT_SAVED_MESSAGE); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h new file mode 100644 index 0000000000..de9e901255 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h @@ -0,0 +1,78 @@ +/* Checkpoint Retry + * + * From: https://github.com/PokemonAutomation/ + * + * The retry policy of a game whose AutoStory runs each checkpoint in its + * own loop (SV's): run the checkpoint, and on an operation failure reset + * the game to the checkpoint's save and try again, report once for + * debugging after some failures, and give up after the last attempt. + * The game supplies what it does at each step; the policy, the counters + * and the log lines (Pokemon_StoryLog.h) live here. + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointRetry_H +#define PokemonAutomation_Pokemon_CheckpointRetry_H + +#include +#include +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_AutoStoryStats.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct CheckpointRetryPolicy{ + // Attempts before the checkpoint gives up. + size_t max_attempts; + // The failure count at which the game reports once for debugging. + size_t report_at_failure; +}; + +// What the game does at each step of the loop. +struct CheckpointRetryActions{ + // Runs attempt `attempt`, counting from 1. Throws + // OperationFailedException when the attempt fails. + std::function run; + // Sends the debugging report, with the exception of the failure that + // reached the policy's count. + std::function report; + // Throws the game's final error after the last attempt failed. + std::function give_up; + // Resets the game to the checkpoint's save. + std::function reset; + // Publishes changed stats. + std::function update_stats; + // Writes one log line. + std::function log; +}; + +// Runs `checkpoint` until an attempt passes, and returns that attempt's +// number. Each reset adds to `stats.m_reset`. +size_t run_checkpoint_with_retries( + std::string_view checkpoint, + const CheckpointRetryPolicy& policy, + const CheckpointRetryActions& actions, + AutoStoryStats& stats +); + + +// The status message sent after the game saved at a checkpoint. +inline constexpr std::string_view CHECKPOINT_SAVED_MESSAGE = "Saved at checkpoint."; + +// Counts a checkpoint the game just saved at, publishes the stats and +// sends CHECKPOINT_SAVED_MESSAGE through `notify`. +void record_checkpoint_saved( + AutoStoryStats& stats, + const std::function& update_stats, + const std::function& notify +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp new file mode 100644 index 0000000000..54f17774af --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp @@ -0,0 +1,225 @@ +/* Checkpoint Retry Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_CheckpointRetry.h" +#include "Pokemon_CheckpointRetry_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// Thrown by the test's give_up, so the test can tell it from the attempt's. +struct GaveUp{}; + +// A checkpoint whose first `failures` attempts fail. +struct CheckpointRetryInput{ + std::string name; + CheckpointRetryPolicy policy; + size_t failures; +}; + +struct CheckpointRetryExpectation{ + // The attempt that passed; 0 if the loop gave up. + size_t passed_on; + // The failure counts at which the loop reported. + std::vector reports; + size_t resets; + std::vector log; +}; + +// One retry loop run and what it must do. +struct CheckpointRetryCase{ + CheckpointRetryInput input; + CheckpointRetryExpectation expectation; +}; + +// What the loop did through the test's actions. +struct CheckpointRetryRecord{ + size_t passed_on = 0; + std::vector reports; + size_t resets = 0; + std::vector log; +}; + +CheckpointRetryRecord run_case(const CheckpointRetryInput& input, AutoStoryStats& stats){ + CheckpointRetryRecord record; + size_t attempts = 0; + CheckpointRetryActions actions{ + .run = [&](size_t attempt){ + attempts = attempt; + if (attempt <= input.failures){ + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "failed"); + } + }, + .report = [&](const OperationFailedException&){ + record.reports.push_back(attempts); + }, + .give_up = [](const OperationFailedException&){ + throw GaveUp(); + }, + .reset = [&](){ + record.resets++; + }, + .update_stats = [](){}, + .log = [&](const std::string& line){ + record.log.push_back(line); + }, + }; + try{ + record.passed_on = run_checkpoint_with_retries("01", input.policy, actions, stats); + }catch (GaveUp&){ + record.passed_on = 0; + } + return record; +} + +class Test_CheckpointRetry : public UnitTest{ +public: + Test_CheckpointRetry(CheckpointRetryCase test_case) + : UnitTest(std::format("Pokemon::CheckpointRetry - {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + AutoStoryStats stats; + const CheckpointRetryRecord record = run_case(m_case.input, stats); + const CheckpointRetryExpectation& expected = m_case.expectation; + if (record.passed_on != expected.passed_on){ + return std::format("Expected a pass on attempt {}, got {}", expected.passed_on, record.passed_on); + } + if (record.reports != expected.reports){ + return std::format("Expected {} reports, got {}", expected.reports.size(), record.reports.size()); + } + if (record.resets != expected.resets || stats.m_reset.load() != expected.resets){ + return std::format( + "Expected {} resets, got {} (stats {})", + expected.resets, record.resets, stats.m_reset.load() + ); + } + if (record.log != expected.log){ + return std::format("Expected {} log lines, got {}", expected.log.size(), record.log.size()); + } + return true; + } + +private: + const CheckpointRetryCase m_case; +}; + +const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { + { + .input = {.name = "one-shot pass", .policy = {.max_attempts = 3, .report_at_failure = 2}, .failures = 0}, + .expectation = { + .passed_on = 1, + .reports = {}, + .resets = 0, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/3", + "[Checkpoint] 01: passed on attempt 1 (one-shot)", + }, + }, + }, + { + .input = {.name = "pass after a reset", .policy = {.max_attempts = 3, .report_at_failure = 2}, .failures = 1}, + .expectation = { + .passed_on = 2, + .reports = {}, + .resets = 1, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/3", + "[Checkpoint] 01: failed, resetting for attempt 2", + "[Checkpoint] 01: attempt 2/3", + "[Checkpoint] 01: passed on attempt 2 (1 reset)", + }, + }, + }, + { + .input = {.name = "report once at its failure count", .policy = {.max_attempts = 5, .report_at_failure = 2}, .failures = 3}, + .expectation = { + .passed_on = 4, + .reports = {2}, + .resets = 3, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/5", + "[Checkpoint] 01: failed, resetting for attempt 2", + "[Checkpoint] 01: attempt 2/5", + "[Checkpoint] 01: failed, resetting for attempt 3", + "[Checkpoint] 01: attempt 3/5", + "[Checkpoint] 01: failed, resetting for attempt 4", + "[Checkpoint] 01: attempt 4/5", + "[Checkpoint] 01: passed on attempt 4 (3 resets)", + }, + }, + }, + { + .input = {.name = "give up after the last attempt, without a reset", .policy = {.max_attempts = 2, .report_at_failure = 2}, .failures = 5}, + .expectation = { + .passed_on = 0, + .reports = {2}, + .resets = 1, + .log = { + "[Checkpoint] 01: start", + "[Checkpoint] 01: attempt 1/2", + "[Checkpoint] 01: failed, resetting for attempt 2", + "[Checkpoint] 01: attempt 2/2", + }, + }, + }, +}; + + +class Test_CheckpointSaved : public UnitTest{ +public: + Test_CheckpointSaved() + : UnitTest("Pokemon::CheckpointRetry - a save counts, publishes and notifies") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + AutoStoryStats stats; + size_t updates = 0; + std::vector messages; + for (size_t i = 0; i < 2; i++){ + record_checkpoint_saved( + stats, + [&](){ updates++; }, + [&](std::string_view message){ messages.emplace_back(message); } + ); + } + if (stats.m_checkpoint.load() != 2 || updates != 2){ + return std::format("Expected 2 checkpoints and updates, got {} and {}", stats.m_checkpoint.load(), updates); + } + if (messages != std::vector{"Saved at checkpoint.", "Saved at checkpoint."}){ + return std::string("Expected \"Saved at checkpoint.\" per save"); + } + return true; + } +}; + + +} // namespace + + +void add_tests_CheckpointRetry(UnitTestDatabase& database){ + for (const CheckpointRetryCase& test_case : CHECKPOINT_RETRY_CASES){ + database.add(test_case); + } + database.add(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h new file mode 100644 index 0000000000..b7b5ccb6f1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h @@ -0,0 +1,23 @@ +/* Checkpoint Retry Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointRetry_Tests_H +#define PokemonAutomation_Pokemon_CheckpointRetry_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the checkpoint retry loop and checkpoint saves. +void add_tests_CheckpointRetry(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index c2d61152df..1db01c4ae9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -4,6 +4,7 @@ * */ +#include #include "Common/Cpp/PrettyPrint.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Exceptions/UnexpectedBattleException.h" @@ -29,6 +30,7 @@ #include "VideoGames/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h" #include "VideoGames/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" #include "VideoGames/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" +#include "Pokemon/AutoStory/Pokemon_CheckpointRetry.h" #include "PokemonSV_AutoStoryTools.h" //#include @@ -1177,11 +1179,71 @@ void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControl } } +namespace{ + +// The loop's historical counts; its messages say 100 attempts and 10 failures. +const Pokemon::CheckpointRetryPolicy SV_CHECKPOINT_RETRY_POLICY{.max_attempts = 102, .report_at_failure = 11}; + +void record_sv_checkpoint_saved( + SingleSwitchProgramEnvironment& env, EventNotificationOption& notif_status_update, AutoStoryStats& stats +){ + Pokemon::record_checkpoint_saved( + stats, + [&env](){ env.update_stats(); }, + [&](std::string_view message){ send_program_status_notification(env, notif_status_update, std::string(message)); } + ); +} + +// `give_up_detail` goes into the final error after its first line: the +// overworld loop names the checkpoint there, the tutorial loop does not. +Pokemon::CheckpointRetryActions sv_checkpoint_retry_actions( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_error_recoverable, + const std::string& checkpoint_text, + std::function run, + std::string give_up_detail +){ + return Pokemon::CheckpointRetryActions{ + .run = std::move(run), + .report = [&env, ¬if_error_recoverable, &checkpoint_text](const OperationFailedException&){ + auto snapshot = env.console.video().snapshot().frame; + send_program_recoverable_error_notification_and_telemetry_report( + env, &env.logger(), env.program_info(), + notif_error_recoverable, + ErrorReportMode::SEND_ERROR_REPORT, + std::format("10 failed attempts. {}", checkpoint_text), + "OperationFailedExceptionWithScreenshot", + *snapshot, + &env.console.history() + ); + }, + .give_up = [&env, give_up_detail = std::move(give_up_detail)](const OperationFailedException& e){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format( + "Autostory checkpoint failed 100 times.\n{}" + "Make sure you selected the correct Start Point, and your character is in the exactly correct starting position." + "Also, make sure you have set the correct Language.\n{}", + give_up_detail, e.message() + ), + env.console + ); + }, + .reset = [&env, &context](){ + context.wait_for_all_requests(); + reset_game(env.program_info(), env.console, context); + }, + .update_stats = [&env](){ env.update_stats(); }, + .log = [&env](const std::string& line){ env.console.log(line); }, + }; +} + +} // namespace + void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update, AutoStoryStats& stats){ save_game_from_overworld(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); + record_sv_checkpoint_saved(env, notif_status_update, stats); } @@ -1433,59 +1495,27 @@ void checkpoint_reattempt_loop( std::function&& action, bool day_skip ){ - size_t max_attempts = 100; - for (size_t i = 0;;i++){ - try{ - if (i==0){ - checkpoint_save(env, context, notif_status_update, stats); - } - - if (day_skip && (i > 0 || ENABLE_TEST)){ - day_skip_from_overworld(env.console, context); - save_game_from_overworld(env.program_info(), env.console, context); - } - - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); - - context.wait_for_all_requests(); - action(i); - - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - - break; - }catch (OperationFailedException& e){ - if (i == 10){ // send an error report for debugging if 10 failed attempts for a given checkpoint. - auto snapshot = env.console.video().snapshot().frame; - std::string message = "10 failed attempts. " + checkpoint_text; - send_program_recoverable_error_notification_and_telemetry_report( - env, &env.logger(), env.program_info(), - notif_error_recoverable, - ErrorReportMode::SEND_ERROR_REPORT, - message, - "OperationFailedExceptionWithScreenshot", - *snapshot, - &env.console.history() - ); - } - - if (i > max_attempts){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "Autostory checkpoint failed " + std::to_string(max_attempts) + " times.\n" + - checkpoint_text + "\n" - "Make sure you selected the correct Start Point, and your character is in the exactly correct starting position." - "Also, make sure you have set the correct Language.\n" + e.message(), - env.console - ); - } - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - + Pokemon::run_checkpoint_with_retries( + checkpoint_text, SV_CHECKPOINT_RETRY_POLICY, + sv_checkpoint_retry_actions( + env, context, notif_error_recoverable, checkpoint_text, + [&](size_t attempt){ + const size_t i = attempt - 1; + if (i == 0){ + checkpoint_save(env, context, notif_status_update, stats); + } + if (day_skip && (i > 0 || ENABLE_TEST)){ + day_skip_from_overworld(env.console, context); + save_game_from_overworld(env.program_info(), env.console, context); + } + context.wait_for_all_requests(); + action(i); + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + }, + std::format("{}\n", checkpoint_text) + ), + stats + ); } void checkpoint_reattempt_loop_tutorial( @@ -1497,53 +1527,23 @@ void checkpoint_reattempt_loop_tutorial( const std::string& checkpoint_text, std::function&& action ){ - size_t max_attempts = 100; - for (size_t i = 0;;i++){ - try{ - if(i==0){ - save_game_tutorial(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); - } - - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); - - context.wait_for_all_requests(); - action(i); - - break; - }catch (OperationFailedException& e){ - if (i == 10){ // send an error report for debugging if 10 failed attempts for a given checkpoint. - auto snapshot = env.console.video().snapshot().frame; - std::string message = "10 failed attempts. " + checkpoint_text; - send_program_recoverable_error_notification_and_telemetry_report( - env, &env.logger(), env.program_info(), - notif_error_recoverable, - ErrorReportMode::SEND_ERROR_REPORT, - message, - "OperationFailedExceptionWithScreenshot", - *snapshot, - &env.console.history() - ); - } - - if (i > max_attempts){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "Autostory checkpoint failed " + std::to_string(max_attempts) + " times.\n" - "Make sure you selected the correct Start Point, and your character is in the exactly correct starting position." - "Also, make sure you have set the correct Language.\n" + e.message(), - env.console - ); - } - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } + Pokemon::run_checkpoint_with_retries( + checkpoint_text, SV_CHECKPOINT_RETRY_POLICY, + sv_checkpoint_retry_actions( + env, context, notif_error_recoverable, checkpoint_text, + [&](size_t attempt){ + const size_t i = attempt - 1; + if (i == 0){ + save_game_tutorial(env.program_info(), env.console, context); + record_sv_checkpoint_saved(env, notif_status_update, stats); + } + context.wait_for_all_requests(); + action(i); + }, + "" + ), + stats + ); } void move_player_forward( diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 8e292ab767..b9af11f84a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1479,6 +1479,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp Source/Pokemon/AutoStory/Pokemon_StoryLog.h Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp From 14144fce7181de4df5ec0ebfc53435112a65ac5a Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 12:52:14 -0800 Subject: [PATCH 03/85] Pokemon AutoStory: CheckpointRetry code-health fixes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_CheckpointRetry.cpp | 6 +- .../AutoStory/Pokemon_CheckpointRetry.h | 25 +++++--- .../Pokemon_CheckpointRetry_Tests.cpp | 60 +++++++++++++++---- .../AutoStory/PokemonSV_AutoStoryTools.cpp | 4 +- 4 files changed, 71 insertions(+), 24 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp index 87d9317d07..3f30be451d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp @@ -42,9 +42,9 @@ size_t run_checkpoint_with_retries( void record_checkpoint_saved( - AutoStoryStats& stats, - const std::function& update_stats, - const std::function& notify + const CheckpointStep& update_stats, + const std::function& notify, + AutoStoryStats& stats ){ stats.m_checkpoint++; update_stats(); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h index de9e901255..05ac68e781 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h @@ -25,6 +25,7 @@ namespace PokemonAutomation{ namespace Pokemon{ +// How often a checkpoint retries and when it reports. struct CheckpointRetryPolicy{ // Attempts before the checkpoint gives up. size_t max_attempts; @@ -32,6 +33,13 @@ struct CheckpointRetryPolicy{ size_t report_at_failure; }; +// A game step that takes nothing: a reset, a stats update. +using CheckpointStep = std::function; +// A game step on the failure that reached a policy count. +using CheckpointFailureStep = std::function; +// Writes one log line. +using CheckpointLogger = std::function; + // What the game does at each step of the loop. struct CheckpointRetryActions{ // Runs attempt `attempt`, counting from 1. Throws @@ -39,15 +47,14 @@ struct CheckpointRetryActions{ std::function run; // Sends the debugging report, with the exception of the failure that // reached the policy's count. - std::function report; + CheckpointFailureStep report; // Throws the game's final error after the last attempt failed. - std::function give_up; + CheckpointFailureStep give_up; // Resets the game to the checkpoint's save. - std::function reset; + CheckpointStep reset; // Publishes changed stats. - std::function update_stats; - // Writes one log line. - std::function log; + CheckpointStep update_stats; + CheckpointLogger log; }; // Runs `checkpoint` until an attempt passes, and returns that attempt's @@ -66,9 +73,9 @@ inline constexpr std::string_view CHECKPOINT_SAVED_MESSAGE = "Saved at checkpoin // Counts a checkpoint the game just saved at, publishes the stats and // sends CHECKPOINT_SAVED_MESSAGE through `notify`. void record_checkpoint_saved( - AutoStoryStats& stats, - const std::function& update_stats, - const std::function& notify + const CheckpointStep& update_stats, + const std::function& notify, + AutoStoryStats& stats ); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp index 54f17774af..3d1015cbc2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -181,31 +182,68 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { }; +// `saves` checkpoint saves in a row. +struct CheckpointSavedInput{ + std::string name; + size_t saves; +}; + +struct CheckpointSavedExpectation{ + uint64_t checkpoints; + size_t updates; + std::vector messages; +}; + +// Checkpoint saves and what they must count and send. +struct CheckpointSavedCase{ + CheckpointSavedInput input; + CheckpointSavedExpectation expectation; +}; + class Test_CheckpointSaved : public UnitTest{ public: - Test_CheckpointSaved() - : UnitTest("Pokemon::CheckpointRetry - a save counts, publishes and notifies") + Test_CheckpointSaved(CheckpointSavedCase test_case) + : UnitTest(std::format("Pokemon::CheckpointRetry - {}", test_case.input.name)) + , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ AutoStoryStats stats; size_t updates = 0; std::vector messages; - for (size_t i = 0; i < 2; i++){ + for (size_t i = 0; i < m_case.input.saves; i++){ record_checkpoint_saved( - stats, [&](){ updates++; }, - [&](std::string_view message){ messages.emplace_back(message); } + [&](std::string_view message){ messages.emplace_back(message); }, + stats ); } - if (stats.m_checkpoint.load() != 2 || updates != 2){ - return std::format("Expected 2 checkpoints and updates, got {} and {}", stats.m_checkpoint.load(), updates); + const CheckpointSavedExpectation& expected = m_case.expectation; + if (stats.m_checkpoint.load() != expected.checkpoints || updates != expected.updates){ + return std::format( + "Expected {} checkpoints and {} updates, got {} and {}", + expected.checkpoints, expected.updates, stats.m_checkpoint.load(), updates + ); } - if (messages != std::vector{"Saved at checkpoint.", "Saved at checkpoint."}){ - return std::string("Expected \"Saved at checkpoint.\" per save"); + if (messages != expected.messages){ + return std::format("Expected {} messages, got {}", expected.messages.size(), messages.size()); } return true; } + +private: + const CheckpointSavedCase m_case; +}; + +const CheckpointSavedCase CHECKPOINT_SAVED_CASES[] = { + { + .input = {.name = "each save counts, publishes and notifies", .saves = 2}, + .expectation = { + .checkpoints = 2, + .updates = 2, + .messages = {"Saved at checkpoint.", "Saved at checkpoint."}, + }, + }, }; @@ -216,7 +254,9 @@ void add_tests_CheckpointRetry(UnitTestDatabase& database){ for (const CheckpointRetryCase& test_case : CHECKPOINT_RETRY_CASES){ database.add(test_case); } - database.add(); + for (const CheckpointSavedCase& test_case : CHECKPOINT_SAVED_CASES){ + database.add(test_case); + } } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index 1db01c4ae9..df9362f3d0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -1188,9 +1188,9 @@ void record_sv_checkpoint_saved( SingleSwitchProgramEnvironment& env, EventNotificationOption& notif_status_update, AutoStoryStats& stats ){ Pokemon::record_checkpoint_saved( - stats, [&env](){ env.update_stats(); }, - [&](std::string_view message){ send_program_status_notification(env, notif_status_update, std::string(message)); } + [&](std::string_view message){ send_program_status_notification(env, notif_status_update, std::string(message)); }, + stats ); } From 9ea62b9b93f0300ef5af8a24a63ff4af1f29b53f Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:37:07 -0800 Subject: [PATCH 04/85] PokemonSV AutoStory: shared checkpoint range options and log lines The tutorial and main story checkpoint dropdowns are now the shared StoryRangeOptions, added under the same keys (START_CHECKPOINT_TUTORIAL, END_CHECKPOINT_TUTORIAL, START_CHECKPOINT_MAINSTORY, END_CHECKPOINT_MAINSTORY) over the same databases, so saved settings load unchanged; the end stays unlocked while running. The start-before-end check is the range's. The checkpoint loops log the shared attempt and reset lines, and the run logs the shared checkpoint start line. Rebased onto autostory/story-range-options (#325) and squashed: it uses only the shared range options (#325) and log lines (#45), not #312. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonSV_AutoStory.cpp | 76 ++++++++----------- .../Programs/AutoStory/PokemonSV_AutoStory.h | 14 ++-- .../AutoStory/PokemonSV_AutoStoryTools.cpp | 8 +- .../AutoStory/PokemonSV_AutoStoryTools.h | 4 +- 4 files changed, 47 insertions(+), 55 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp index 130271139b..945731d147 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -28,6 +28,7 @@ #include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "Pokemon/Pokemon_Strings.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" #include "VideoGames/PokemonSV/PokemonSV_Settings.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" @@ -347,6 +348,10 @@ AutoStory::~AutoStory(){ ENDPOINT_TUTORIAL.remove_listener(*this); STARTPOINT_MAINSTORY.remove_listener(*this); ENDPOINT_MAINSTORY.remove_listener(*this); + TUTORIAL_CHECKPOINTS.START_CHECKPOINT.remove_listener(*this); + TUTORIAL_CHECKPOINTS.END_CHECKPOINT.remove_listener(*this); + MAINSTORY_CHECKPOINTS.START_CHECKPOINT.remove_listener(*this); + MAINSTORY_CHECKPOINTS.END_CHECKPOINT.remove_listener(*this); ENABLE_TEST_CHECKPOINTS.remove_listener(*this); ENABLE_MISC_TEST.remove_listener(*this); TEST_PBF_LEFT_JOYSTICK.remove_listener(*this); @@ -395,30 +400,9 @@ AutoStory::AutoStory() LockMode::UNLOCK_WHILE_RUNNING, std::to_string(ALL_SEGMENTS_SELECT_DATABASE().case_list().size()-1) ) - , START_CHECKPOINT_TUTORIAL( - "Start Checkpoint:", //
Program will start with this checkpoint. - TUTORIAL_CHECKPOINTS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - "0" - ) - , END_CHECKPOINT_TUTORIAL( - "End Checkpoint:", //
Program will stop after completing this checkpoint. - TUTORIAL_CHECKPOINTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - std::to_string(INDEX_OF_LAST_TUTORIAL_CHECKPOINT) - ) - , START_CHECKPOINT_MAINSTORY( - "Start Checkpoint:", //
Program will start with this checkpoint. - MAINSTORY_CHECKPOINTS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - std::to_string(INDEX_OF_LAST_TUTORIAL_CHECKPOINT+1) - ) - , END_CHECKPOINT_MAINSTORY( - "End Checkpoint:", //
Program will stop after completing this checkpoint. - MAINSTORY_CHECKPOINTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - std::to_string(ALL_CHECKPOINTS_SELECT_DATABASE().case_list().size()-1) - ) + // The end is read after each checkpoint, so it stays unlocked. + , TUTORIAL_CHECKPOINTS("Tutorial Checkpoints", TUTORIAL_CHECKPOINTS_SELECT_DATABASE(), LockMode::UNLOCK_WHILE_RUNNING) + , MAINSTORY_CHECKPOINTS("Main Story Checkpoints", MAINSTORY_CHECKPOINTS_SELECT_DATABASE(), LockMode::UNLOCK_WHILE_RUNNING) , SETUP_NOTE{ "NOTE: Make sure you have selected the correct Start Point. " "Make sure your player character is in the exact correct start position for that Start Point, " @@ -710,11 +694,11 @@ AutoStory::AutoStory() PA_ADD_OPTION(ENDPOINT_MAINSTORY); PA_ADD_OPTION(END_DESCRIPTION); - PA_ADD_OPTION(START_CHECKPOINT_TUTORIAL); - PA_ADD_OPTION(START_CHECKPOINT_MAINSTORY); + add_option(TUTORIAL_CHECKPOINTS.START_CHECKPOINT, "START_CHECKPOINT_TUTORIAL"); + add_option(MAINSTORY_CHECKPOINTS.START_CHECKPOINT, "START_CHECKPOINT_MAINSTORY"); PA_ADD_OPTION(START_CHECKPOINT_DESCRIPTION); - PA_ADD_OPTION(END_CHECKPOINT_TUTORIAL); - PA_ADD_OPTION(END_CHECKPOINT_MAINSTORY); + add_option(TUTORIAL_CHECKPOINTS.END_CHECKPOINT, "END_CHECKPOINT_TUTORIAL"); + add_option(MAINSTORY_CHECKPOINTS.END_CHECKPOINT, "END_CHECKPOINT_MAINSTORY"); PA_ADD_OPTION(END_CHECKPOINT_DESCRIPTION); PA_ADD_OPTION(STARTERCHOICE); @@ -738,10 +722,10 @@ AutoStory::AutoStory() STARTPOINT_MAINSTORY.add_listener(*this); ENDPOINT_MAINSTORY.add_listener(*this); - START_CHECKPOINT_TUTORIAL.add_listener(*this); - END_CHECKPOINT_TUTORIAL.add_listener(*this); - START_CHECKPOINT_MAINSTORY.add_listener(*this); - END_CHECKPOINT_MAINSTORY.add_listener(*this); + TUTORIAL_CHECKPOINTS.START_CHECKPOINT.add_listener(*this); + TUTORIAL_CHECKPOINTS.END_CHECKPOINT.add_listener(*this); + MAINSTORY_CHECKPOINTS.START_CHECKPOINT.add_listener(*this); + MAINSTORY_CHECKPOINTS.END_CHECKPOINT.add_listener(*this); ENABLE_ADVANCED_MODE.add_listener(*this); @@ -769,10 +753,10 @@ void AutoStory::on_config_value_changed(void* object){ STARTPOINT_MAINSTORY.set_visibility(mainstory_segments ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); ENDPOINT_MAINSTORY.set_visibility(mainstory_segments ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - START_CHECKPOINT_TUTORIAL.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - END_CHECKPOINT_TUTORIAL.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - START_CHECKPOINT_MAINSTORY.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - END_CHECKPOINT_MAINSTORY.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + TUTORIAL_CHECKPOINTS.START_CHECKPOINT.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + TUTORIAL_CHECKPOINTS.END_CHECKPOINT.set_visibility(tutorial_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + MAINSTORY_CHECKPOINTS.START_CHECKPOINT.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + MAINSTORY_CHECKPOINTS.END_CHECKPOINT.set_visibility(mainstory_checkpoints ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); MAINSTORY_NOTE.set_visibility(STORY_SECTION == StorySection::TUTORIAL ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); START_DESCRIPTION.set_text(start_segment_description()); @@ -1063,20 +1047,22 @@ std::string AutoStory::end_checkpoint_description(){ return " End: " + ALL_AUTO_STORY_CHECKPOINT_LIST()[checkpoint_index]->end_text(); } +const Pokemon::StoryRangeOptions& AutoStory::checkpoint_range() const{ + return STORY_SECTION == StorySection::MAIN_STORY ? MAINSTORY_CHECKPOINTS : TUTORIAL_CHECKPOINTS; +} + size_t AutoStory::get_start_checkpoint_index(){ - const bool main_story = STORY_SECTION == StorySection::MAIN_STORY; return story_index( - main_story, - main_story ? START_CHECKPOINT_MAINSTORY.index() : START_CHECKPOINT_TUTORIAL.index(), + STORY_SECTION == StorySection::MAIN_STORY, + checkpoint_range().start_index(), INDEX_OF_LAST_TUTORIAL_CHECKPOINT + 1 ); } size_t AutoStory::get_end_checkpoint_index(){ - const bool main_story = STORY_SECTION == StorySection::MAIN_STORY; return story_index( - main_story, - main_story ? END_CHECKPOINT_MAINSTORY.index() : END_CHECKPOINT_TUTORIAL.index(), + STORY_SECTION == StorySection::MAIN_STORY, + checkpoint_range().end_index(), INDEX_OF_LAST_TUTORIAL_CHECKPOINT + 1 ); } @@ -1216,8 +1202,8 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex } if (ENABLE_ADVANCED_MODE){ - if (get_start_checkpoint_index() > get_end_checkpoint_index()){ - throw UserSetupError(env.logger(), "The start checkpoint cannot be later than the end segment."); + if (!checkpoint_range().check_validity().empty()){ + throw UserSetupError(env.logger(), checkpoint_range().check_validity()); } }else{ @@ -1230,7 +1216,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex require_player(env.console, context, BUTTON_L); if (ENABLE_ADVANCED_MODE){ - env.console.log("Start Checkpoint " + ALL_AUTO_STORY_CHECKPOINT_LIST()[get_start_checkpoint_index()]->name(), COLOR_ORANGE); + env.console.log(Pokemon::checkpoint_start_line(ALL_AUTO_STORY_CHECKPOINT_LIST()[get_start_checkpoint_index()]->name()), COLOR_ORANGE); }else{ env.console.log("Start Segment " + ALL_AUTO_STORY_SEGMENT_LIST()[get_start_segment_index()]->name(), COLOR_ORANGE); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h index d62d9b2ad2..b2ca877499 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h @@ -16,6 +16,7 @@ #include "CommonTools/Options/StringSelectOption.h" #include "CommonTools/Options/LanguageOCROption.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Pokemon/Options/Pokemon_StoryRangeOptions.h" #include "PokemonSV_AutoStoryTools.h" namespace PokemonAutomation{ @@ -69,6 +70,9 @@ class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Liste std::string start_checkpoint_description(); std::string end_checkpoint_description(); + // The checkpoint range of the chosen section. + const Pokemon::StoryRangeOptions& checkpoint_range() const; + private: OCR::LanguageOCROption LANGUAGE; @@ -85,11 +89,11 @@ class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Liste StringSelectOption STARTPOINT_MAINSTORY; StringSelectOption ENDPOINT_MAINSTORY; - StringSelectOption START_CHECKPOINT_TUTORIAL; - StringSelectOption END_CHECKPOINT_TUTORIAL; - - StringSelectOption START_CHECKPOINT_MAINSTORY; - StringSelectOption END_CHECKPOINT_MAINSTORY; + // The shared start/end checkpoint range of each section. Their + // dropdowns are added to this program's options directly, under the + // keys saved settings already use. + Pokemon::StoryRangeOptions TUTORIAL_CHECKPOINTS; + Pokemon::StoryRangeOptions MAINSTORY_CHECKPOINTS; StaticTextOption SETUP_NOTE; StaticTextOption MAINSTORY_NOTE; diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index c2d61152df..759350295e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -1445,7 +1445,7 @@ void checkpoint_reattempt_loop( save_game_from_overworld(env.program_info(), env.console, context); } - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); + env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); context.wait_for_all_requests(); action(i); @@ -1479,7 +1479,7 @@ void checkpoint_reattempt_loop( ); } context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); + env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); @@ -1507,7 +1507,7 @@ void checkpoint_reattempt_loop_tutorial( send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); } - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); + env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); context.wait_for_all_requests(); action(i); @@ -1538,7 +1538,7 @@ void checkpoint_reattempt_loop_tutorial( ); } context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); + env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index e39d8a47da..312533cde7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -7,6 +7,7 @@ #ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H #define PokemonAutomation_PokemonSV_AutoStoryTools_H +#include #include #include "CommonFramework/Language.h" #include "CommonFramework/ImageTools/ImageBoxes.h" @@ -15,6 +16,7 @@ #include "ML/Inference/ML_YOLONavigation.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" namespace PokemonAutomation{ @@ -108,7 +110,7 @@ class AutoStory_Checkpoint { AutoStoryStats& stats) const = 0; std::string checkpoint_text() const { - return "Checkpoint:: " + name() + ". Start point: " + start_text(); + return std::format("{}. Start point: {}", name(), start_text()); } }; From c4962c458e0d10b3b3b7287ca92e679485bf39f9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 23:09:57 -0800 Subject: [PATCH 05/85] BDSP AutoStory: run story steps on the shared story engine BDSP's own StoryExecutor (an action table run by TableExecutor) is gone. The story's actions are now the engine's StoryGame, dispatched by the engine's StoryActionRegistry and StoryStepRunner (story_game(), StoryEngineSteps); the console (ConsoleStory) and the simulation (SimExecutor) bind the same game. Kept as before: the walking steps on StoryWalkSteps, the console actions (moved unchanged into ConsoleStory), each event found by name for a step of any kind, the step guard's log lines and failure screenshot, the interrupts cleared between steps (still TableExecutor's: the engine has neither yet), and the program's run loop (StoryRun's run_segment, start saves). The story row types and make_story_segment() move unchanged into StoryCheckpoint.h; a row's start save names its map in the "saves_in" arg instead of the step's action, so the engine finds the SAVE action by name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Actions/PokemonBDSP_AutoStory_Events.cpp | 4 +- .../Actions/PokemonBDSP_AutoStory_Events.h | 8 +- .../PokemonBDSP_AutoStory_Events_Jubilife.cpp | 6 +- .../PokemonBDSP_AutoStory_Events_Lake.cpp | 8 +- .../AutoStory/PokemonBDSP_AutoStory.cpp | 3 +- .../AutoStory/PokemonBDSP_AutoStory.h | 2 +- ...=> PokemonBDSP_AutoStory_ConsoleStory.cpp} | 133 +++-------- ...h => PokemonBDSP_AutoStory_ConsoleStory.h} | 121 +++------- ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 2 +- ...PokemonBDSP_AutoStory_RouteBench_Tests.cpp | 2 +- ...monBDSP_AutoStory_SimulatedRoute_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryActions.cpp | 220 ++++++++++++++---- .../PokemonBDSP_AutoStory_StoryActions.h | 113 +++++++-- .../PokemonBDSP_AutoStory_StoryCheckpoint.cpp | 86 +++++++ .../PokemonBDSP_AutoStory_StoryCheckpoint.h | 102 ++++++++ .../PokemonBDSP_AutoStory_StoryData.h | 2 +- .../PokemonBDSP_AutoStory_StoryTable.h | 2 +- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 4 +- .../PokemonBDSP_AutoStory_TableRoutes.cpp | 2 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 4 +- ...kemonBDSP_AutoStory_StoryActions_Tests.cpp | 72 ++++-- ...PokemonBDSP_AutoStory_StoryActions_Tests.h | 2 +- .../PokemonBDSP_AutoStory_StorySim.cpp | 8 +- .../PokemonBDSP_AutoStory_StorySim.h | 21 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 2 +- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 8 +- ...emonBDSP_AutoStory_WallBattleSim_Tests.cpp | 2 +- SerialPrograms/cmake/SourceFiles.cmake | 6 +- 30 files changed, 627 insertions(+), 324 deletions(-) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{PokemonBDSP_AutoStory_StoryExecutor.cpp => PokemonBDSP_AutoStory_ConsoleStory.cpp} (72%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{PokemonBDSP_AutoStory_StoryExecutor.h => PokemonBDSP_AutoStory_ConsoleStory.h} (57%) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.cpp index 40fa26813b..ee112c5be7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.cpp @@ -26,8 +26,8 @@ const StoryEvents& story_events(){ } StoryEvent console_event(std::function action){ - return [action = std::move(action)](StoryExecutor& executor, Pokemon::RunState&, const Pokemon::StoryStep&){ - action(executor.stream(), executor.context()); + return [action = std::move(action)](StoryEnv& console, Pokemon::RunState&, const Pokemon::StoryStep&){ + action(console.env.console, console.context); return Pokemon::outcome_ok(); }; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h index a39c9738d9..d8243f3f72 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h @@ -4,14 +4,14 @@ * From: https://github.com/PokemonAutomation/ * * The story's steps that only BDSP has, by name: a step of the table whose - * variant names one of these runs it (StoryExecutor::run()). Some are the + * variant names one of these runs it (story_game()). Some are the * scripted scenes (the Azure Flute, the lake's briefcase, the starter, * Dawn's catching tutorial and the catch); the rest do what the shared * steps cannot, as they ran on the console: the Poke Mart lady's Potions * and the stairs into Jubilife (00.04c, 00.04d), a clown who wanders * (00.05b), the Gym's tries from the Pokemon Center (01.04) and Rock Smash * (01.09). Each fails by throwing, with a screenshot; the executor turns - * that into a failed step. + * that into a failed step (TableExecutor::run()). * * They are in files by area: _Events_Lake (00.00 to 00.04), _Sandgem * (00.04c, 00.04d), _Jubilife (00.05b), _Oreburgh (01.04) and _Route204 @@ -25,7 +25,7 @@ #include #include #include -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -35,7 +35,7 @@ namespace PokemonBDSP{ // Runs a step on the console. Returns where it left the player when it // knows; throws OperationFailedException when it fails. using StoryEvent = std::function; // Map of story event names to their execution functions. using StoryEvents = std::map; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Jubilife.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Jubilife.cpp index 86413db20a..a05d0b5471 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Jubilife.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Jubilife.cpp @@ -55,9 +55,9 @@ void step_along(VideoStream& stream, ProControllerContext& context, int east, co route_turn(stream, context, east > 0 ? Direction::EAST : Direction::WEST); walk_tiles_dpad(stream, context, run_from_wild_battle, {east > 0 ? 1.0 : -1.0, 0}, 1, label); } -Pokemon::Outcome talk_to_wanderer(StoryExecutor& executor, Pokemon::RunState&, const Pokemon::StoryStep& step){ - VideoStream& stream = executor.stream(); - ProControllerContext& context = executor.context(); +Pokemon::Outcome talk_to_wanderer(StoryEnv& console, Pokemon::RunState&, const Pokemon::StoryStep& step){ + VideoStream& stream = console.env.console; + ProControllerContext& context = console.context; const std::string label = "Along the row below " + step.name; // Home, east, west, west, east: each move one tile on the D-pad. const int moves[] = {0, 1, -1, -1, 1}; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp index 0c7841c7fe..e7328cb336 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp @@ -62,11 +62,11 @@ void starter_briefcase(VideoStream& stream, ProControllerContext& context){ // 00.02: the starter from the program's option, in the briefcase: Turtwig // is first, Chimchar a press right, Piplup two; ZL picks, then Up and ZL // answer "this one?" with Yes. -Pokemon::Outcome choose_starter(StoryExecutor& executor, Pokemon::RunState&, const Pokemon::StoryStep&){ - VideoStream& stream = executor.stream(); - ProControllerContext& context = executor.context(); +Pokemon::Outcome choose_starter(StoryEnv& console, Pokemon::RunState&, const Pokemon::StoryStep&){ + VideoStream& stream = console.env.console; + ProControllerContext& context = console.context; size_t rights = 0; - switch (executor.env().starter){ + switch (console.starter){ case StarterChoice::TURTWIG: rights = 0; break; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 9e10c1ac1f..01d7c2eb4e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -25,6 +25,7 @@ #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" +#include "PokemonBDSP_AutoStory_ConsoleStory.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory.h" @@ -247,7 +248,7 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo set_story_language(RUN.language()); StoryEnv story{env, context, STARTER, PLAYER_NAME}; - StoryExecutor executor(story); + ConsoleStory executor(story); executor.set_stop_rows(rows_that_stop(checkpoints)); // A start with a save always loads it first, so the run never walks // from wherever the game was left (console B, 2026-11-11: a run from diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index 154eccade4..70a8182d08 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -19,7 +19,7 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" namespace PokemonAutomation{ namespace NintendoSwitch{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.cpp similarity index 72% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.cpp index 4bfb37b98b..89aea93dc2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.cpp @@ -1,4 +1,4 @@ -/* BDSP AutoStory - Story executor +/* BDSP AutoStory - Console story * * From: https://github.com/PokemonAutomation/ * @@ -6,7 +6,9 @@ #include #include +#include #include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/PrettyPrint.h" @@ -48,7 +50,7 @@ #include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP_AutoStory_Walks.h" #include "Actions/PokemonBDSP_AutoStory_WildBattle.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_ConsoleStory.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -65,23 +67,6 @@ using Pokemon::TilePos; using Pokemon::story_arg; -std::optional story_route_costs(const std::string& action){ - if (action.empty() || action == ROUTE_ONTO_TRIGGER || action == ROUTE_INTO_SCENE || action == "route"){ - return route_plan_costs(); - } - if (action == "town"){ - return town_plan_costs(); - } - if (action == "robust"){ - return RobustPlanCosts(); - } - if (action == "line"){ - return waypoint_plan_costs(); - } - return std::nullopt; -} - - namespace{ // "to_catch_grass" as "to catch grass", for the logs. @@ -138,36 +123,37 @@ void ConsoleStepGuard::on_screen(const StoryStep& step, const Pokemon::ScreenSet // The table and the guard are members, built after the base: it only // keeps references to them until a step runs. -StoryExecutor::StoryExecutor(StoryEnv& env) - : Pokemon::TableExecutor(m_table, m_guard) +ConsoleStory::ConsoleStory(StoryEnv& env) + : Pokemon::TableExecutor(m_no_table, m_guard) , m_env(env) , m_io(env.env.console, env.context) , m_walks(m_io) , m_guard(env.env.console, m_checkpoint) - , m_table(story_action_table(m_walks, console_actions())) + , m_backend(Pokemon::StoryBackendKind::CONSOLE, [&env](std::string_view line){ env.env.console.log(std::string(line)); }, env.context) + , m_steps(m_walks, console_actions(), m_backend) , m_look(env.env.console, env.context) , m_interrupts(story_interrupts([this](bool fresh){ return m_look.look(fresh); }, console_interrupt_actions())) { set_interrupts(&m_interrupts); } -StoryBoundActions StoryExecutor::console_actions(){ - const auto method = [this](Outcome (StoryExecutor::*action)(RunState&, const StoryStep&)){ +StoryBoundActions ConsoleStory::console_actions(){ + const auto method = [this](Outcome (ConsoleStory::*action)(RunState&, const StoryStep&)){ return [this, action](const StoryStep& step, RunState& state){ return (this->*action)(state, step); }; }; return StoryBoundActions{ - .new_game = method(&StoryExecutor::new_game), - .options = method(&StoryExecutor::options), - .answer = method(&StoryExecutor::answer), - .battle = method(&StoryExecutor::battle), - .train = method(&StoryExecutor::train), - .heal = method(&StoryExecutor::heal), - .save = method(&StoryExecutor::save), - .event = [this](const std::string& name) -> Pokemon::StoryActionFunction{ + .new_game = method(&ConsoleStory::new_game), + .options = method(&ConsoleStory::options), + .answer = method(&ConsoleStory::answer), + .battle = method(&ConsoleStory::battle), + .train = method(&ConsoleStory::train), + .heal = method(&ConsoleStory::heal), + .save = method(&ConsoleStory::save), + .event = [this](const std::string& name) -> StoryBoundAction{ return [this, event = story_events().at(name)](const StoryStep& step, RunState& state){ - return event(*this, state, step); + return event(m_env, state, step); }; }, }; @@ -175,7 +161,7 @@ StoryBoundActions StoryExecutor::console_actions(){ // A wild battle is run from, a trainer who saw us fought, a dialog or a // warp's scene pressed through to the quiet overworld. -StoryInterruptActions StoryExecutor::console_interrupt_actions(){ +StoryInterruptActions ConsoleStory::console_interrupt_actions(){ const auto settle = [this](std::string label){ return [this, label](const Pokemon::InterruptVerdict&, RunState&){ m_io.settle(BUTTON_B, label, SettleKind::TALK, ""); @@ -196,24 +182,28 @@ StoryInterruptActions StoryExecutor::console_interrupt_actions(){ }; } -void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ +void ConsoleStory::begin_attempt(const Pokemon::StoryCheckpoint& data){ m_checkpoint = data.id; m_walks.begin_attempt(data.id, data.steps); } +Outcome ConsoleStory::run_action(const StoryStep& step, RunState& state){ + return m_steps.act(step, state); +} + -Outcome StoryExecutor::new_game(RunState&, const StoryStep&){ +Outcome ConsoleStory::new_game(RunState&, const StoryStep&){ play_new_game_intro(m_env.env, context(), m_env.player_name); return Pokemon::outcome_ok(); } -Outcome StoryExecutor::options(RunState&, const StoryStep&){ +Outcome ConsoleStory::options(RunState&, const StoryStep&){ verify_tutorial_settings(stream(), context()); context().wait_for_all_requests(); return Pokemon::outcome_ok(); } -Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ +Outcome ConsoleStory::answer(RunState&, const StoryStep& step){ wait_for_dialogue(stream(), context(), label_of(step)); const bool yes = story_arg(step.args, "yes"); pbf_press_button(context(), yes ? BUTTON_A : BUTTON_B, 80ms, 1000ms); @@ -221,7 +211,7 @@ Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::battle(RunState&, const StoryStep& step){ +Outcome ConsoleStory::battle(RunState&, const StoryStep& step){ // "starter": the Starly battle at the lake (00.02). It opens on its own, // with no talk, and the starter has no Poke Balls to throw; the scene // goes on whoever wins. @@ -246,7 +236,7 @@ Outcome StoryExecutor::battle(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::train(RunState&, const StoryStep& step){ +Outcome ConsoleStory::train(RunState&, const StoryStep& step){ const int64_t battles = story_arg(step.args, "battles"); for (int64_t battle = 0; battle < battles; battle++){ const std::string label = std::format("Training battle {}/{}", battle + 1, battles); @@ -257,7 +247,7 @@ Outcome StoryExecutor::train(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ +Outcome ConsoleStory::heal(RunState&, const StoryStep& step){ // From the planned tile below the door, run in like any door. The lit- // doorway lineup is for when the run in finds no door: people on the // way can leave the route unsure of the column (r59, Jubilife). Below @@ -306,17 +296,19 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::save(RunState&, const StoryStep& step){ - if (step.action.empty()){ +Outcome ConsoleStory::save(RunState&, const StoryStep& step){ + const auto saves_in = step.args.find(SAVES_IN_ARG); + const std::string* map = saves_in == step.args.end() ? nullptr : std::get_if(&saves_in->second); + if (map == nullptr || map->empty()){ save_game(m_env.env, context()); return Pokemon::outcome_ok(); } - // A row's start save, its action the map the card must name. With a - // map, save_game() throws only when the card names another one, having + // A row's start save, its SAVES_IN_ARG the map the card must name. With + // a map, save_game() throws only when the card names another one, having // backed out unsaved. That stops the program: a reset would load an // older save and run this row from wherever that is. try{ - save_game(m_env.env, context(), step.action); + save_game(m_env.env, context(), *map); }catch (OperationFailedException& e){ throw FatalProgramException( ErrorReportMode::NO_ERROR_REPORT, @@ -327,56 +319,7 @@ Outcome StoryExecutor::save(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::game(RunState&, const StoryStep& step){ - return Pokemon::outcome_failed("unknown_event", step.action); -} - -Pokemon::Segment make_story_segment( - const std::vector& rows, Pokemon::StoryStepExecutor& executor, - std::set& saved -){ - static const StoryStep SAVE_AT_START = []{ - StoryStep step; - step.kind = Pokemon::StoryStepKind::SAVE; - step.name = "save"; - step.why = "the save a failed step resets to"; - return step; - }(); - Pokemon::Segment segment; - segment.id = "BDSP"; - for (const StoryCheckpoint& row : rows){ - segment.checkpoints.push_back(Pokemon::CheckpointSpec{ - .id = row.id, .title = row.title, .saves = false, - .build = [&row, &executor, &saved]{ - Pokemon::Checkpoint steps = Pokemon::build_story_checkpoint(row, executor); - if (row.on_failure != StoryFailure::RELOAD_AND_RETRY){ - return steps; - } - StoryStep save_at_start = SAVE_AT_START; - save_at_start.action = row.saves_in; - Pokemon::Event save = Pokemon::story_event(save_at_start, executor); - save.skip_if.push_back(Pokemon::condition("saved at the start", [&saved, id = row.id](RunState&){ - return saved.contains(id); - })); - // A save that fails is a failed first attempt: the retry - // resets and does not save again. - save.act = [&executor, &saved, id = row.id, save_at_start](RunState& state){ - saved.insert(id); - return executor.run(save_at_start, state); - }; - Pokemon::Checkpoint checkpoint; - checkpoint.id = row.id; - checkpoint.events.push_back(std::move(save)); - for (Pokemon::Event& event : steps.events){ - checkpoint.events.push_back(std::move(event)); - } - return checkpoint; - }, - }); - } - return segment; -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.h similarity index 57% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.h index 419d93af74..941caef321 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.h @@ -1,19 +1,17 @@ -/* BDSP AutoStory - Story executor - * -// code-health: allow header_symbols -- BDSP story executor and checkpoint execution primitives +/* BDSP AutoStory - Console story * * From: https://github.com/PokemonAutomation/ * - * BDSP's way of doing the shared story steps - * (Pokemon/AutoStory/Pokemon_StorySteps.h) on the console. A route is - * planned on the joined maps that hold its start and its target - * (story_plan_world()), from the tiles the run's pose holds, and walked by - * the walker, which fights the trainers who see us and runs from wild - * battles. A step whose variant names one of the story's events - * (story_events(), PokemonBDSP_AutoStory_Events.h) runs that event, - * whatever its kind: the scripted scenes and the console-measured walks - * of segment 01. It is the console's binding of the story's action table - * (story_action_table()); the simulation binds the same table. + * BDSP's story steps on the console: the story's actions (story_game(), + * PokemonBDSP_AutoStory_StoryActions.h) bound to the console and run by the + * shared story engine's step runner. A route is planned on the joined maps + * that hold its start and its target (story_plan_world()), from the tiles + * the run's pose holds, and walked by the walker, which fights the + * trainers who see us and runs from wild battles. A step whose variant + * names one of the story's events (story_events(), + * PokemonBDSP_AutoStory_Events.h) runs that event, whatever its kind: the + * scripted scenes and the console-measured walks of segment 01. The + * simulation binds the same actions. * * Every step runs inside a guard (ConsoleStepGuard) that turns a failed * console step into a failed Outcome, with a screenshot and the @@ -24,28 +22,20 @@ * */ -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryExecutor_H -#define PokemonAutomation_PokemonBDSP_AutoStory_StoryExecutor_H +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_ConsoleStory_H +#define PokemonAutomation_PokemonBDSP_AutoStory_ConsoleStory_H #include -#include #include #include -#include #include -#include #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" #include "Pokemon/AutoStory/Pokemon_StoryActions.h" -#include "Pokemon/AutoStory/Pokemon_StorySegments.h" -#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" -#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP_AutoStory_StoryActions.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryInterrupts.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -55,58 +45,6 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ -// Starter Pokemon options for BDSP story automation. -enum class StarterChoice{ - TURTWIG, - CHIMCHAR, - PIPLUP, -}; - -// What a row does when one of its steps fails. -enum class StoryFailure{ - // Save before the first step; on a failure reset to that save and run - // the row again from its first step. - RELOAD_AND_RETRY, - // No save and no retry: the failure ends the program (00.00, before - // the game has anything worth saving). - STOP, -}; - -// A row of the story table: the shared checkpoint, and what a failure does. -struct StoryCheckpoint : public Pokemon::StoryCheckpoint{ - StoryFailure on_failure = StoryFailure::RELOAD_AND_RETRY; - // The map the save screen's card names where the row starts ("Route - // 203"). The save at its start is refused anywhere else and the program - // stops: r76/r77 started 01.06 a walk away from its start and saved over - // the good save there. Empty for a row that does not save first. - std::string saves_in; -}; - -// What the story's steps act on. -struct StoryEnv{ - SingleSwitchProgramEnvironment& env; - ProControllerContext& context; - StarterChoice starter = StarterChoice::CHIMCHAR; - std::string player_name; -}; - - -// The variant of a ROUTE step whose target is the next scene's trigger: -// the scene starts there and stops the walk, as a wall would (00.04's -// Mom's call on (6, 9)). It plans with the route costs. -inline constexpr std::string_view ROUTE_ONTO_TRIGGER = "trigger"; - -// The variant of a ROUTE step that, once at its target, runs its one leg -// ("legs") until a scene's dialogue starts. It plans with the route costs. -inline constexpr std::string_view ROUTE_INTO_SCENE = "into_scene"; - -// The plan costs a ROUTE step's variant names: "", ROUTE_ONTO_TRIGGER and -// ROUTE_INTO_SCENE the route costs, "town" town_plan_costs(), "robust" the planner's -// defaults, "line" waypoint_plan_costs() (a stretch of a line a human -// walked). Nothing for another name. -std::optional story_route_costs(const std::string& variant); - - // What the console does around each story step: the step's log line, and // a failed step's "checkpoint_reattempt_loop" line and screenshot. class ConsoleStepGuard : public Pokemon::StepGuard{ @@ -135,11 +73,12 @@ class ConsoleStepGuard : public Pokemon::StepGuard{ }; -// Does BDSP's kinds of story step on the console: the story's action -// table, its rows that need the console bound to the methods below. -class StoryExecutor : public Pokemon::TableExecutor{ +// Does BDSP's kinds of story step on the console: the story's actions on +// the engine (StoryEngineSteps), those that need the console bound to the +// methods below. +class ConsoleStory : public Pokemon::TableExecutor{ public: - explicit StoryExecutor(StoryEnv& env); + explicit ConsoleStory(StoryEnv& env); StoryEnv& env(){ return m_env; @@ -178,9 +117,10 @@ class StoryExecutor : public Pokemon::TableExecutor{ // In front of a Pokemon Center, its lit doorway on screen: in, the // nurse, and out (heal_at_pokemon_center()). Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step); + // The game; a row's start save (SAVES_IN_ARG) only where the card names its map. Pokemon::Outcome save(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // The event its variant names (story_events()). - Pokemon::Outcome game(Pokemon::RunState& state, const Pokemon::StoryStep& step); + // The engine's action for the step. + virtual Pokemon::Outcome run_action(const Pokemon::StoryStep& step, Pokemon::RunState& state) override; private: StoryBoundActions console_actions(); @@ -209,25 +149,18 @@ class StoryExecutor : public Pokemon::TableExecutor{ // variant "a": A through it, for lines that give an item. StoryWalkSteps m_walks; std::string m_checkpoint; - std::map m_run_counts; ConsoleStepGuard m_guard; - // The story's actions, its console rows bound to this executor. - Pokemon::StoryActionTable m_table; + // TableExecutor's table: empty, as run_action() runs the engine's actions. + Pokemon::StoryActionTable m_no_table; + StoryLogBackend m_backend; + // The story's actions, those that need the console bound to this. + StoryEngineSteps m_steps; // What is cleared between steps, looked for on the screen. ConsoleScreenLook m_look; Pokemon::StoryInterrupts m_interrupts; }; -// `rows` (kept alive by the caller) as one segment. A row that reloads on -// failure saves first, unless `saved` says it has in this run: a retry -// starts from that save. `executor` and `saved` must outlive the segment. -Pokemon::Segment make_story_segment( - const std::vector& rows, Pokemon::StoryStepExecutor& executor, - std::set& saved -); - - } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp index d5f507d724..9d97d4bfef 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -30,7 +30,7 @@ #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "Utils/PokemonBDSP_AutoStory_StoryLanguage.h" #include "Utils/PokemonBDSP_AutoStory_RouteTiming.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp index 0c9fa562f8..7a9b7a8d50 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp @@ -29,7 +29,7 @@ #include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Utils/PokemonBDSP_AutoStory_RouteChoice.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_TableRoutes.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.cpp index e85849305c..c6256ae164 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.cpp @@ -30,7 +30,7 @@ #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_SimulatedRoute_Tests.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp index 9eb9ef9fde..6e8da5bcb9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp @@ -4,8 +4,16 @@ * */ +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryGame.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryStepRunner.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryData.h" #include "PokemonBDSP_AutoStory_StoryActions.h" @@ -13,77 +21,197 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +using Pokemon::GridPose; using Pokemon::Outcome; using Pokemon::RunState; -using Pokemon::StoryAction; using Pokemon::StoryStep; using Pokemon::StoryStepKind; +using GameAction = Pokemon::StoryAction; + namespace{ -// Adds `action` for `kind`'s default and for each of its named actions in -// bdsp_story_actions(), each with that spec's args, so lint_story_checkpoint() -// checks a step's args against the action it names. -void add_with_specs(Pokemon::StoryActionTable& table, StoryStepKind kind, const StoryAction& action){ +// `act` as the engine's handler: it runs the step the engine runs, with +// the step's own args. +Pokemon::StoryActionHandler handler_of(StoryBoundAction act){ + return [act = std::move(act)](Pokemon::StoryBackend&, const Pokemon::StoryActionCall& call, RunState& state){ + return act(call.step, state); + }; +} + +// What a step of a kind BDSP has no action for does. +Outcome unsupported(Pokemon::StoryBackend&, const Pokemon::StoryActionCall& call, RunState&){ + return Pokemon::unsupported_step(call.step); +} + +// The variants a kind's action reads that have no spec of their own: they +// take the kind's default's args. +const std::map>& variants_without_spec(){ + static const std::map> variants{ + {StoryStepKind::LEGS, {"measured"}}, + {StoryStepKind::STEP, {"tap"}}, + }; + return variants; +} + +// Adds `act` for `kind`: first as the kind's default, `name`, which is the +// built-in action's name where there is one, so it takes the built-in's +// place (the engine's default is a kind's first action), with the args of +// the kind's first spec in bdsp_story_actions(); then for each of the +// kind's other specs and variants. A name that is also a story event stays +// the event's. +void add_kind(std::vector& actions, StoryStepKind kind, std::string name, const StoryBoundAction& act){ const std::span specs = bdsp_story_actions(); - StoryAction fallback = action; + Pokemon::StoryActionSpec first{.kind = kind, .name = std::move(name), .args = {}}; if (const Pokemon::StoryActionSpec* spec = Pokemon::find_story_action(specs, kind, "")){ - fallback.args = spec->args; + first.args = spec->args; } - table.add(kind, "", std::move(fallback)); + actions.push_back({.spec = first, .handler = handler_of(act)}); for (const Pokemon::StoryActionSpec& spec : specs){ - // A name that is also a story event stays the event's. - if (spec.kind != kind || spec.name.empty() || story_events().contains(spec.name)){ + if (spec.kind != kind || spec.name.empty() || spec.name == first.name || story_events().contains(spec.name)){ continue; } - StoryAction named = action; - named.args = spec.args; - table.add(kind, spec.name, std::move(named)); + actions.push_back({.spec = spec, .handler = handler_of(act)}); + } + const auto variants = variants_without_spec().find(kind); + if (variants == variants_without_spec().end()){ + return; + } + for (const std::string& variant : variants->second){ + actions.push_back({.spec = {.kind = kind, .name = variant, .args = first.args}, .handler = handler_of(act)}); } } -} // namespace +// Each story event, for a step of any kind, with its spec's args if it has any. +void add_events(std::vector& actions, const StoryBoundActions& bound){ + for (const auto& item : story_events()){ + std::vector args; + for (const Pokemon::StoryActionSpec& spec : bdsp_story_actions()){ + if (spec.name == item.first && !spec.args.empty()){ + args = spec.args; + break; + } + } + const Pokemon::StoryActionHandler event = handler_of(bound.event(item.first)); + for (int kind = 0; kind <= (int)StoryStepKind::GAME; kind++){ + actions.push_back({.spec = {.kind = (StoryStepKind)kind, .name = item.first, .args = args}, .handler = event}); + } + } +} +// BDSP's story actions as the engine's game: the walking steps on +// `walks`, the rest `bound`'s. +Pokemon::StoryGame story_game(StoryWalkSteps& walks, const StoryBoundActions& bound){ + Pokemon::StoryGame game; + game.id = "bdsp"; + std::vector& actions = game.actions; + // A GAME step names its event: an unnamed one finds this. + actions.push_back({.spec = {.kind = StoryStepKind::GAME, .name = "", .args = {}}, .handler = &unsupported}); -Pokemon::StoryActionTable story_action_table(StoryWalkSteps& walks, const StoryBoundActions& bound){ - Pokemon::StoryActionTable table; using WalkMethod = Outcome (StoryWalkSteps::*)(RunState&, const StoryStep&); - const auto walk = [&](StoryStepKind kind, WalkMethod method){ - add_with_specs(table, kind, StoryAction{ - .act = [&walks, method](const StoryStep& step, RunState& state){ - return (walks.*method)(state, step); - }, + const auto walk = [&](StoryStepKind kind, std::string name, WalkMethod method){ + add_kind(actions, kind, std::move(name), [&walks, method](const StoryStep& step, RunState& state){ + return (walks.*method)(state, step); }); }; - walk(StoryStepKind::ROUTE, &StoryWalkSteps::route); - walk(StoryStepKind::LEGS, &StoryWalkSteps::legs); - walk(StoryStepKind::STEP, &StoryWalkSteps::step); - walk(StoryStepKind::TALK, &StoryWalkSteps::talk); - walk(StoryStepKind::MASH, &StoryWalkSteps::mash); - - const auto console = [&](StoryStepKind kind, const Pokemon::StoryActionFunction& act){ - add_with_specs(table, kind, StoryAction{.act = act, .needs_console = true}); - }; - console(StoryStepKind::NEW_GAME, bound.new_game); - console(StoryStepKind::OPTIONS, bound.options); - console(StoryStepKind::ANSWER, bound.answer); - console(StoryStepKind::BATTLE, bound.battle); - console(StoryStepKind::TRAIN, bound.train); - console(StoryStepKind::HEAL, bound.heal); - console(StoryStepKind::SAVE, bound.save); + walk(StoryStepKind::ROUTE, "route", &StoryWalkSteps::route); + walk(StoryStepKind::LEGS, "legs", &StoryWalkSteps::legs); + walk(StoryStepKind::STEP, "face", &StoryWalkSteps::step); + walk(StoryStepKind::TALK, "talk", &StoryWalkSteps::talk); + walk(StoryStepKind::MASH, "mash", &StoryWalkSteps::mash); - for (const auto& item : story_events()){ - StoryAction event{.act = bound.event(item.first), .needs_console = true}; - for (const Pokemon::StoryActionSpec& spec : bdsp_story_actions()){ - if (spec.name == item.first && !spec.args.empty()){ - event.args = spec.args; - break; - } + add_kind(actions, StoryStepKind::NEW_GAME, "new_game", bound.new_game); + add_kind(actions, StoryStepKind::OPTIONS, "options", bound.options); + add_kind(actions, StoryStepKind::ANSWER, "answer", bound.answer); + add_kind(actions, StoryStepKind::BATTLE, "fight", bound.battle); + add_kind(actions, StoryStepKind::TRAIN, "train", bound.train); + add_kind(actions, StoryStepKind::HEAL, "heal", bound.heal); + add_kind(actions, StoryStepKind::SAVE, "save", bound.save); + // A row's start save names the map its card must show (make_story_segment()). + actions.back().spec.args.push_back(Pokemon::StoryArgSpec{ + .key = std::string(SAVES_IN_ARG), .type = Pokemon::StoryArgType::WORD, .required = false, + .fallback = std::nullopt, .why = "the map the save card must name; none saves anywhere", + }); + + // No SHOP or READY of BDSP's own: the built-in ones would need the game's. + for (const Pokemon::StoryActionSpec& spec : Pokemon::builtin_story_actions()){ + if (spec.kind == StoryStepKind::SHOP || spec.kind == StoryStepKind::READY){ + actions.push_back({.spec = spec, .handler = &unsupported}); } - table.add_any_kind(item.first, std::move(event)); } - return table; + add_events(actions, bound); + return game; +} + +// Why the backend's inputs throw. +inline constexpr std::string_view NO_BACKEND_INPUT = "BDSP's story actions play through StoryStepIO, not the backend's inputs."; + +} // namespace + + +StoryLogBackend::StoryLogBackend(Pokemon::StoryBackendKind kind, std::function log, CancellableScope& scope) + : m_kind(kind) + , m_log(std::move(log)) + , m_scope(scope) +{} + +void StoryLogBackend::press(Button, Milliseconds, Milliseconds){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string(NO_BACKEND_INPUT)); +} +void StoryLogBackend::tap(Pokemon::Direction){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string(NO_BACKEND_INPUT)); +} +void StoryLogBackend::hold(Pokemon::Direction, Milliseconds, Pokemon::StoryPace){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string(NO_BACKEND_INPUT)); +} +void StoryLogBackend::stick(double, Milliseconds, Milliseconds, Pokemon::StoryPace){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string(NO_BACKEND_INPUT)); +} +void StoryLogBackend::wait(Milliseconds){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string(NO_BACKEND_INPUT)); +} + +Pokemon::Observation StoryLogBackend::observe(){ + return {}; +} + +Outcome StoryLogBackend::battle(const Pokemon::StoryActionArgs&){ + return Pokemon::outcome_failed("unsupported_step", "BDSP fights in its BATTLE action"); +} + +void StoryLogBackend::log(std::string_view line){ + if (m_log){ + m_log(line); + } +} + + +// The game first: the registry and the runner keep references to it. +struct StoryEngineSteps::Engine{ + Engine(StoryWalkSteps& walks, const StoryBoundActions& bound, Pokemon::StoryBackend& backend) + : game(story_game(walks, bound)) + , registry(game) + , runner(registry, backend) + {} + + Pokemon::StoryGame game; + Pokemon::StoryActionRegistry registry; + Pokemon::StoryStepRunner runner; +}; + +StoryEngineSteps::StoryEngineSteps(StoryWalkSteps& walks, const StoryBoundActions& bound, Pokemon::StoryBackend& backend) + : m_engine(std::make_unique(walks, bound, backend)) +{} + +StoryEngineSteps::~StoryEngineSteps() = default; + +Outcome StoryEngineSteps::act(const StoryStep& step, RunState& state){ + return m_engine->runner.act(step, state); +} + +std::vector StoryEngineSteps::check(const StoryStep& step) const{ + return m_engine->registry.check(step); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h index 6204f74751..8c7616c357 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h @@ -2,16 +2,28 @@ * * From: https://github.com/PokemonAutomation/ * - * BDSP's story steps as one action table (Pokemon_StoryActions.h), which - * the console (StoryExecutor) and the simulation (SimExecutor) each bind. - * The walking steps (ROUTE, LEGS, STEP, TALK, MASH) are the same code on - * both: StoryWalkSteps on the binding's StoryStepIO. The steps that need - * the console (the intro, the options, answers, battles, training, the - * Center, saves, and the story's events, story_events()) are the - * binding's own: played on the console, stood in for on the simulation. + * BDSP's story steps as the actions of the shared story engine + * (Pokemon/AutoStory/Engine/): one StoryGame, run by the engine's step + * runner (StoryEngineSteps), which the console (ConsoleStory) and the + * simulation (SimExecutor) each bind. The walking steps (ROUTE, LEGS, + * STEP, TALK, MASH) are the same code on both: StoryWalkSteps on the + * binding's StoryStepIO. The steps that need the console (the intro, the + * options, answers, battles, training, the Center, saves, and the story's + * events, story_events()) are the binding's own: played on the console, + * stood in for on the simulation. * - * A GAME step runs only the event its variant names, and BDSP has no SHOP - * or READY step: lint_story_checkpoint() reports a step with neither. + * An action is found by its step's kind and name, as the engine finds it; + * a story event's name finds its event for a step of any kind. A GAME + * step runs only the event its variant names, and BDSP has no SHOP or + * READY step: the engine's built-in ones fail as unsupported_step(). + * + * BDSP's actions drive the game through StoryStepIO, not through the + * engine backend's inputs yet: StoryLogBackend gives the runner the log, + * the scope and what it plays on. The engine has no step guard and no + * look between steps yet: the bindings run each step inside + * TableExecutor's (Pokemon_StoryActions.h), whose run_action() is + * StoryEngineSteps::act(). This header leaves out the engine's StoryGame, + * whose StoryAction would clash with that header's. * */ @@ -19,8 +31,13 @@ #define PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_H #include +#include #include -#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "Pokemon/AutoStory/Engine/Pokemon_StoryBackend.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" namespace PokemonAutomation{ @@ -28,23 +45,77 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// Does `step`, from the run so far. +using StoryBoundAction = std::function; + // The actions a binding does its own way, one per kind that needs the // console. struct StoryBoundActions{ - Pokemon::StoryActionFunction new_game = {}; - Pokemon::StoryActionFunction options = {}; - Pokemon::StoryActionFunction answer = {}; - Pokemon::StoryActionFunction battle = {}; - Pokemon::StoryActionFunction train = {}; - Pokemon::StoryActionFunction heal = {}; - Pokemon::StoryActionFunction save = {}; + StoryBoundAction new_game = {}; + StoryBoundAction options = {}; + StoryBoundAction answer = {}; + StoryBoundAction battle = {}; + StoryBoundAction train = {}; + StoryBoundAction heal = {}; + StoryBoundAction save = {}; // The action for the story event named `name` (story_events()). - std::function event = {}; + std::function event = {}; +}; + + +// The engine's backend for BDSP: the log, the scope and the kind. Its +// inputs throw InternalProgramError and observe() sees nothing: BDSP's +// actions play through StoryStepIO. +// code-health: allow public_methods -- these are the engine's StoryBackend overrides, which the engine fixes; none can move out +class StoryLogBackend : public Pokemon::StoryBackend{ +public: + // `scope` must outlive the backend. + StoryLogBackend(Pokemon::StoryBackendKind kind, std::function log, CancellableScope& scope); + + virtual Pokemon::StoryBackendKind kind() const override{ + return m_kind; + } + virtual void press(Button button, Milliseconds hold, Milliseconds release) override; + virtual void tap(Pokemon::Direction direction) override; + virtual void hold(Pokemon::Direction direction, Milliseconds duration, Pokemon::StoryPace pace) override; + virtual void stick(double degrees, Milliseconds duration, Milliseconds release, Pokemon::StoryPace pace) override; + virtual void wait(Milliseconds duration) override; + virtual Pokemon::Observation observe() override; + virtual Pokemon::Outcome battle(const Pokemon::StoryActionArgs& args) override; + virtual void log(std::string_view line) override; + virtual CancellableScope& scope() override{ + return m_scope; + } + +private: + Pokemon::StoryBackendKind m_kind; + std::function m_log; + CancellableScope& m_scope; }; -// BDSP's story actions: the walking steps on `walks`, the rest `bound`'s. -// `walks` must outlive the table. -Pokemon::StoryActionTable story_action_table(StoryWalkSteps& walks, const StoryBoundActions& bound); + +// BDSP's story actions on the engine: the walking steps on `walks`, the +// rest `bound`'s, run by the engine's step runner on `backend`. `walks` +// and `backend` must outlive it. +class StoryEngineSteps{ +public: + StoryEngineSteps(StoryWalkSteps& walks, const StoryBoundActions& bound, Pokemon::StoryBackend& backend); + ~StoryEngineSteps(); + StoryEngineSteps(const StoryEngineSteps&) = delete; + StoryEngineSteps& operator=(const StoryEngineSteps&) = delete; + + // `step`'s action (StoryStepRunner::act()): unsupported_step() for a + // step with none. + Pokemon::Outcome act(const Pokemon::StoryStep& step, Pokemon::RunState& state); + + // What is wrong with `step` before it runs (StoryActionRegistry::check()): + // no action for it, or args that don't fit its action's. + std::vector check(const Pokemon::StoryStep& step) const; + +private: + struct Engine; + std::unique_ptr m_engine; +}; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.cpp new file mode 100644 index 0000000000..ca80cf782f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.cpp @@ -0,0 +1,86 @@ +/* BDSP AutoStory - Story checkpoint + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::RunState; +using Pokemon::StoryStep; + + +std::optional story_route_costs(const std::string& action){ + if (action.empty() || action == ROUTE_ONTO_TRIGGER || action == ROUTE_INTO_SCENE || action == "route"){ + return route_plan_costs(); + } + if (action == "town"){ + return town_plan_costs(); + } + if (action == "robust"){ + return RobustPlanCosts(); + } + if (action == "line"){ + return waypoint_plan_costs(); + } + return std::nullopt; +} + + +Pokemon::Segment make_story_segment( + const std::vector& rows, Pokemon::StoryStepExecutor& executor, + std::set& saved +){ + static const StoryStep SAVE_AT_START = []{ + StoryStep step; + step.kind = Pokemon::StoryStepKind::SAVE; + step.name = "save"; + step.why = "the save a failed step resets to"; + return step; + }(); + Pokemon::Segment segment; + segment.id = "BDSP"; + for (const StoryCheckpoint& row : rows){ + segment.checkpoints.push_back(Pokemon::CheckpointSpec{ + .id = row.id, .title = row.title, .saves = false, + .build = [&row, &executor, &saved]{ + Pokemon::Checkpoint steps = Pokemon::build_story_checkpoint(row, executor); + if (row.on_failure != StoryFailure::RELOAD_AND_RETRY){ + return steps; + } + StoryStep save_at_start = SAVE_AT_START; + save_at_start.args.emplace(SAVES_IN_ARG, row.saves_in); + Pokemon::Event save = Pokemon::story_event(save_at_start, executor); + save.skip_if.push_back(Pokemon::condition("saved at the start", [&saved, id = row.id](RunState&){ + return saved.contains(id); + })); + // A save that fails is a failed first attempt: the retry + // resets and does not save again. + save.act = [&executor, &saved, id = row.id, save_at_start](RunState& state){ + saved.insert(id); + return executor.run(save_at_start, state); + }; + Pokemon::Checkpoint checkpoint; + checkpoint.id = row.id; + checkpoint.events.push_back(std::move(save)); + for (Pokemon::Event& event : steps.events){ + checkpoint.events.push_back(std::move(event)); + } + return checkpoint; + }, + }); + } + return segment; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h new file mode 100644 index 0000000000..e6cdd9f387 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h @@ -0,0 +1,102 @@ +/* BDSP AutoStory - Story checkpoint + * +// code-health: allow header_symbols -- the story table's row type, the run's options and the segment its rows make + * + * From: https://github.com/PokemonAutomation/ + * + * A row of BDSP's story table, what the run plays with (the starter, the + * player's name), the plan costs a ROUTE step's variant names, and the + * segment the rows make for the shared runner (Pokemon_StorySegments.h). + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryCheckpoint_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryCheckpoint_H + +#include +#include +#include +#include +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Starter Pokemon options for BDSP story automation. +enum class StarterChoice{ + TURTWIG, + CHIMCHAR, + PIPLUP, +}; + +// What a row does when one of its steps fails. +enum class StoryFailure{ + // Save before the first step; on a failure reset to that save and run + // the row again from its first step. + RELOAD_AND_RETRY, + // No save and no retry: the failure ends the program (00.00, before + // the game has anything worth saving). + STOP, +}; + +// A row of the story table: the shared checkpoint, and what a failure does. +struct StoryCheckpoint : public Pokemon::StoryCheckpoint{ + StoryFailure on_failure = StoryFailure::RELOAD_AND_RETRY; + // The map the save screen's card names where the row starts ("Route + // 203"). The save at its start is refused anywhere else and the program + // stops: r76/r77 started 01.06 a walk away from its start and saved over + // the good save there. Empty for a row that does not save first. + std::string saves_in; +}; + +// What the story's steps act on. +struct StoryEnv{ + SingleSwitchProgramEnvironment& env; + ProControllerContext& context; + StarterChoice starter = StarterChoice::CHIMCHAR; + std::string player_name; +}; + + +// The variant of a ROUTE step whose target is the next scene's trigger: +// the scene starts there and stops the walk, as a wall would (00.04's +// Mom's call on (6, 9)). It plans with the route costs. +inline constexpr std::string_view ROUTE_ONTO_TRIGGER = "trigger"; + +// The variant of a ROUTE step that, once at its target, runs its one leg +// ("legs") until a scene's dialogue starts. It plans with the route costs. +inline constexpr std::string_view ROUTE_INTO_SCENE = "into_scene"; + +// The plan costs a ROUTE step's variant names: "", ROUTE_ONTO_TRIGGER and +// ROUTE_INTO_SCENE the route costs, "town" town_plan_costs(), "robust" the planner's +// defaults, "line" waypoint_plan_costs() (a stretch of a line a human +// walked). Nothing for another name. +std::optional story_route_costs(const std::string& variant); + + +// The arg of a row's start save (a SAVE step) that names the map its card +// must show: the row's saves_in. +inline constexpr std::string_view SAVES_IN_ARG = "saves_in"; + +// `rows` (kept alive by the caller) as one segment. A row that reloads on +// failure saves first, unless `saved` says it has in this run: a retry +// starts from that save. `executor` and `saved` must outlive the segment. +Pokemon::Segment make_story_segment( + const std::vector& rows, Pokemon::StoryStepExecutor& executor, + std::set& saved +); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h index 052cd044d8..19012099db 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h @@ -14,7 +14,7 @@ #include #include "Common/Cpp/Json/JsonValue.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryActionSpec.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" namespace PokemonAutomation{ namespace NintendoSwitch{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 72504da1b8..39bfeffd90 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -16,7 +16,7 @@ #include #include -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" namespace PokemonAutomation{ namespace NintendoSwitch{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index a48158f2ca..33ee03e9f7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -29,7 +29,7 @@ #include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" #include "Data/PokemonBDSP_AutoStory_WalkRules.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_TableRoutes.h" #include "PokemonBDSP_AutoStory_StoryTable.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index cd37db912c..8472b10b0c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -24,7 +24,7 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkDpad.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 344e2b80c1..9f52467e64 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -3,7 +3,7 @@ * From: https://github.com/PokemonAutomation/ * * The story steps that walk and talk (ROUTE, LEGS, STEP, TALK, MASH), on a - * StoryStepIO: StoryExecutor runs them on the console, the story's + * StoryStepIO: ConsoleStory runs them on the console, the story's * simulation tests on a simulated player. * */ @@ -93,7 +93,7 @@ class StoryWalkSteps{ // With a leg, then runs on toward its direction until a dialogue starts, // for its tiles at most (run_to_dialogue()). Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // See StoryExecutor::legs(). + // See ConsoleStory's LEGS. Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step); // One D-pad step, or a run through a door when the step changes map. Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp index 9f55f5a6c2..c6ae3d160a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp @@ -8,7 +8,7 @@ #include #include "Data/PokemonBDSP_AutoStory_RobustRoute.h" #include "Data/PokemonBDSP_AutoStory_WallRecovery.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "Utils/PokemonBDSP_AutoStory_RouteChoice.h" #include "PokemonBDSP_AutoStory_StoryTable.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 0185a04e74..48ed98935e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -30,7 +30,7 @@ #include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP_AutoStory_OldStorySteps.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" @@ -311,7 +311,7 @@ std::optional pose_after_step(const std::optional& at, const StorySt } // Every ROUTE step of the table that starts from a known pose, from its -// first and its last tile, at the pace StoryExecutor walks it. +// first and its last tile, at the pace ConsoleStory walks it. std::vector table_routes(){ std::vector routes; for (const StoryCheckpoint& row : story_checkpoints()){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp index 9b795d8b73..95bc677c9a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp @@ -10,9 +10,9 @@ #include #include #include +#include "Common/Cpp/CancellableScope.h" #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" -#include "Pokemon/AutoStory/Pokemon_StoryActions.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" @@ -44,7 +44,7 @@ std::vector> story_steps(){ StoryStep save; save.kind = StoryStepKind::SAVE; save.name = "save"; - save.action = row.saves_in; + save.args.emplace(SAVES_IN_ARG, row.saves_in); out.emplace_back(row.id, std::move(save)); } return out; @@ -65,7 +65,7 @@ std::string old_dispatch(const StoryStep& step){ case StoryStepKind::STEP: case StoryStepKind::TALK: case StoryStepKind::MASH: - return "walk " + kind; + return std::format("walk {}", kind); case StoryStepKind::NEW_GAME: case StoryStepKind::OPTIONS: case StoryStepKind::ANSWER: @@ -75,7 +75,7 @@ std::string old_dispatch(const StoryStep& step){ case StoryStepKind::SAVE: return "console " + kind; default: - return "executor " + kind; + return std::format("executor {}", kind); } } @@ -94,7 +94,7 @@ StoryBoundActions naming_actions(){ .train = named(StoryStepKind::TRAIN), .heal = named(StoryStepKind::HEAL), .save = named(StoryStepKind::SAVE), - .event = [](const std::string& name) -> Pokemon::StoryActionFunction{ + .event = [](const std::string& name) -> StoryBoundAction{ return [name](const StoryStep&, RunState&){ return Pokemon::outcome_failed("event", name); }; @@ -102,19 +102,40 @@ StoryBoundActions naming_actions(){ }; } -// What `table` runs for `step`, in old_dispatch()'s words. A walking row +// Whether `step` runs one of the binding's own actions, which need the +// console: an event, or a kind StoryWalkSteps does not do. +bool needs_console(const StoryStep& step){ + if (story_events().contains(step.action)){ + return true; + } + switch (step.kind){ + case StoryStepKind::ROUTE: + case StoryStepKind::LEGS: + case StoryStepKind::STEP: + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return false; + default: + return true; + } +} + +// What `steps` runs for `step`, in old_dispatch()'s words. A walking step // is not run: it would walk. -std::string table_dispatch(const Pokemon::StoryActionTable& table, const StoryStep& step){ - const Pokemon::StoryAction* action = table.find(step); - if (action == nullptr){ - return std::string("executor ") + Pokemon::story_step_kind_name(step.kind); +std::string engine_dispatch(StoryEngineSteps& steps, const StoryStep& step){ + const std::string kind = Pokemon::story_step_kind_name(step.kind); + if (!steps.check(step).empty()){ + return std::format("executor {}", kind); } - if (!action->needs_console){ - return std::string("walk ") + Pokemon::story_step_kind_name(step.kind); + if (!needs_console(step)){ + return std::format("walk {}", kind); } RunState state; - const Pokemon::Outcome outcome = action->act(step, state); - return outcome.failure + " " + outcome.detail; + const Pokemon::Outcome outcome = steps.act(step, state); + if (outcome.failure == "unsupported_step"){ + return std::format("executor {}", kind); + } + return std::format("{} {}", outcome.failure, outcome.detail); } @@ -122,9 +143,15 @@ UnitTestResult test_every_step_has_an_action(Logger& logger){ SimExecutor sim(logger); size_t steps = 0; for (const StoryCheckpoint& row : story_checkpoints()){ - const std::vector unbound = Pokemon::lint_story_checkpoint(row, sim.actions()); - if (!unbound.empty()){ - return unbound.front(); + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + const std::vector problems = sim.steps().check(step); + if (!problems.empty()){ + return std::format( + "{} step {} {}: {} for {} '{}'", + row.id, c + 1, step.name, problems.front(), Pokemon::story_step_kind_name(step.kind), step.action + ); + } } steps += row.steps.size(); } @@ -140,7 +167,9 @@ UnitTestResult test_table_runs_what_the_old_dispatch_ran(Logger& logger){ const std::string step_name; SimStoryStepIO io(sim, notes, misses, knobs, step_name, []{ return false; }, [](const Pokemon::Pose&){}); StoryWalkSteps walks(io); - const Pokemon::StoryActionTable table = story_action_table(walks, naming_actions()); + CancellableHolder scope; + StoryLogBackend backend(Pokemon::StoryBackendKind::SCRIPT, {}, scope); + StoryEngineSteps engine(walks, naming_actions(), backend); std::set> seen; for (const auto& [row, step] : story_steps()){ @@ -148,9 +177,9 @@ UnitTestResult test_table_runs_what_the_old_dispatch_ran(Logger& logger){ continue; } const std::string expected = old_dispatch(step); - const std::string actual = table_dispatch(table, step); + const std::string actual = engine_dispatch(engine, step); if (actual != expected){ - return std::format("{} {} ({} \"{}\"): the table runs \"{}\", the old dispatch ran \"{}\".", + return std::format("{} {} ({} \"{}\"): the engine runs \"{}\", the old dispatch ran \"{}\".", row, step.name, Pokemon::story_step_kind_name(step.kind), step.action, actual, expected); } } @@ -163,8 +192,7 @@ UnitTestResult test_stubbed_steps_need_the_console(Logger& logger){ run_rows_on(sim, logger, {.from = "00.00", .to = "01.11"}); logger.log("Steps the simulation does not play, by row:\n" + stub_report(sim.result())); for (const auto& [row, step] : story_steps()){ - const Pokemon::StoryAction* action = sim.actions().find(step); - if (action != nullptr && action->needs_console){ + if (needs_console(step)){ continue; } for (const SimRun::RowStart& start : sim.result().rows){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h index ee24d30c9a..613e13f857 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h @@ -15,7 +15,7 @@ namespace PokemonBDSP{ -// The story's action table (story_action_table()): every step of the +// The story's actions on the engine (StoryEngineSteps): every step of the // story has an action, each runs what the executors' own dispatch ran // before the table, and the steps the simulation stubs need the console. void add_tests_AutoStory_StoryActions(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 7e63509263..6caea97b5b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -13,6 +13,7 @@ #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -675,7 +676,7 @@ StoryBoundActions SimExecutor::sim_actions(){ return heal(state, step); }, .save = stubbed, - .event = [stubbed](const std::string&) -> Pokemon::StoryActionFunction{ + .event = [stubbed](const std::string&) -> StoryBoundAction{ return stubbed; }, }; @@ -737,7 +738,7 @@ Outcome SimExecutor::run_action(const StoryStep& step, RunState& state){ } m_dialog_up = false; } - return Pokemon::TableExecutor::run_action(step, state); + return m_steps.act(step, state); } Outcome SimExecutor::run_step(const StoryStep& step, RunState& state){ @@ -748,10 +749,9 @@ Outcome SimExecutor::run_step(const StoryStep& step, RunState& state){ // A scene goes on from where the step before left us. A route walks // on the world it plans on (Jubilife alone has no Route 204 north of it). // An event of a walking kind (talk_to_wanderer) is the console's. - const Pokemon::StoryAction* action = m_table.find(step); const bool walks = (step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK) && - action != nullptr && !action->needs_console; + !story_events().contains(step.action); const GridPose* target_ptr = step.args.contains("target") ? &story_arg(step.args, "target") : nullptr; const StoryWorld* on = step.kind == StoryStepKind::ROUTE && target_ptr && !state.pose.map.empty() ? story_plan_world(state.pose.map, target_ptr->map) : nullptr; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index d467e53da6..7ca0689533 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -21,8 +21,10 @@ #include #include #include +#include #include #include +#include "Common/Cpp/CancellableScope.h" #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/ImageTools/ImageStats.h" @@ -31,7 +33,7 @@ #include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" @@ -418,21 +420,22 @@ std::vector story_triggers(); } // namespace detail // The program's walking steps on the simulation, the rest stubbed: the -// story's action table (story_action_table()), its rows that need the +// story's actions on the engine (StoryEngineSteps), those that need the // console bound to the stand-ins below. class SimExecutor : public Pokemon::TableExecutor{ public: // The table and the guard are members, built after the base: it only // keeps references to them until a step runs. explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) - : Pokemon::TableExecutor(m_table, m_guard) + : Pokemon::TableExecutor(m_no_table, m_guard) , m_logger(logger) , m_misses(misses) , m_knobs(std::move(knobs)) , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) , m_walks(m_io) - , m_table(story_action_table(m_walks, sim_actions())) + , m_backend(Pokemon::StoryBackendKind::SIMULATION, [&logger](std::string_view line){ logger.log(std::string(line)); }, m_scope) + , m_steps(m_walks, sim_actions(), m_backend) , m_interrupts(story_interrupts([this](bool fresh){ return look(fresh); }, sim_interrupt_actions())) { if (m_knobs.clear_interrupts){ @@ -452,8 +455,8 @@ class SimExecutor : public Pokemon::TableExecutor{ return m_notes; } // The story's actions as the simulation binds them. - const Pokemon::StoryActionTable& actions() const{ - return m_table; + const StoryEngineSteps& steps() const{ + return m_steps; } virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ m_row = data.id; @@ -526,7 +529,11 @@ class SimExecutor : public Pokemon::TableExecutor{ SimStoryStepIO m_io; StoryWalkSteps m_walks; SimStepGuard m_guard; - Pokemon::StoryActionTable m_table; + // TableExecutor's table: empty, as run_action() runs the engine's actions. + Pokemon::StoryActionTable m_no_table; + CancellableHolder m_scope; + StoryLogBackend m_backend; + StoryEngineSteps m_steps; Pokemon::StoryInterrupts m_interrupts; // The scenes fought so far that SimRun::scenes_fought has. size_t m_scenes_fought = 0; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 56af9971a4..140b80d5c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -46,7 +46,7 @@ #include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 0470926be7..bf7491f748 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -129,7 +130,7 @@ void add_golden_lines( } } -// A ROUTE step from `from`, planned as StoryExecutor::walk_to() walks it. +// A ROUTE step from `from`, planned as the ROUTE action walks it. Walked plan_route(const Pose& from, const StoryStep& step){ const GridPose& target = story_arg(step.args, "target"); const Pose goal = Pokemon::pose_of(target); @@ -343,8 +344,9 @@ class FakeGame : public Pokemon::StoryStepExecutor{ } Outcome save(RunState&, const StoryStep& step){ trace.push_back("save in " + m_row); - if (!step.action.empty()){ - trace.push_back("card for " + m_row + ": " + step.action); + const auto saves_in = step.args.find(SAVES_IN_ARG); + if (saves_in != step.args.end()){ + trace.push_back("card for " + m_row + ": " + std::get(saves_in->second)); } return Pokemon::outcome_ok(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp index dc74a850ec..a5ae179f82 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp @@ -25,7 +25,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 0401ea70ba..33e8de2b7d 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1774,6 +1774,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_ConsoleStory.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -1794,12 +1796,12 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp From 208f732f5c52b1544d7f19ed416bc0932850174c Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 00:36:24 -0800 Subject: [PATCH 06/85] Pokemon Navigation: golden files for the overworld simulations Shared plumbing for seam 3's sim goldens: a golden's path beside its test, its text, the first differing line, and a check that rewrites the file when PA_UPDATE_SIM_GOLDENS is set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Simulation/Pokemon_SimGolden.cpp | 132 ++++++++++++++++++ .../Navigation/Simulation/Pokemon_SimGolden.h | 57 ++++++++ .../Simulation/Pokemon_SimGolden_Tests.cpp | 122 ++++++++++++++++ .../Simulation/Pokemon_SimGolden_Tests.h | 23 +++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 340 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 57691f3c19..45575d5d68 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -41,6 +41,7 @@ #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" +#include "Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" #include "VideoGames/PokemonLA/PokemonLA_Tests.h" @@ -85,6 +86,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_SimGolden(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp new file mode 100644 index 0000000000..ea8b6fe80d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp @@ -0,0 +1,132 @@ +/* Sim Golden + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Pokemon_SimGolden.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// `text` with every "\n" made "\r\n" and no "\r" of its own. +std::string with_crlf(std::string_view text){ + std::string out; + out.reserve(text.size() + text.size() / 16); + for (char ch : text){ + if (ch == '\r'){ + continue; + } + if (ch == '\n'){ + out += '\r'; + } + out += ch; + } + return out; +} + +// Line `begin` of `text` up to its "\n", without a "\r" at its end. +std::string_view line_at(std::string_view text, size_t begin){ + if (begin >= text.size()){ + return {}; + } + const size_t end = std::min(text.find('\n', begin), text.size()); + std::string_view line = text.substr(begin, end - begin); + if (line.ends_with('\r')){ + line.remove_suffix(1); + } + return line; +} + +// Where the line after the one at `begin` starts; past the end if none. +size_t next_line(std::string_view text, size_t begin){ + if (begin >= text.size()){ + return text.size() + 1; + } + const size_t end = text.find('\n', begin); + return end == std::string_view::npos ? text.size() + 1 : end + 1; +} + +} // namespace + + +bool sim_golden_update_requested(){ + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* value = std::getenv(std::string(SIM_GOLDEN_UPDATE_VARIABLE).c_str()); + return value != nullptr && value[0] != '\0' && std::string_view(value) != "0"; +} + +std::string sim_golden_path(std::string_view source_file, std::string_view name){ + const size_t slash = source_file.find_last_of("/\\"); + std::string out = slash == std::string_view::npos ? std::string() : std::string(source_file.substr(0, slash + 1)); + out += name; + return out; +} + +std::string sim_golden_text(std::string_view about, const std::vector& lines){ + std::string out = "# "; + out += about; + out += "\n"; + for (const std::string& line : lines){ + out += line; + out += "\n"; + } + return out; +} + +std::string first_golden_difference(std::string_view golden, std::string_view actual){ + size_t a = 0; + size_t b = 0; + for (size_t line = 1; a < golden.size() || b < actual.size(); line++){ + const std::string_view golden_line = line_at(golden, a); + const std::string_view actual_line = line_at(actual, b); + const bool golden_ended = a >= golden.size(); + const bool actual_ended = b >= actual.size(); + if (golden_line != actual_line || golden_ended != actual_ended){ + return std::format( + "line {}:\n--- golden: {}\n+++ actual: {}", line, + golden_ended ? "(end of file)" : golden_line, + actual_ended ? "(end of file)" : actual_line + ); + } + a = next_line(golden, a); + b = next_line(actual, b); + } + return ""; +} + +UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const std::string& text){ + if (sim_golden_update_requested()){ + const std::string crlf = with_crlf(text); + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(crlf) != crlf.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return std::format("No golden at {}: run with {}=1 to write it.", path, SIM_GOLDEN_UPDATE_VARIABLE); + } + const std::string difference = first_golden_difference(golden, text); + if (!difference.empty()){ + return std::format( + "{} differs from the simulation at {}\nRun with {}=1 to rewrite it if the change is meant.", + path, difference, SIM_GOLDEN_UPDATE_VARIABLE + ); + } + return true; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h new file mode 100644 index 0000000000..4d3210a1fc --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h @@ -0,0 +1,57 @@ +/* Sim Golden + * + * From: https://github.com/PokemonAutomation/ + * + * Golden files for the games' overworld simulations: what a simulation + * observably does (the legs it walks, where steps end, the events it + * shows, how injected faults turn out), written as text a line per fact + * and checked in beside the test that writes it. A refactor of a + * simulation that should change nothing must leave its golden as it is; + * a change that should, shows as the golden's diff in review. + * + * A golden test builds its text and hands it to check_sim_golden(). With + * SIM_GOLDEN_UPDATE_VARIABLE set to anything but "" or "0", the golden is + * rewritten instead, with CRLF line endings as the source tree keeps. + * + */ + +#ifndef PokemonAutomation_Pokemon_SimGolden_H +#define PokemonAutomation_Pokemon_SimGolden_H + +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Set it to rewrite the golden files instead of checking them. +inline constexpr std::string_view SIM_GOLDEN_UPDATE_VARIABLE = "PA_UPDATE_SIM_GOLDENS"; + +// Whether SIM_GOLDEN_UPDATE_VARIABLE asks for the goldens to be rewritten. +bool sim_golden_update_requested(); + +// The file `name` in the directory of `source_file`, a test's __FILE__. +std::string sim_golden_path(std::string_view source_file, std::string_view name); + +// The golden text: `about` as a "# " comment line, then `lines`, each +// ended by "\n". +std::string sim_golden_text(std::string_view about, const std::vector& lines); + +// The first line where `golden` and `actual` differ, carriage returns +// ignored: "line N:\n--- golden: ...\n+++ actual: ...". "" if none. +std::string first_golden_difference(std::string_view golden, std::string_view actual); + +// Checks `text` against the golden file at `path`, or rewrites the file +// with it when SIM_GOLDEN_UPDATE_VARIABLE is set. Fails with the first +// difference, or with how to write a golden that is missing. +UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const std::string& text); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp new file mode 100644 index 0000000000..99d4d2d7a8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -0,0 +1,122 @@ +/* Sim Golden Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The golden file plumbing on its own: paths beside a test, the text, and + * the first difference a check reports. + * + */ + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_SimGolden.h" +#include "Pokemon_SimGolden_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct SimGoldenTestCase{ + std::string name; + UnitTestResult (*body)(Logger& logger); +}; + +class Test_SimGolden : public UnitTest{ +public: + explicit Test_SimGolden(SimGoldenTestCase scenario) + : UnitTest("Pokemon::Navigation - Sim golden: " + scenario.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return m_scenario.body(logger); + } + +private: + SimGoldenTestCase m_scenario; +}; + +UnitTestResult expect_equal(std::string_view what, std::string_view actual, std::string_view expected){ + if (actual == expected){ + return true; + } + return std::string(what) + ": expected \"" + std::string(expected) + "\", got \"" + std::string(actual) + "\"."; +} + +UnitTestResult test_path_beside_source(Logger&){ + UnitTestResult result = expect_equal("posix", sim_golden_path("/a/b/Test.cpp", "x.golden.txt"), "/a/b/x.golden.txt"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("windows", sim_golden_path("C:\\a\\Test.cpp", "x.txt"), "C:\\a\\x.txt"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal("no directory", sim_golden_path("Test.cpp", "x.txt"), "x.txt"); +} + +UnitTestResult test_text(Logger&){ + return expect_equal("text", sim_golden_text("about", {"a", "b"}), "# about\na\nb\n"); +} + +UnitTestResult test_same_text_ignoring_crlf(Logger&){ + return expect_equal("difference", first_golden_difference("# x\r\na\r\nb\r\n", "# x\na\nb\n"), ""); +} + +UnitTestResult test_first_differing_line(Logger&){ + return expect_equal( + "difference", first_golden_difference("# x\r\na\r\nb\r\n", "# x\na\nc\n"), + "line 3:\n--- golden: b\n+++ actual: c" + ); +} + +UnitTestResult test_extra_line(Logger&){ + UnitTestResult result = expect_equal( + "longer actual", first_golden_difference("a\n", "a\nb\n"), + "line 2:\n--- golden: (end of file)\n+++ actual: b" + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal( + "shorter actual", first_golden_difference("a\nb\n", "a\n"), + "line 2:\n--- golden: b\n+++ actual: (end of file)" + ); +} + +UnitTestResult test_missing_golden_fails(Logger& logger){ + if (sim_golden_update_requested()){ + return UnitTestResult(UnitTestResult::SKIPPED, "the goldens are being rewritten"); + } + const UnitTestResult result = check_sim_golden(logger, sim_golden_path(__FILE__, "no_such.golden.txt"), "x\n"); + if (result.result == UnitTestResult::PASSED){ + return "Expected a missing golden to fail the check."; + } + return true; +} + +const SimGoldenTestCase SIM_GOLDEN_CASES[] = { + {.name = "the golden's path is beside the test's source", .body = test_path_beside_source}, + {.name = "the text is a comment line, then a line each", .body = test_text}, + {.name = "CRLF and LF text compare the same", .body = test_same_text_ignoring_crlf}, + {.name = "the first differing line is reported", .body = test_first_differing_line}, + {.name = "a line more or less is reported", .body = test_extra_line}, + {.name = "a missing golden fails", .body = test_missing_golden_fails}, +}; + +} // namespace + + +void add_tests_SimGolden(UnitTestDatabase& database){ + for (const SimGoldenTestCase& scenario : SIM_GOLDEN_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h new file mode 100644 index 0000000000..3119fb8b6a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h @@ -0,0 +1,23 @@ +/* Sim Golden Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_SimGolden_Tests_H +#define PokemonAutomation_Pokemon_SimGolden_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the sim golden file tests. +void add_tests_SimGolden(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index f90c6bc950..dc1aad5e85 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1500,6 +1500,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h From db23c630668c4527976042be9fe79a20c5e8b608 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 00:45:21 -0800 Subject: [PATCH 07/85] Pokemon Navigation: sim golden tests as input and expectation cases Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimGolden_Tests.cpp | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp index 99d4d2d7a8..a71b34adc8 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -20,19 +20,28 @@ namespace Pokemon{ namespace{ -struct SimGoldenTestCase{ +struct SimGoldenInput{ std::string name; UnitTestResult (*body)(Logger& logger); }; +struct SimGoldenExpectation{ + std::string_view description; +}; + +struct SimGoldenTestCase{ + SimGoldenInput input; + SimGoldenExpectation expectation; +}; + class Test_SimGolden : public UnitTest{ public: explicit Test_SimGolden(SimGoldenTestCase scenario) - : UnitTest("Pokemon::Navigation - Sim golden: " + scenario.name) + : UnitTest("Pokemon::Navigation - Sim golden: " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - return m_scenario.body(logger); + return m_scenario.input.body(logger); } private: @@ -99,12 +108,12 @@ UnitTestResult test_missing_golden_fails(Logger& logger){ } const SimGoldenTestCase SIM_GOLDEN_CASES[] = { - {.name = "the golden's path is beside the test's source", .body = test_path_beside_source}, - {.name = "the text is a comment line, then a line each", .body = test_text}, - {.name = "CRLF and LF text compare the same", .body = test_same_text_ignoring_crlf}, - {.name = "the first differing line is reported", .body = test_first_differing_line}, - {.name = "a line more or less is reported", .body = test_extra_line}, - {.name = "a missing golden fails", .body = test_missing_golden_fails}, + {.input = {.name = "the golden's path is beside the test's source", .body = test_path_beside_source}, .expectation = {}}, + {.input = {.name = "the text is a comment line, then a line each", .body = test_text}, .expectation = {}}, + {.input = {.name = "CRLF and LF text compare the same", .body = test_same_text_ignoring_crlf}, .expectation = {}}, + {.input = {.name = "the first differing line is reported", .body = test_first_differing_line}, .expectation = {}}, + {.input = {.name = "a line more or less is reported", .body = test_extra_line}, .expectation = {}}, + {.input = {.name = "a missing golden fails", .body = test_missing_golden_fails}, .expectation = {}}, }; } // namespace From ab559c968320e102d25b18f55c3996a23c6e4786 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 01:00:21 -0800 Subject: [PATCH 08/85] Pokemon Navigation: shared fault classes and per-class fault counters for the sims Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Simulation/Pokemon_SimFaults.cpp | 94 +++++++++++ .../Navigation/Simulation/Pokemon_SimFaults.h | 109 ++++++++++++ .../Simulation/Pokemon_SimFaults_Tests.cpp | 157 ++++++++++++++++++ .../Simulation/Pokemon_SimFaults_Tests.h | 23 +++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 389 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 45575d5d68..e9710fd73f 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -41,6 +41,7 @@ #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" +#include "Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h" #include "Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" @@ -86,6 +87,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_SimFaults(ret); Pokemon::add_tests_SimGolden(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp new file mode 100644 index 0000000000..6d0bf64fb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp @@ -0,0 +1,94 @@ +/* Sim Faults + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_SimFaults.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const std::vector& fault_classes(){ + static const std::vector classes{ + FaultClass::SCENE_END_POSE, + FaultClass::SCENE_EARLY, + FaultClass::BATTLE_OPENING, + FaultClass::WILD_BATTLES, + FaultClass::LATE_FADE, + FaultClass::SLOW_FADE_IN, + FaultClass::WARP_NO_OP, + FaultClass::DARK_CAVE, + FaultClass::LOST_TAP, + FaultClass::UNSEEN_STEP, + }; + return classes; +} + +std::string_view fault_class_name(FaultClass fault){ + switch (fault){ + case FaultClass::SCENE_END_POSE: + return "scene end pose"; + case FaultClass::SCENE_EARLY: + return "scene early"; + case FaultClass::BATTLE_OPENING: + return "battle opening"; + case FaultClass::WILD_BATTLES: + return "wild battles"; + case FaultClass::LATE_FADE: + return "late fade"; + case FaultClass::SLOW_FADE_IN: + return "slow fade-in"; + case FaultClass::WARP_NO_OP: + return "warp no-op"; + case FaultClass::DARK_CAVE: + return "dark cave"; + case FaultClass::LOST_TAP: + return "lost tap"; + case FaultClass::UNSEEN_STEP: + return "unseen step"; + } + return "?"; +} + + +FaultOccurrences::FaultOccurrences(std::set faulted) + : m_numbers(std::move(faulted)) +{} + +bool FaultOccurrences::next(){ + m_chances++; + if (!m_numbers.contains(m_chances)){ + return false; + } + m_faulted++; + return true; +} + + +SimFaults::SimFaults(std::map> faulted){ + for (auto& [fault, numbers] : faulted){ + m_classes.emplace(fault, FaultOccurrences(std::move(numbers))); + } +} + +bool SimFaults::next(FaultClass fault){ + return m_classes[fault].next(); +} + +int SimFaults::chances(FaultClass fault) const{ + const auto iter = m_classes.find(fault); + return iter == m_classes.end() ? 0 : iter->second.chances(); +} + +int SimFaults::faulted(FaultClass fault) const{ + const auto iter = m_classes.find(fault); + return iter == m_classes.end() ? 0 : iter->second.faulted(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h new file mode 100644 index 0000000000..f58b09b854 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h @@ -0,0 +1,109 @@ +/* Sim Faults + * + * From: https://github.com/PokemonAutomation/ + * + * The faults the games' overworld simulations inject, shared by BDSP's + * and FRLG's: the classes of failure the consoles showed, and a counter + * per class that says which of a fault's chances to fault. A chance is + * each time the sim reaches a point where the game could fail that way + * (a tap, a warp, a step's end); a test names the chances it faults by + * number, from 1 in the order the sim reaches them. + * + * How a class is injected is each game's (its sim's knobs and its fault + * sweep); a game may inject only some of the classes. + * + */ + +#ifndef PokemonAutomation_Pokemon_SimFaults_H +#define PokemonAutomation_Pokemon_SimFaults_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A class of failure a console showed, which a sim can inject. +enum class FaultClass{ + // A step whose end the game sets (a talk, a scene, a battle) leaves the + // player on another walkable tile next to the expected one. + SCENE_END_POSE, + // A scene starts on the last tiles of the walk before it. + SCENE_EARLY, + // A battle's opening is still playing when a step starts. + BATTLE_OPENING, + // Wild battles while walking, more than a clean run meets. + WILD_BATTLES, + // A warp's fade shows late. + LATE_FADE, + // Every warp's fade-in runs long: a move right after it goes nowhere. + SLOW_FADE_IN, + // A step onto a warp shows the fade's black but does not warp. + WARP_NO_OP, + // A dark cave walked without Flash. + DARK_CAVE, + // A tap the game drops. + LOST_TAP, + // A step tap that moved the player, read as not moved. + UNSEEN_STEP, +}; + +// Every fault class, in the enum's order. +const std::vector& fault_classes(); + +// The class's name for logs: "scene end pose". +std::string_view fault_class_name(FaultClass fault); + + +// Which chances of one fault to fault: those numbered in `faulted`, +// counted from 1 as next() reaches them. +class FaultOccurrences{ +public: + FaultOccurrences() = default; + explicit FaultOccurrences(std::set faulted); + + // Counts one more chance: whether it is one to fault. + bool next(); + + // The chances counted so far. + int chances() const{ + return m_chances; + } + // How many of them were faulted. + int faulted() const{ + return m_faulted; + } + +private: + std::set m_numbers; + int m_chances = 0; + int m_faulted = 0; +}; + + +// A FaultOccurrences per fault class: a class not given counts its +// chances and faults none. +class SimFaults{ +public: + SimFaults() = default; + explicit SimFaults(std::map> faulted); + + // Counts one more chance of `fault`: whether it is one to fault. + bool next(FaultClass fault); + + // The chances of `fault` counted so far, and how many were faulted. + int chances(FaultClass fault) const; + int faulted(FaultClass fault) const; + +private: + std::map m_classes; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp new file mode 100644 index 0000000000..c7ac4b7008 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -0,0 +1,157 @@ +/* Sim Faults Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The fault counters on their own: which chances a counter faults, what + * it counts, that each class counts apart, and the classes' names. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_SimFaults.h" +#include "Pokemon_SimFaults_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct SimFaultsInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct SimFaultsExpectation{ + std::string_view description; +}; + +struct SimFaultsTestCase{ + SimFaultsInput input; + SimFaultsExpectation expectation; +}; + +class Test_SimFaults : public UnitTest{ +public: + explicit Test_SimFaults(SimFaultsTestCase scenario) + : UnitTest("Pokemon::Navigation - Sim faults: " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.body(); + } + +private: + SimFaultsTestCase m_scenario; +}; + +// What `chances` chances of FaultClass::LOST_TAP did with `faulted` +// named, taken as a game's sim takes them, a chance of +// FaultClass::WARP_NO_OP (none named) after each. +struct Counted{ + std::vector faulted_at; + int chances = 0; + int faulted = 0; + int other_chances = 0; + int other_faulted = 0; + int never_reached = 0; +}; + +Counted count(const std::set& faulted, int chances){ + SimFaults faults({{FaultClass::LOST_TAP, faulted}}); + Counted out; + for (int chance = 1; chance <= chances; chance++){ + if (faults.next(FaultClass::LOST_TAP)){ + out.faulted_at.push_back(chance); + } + faults.next(FaultClass::WARP_NO_OP); + } + out.chances = faults.chances(FaultClass::LOST_TAP); + out.faulted = faults.faulted(FaultClass::LOST_TAP); + out.other_chances = faults.chances(FaultClass::WARP_NO_OP); + out.other_faulted = faults.faulted(FaultClass::WARP_NO_OP); + out.never_reached = faults.chances(FaultClass::DARK_CAVE); + return out; +} + +// "[1, 3]". +std::string numbers_text(const std::vector& numbers){ + std::string out; + for (int number : numbers){ + out += out.empty() ? std::format("{}", number) : std::format(", {}", number); + } + return std::format("[{}]", out); +} + +UnitTestResult expect_counted(const std::set& faulted, int chances, const std::vector& faulted_at){ + const Counted counted = count(faulted, chances); + if (counted.faulted_at != faulted_at){ + return std::format("Faulted chances {}, expected {}.", numbers_text(counted.faulted_at), numbers_text(faulted_at)); + } + if (counted.chances != chances || counted.faulted != (int)faulted_at.size()){ + return std::format("Counted {} chances, {} faulted; expected {}, {}.", counted.chances, counted.faulted, chances, faulted_at.size()); + } + if (counted.other_chances != chances || counted.other_faulted != 0){ + return std::format("The other class counted {} chances, {} faulted; expected {}, 0.", counted.other_chances, counted.other_faulted, chances); + } + if (counted.never_reached != 0){ + return std::format("A class never reached counted {} chances.", counted.never_reached); + } + return true; +} + +UnitTestResult test_none_named(){ + return expect_counted({}, 3, {}); +} + +UnitTestResult test_named_from_one(){ + return expect_counted({1, 3}, 4, {1, 3}); +} + +UnitTestResult test_never_reached(){ + return expect_counted({2, 9}, 3, {2}); +} + +UnitTestResult test_no_chances(){ + return expect_counted({1}, 0, {}); +} + +UnitTestResult test_class_names(){ + std::map seen; + for (FaultClass fault : fault_classes()){ + const std::string_view name = fault_class_name(fault); + if (name == "?" || !seen.emplace(name, fault).second){ + return std::format("Fault class {} has no name of its own: {}", static_cast(fault), name); + } + } + return true; +} + +const SimFaultsTestCase SIM_FAULTS_CASES[] = { + {.input = {.name = "none named faults none", .body = test_none_named}, .expectation = {.description = "3 chances, none faulted"}}, + {.input = {.name = "the named chances are faulted, from 1", .body = test_named_from_one}, .expectation = {.description = "1 and 3 of 4 faulted"}}, + {.input = {.name = "a chance never reached is not faulted", .body = test_never_reached}, .expectation = {.description = "2 of 3 faulted, 9 never reached"}}, + {.input = {.name = "no chances, nothing counted", .body = test_no_chances}, .expectation = {.description = "0 chances, none faulted"}}, + {.input = {.name = "each class has its own name", .body = test_class_names}, .expectation = {.description = "no two classes share a name"}}, +}; + +} // namespace + + +void add_tests_SimFaults(UnitTestDatabase& database){ + for (const SimFaultsTestCase& scenario : SIM_FAULTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h new file mode 100644 index 0000000000..000b660a23 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h @@ -0,0 +1,23 @@ +/* Sim Faults Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_SimFaults_Tests_H +#define PokemonAutomation_Pokemon_SimFaults_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the sim fault counter tests. +void add_tests_SimFaults(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index dc1aad5e85..32169ccf96 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1500,6 +1500,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp From 625bc00718eaed8d5ffe07f0ac6f82f4397f0895 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 10:50:09 -0800 Subject: [PATCH 09/85] runtime-map-tests: link Pokemon_Direction.cpp (MapData uses direction_name) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- devtools/runtime-map-tests/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/devtools/runtime-map-tests/CMakeLists.txt b/devtools/runtime-map-tests/CMakeLists.txt index 8a91248664..eb200ef5cc 100644 --- a/devtools/runtime-map-tests/CMakeLists.txt +++ b/devtools/runtime-map-tests/CMakeLists.txt @@ -11,6 +11,7 @@ add_library(RuntimeMapDecoder STATIC "${NAV}/Pokemon_RuntimeMap.cpp" "${NAV}/Pokemon_MapData.cpp" "${NAV}/Pokemon_Grid.cpp" + "${NAV}/Pokemon_Direction.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp" "${ROOT}/Common/Cpp/Json/JsonObject.cpp" From f10f18ffc0d0349017f0c65f9f40cfe5adc4b362 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:15:33 -0800 Subject: [PATCH 10/85] StoryRun tests: one case struct per UnitTest (code-health test-case rule) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 151 +++++++++++++++--- 1 file changed, 128 insertions(+), 23 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index a45f39b5a4..0b47fa5138 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -260,10 +260,24 @@ const FirstSaveCase FIRST_SAVE_CASES[] = { // A failed attempt's reload loads the save through the game. +struct ReloadInput{ + std::string name; +}; +struct ReloadExpectation{ + size_t loads; + size_t rereads; + std::string log_line; +}; +struct ReloadCase{ + ReloadInput input; + ReloadExpectation expectation; +}; + class Test_StoryReload : public UnitTest{ public: - Test_StoryReload() - : UnitTest("Pokemon::StoryRun - a retry reloads the save") + Test_StoryReload(const ReloadCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -272,20 +286,46 @@ class Test_StoryReload : public UnitTest{ SegmentHooks hooks = story_segment_hooks(game); RunState state; const Outcome outcome = hooks.reload(state); - if (!outcome.succeeded() || fake.loads != 1 || fake.rereads != 1 || !fake.logged("[Story] retry: loading the save")){ - return std::format("Expected one load and reread, got {} and {} ({})", fake.loads, fake.rereads, to_string(outcome)); + const ReloadExpectation& expected = m_case.expectation; + if (!outcome.succeeded() || fake.loads != expected.loads || fake.rereads != expected.rereads || !fake.logged(expected.log_line)){ + return std::format("Expected {} load and {} reread, got {} and {} ({})", expected.loads, expected.rereads, fake.loads, fake.rereads, to_string(outcome)); } return true; } + +private: + const ReloadCase m_case; +}; + +const ReloadCase RELOAD_CASES[] = { + { + .input = {.name = "a retry reloads the save"}, + .expectation = {.loads = 1, .rereads = 1, .log_line = "[Story] retry: loading the save"}, + }, }; // A run that stopped short throws, logs the failure line and touches // nothing in the game: no reload, no save, no reset to HOME. +struct FailureInput{ + std::string name; + std::string checkpoint; + std::string event; + std::string stopped_after; +}; +struct FailureExpectation{ + std::string message; +}; +struct FailureCase{ + FailureInput input; + FailureExpectation expectation; +}; + class Test_StoryFailureLeavesGame : public UnitTest{ public: - Test_StoryFailureLeavesGame() - : UnitTest("Pokemon::StoryRun - a failed run leaves the game where it failed") + Test_StoryFailureLeavesGame(const FailureCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -293,18 +333,18 @@ class Test_StoryFailureLeavesGame : public UnitTest{ StoryGameHooks game = fake.hooks(); SegmentReport report; report.completed = false; - report.failed_checkpoint = "00.04b"; - report.failed_event = "talk_mom"; + report.failed_checkpoint = m_case.input.checkpoint; + report.failed_event = m_case.input.event; report.failure = outcome_failed("expect_failed", "dialogue opened"); AutoStoryStats stats; std::string message; try{ - finish_story_run(report, "00.05", stats, game); + finish_story_run(report, m_case.input.stopped_after, stats, game); return "Expected an OperationFailedException"; }catch (OperationFailedException& e){ message = e.message(); } - if (message != "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"){ + if (message != m_case.expectation.message){ return std::format("Unexpected message: {}", message); } if (!fake.logged(STORY_LEFT_WHERE_FAILED)){ @@ -315,14 +355,37 @@ class Test_StoryFailureLeavesGame : public UnitTest{ } return true; } + +private: + const FailureCase m_case; +}; + +const FailureCase FAILURE_CASES[] = { + { + .input = {.name = "a failed run leaves the game where it failed", .checkpoint = "00.04b", .event = "talk_mom", .stopped_after = "00.05"}, + .expectation = {.message = "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"}, + }, }; // A completed run logs and returns the line the finish notification sends. +struct FinishedInput{ + std::string name; + std::string last_checkpoint; +}; +struct FinishedExpectation{ + std::string line; +}; +struct FinishedCase{ + FinishedInput input; + FinishedExpectation expectation; +}; + class Test_StoryFinished : public UnitTest{ public: - Test_StoryFinished() - : UnitTest("Pokemon::StoryRun - a completed run is done through its last checkpoint") + Test_StoryFinished(const FinishedCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -331,20 +394,44 @@ class Test_StoryFinished : public UnitTest{ SegmentReport report; report.completed = true; AutoStoryStats stats; - const std::string done = finish_story_run(report, "00.05", stats, game); - if (done != "AutoStory: done through 00.05." || !fake.logged(done)){ + const std::string done = finish_story_run(report, m_case.input.last_checkpoint, stats, game); + if (done != m_case.expectation.line || !fake.logged(done)){ return std::format("Unexpected finish line: {}", done); } return true; } + +private: + const FinishedCase m_case; +}; + +const FinishedCase FINISHED_CASES[] = { + { + .input = {.name = "a completed run is done through its last checkpoint", .last_checkpoint = "00.05"}, + .expectation = {.line = "AutoStory: done through 00.05."}, + }, }; // A verify run short of its passes throws with the summary. +struct VerifyInput{ + std::string name; + std::string checkpoint; + size_t passes; +}; +struct VerifyExpectation{ + std::string message; +}; +struct VerifyCase{ + VerifyInput input; + VerifyExpectation expectation; +}; + class Test_StoryVerifyFailed : public UnitTest{ public: - Test_StoryVerifyFailed() - : UnitTest("Pokemon::StoryRun - an unverified checkpoint fails with its summary") + Test_StoryVerifyFailed(const VerifyCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -352,20 +439,30 @@ class Test_StoryVerifyFailed : public UnitTest{ StoryGameHooks game = fake.hooks(); VerifyPolicy policy; VerifyReport report; - report.passes = 1; + report.passes = m_case.input.passes; report.verified = false; std::string message; try{ - finish_story_verify("00.15b", policy, report, game); + finish_story_verify(m_case.input.checkpoint, policy, report, game); return "Expected an OperationFailedException"; }catch (OperationFailedException& e){ message = e.message(); } - if (message != "AutoStory verify: 00.15b 1/3 passed, 2 needed." || !fake.logged(STORY_LEFT_WHERE_FAILED)){ + if (message != m_case.expectation.message || !fake.logged(STORY_LEFT_WHERE_FAILED)){ return std::format("Unexpected message: {}", message); } return true; } + +private: + const VerifyCase m_case; +}; + +const VerifyCase VERIFY_CASES[] = { + { + .input = {.name = "an unverified checkpoint fails with its summary", .checkpoint = "00.15b", .passes = 1}, + .expectation = {.message = "AutoStory verify: 00.15b 1/3 passed, 2 needed."}, + }, }; } // namespace @@ -381,10 +478,18 @@ void add_tests_StoryRun(UnitTestDatabase& database){ for (const FirstSaveCase& test_case : FIRST_SAVE_CASES){ database.add(test_case); } - database.add(); - database.add(); - database.add(); - database.add(); + for (const ReloadCase& test_case : RELOAD_CASES){ + database.add(test_case); + } + for (const FailureCase& test_case : FAILURE_CASES){ + database.add(test_case); + } + for (const FinishedCase& test_case : FINISHED_CASES){ + database.add(test_case); + } + for (const VerifyCase& test_case : VERIFY_CASES){ + database.add(test_case); + } } From ea9b142d530a95c70c3bcee13bf01e948d398a9c Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:33:34 -0800 Subject: [PATCH 11/85] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_AuthoredCheckpointJson_Tests.cpp | 32 ++--- .../Data/Pokemon_StoryStepJson_Tests.cpp | 32 ++--- .../Pokemon_StoryEnginePolicy_Tests.cpp | 128 +++++++++--------- .../Engine/Pokemon_StoryEngineRuns_Tests.cpp | 52 +++---- .../Engine/Pokemon_StoryEngine_Tests.cpp | 98 +++++++------- .../Pokemon_AutoStoryStats_Tests.cpp | 32 ++--- .../AutoStory/Pokemon_ScreenEvents_Tests.cpp | 19 ++- .../AutoStory/Pokemon_StoryEvents_Tests.cpp | 20 +-- .../AutoStory/Pokemon_StoryLog_Tests.cpp | 26 ++-- .../Pokemon_StorySavePolicy_Tests.cpp | 26 ++-- .../AutoStory/Pokemon_StorySegments_Tests.cpp | 20 +-- .../Pokemon_StoryStepExecutor_Tests.cpp | 20 +-- .../Types/Pokemon_StoryActionArg_Tests.cpp | 28 ++-- .../Navigation/Pokemon_LegPlanner_Tests.cpp | 20 +-- .../Navigation/Pokemon_LegWalker_Tests.cpp | 20 +-- .../Navigation/Pokemon_MapData_Tests.cpp | 20 +-- .../Navigation/Pokemon_RouteLog_Tests.cpp | 18 +-- .../Navigation/Pokemon_RuntimeMap_Tests.cpp | 24 ++-- .../Navigation/Pokemon_WallRecovery_Tests.cpp | 50 +++---- .../Pokemon_StoryRangeOptions_Tests.cpp | 36 ++--- 20 files changed, 360 insertions(+), 361 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp index 147fa168a9..ae61bbc538 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -33,24 +33,24 @@ enum class Failure{ MISSING_RESOURCE, }; -struct AuthoredInput{ - std::string name; - std::string json; - std::string game = "frlg"; - bool resource = false; - std::string file = "plan"; -}; +struct AuthoredCase{ + struct Input{ + std::string name; + std::string json; + std::string game = "frlg"; + bool resource = false; + std::string file = "plan"; + }; -struct AuthoredExpectation{ - std::string checkpoint = "00.05"; - std::string execution = R"({"menu":"before_pokedex"})"; - std::vector events = {"first", "second"}; - Failure failure = Failure::NONE; -}; + struct Expectation{ + std::string checkpoint = "00.05"; + std::string execution = R"({"menu":"before_pokedex"})"; + std::vector events = {"first", "second"}; + Failure failure = Failure::NONE; + }; -struct AuthoredCase{ - AuthoredInput input; - AuthoredExpectation expectation; + Input input; + Expectation expectation; }; const AuthoredCase CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 0433258cbb..69f213ad13 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -36,28 +36,28 @@ enum class Record{ CHECKPOINT, }; -// A record to read, and which kind it is. -struct WireInput{ - std::string_view name; - Record record = Record::STEP; - std::string_view json; -}; - // What a read gives. using ReadRecord = std::variant; // "" when the record read is as expected, else what differs. using ReadCheck = std::string (*)(const ReadRecord& record); -// What reading it gives: a record the check accepts, or a rejection. -struct WireExpectation{ - ReadCheck check = nullptr; - bool rejected = false; -}; - struct WireCase{ - WireInput input; - WireExpectation expectation; + // A record to read, and which kind it is. + struct Input{ + std::string_view name; + Record record = Record::STEP; + std::string_view json; + }; + + // What reading it gives: a record the check accepts, or a rejection. + struct Expectation{ + ReadCheck check = nullptr; + bool rejected = false; + }; + + Input input; + Expectation expectation; }; std::string expect(bool ok, std::string_view what){ @@ -201,7 +201,7 @@ std::vector test_actions(){ // `input` read. -ReadRecord read_record(const WireInput& input){ +ReadRecord read_record(const WireCase::Input& input){ static const std::vector actions = test_actions(); const JsonValue value = parse_json(std::string(input.json)); switch (input.record){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp index 1a208e8862..7dfd736896 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp @@ -83,29 +83,29 @@ StoryGame engine_game(std::optional candies){ -// One engine run of 00.31 in `phase`, the player ending on `end_map`. -struct EngineInput{ - std::string_view name; - std::string_view phase; - HashRecord hash = HashRecord::MATCHING; - std::string_view steps = TALK_STEPS; - // Where the talk leaves the player; empty: the talk opens no text. - std::string_view end_map = "RocketHideout_B3F"; - std::optional candies = 2; -}; +struct EngineCase{ + // One engine run of 00.31 in `phase`, the player ending on `end_map`. + struct Input{ + std::string_view name; + std::string_view phase; + HashRecord hash = HashRecord::MATCHING; + std::string_view steps = TALK_STEPS; + // Where the talk leaves the player; empty: the talk opens no text. + std::string_view end_map = "RocketHideout_B3F"; + std::optional candies = 2; + }; -// The save mode chosen, the verdict, whether the game saved (each save -// logs "[Test] save") and a line the run logged. -struct EngineExpectation{ - StorySaveMode mode = StorySaveMode::NONE; - CheckpointVerdict verdict = CheckpointVerdict::PASSED; - size_t saves = 0; - std::string_view line = {}; -}; + // The save mode chosen, the verdict, whether the game saved (each save + // logs "[Test] save") and a line the run logged. + struct Expectation{ + StorySaveMode mode = StorySaveMode::NONE; + CheckpointVerdict verdict = CheckpointVerdict::PASSED; + size_t saves = 0; + std::string_view line = {}; + }; -struct EngineCase{ - EngineInput input; - EngineExpectation expectation; + Input input; + Expectation expectation; }; const EngineCase ENGINE_CASES[] = { @@ -201,23 +201,23 @@ class StoryEngineSaveTest : public UnitTest{ -// Two checkpoints' events, hashed with the built-in actions. -struct HashInput{ - std::string_view name; - std::string_view a; - std::string_view b; -}; +struct HashCase{ + // Two checkpoints' events, hashed with the built-in actions. + struct Input{ + std::string_view name; + std::string_view a; + std::string_view b; + }; -// Whether they hash the same, and `a`'s hash when pinned: a change to it -// means every recorded verification goes stale. -struct HashExpectation{ - bool same = true; - std::optional hash_a = std::nullopt; -}; + // Whether they hash the same, and `a`'s hash when pinned: a change to it + // means every recorded verification goes stale. + struct Expectation{ + bool same = true; + std::optional hash_a = std::nullopt; + }; -struct HashCase{ - HashInput input; - HashExpectation expectation; + Input input; + Expectation expectation; }; inline constexpr std::string_view ROUTE_B3F = R"([{"id": "go", "kind": "route", "args": {"target": {"map": "RocketHideout_B3F", "tiles": [[12, 13]]}}}])"; @@ -271,23 +271,23 @@ class StoryStepsHashTest : public UnitTest{ -// A checkpoint's "metadata", read. -struct MetadataInput{ - std::string_view name; - std::string_view metadata; -}; +struct MetadataCase{ + // A checkpoint's "metadata", read. + struct Input{ + std::string_view name; + std::string_view metadata; + }; -// The error the read throws (contained), or what it read. -struct MetadataExpectation{ - std::string_view error = {}; - StoryPhase phase = StoryPhase::TESTING; - std::string_view steps_hash = {}; - size_t items = 0; -}; + // The error the read throws (contained), or what it read. + struct Expectation{ + std::string_view error = {}; + StoryPhase phase = StoryPhase::TESTING; + std::string_view steps_hash = {}; + size_t items = 0; + }; -struct MetadataCase{ - MetadataInput input; - MetadataExpectation expectation; + Input input; + Expectation expectation; }; const MetadataCase METADATA_CASES[] = { @@ -341,21 +341,21 @@ class StoryMetadataTest : public UnitTest{ -// What a look showed, classified by ScreenMachine states that match on -// observations. -struct ScreenInput{ - std::string_view name; - std::vector events; -}; +struct ScreenCase{ + // What a look showed, classified by ScreenMachine states that match on + // observations. + struct Input{ + std::string_view name; + std::vector events; + }; -// The state matched; none when no state did. -struct ScreenExpectation{ - std::optional state = std::nullopt; -}; + // The state matched; none when no state did. + struct Expectation{ + std::optional state = std::nullopt; + }; -struct ScreenCase{ - ScreenInput input; - ScreenExpectation expectation; + Input input; + Expectation expectation; }; const ScreenCase SCREEN_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp index d272a19648..e15bd54774 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp @@ -585,22 +585,22 @@ std::string segment_no_reload_for_console_only(CancellableScope& scope){ // Gap 7: the first checkpoint is retried after a reload; one after it // only when the one before saved at its end (#329). -struct SegmentInput{ - std::string_view name; - StoryPhase phase; - // Which checkpoint fails once: 0 or 1. - size_t flaky = 0; -}; +struct SegmentCase{ + struct Input{ + std::string_view name; + StoryPhase phase; + // Which checkpoint fails once: 0 or 1. + size_t flaky = 0; + }; -struct SegmentExpectation{ - bool completed = false; - size_t reloads = 0; - size_t saves = 0; -}; + struct Expectation{ + bool completed = false; + size_t reloads = 0; + size_t saves = 0; + }; -struct SegmentCase{ - SegmentInput input; - SegmentExpectation expectation; + Input input; + Expectation expectation; }; const SegmentCase SEGMENT_CASES[] = { @@ -675,20 +675,20 @@ std::string verify_saves_after_all_passed(CancellableScope& scope){ } -// One check above, by name. -struct RunsInput{ - std::string_view name; - std::string (*check)(CancellableScope& scope); -}; +struct RunsCase{ + // One check above, by name. + struct Input{ + std::string_view name; + std::string (*check)(CancellableScope& scope); + }; -// The check's error: none. -struct RunsExpectation{ - std::string_view error = {}; -}; + // The check's error: none. + struct Expectation{ + std::string_view error = {}; + }; -struct RunsCase{ - RunsInput input; - RunsExpectation expectation; + Input input; + Expectation expectation; }; const RunsCase RUNS_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp index 4548921c9b..4e16d05e13 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -127,24 +127,24 @@ StoryStep make_step(StoryStepKind kind, std::string action, StoryActionArgs args -// A step checked and, when it lints clean, dispatched on a backend that -// shows talk text once, then the overworld. -struct RegistryInput{ - std::string_view name; - StoryStep step; -}; - -// The lint errors joined by "; ", then (for a clean step) the failure and -// the inputs sent. -struct RegistryExpectation{ - std::string_view lint = {}; - std::string_view failure = {}; - std::string_view inputs = {}; -}; - struct RegistryCase{ - RegistryInput input; - RegistryExpectation expectation; + // A step checked and, when it lints clean, dispatched on a backend that + // shows talk text once, then the overworld. + struct Input{ + std::string_view name; + StoryStep step; + }; + + // The lint errors joined by "; ", then (for a clean step) the failure and + // the inputs sent. + struct Expectation{ + std::string_view lint = {}; + std::string_view failure = {}; + std::string_view inputs = {}; + }; + + Input input; + Expectation expectation; }; const RegistryCase REGISTRY_CASES[] = { @@ -208,26 +208,26 @@ class StoryActionRegistryTest : public UnitTest{ -// One step, read from JSON, run by the step runner on a backend that -// shows the overworld, with `flags` set and the "door_open" reader -// reading `door_open`. -struct RunnerInput{ - std::string_view name; - std::string_view step; - std::vector flags = {}; - std::optional door_open = std::nullopt; -}; - -// The failure, a line the run logged and the map of the outcome's pose. -struct RunnerExpectation{ - std::string_view failure = {}; - std::string_view line = {}; - std::string_view pose_map = {}; -}; - struct RunnerCase{ - RunnerInput input; - RunnerExpectation expectation; + // One step, read from JSON, run by the step runner on a backend that + // shows the overworld, with `flags` set and the "door_open" reader + // reading `door_open`. + struct Input{ + std::string_view name; + std::string_view step; + std::vector flags = {}; + std::optional door_open = std::nullopt; + }; + + // The failure, a line the run logged and the map of the outcome's pose. + struct Expectation{ + std::string_view failure = {}; + std::string_view line = {}; + std::string_view pose_map = {}; + }; + + Input input; + Expectation expectation; }; const RunnerCase RUNNER_CASES[] = { @@ -283,20 +283,20 @@ class StoryStepRunnerTest : public UnitTest{ -// take_warp north to B3F, from B4F, on a scripted game. -struct WarpInput{ - std::string_view name; - std::vector> looks; -}; - -// How take_warp ended: "" for arrived. -struct WarpExpectation{ - std::string_view failure = {}; -}; - struct WarpCase{ - WarpInput input; - WarpExpectation expectation; + // take_warp north to B3F, from B4F, on a scripted game. + struct Input{ + std::string_view name; + std::vector> looks; + }; + + // How take_warp ended: "" for arrived. + struct Expectation{ + std::string_view failure = {}; + }; + + Input input; + Expectation expectation; }; const WarpCase WARP_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp index 453a975516..044c77b930 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp @@ -18,23 +18,23 @@ namespace Pokemon{ namespace{ -// Counts added to fresh stats, in order. -struct StoryCountsInput{ - std::string name; - std::vector added; -}; - -// The stats after them: counts add up rather than replace. -struct StoryCountsExpectation{ - uint64_t segments; - uint64_t checkpoints; - uint64_t resets; -}; - // Counts recorded into the AutoStory stats and the totals they must reach. struct StoryCountsCase{ - StoryCountsInput input; - StoryCountsExpectation expectation; + // Counts added to fresh stats, in order. + struct Input{ + std::string name; + std::vector added; + }; + + // The stats after them: counts add up rather than replace. + struct Expectation{ + uint64_t segments; + uint64_t checkpoints; + uint64_t resets; + }; + + Input input; + Expectation expectation; }; class Test_StoryCounts : public UnitTest{ @@ -49,7 +49,7 @@ class Test_StoryCounts : public UnitTest{ for (const StoryRunCounts& counts : m_case.input.added){ record_story_counts(counts, stats); } - const StoryCountsExpectation& expected = m_case.expectation; + const StoryCountsCase::Expectation& expected = m_case.expectation; if (stats.m_segment != expected.segments || stats.m_checkpoint != expected.checkpoints || stats.m_reset != expected.resets){ return std::format( "Expected {} segments, {} checkpoints and {} resets, got {}, {} and {}", diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp index 82aae9bf03..f7c7e32402 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -131,17 +131,16 @@ UnitTestResult test_watcher(){ } -struct ScreenEventsInput{ - std::string name; - std::function body; -}; - -struct ScreenEventsExpectation{ -}; - struct ScreenEventsCase{ - ScreenEventsInput input; - ScreenEventsExpectation expectation; + struct Input{ + std::string name; + std::function body; + }; + struct Expectation{ + }; + + Input input; + Expectation expectation; }; class Test_ScreenEvents : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp index a1d485644e..cafb66cd54 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -611,18 +611,18 @@ UnitTestResult test_lint(){ } -struct StoryEventInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StoryEventTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StoryEventExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryEventTestCase{ - StoryEventInput input; - StoryEventExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryEvents : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp index 1cc32c258b..5172022a55 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -16,21 +16,21 @@ namespace Pokemon{ namespace{ -// A formatter's line, made when the table is built. -struct StoryLogInput{ - std::string name; - std::string line; -}; - -// The exact line: the lab watcher and the engine tests read these. -struct StoryLogExpectation{ - std::string line; -}; - // One formatter call and the line it must make. struct StoryLogCase{ - StoryLogInput input; - StoryLogExpectation expectation; + // A formatter's line, made when the table is built. + struct Input{ + std::string name; + std::string line; + }; + + // The exact line: the lab watcher and the engine tests read these. + struct Expectation{ + std::string line; + }; + + Input input; + Expectation expectation; }; class Test_StoryLog : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp index bae25ec95a..72dcc9961a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp @@ -391,21 +391,21 @@ UnitTestResult test_end_pose_from_the_plan(){ } -// The scenario to run. -struct SavePolicyInput{ - std::string name; - UnitTestResult (*test)() = nullptr; -}; - -// What the scenario checks; it returns its own failure. -struct SavePolicyExpectation{ - std::string_view description; -}; - // A save-policy scenario and its expected result. struct SavePolicyCase{ - SavePolicyInput input; - SavePolicyExpectation expectation; + // The scenario to run. + struct Input{ + std::string name; + UnitTestResult (*test)() = nullptr; + }; + + // What the scenario checks; it returns its own failure. + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; }; class Test_StorySavePolicy : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp index c4073dd8d5..efcacab7ca 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp @@ -407,18 +407,18 @@ UnitTestResult test_describe(){ } -struct StorySegmentInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StorySegmentTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StorySegmentExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StorySegmentTestCase{ - StorySegmentInput input; - StorySegmentExpectation expectation; + Input input; + Expectation expectation; }; class Test_StorySegments : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index 1d9ef32865..e22aa36eea 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -727,18 +727,18 @@ UnitTestResult test_lint(){ } -struct StoryStepInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StoryStepTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StoryStepExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryStepTestCase{ - StoryStepInput input; - StoryStepExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryStepExecutor : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp index 50cda4ade3..d26fb413e3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -36,21 +36,21 @@ const StoryActionSpec& mart_spec(){ return spec; } -// Args checked against the Mart's spec, then filled in. -struct ArgsInput{ - std::string_view name; - StoryActionArgs args; -}; - -// The errors joined by "; ", and the args with their fallbacks. -struct ArgsExpectation{ - std::string_view error = {}; - StoryActionArgs filled = {}; -}; - struct ArgsCase{ - ArgsInput input; - ArgsExpectation expectation; + // Args checked against the Mart's spec, then filled in. + struct Input{ + std::string_view name; + StoryActionArgs args; + }; + + // The errors joined by "; ", and the args with their fallbacks. + struct Expectation{ + std::string_view error = {}; + StoryActionArgs filled = {}; + }; + + Input input; + Expectation expectation; }; const ArgsCase CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp index 0d2db0642b..eea9549166 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp @@ -329,18 +329,18 @@ UnitTestResult test_unreachable(){ } -struct LegPlannerInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct LegPlannerTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct LegPlannerExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct LegPlannerTestCase{ - LegPlannerInput input; - LegPlannerExpectation expectation; + Input input; + Expectation expectation; }; class Test_LegPlanner : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp index e676450cb0..a43e06f966 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -224,18 +224,18 @@ UnitTestResult test_watch_along(){ } -struct LegWalkerInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct LegWalkerTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct LegWalkerExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct LegWalkerTestCase{ - LegWalkerInput input; - LegWalkerExpectation expectation; + Input input; + Expectation expectation; }; class Test_LegWalker : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp index 25c3ecfcb8..fcf299992e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -401,18 +401,18 @@ UnitTestResult test_built_in_maps(){ return true; } -struct MapDataTestInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct MapDataTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct MapDataTestExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct MapDataTestCase{ - MapDataTestInput input; - MapDataTestExpectation expectation; + Input input; + Expectation expectation; }; class Test_MapData : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp index 843fc32db0..5715211f01 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp @@ -22,16 +22,16 @@ namespace Pokemon{ namespace{ -struct RouteLogInput{ - std::string name; - std::string line; -}; -struct RouteLogExpectation{ - std::string expected; -}; struct RouteLogTestCase{ - RouteLogInput input; - RouteLogExpectation expectation; + struct Input{ + std::string name; + std::string line; + }; + struct Expectation{ + std::string expected; + }; + Input input; + Expectation expectation; }; class Test_RouteLog : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp index 343416ca4d..254d51fc68 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -18,19 +18,19 @@ namespace PokemonAutomation{ namespace Pokemon{ namespace{ -struct RuntimeMapInput{ - std::string_view name; - std::string_view fields; -}; - -struct RuntimeMapExpectation{ - std::string_view error = {}; - std::string_view normalized_fields = {}; -}; - struct RuntimeMapCase{ - RuntimeMapInput input; - RuntimeMapExpectation expectation; + struct Input{ + std::string_view name; + std::string_view fields; + }; + + struct Expectation{ + std::string_view error = {}; + std::string_view normalized_fields = {}; + }; + + Input input; + Expectation expectation; }; const std::string GOLDEN_V2 = R"( diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp index f563a0f9aa..e3a68cfaa6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp @@ -69,21 +69,21 @@ std::string describe_holds(std::span holds){ } // Inputs and expectations are separate aggregates; each registered test owns one row. -struct CorridorInput{ - std::string name; - std::vector positions; - std::optional person; - size_t budget; -}; +struct CorridorTestCase{ + struct Input{ + std::string name; + std::vector positions; + std::optional person; + size_t budget; + }; -struct CorridorExpectation{ - std::optional first_anchor; - std::vector holds; -}; + struct Expectation{ + std::optional first_anchor; + std::vector holds; + }; -struct CorridorTestCase{ - CorridorInput input; - CorridorExpectation expectation; + Input input; + Expectation expectation; }; class Test_WallRecovery : public UnitTest{ @@ -187,20 +187,20 @@ class CornerPolicy{ } }; -struct CornerInput{ - std::string name; - std::array positions; - size_t budget; -}; +struct CornerTestCase{ + struct Input{ + std::string name; + std::array positions; + size_t budget; + }; -struct CornerExpectation{ - std::optional first_anchor; - std::vector holds; -}; + struct Expectation{ + std::optional first_anchor; + std::vector holds; + }; -struct CornerTestCase{ - CornerInput input; - CornerExpectation expectation; + Input input; + Expectation expectation; }; class Test_WallRecoveryCorner : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp index 4cd40b9e7e..a0f621aafa 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp @@ -47,25 +47,25 @@ const StringSelectDatabase& main_story_database(){ return database; } -// The start and end set by slug, as saved settings load them; empty -// leaves the default. -struct StoryRangeInput{ - std::string name; - std::string start_slug; - std::string end_slug; -}; - -// The indexes in the dropdown, and whether the range is valid. -struct StoryRangeExpectation{ - size_t start; - size_t end; - bool valid; -}; - // A range chosen in the main story's dropdowns and what the group reads from it. struct StoryRangeCase{ - StoryRangeInput input; - StoryRangeExpectation expectation; + // The start and end set by slug, as saved settings load them; empty + // leaves the default. + struct Input{ + std::string name; + std::string start_slug; + std::string end_slug; + }; + + // The indexes in the dropdown, and whether the range is valid. + struct Expectation{ + size_t start; + size_t end; + bool valid; + }; + + Input input; + Expectation expectation; }; class Test_StoryRange : public UnitTest{ @@ -83,7 +83,7 @@ class Test_StoryRange : public UnitTest{ if (!m_case.input.end_slug.empty()){ range.END_CHECKPOINT.set_by_slug(m_case.input.end_slug); } - const StoryRangeExpectation& expected = m_case.expectation; + const StoryRangeCase::Expectation& expected = m_case.expectation; if (range.start_index() != expected.start || range.end_index() != expected.end){ return std::format( "Expected indexes {} to {}, got {} to {}", From 3be04b248f3f1a409ab6fd83104b191498b1afac Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:34:29 -0800 Subject: [PATCH 12/85] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_Interrupts_Tests.cpp | 83 +++++++++-------- .../AutoStory/Pokemon_SceneJudges_Tests.cpp | 18 ++-- .../AutoStory/Pokemon_Transitions_Tests.cpp | 90 +++++++++---------- 3 files changed, 94 insertions(+), 97 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp index f321c506ab..c5d55435a2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -186,17 +186,16 @@ UnitTestResult test_watcher_log(){ } -struct InterruptsInput{ - std::string name; - std::function body; -}; - -struct InterruptsExpectation{ -}; - struct InterruptsCase{ - InterruptsInput input; - InterruptsExpectation expectation; + struct Input{ + std::string name; + std::function body; + }; + struct Expectation{ + }; + + Input input; + Expectation expectation; }; class Test_Interrupts : public UnitTest{ @@ -214,23 +213,22 @@ class Test_Interrupts : public UnitTest{ }; -// A synthetic scene, and the window of it to judge. -struct ClassifyInput{ - std::string name; - std::vector frames; - int until_ms = 0; - InterruptKnobs knobs = {}; - int window_from_ms = 0; -}; - -struct ClassifyExpectation{ - // describe(verdict, T0). - std::string verdict; -}; - struct ClassifyCase{ - ClassifyInput input; - ClassifyExpectation expectation; + // A synthetic scene, and the window of it to judge. + struct Input{ + std::string name; + std::vector frames; + int until_ms = 0; + InterruptKnobs knobs = {}; + int window_from_ms = 0; + }; + struct Expectation{ + // describe(verdict, T0). + std::string verdict; + }; + + Input input; + Expectation expectation; }; class Test_InterruptClassify : public UnitTest{ @@ -240,7 +238,7 @@ class Test_InterruptClassify : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const ClassifyInput& input = m_case.input; + const ClassifyCase::Input& input = m_case.input; const ScreenEventLog log = log_of(input.frames, input.until_ms); const InterruptWindow window{T0 + Milliseconds(input.window_from_ms), T0 + Milliseconds(input.until_ms)}; const InterruptVerdict verdict = classify_interrupt(log, window, input.knobs); @@ -252,22 +250,21 @@ class Test_InterruptClassify : public UnitTest{ }; -// A synthetic scene, classified over all of it, and the lags to time it. -struct StepTimeInput{ - std::string name; - std::vector frames; - int until_ms = 0; - std::vector lags; -}; - -struct StepTimeExpectation{ - // "+700 ms" from T0, or "none". - std::string step; -}; - struct StepTimeCase{ - StepTimeInput input; - StepTimeExpectation expectation; + // A synthetic scene, classified over all of it, and the lags to time it. + struct Input{ + std::string name; + std::vector frames; + int until_ms = 0; + std::vector lags; + }; + struct Expectation{ + // "+700 ms" from T0, or "none". + std::string step; + }; + + Input input; + Expectation expectation; }; class Test_InterruptStepTime : public UnitTest{ @@ -277,7 +274,7 @@ class Test_InterruptStepTime : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const StepTimeInput& input = m_case.input; + const StepTimeCase::Input& input = m_case.input; const InterruptVerdict verdict = classify_interrupt(log_of(input.frames, input.until_ms), whole(input.until_ms), {}); const std::optional step = interrupt_step_time(verdict, input.lags); const std::string got = step diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp index 7073e27efb..33904b16f6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp @@ -113,17 +113,17 @@ UnitTestResult test_talk_over(){ } -struct SceneJudgesInput{ - std::string name; - std::function body; -}; +struct SceneJudgesCase{ + struct Input{ + std::string name; + std::function body; + }; -struct SceneJudgesExpectation{ -}; + struct Expectation{ + }; -struct SceneJudgesCase{ - SceneJudgesInput input; - SceneJudgesExpectation expectation; + Input input; + Expectation expectation; }; class Test_SceneJudges : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp index ef4818a42e..75baebe6c3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -78,25 +78,25 @@ std::string run_tracker(const std::vector& spans, TransitionTracker& track } -// A synthetic stream of frames, through one game's profile. -struct TrackInput{ - std::string name; - std::vector spans; - const FadeProfile* profile = &BDSP_FADE_PROFILE; - bool compare = true; -}; - -struct TrackExpectation{ - // The transitions completed, as run_tracker() puts them. - std::string transitions; - // What judge_warp() makes of the tracker's current() at the end; empty - // for none. - std::string warp = ""; -}; - struct TrackCase{ - TrackInput input; - TrackExpectation expectation; + // A synthetic stream of frames, through one game's profile. + struct Input{ + std::string name; + std::vector spans; + const FadeProfile* profile = &BDSP_FADE_PROFILE; + bool compare = true; + }; + + struct Expectation{ + // The transitions completed, as run_tracker() puts them. + std::string transitions; + // What judge_warp() makes of the tracker's current() at the end; empty + // for none. + std::string warp = ""; + }; + + Input input; + Expectation expectation; }; class Test_TransitionTracker : public UnitTest{ @@ -106,7 +106,7 @@ class Test_TransitionTracker : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const TrackInput& input = m_case.input; + const TrackCase::Input& input = m_case.input; TransitionTracker tracker(*input.profile, input.compare ? compare_means : TransitionTracker::CompareScenes()); const std::string got = run_tracker(input.spans, tracker); if (got != m_case.expectation.transitions){ @@ -161,21 +161,21 @@ UnitTestResult test_sample_of_frame(){ } -// Captured frames: CommandLineTests//Transitions// holds -// frames named by their time in ms ("0.png", "250.png"), and expected.txt -// with the transitions run_tracker() should report (no scene comparison). -struct CapturedInput{ - std::string game; - const FadeProfile* profile; -}; - -// Each case folder's expected.txt holds its expectation. -struct CapturedExpectation{ -}; - struct CapturedCase{ - CapturedInput input; - CapturedExpectation expectation; + // Captured frames: CommandLineTests//Transitions// holds + // frames named by their time in ms ("0.png", "250.png"), and expected.txt + // with the transitions run_tracker() should report (no scene comparison). + struct Input{ + std::string game; + const FadeProfile* profile; + }; + + // Each case folder's expected.txt holds its expectation. + struct Expectation{ + }; + + Input input; + Expectation expectation; }; std::string track_captured_case(const Filesystem::Path& folder, const FadeProfile& profile){ @@ -226,22 +226,22 @@ class Test_CapturedTransitions : public UnitTest{ } private: - CapturedInput m_input; + CapturedCase::Input m_input; }; -struct TransitionsInput{ - std::string name; - UnitTestResult (*body)(); -}; +struct TransitionsCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; -// The body checks its own expectations. -struct TransitionsExpectation{ -}; + // The body checks its own expectations. + struct Expectation{ + }; -struct TransitionsCase{ - TransitionsInput input; - TransitionsExpectation expectation; + Input input; + Expectation expectation; }; class Test_Transitions : public UnitTest{ @@ -255,7 +255,7 @@ class Test_Transitions : public UnitTest{ } private: - TransitionsInput m_input; + TransitionsCase::Input m_input; }; } // namespace From 3c4d8671e11387e5d80e873f972124262aa0bdaf Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:25 -0800 Subject: [PATCH 13/85] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryActions_Tests.cpp | 20 +-- .../Pokemon_StoryInterrupts_Tests.cpp | 20 +-- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 142 +++++++++--------- .../Pokemon_ConnectedMaps_Tests.cpp | 68 +++++---- .../Pokemon_MoveMechanics_Tests.cpp | 22 +-- ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 24 +-- 6 files changed, 149 insertions(+), 147 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index 4e3b98983a..a4e8020210 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -253,18 +253,18 @@ UnitTestResult test_guard_stop_rethrows(){ } -struct StoryActionsInput{ - std::string_view name; - UnitTestResult (*test)(); -}; +struct StoryActionsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; -struct StoryActionsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryActionsCase{ - StoryActionsInput input; - StoryActionsExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryActions : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 234e0d926b..f02b59c42f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -592,18 +592,18 @@ UnitTestResult test_settle_of_a_look(){ } -struct StoryInterruptsInput{ - std::string_view name; - UnitTestResult (*test)(); -}; +struct StoryInterruptsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; -struct StoryInterruptsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryInterruptsCase{ - StoryInterruptsInput input; - StoryInterruptsExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryInterrupts : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 0b47fa5138..7d9f3d6e99 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -62,21 +62,21 @@ struct FakeGame{ }; // A start as the program asks for it, and what the game must have done. -struct StartInput{ - std::string name; - StoryStart start; - std::string place_error; - StoryPreflight preflight; -}; -struct StartExpectation{ - bool succeeds; - size_t loads; - size_t rereads; - bool save_loaded; -}; struct StartCase{ - StartInput input; - StartExpectation expectation; + struct Input{ + std::string name; + StoryStart start; + std::string place_error; + StoryPreflight preflight; + }; + struct Expectation{ + bool succeeds; + size_t loads; + size_t rereads; + bool save_loaded; + }; + Input input; + Expectation expectation; }; constexpr StoryPreflight READY{.video_alive = true, .controller_ready = true, .game_running = true}; @@ -176,16 +176,16 @@ const StartCase START_CASES[] = { // A preflight's checks, and the failure it reads as: the setup's, not // the story's, naming every check that failed. -struct PreflightInput{ - std::string name; - StoryPreflight preflight; -}; -struct PreflightExpectation{ - std::string outcome; -}; struct PreflightCase{ - PreflightInput input; - PreflightExpectation expectation; + struct Input{ + std::string name; + StoryPreflight preflight; + }; + struct Expectation{ + std::string outcome; + }; + Input input; + Expectation expectation; }; class Test_StoryPreflight : public UnitTest{ @@ -223,15 +223,15 @@ const PreflightCase PREFLIGHT_CASES[] = { // Whether the first checkpoint saves at its start: only a new game's. After // a load the save is already there; from the game as it is the place is // unconfirmed (console B, 2026-11-11: "save" ran first on HOME). -struct FirstSaveInput{ - StoryStart start; -}; -struct FirstSaveExpectation{ - bool saves; -}; struct FirstSaveCase{ - FirstSaveInput input; - FirstSaveExpectation expectation; + struct Input{ + StoryStart start; + }; + struct Expectation{ + bool saves; + }; + Input input; + Expectation expectation; }; class Test_StoryFirstSave : public UnitTest{ @@ -260,17 +260,17 @@ const FirstSaveCase FIRST_SAVE_CASES[] = { // A failed attempt's reload loads the save through the game. -struct ReloadInput{ - std::string name; -}; -struct ReloadExpectation{ - size_t loads; - size_t rereads; - std::string log_line; -}; struct ReloadCase{ - ReloadInput input; - ReloadExpectation expectation; + struct Input{ + std::string name; + }; + struct Expectation{ + size_t loads; + size_t rereads; + std::string log_line; + }; + Input input; + Expectation expectation; }; class Test_StoryReload : public UnitTest{ @@ -307,18 +307,18 @@ const ReloadCase RELOAD_CASES[] = { // A run that stopped short throws, logs the failure line and touches // nothing in the game: no reload, no save, no reset to HOME. -struct FailureInput{ - std::string name; - std::string checkpoint; - std::string event; - std::string stopped_after; -}; -struct FailureExpectation{ - std::string message; -}; struct FailureCase{ - FailureInput input; - FailureExpectation expectation; + struct Input{ + std::string name; + std::string checkpoint; + std::string event; + std::string stopped_after; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; }; class Test_StoryFailureLeavesGame : public UnitTest{ @@ -369,16 +369,16 @@ const FailureCase FAILURE_CASES[] = { // A completed run logs and returns the line the finish notification sends. -struct FinishedInput{ - std::string name; - std::string last_checkpoint; -}; -struct FinishedExpectation{ - std::string line; -}; struct FinishedCase{ - FinishedInput input; - FinishedExpectation expectation; + struct Input{ + std::string name; + std::string last_checkpoint; + }; + struct Expectation{ + std::string line; + }; + Input input; + Expectation expectation; }; class Test_StoryFinished : public UnitTest{ @@ -414,17 +414,17 @@ const FinishedCase FINISHED_CASES[] = { // A verify run short of its passes throws with the summary. -struct VerifyInput{ - std::string name; - std::string checkpoint; - size_t passes; -}; -struct VerifyExpectation{ - std::string message; -}; struct VerifyCase{ - VerifyInput input; - VerifyExpectation expectation; + struct Input{ + std::string name; + std::string checkpoint; + size_t passes; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; }; class Test_StoryVerifyFailed : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp index ceafa9304d..788bfe9b84 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -68,14 +68,8 @@ std::string describe(const ConnectedMaps& world, const std::optional& return std::format("{} {}", world.map(place->map).name, to_string(place->tile)); } -// Where a step or a warp should put the player, or nothing for nowhere. -struct PlaceExpectation{ - std::optional place; -}; - // Why `actual` is not `expected`, if it is not. -std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const PlaceExpectation& expectation){ - const std::optional& expected = expectation.place; +std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const std::optional& expected){ std::optional wanted; if (expected){ wanted = MapPlace{*world.find(expected->map), expected->tile}; @@ -87,14 +81,18 @@ std::optional mismatch(const ConnectedMaps& world, const std::optio } -struct StepInput{ - std::string_view name; - NamedPlace from; - Direction direction; -}; struct StepCase{ - StepInput input; - PlaceExpectation expectation; + struct Input{ + std::string_view name; + NamedPlace from; + Direction direction; + }; + // Where the step should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; }; class Test_ConnectedMaps_Step : public UnitTest{ @@ -104,9 +102,9 @@ class Test_ConnectedMaps_Step : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ConnectedMaps world(test_maps()); - const StepInput& input = m_scenario.input; + const StepCase::Input& input = m_scenario.input; const MapPlace from{*world.find(input.from.map), input.from.tile}; - if (std::optional error = mismatch(world, world.neighbour(from, input.direction), m_scenario.expectation)){ + if (std::optional error = mismatch(world, world.neighbour(from, input.direction), m_scenario.expectation.place)){ return *error; } return true; @@ -159,13 +157,17 @@ const StepCase STEP_CASES[] = { }; -struct WarpInput{ - std::string_view name; - MapWarp warp; -}; struct WarpCase{ - WarpInput input; - PlaceExpectation expectation; + struct Input{ + std::string_view name; + MapWarp warp; + }; + // Where the warp should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; }; class Test_ConnectedMaps_Warp : public UnitTest{ @@ -175,7 +177,7 @@ class Test_ConnectedMaps_Warp : public UnitTest{ {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const ConnectedMaps world(test_maps()); - if (std::optional error = mismatch(world, world.warp_arrival(m_scenario.input.warp), m_scenario.expectation)){ + if (std::optional error = mismatch(world, world.warp_arrival(m_scenario.input.warp), m_scenario.expectation.place)){ return *error; } return true; @@ -204,17 +206,17 @@ const WarpCase WARP_CASES[] = { }; -struct StalePlaceInput{ - std::string_view name; - size_t map; -}; -struct StalePlaceExpectation{ - // Whether reading the place throws InternalProgramError. - bool rejected = false; -}; struct StalePlaceCase{ - StalePlaceInput input; - StalePlaceExpectation expectation; + struct Input{ + std::string_view name; + size_t map; + }; + struct Expectation{ + // Whether reading the place throws InternalProgramError. + bool rejected = false; + }; + Input input; + Expectation expectation; }; // A place whose map index is past the loaded maps (from another world, or diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp index c0de39e0f5..bf50a717ec 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -18,18 +18,18 @@ namespace Pokemon{ namespace{ -struct MoveMechanicsInput{ - std::string_view game; - MoveMechanics mechanics; -}; -struct MoveMechanicsExpectation{ - // How the walker presses an open leg on foot (the user's pick, - // 2026-11-11: BDSP taps, FRLG timed holds). - OpenLegPress open_legs_on_foot; -}; struct MoveMechanicsCase{ - MoveMechanicsInput input; - MoveMechanicsExpectation expectation; + struct Input{ + std::string_view game; + MoveMechanics mechanics; + }; + struct Expectation{ + // How the walker presses an open leg on foot (the user's pick, + // 2026-11-11: BDSP taps, FRLG timed holds). + OpenLegPress open_legs_on_foot; + }; + Input input; + Expectation expectation; }; // Why `faster` is not faster than `slower` on both axes, if it is not. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp index 8bd21ac0f9..f71a8a3aae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -26,19 +26,19 @@ using Pokemon::ScreenEvents; namespace{ -struct ScreenEventsInput{ - std::string name; - // The frame's colour; 0 for no frame. - uint32_t color; -}; - -struct ScreenEventsExpectation{ - ScreenEvents events; -}; - struct ScreenEventsCase{ - ScreenEventsInput input; - ScreenEventsExpectation expectation; + struct Input{ + std::string name; + // The frame's colour; 0 for no frame. + uint32_t color; + }; + + struct Expectation{ + ScreenEvents events; + }; + + Input input; + Expectation expectation; }; class Test_AutoStoryScreenEvents : public UnitTest{ From b3990fd0304bc85b3b2d48d313df7a57c355d54d Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:42 -0800 Subject: [PATCH 14/85] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimGolden_Tests.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp index a71b34adc8..06b48f2f5f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -20,18 +20,18 @@ namespace Pokemon{ namespace{ -struct SimGoldenInput{ - std::string name; - UnitTestResult (*body)(Logger& logger); -}; +struct SimGoldenTestCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(Logger& logger); + }; -struct SimGoldenExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct SimGoldenTestCase{ - SimGoldenInput input; - SimGoldenExpectation expectation; + Input input; + Expectation expectation; }; class Test_SimGolden : public UnitTest{ From 373d5bc8822cbc9b38eb07f232f02ff13ec30d92 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:35:52 -0800 Subject: [PATCH 15/85] Tests: nest Input and Expectation inside each native test case struct Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimFaults_Tests.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp index c7ac4b7008..957a88e0bd 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -24,18 +24,18 @@ namespace Pokemon{ namespace{ -struct SimFaultsInput{ - std::string name; - UnitTestResult (*body)(); -}; +struct SimFaultsTestCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; -struct SimFaultsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct SimFaultsTestCase{ - SimFaultsInput input; - SimFaultsExpectation expectation; + Input input; + Expectation expectation; }; class Test_SimFaults : public UnitTest{ From b681c75f392ddadf1ec052447c416b0efd1889d5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:41:39 -0800 Subject: [PATCH 16/85] StoryRun tests: use ReloadCase::Expectation in the reload test Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 7d9f3d6e99..78a24e0399 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -286,7 +286,7 @@ class Test_StoryReload : public UnitTest{ SegmentHooks hooks = story_segment_hooks(game); RunState state; const Outcome outcome = hooks.reload(state); - const ReloadExpectation& expected = m_case.expectation; + const ReloadCase::Expectation& expected = m_case.expectation; if (!outcome.succeeded() || fake.loads != expected.loads || fake.rereads != expected.rereads || !fake.logged(expected.log_line)){ return std::format("Expected {} load and {} reread, got {} and {} ({})", expected.loads, expected.rereads, fake.loads, fake.rereads, to_string(outcome)); } From 91d62357f5d04fbf7aa38fcfd1dd9fd5da1819e8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 14:59:44 -0800 Subject: [PATCH 17/85] Review fixes: comment content, designated initializers, include placement, README counts Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_LegTypes.h | 3 ++- .../Pokemon/Navigation/Pokemon_LegWalker.h | 3 +-- .../Navigation/Pokemon_LegWalker_Tests.cpp | 26 +++++++++---------- .../Pokemon/Navigation/Pokemon_MapFeatures.h | 2 +- .../Pokemon/Navigation/Pokemon_MapTiles.h | 2 +- .../Pokemon/Navigation/Pokemon_RouteLog.h | 3 +-- .../Pokemon/Navigation/Pokemon_RouteLogLegs.h | 2 +- .../Navigation/Pokemon_RouteLogTypes.h | 2 +- .../Navigation/Pokemon_RuntimeMap_Tests.cpp | 5 ++-- devtools/runtime-map-tests/README.md | 9 ++++--- 10 files changed, 29 insertions(+), 28 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h index c1a7401c3b..c8b79dc4e6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_LegWalker.h, unchanged; it includes this header. + * A leg of a route walk: what to walk (LegSpec) and what the walk found (LegResult). + * Pokemon_LegWalker.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h index 31be625cb4..c00ecc7910 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h @@ -68,8 +68,7 @@ LegResult walk_leg_with(const LegSpec& leg, const LegCalls& calls, size_t max_in // keeps whether it fired. A warp's fade can be over before the hold onto // the warp ends, so a wait for it that starts after the hold sees nothing: // the walk watches the hold with this, then waits on with the same watcher -// if it has not fired (FRLG 00.27, console B, 2026-11-09 01:41, the warp to -// CeruleanCity: the watch started 1.3 s into the hold and missed the fade). +// if it has not fired. class WatchAlong : public VisualInferenceCallback{ public: explicit WatchAlong(VisualInferenceCallback& watcher) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp index a43e06f966..10e2593ab0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -57,13 +57,13 @@ struct ScriptedLeg{ // An interrupt set off by step `step`, seen DELAY after it ends. HoldOutcome after_step(int step){ - return HoldOutcome{0, TILE * step + DELAY}; + return HoldOutcome{.interrupt = 0, .elapsed = TILE * step + DELAY}; } UnitTestResult test_hold_times(){ - const LegSpec open{Direction::EAST, 4, false, TILE}; - const LegSpec wall{Direction::EAST, 4, true, TILE}; + const LegSpec open{.direction = Direction::EAST, .tiles = 4, .to_wall = false, .tile_time = TILE}; + const LegSpec wall{.direction = Direction::EAST, .tiles = 4, .to_wall = true, .tile_time = TILE}; if (leg_hold(open, 4) != TILE * 3 + TILE / 2){ return std::format("Open leg: {}ms", leg_hold(open, 4).count()); } @@ -83,7 +83,7 @@ UnitTestResult test_hold_times(){ } UnitTestResult test_tiles_before_interrupt(){ - const LegSpec leg{Direction::EAST, 8, false, TILE}; + const LegSpec leg{.direction = Direction::EAST, .tiles = 8, .to_wall = false, .tile_time = TILE}; for (int step = 0; step <= 8; step++){ for (Milliseconds jitter : {-100ms, 0ms, 100ms}){ const int walked = tiles_before_interrupt(leg, TILE * step + DELAY + jitter, DELAY, 8); @@ -104,7 +104,7 @@ UnitTestResult test_tiles_before_interrupt(){ UnitTestResult test_wall_leg_walked_again(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = true, .tile_time = TILE}; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 6)){ return "Expected the whole leg held again."; @@ -118,7 +118,7 @@ UnitTestResult test_wall_leg_walked_again(){ UnitTestResult test_open_leg_rest_walked(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 4)){ return "Expected the remaining 4 tiles held."; @@ -132,7 +132,7 @@ UnitTestResult test_open_leg_rest_walked(){ UnitTestResult test_open_leg_interrupted_at_end(){ ScriptedLeg script; script.outcomes = {after_step(6)}; - const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 1){ return "Nothing was left to walk after the last step."; @@ -145,7 +145,7 @@ UnitTestResult test_open_leg_interrupted_at_end(){ UnitTestResult test_open_leg_stops(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - LegSpec leg{Direction::NORTH, 6, false, TILE}; + LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; leg.stop_on_interrupt = true; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 1 || !result.stopped || result.exact || script.cleared.size() != 1){ @@ -157,12 +157,12 @@ UnitTestResult test_open_leg_stops(){ return true; } -// Console B, 2026-11-01, run 16: held south into a sign, the leg to a wall -// was interrupted by its message 600ms into every hold, six times. +// Held south into a sign: the leg to a wall is interrupted by the sign's +// message 600ms into every hold, again and again. UnitTestResult test_wall_leg_blocked(){ ScriptedLeg script; - script.outcomes = {HoldOutcome{0, 2200ms}, HoldOutcome{0, 600ms}, HoldOutcome{0, 600ms}}; - LegSpec leg{Direction::SOUTH, 23, true, TILE}; + script.outcomes = {HoldOutcome{.interrupt = 0, .elapsed = 2200ms}, HoldOutcome{.interrupt = 0, .elapsed = 600ms}, HoldOutcome{.interrupt = 0, .elapsed = 600ms}}; + LegSpec leg{.direction = Direction::SOUTH, .tiles = 23, .to_wall = true, .tile_time = TILE}; leg.stop_if_blocked = true; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || !result.stopped){ @@ -176,7 +176,7 @@ UnitTestResult test_too_many_interruptions(){ for (int c = 0; c < 4; c++){ script.outcomes.push_back(after_step(0)); } - const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = true, .tile_time = TILE}; try{ walk_leg_with(leg, script.calls(), 3); }catch (std::runtime_error&){ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h index e7af9fd8be..b39d50bbf7 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * The features a map's tiles can carry. Pokemon_MapData.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h index 6f3cf1373e..63ebf79735 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * A map's tile grid. Pokemon_MapData.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h index 17cdaef020..4a907f056d 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -4,8 +4,7 @@ * * The log lines a route walk writes, shared by the games' walkers so that * every game's log reads the same and devtools/maps can draw any run's - * routes from it. These are BDSP AutoStory's route lines, lifted from - * PokemonBDSP_AutoStory_RouteWalk.cpp, with what the other games need: + * routes from it. These are BDSP AutoStory's route lines, with what the other games need: * * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26); north 5 (to wall) to Route 202 (23, 24) * [Route] Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h index bfe6778a8e..c1da9ce723 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_RouteLog.h, unchanged; it includes this header. + * The legs of a route as its log lines name them. Pokemon_RouteLog.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h index c98a70d243..cbdd909b62 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_RouteLog.h, unchanged; it includes this header. + * The types of a route log's lines. Pokemon_RouteLog.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp index 254d51fc68..81a28b60e1 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -3,14 +3,15 @@ * From: https://github.com/PokemonAutomation/ */ #include -#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" #include "Pokemon_MapData.h" #include "Pokemon_RuntimeMap.h" -#ifndef PA_RUNTIME_MAP_STANDALONE +#ifdef PA_RUNTIME_MAP_STANDALONE +#include +#else #include "Pokemon_RuntimeMap_Tests.h" #endif diff --git a/devtools/runtime-map-tests/README.md b/devtools/runtime-map-tests/README.md index 18235bb554..77b34cd011 100644 --- a/devtools/runtime-map-tests/README.md +++ b/devtools/runtime-map-tests/README.md @@ -30,14 +30,15 @@ cmake --build /path/to/build -j4 ctest --test-dir /path/to/build --output-on-failure ``` -The focused target also runs all eight existing registered MapData cases, -including their legacy diagnostics and embedded map assets. The 26 new cases are registered in the application's native test +The focused target also runs the existing registered MapData cases, +including their legacy diagnostics and embedded map assets. The runtime-map cases are registered in the application's native test database. They cover v1 compatibility, mixed/malformed versions and pairs, inclusive wander bounds, object groups, interaction-vs-item rejection, coordinate events and complete normalized JSON parity, including unknown metadata. -For real data, prepare a clean PokemonSimulation checkout at -`40717c7c809c415c751fd7a348dfc1895f7ec3d7` (merged #53), then run: +For real data, prepare a clean PokemonSimulation checkout at the revision +that `.github/workflows/runtime-map-reader.yml` pins (CI passes it as +`--publisher-revision`; the script refuses any other), then run: ```sh python3 devtools/runtime-map-tests/prepare_parity.py \ From 2c1815bb44f52246c51f82138fb9b0c5fc860b88 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:01:15 -0800 Subject: [PATCH 18/85] Review fixes: comment content, optional instead of a max() sentinel, shared expect_equal, frame-name parsing Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_FadeProfiles.h | 9 ++---- .../Pokemon/AutoStory/Pokemon_Interrupts.cpp | 2 ++ .../AutoStory/Pokemon_Interrupts_Tests.cpp | 11 ++----- .../Pokemon/AutoStory/Pokemon_SceneJudges.cpp | 32 +++++++++---------- .../Pokemon/AutoStory/Pokemon_SceneJudges.h | 19 +++++------ .../AutoStory/Pokemon_SceneJudges_Tests.cpp | 16 +++------- .../Pokemon/AutoStory/Pokemon_TestExpect.h | 31 ++++++++++++++++++ .../AutoStory/Pokemon_Transitions_Tests.cpp | 17 ++++++++-- .../Pokemon/AutoStory/Pokemon_WarpJudge.h | 3 +- SerialPrograms/cmake/SourceFiles.cmake | 1 + 10 files changed, 86 insertions(+), 55 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h index a4dd2ac915..7a2ac6ac4e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_Transitions.h, unchanged; it includes this header. + * Per-game fade thresholds (FadeProfile) and the transition kinds the tracker + * reports. Their definitions are in Pokemon_Transitions.cpp. * */ @@ -10,12 +11,8 @@ #define PokemonAutomation_Pokemon_FadeProfiles_H #include -#include -#include #include #include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -64,7 +61,7 @@ struct FadeProfile{ }; // BDSP. The uniform tier is the shared walk's (FADE_MAX_STDDEV_SUM, the -// Oreburgh Gate's textured floor is no fade, lab-B 2026-11-08); the partial +// Oreburgh Gate's textured floor is no fade); the partial // tier is run_into_door()'s 60, which caught the doorway's dim fade frames. // A cave mouth's fade is dim (45 to 64 a channel), hence the dark sum of 225. // The flash and white-fade holds are provisional: no console frames of an diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp index 53aedfbe7c..57740f5820 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp @@ -5,7 +5,9 @@ */ #include +#include #include +#include #include "Pokemon_Interrupts.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp index c5d55435a2..111d42035f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -8,7 +8,6 @@ */ #include -#include #include #include #include @@ -18,6 +17,7 @@ #include "Pokemon_Interrupts.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_ScreenEvents.h" +#include "Pokemon_TestExpect.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -28,13 +28,6 @@ using namespace std::chrono_literals; const WallClock T0 = WallClock() + std::chrono::hours(1); -UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ - if (got == expected){ - return true; - } - return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); -} - // One frame of a synthetic scene: its events, at `ms` after T0. struct Frame{ int ms; @@ -189,7 +182,7 @@ UnitTestResult test_watcher_log(){ struct InterruptsCase{ struct Input{ std::string name; - std::function body; + UnitTestResult (*body)(); }; struct Expectation{ }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp index 4ded229245..bc587ba860 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -33,37 +33,37 @@ std::string describe(const WarpSeen& seen){ } -SceneMove TalkOver::look(const ScreenEvents& look, WallClock now){ - if (look.has(ScreenEvent::BATTLE_STARTED)){ - m_quiet_since = WallClock::max(); - m_calm_since = WallClock::max(); +SceneMove TalkOver::look(const ScreenEvents& events, WallClock now){ + if (events.has(ScreenEvent::BATTLE_STARTED)){ + m_quiet_since.reset(); + m_calm_since.reset(); return SceneMove::BATTLE; } - m_fade_showing = fade_in(look); + m_fade_showing = fade_in(events); if (m_fade_showing != WarpFade::NONE){ m_fade = m_fade_showing; } - m_banner |= look.has(ScreenEvent::LOCATION_BANNER); - const bool box = look.has(ScreenEvent::DIALOG_BOX); + m_banner |= events.has(ScreenEvent::LOCATION_BANNER); + const bool box = events.has(ScreenEvent::DIALOG_BOX); // A fade is never calm: BDSP's overworld reads a black frame as no // box, and black stays still, so a closing fade counted as quiet and - // ended Mom's scene as it went down (lab-B 2026-11-09 14:33). + // ended the scene as it went down. const bool calm = !box && m_fade_showing == WarpFade::NONE && - look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); - const bool quiet = calm && look.has(ScreenEvent::SCREEN_STILL); + events.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); + const bool quiet = calm && events.has(ScreenEvent::SCREEN_STILL); if (!calm){ - m_calm_since = WallClock::max(); - }else if (m_calm_since == WallClock::max()){ + m_calm_since.reset(); + }else if (!m_calm_since.has_value()){ m_calm_since = now; } if (!quiet){ - m_quiet_since = WallClock::max(); - }else if (m_quiet_since == WallClock::max()){ + m_quiet_since.reset(); + }else if (!m_quiet_since.has_value()){ m_quiet_since = now; } const bool over = - (quiet && now - m_quiet_since >= TALK_OVER_QUIET) || - (calm && now - m_calm_since >= TALK_OVER_CALM); + (quiet && now - *m_quiet_since >= TALK_OVER_QUIET) || + (calm && now - *m_calm_since >= TALK_OVER_CALM); if (over && m_rule.end_on_quiet){ return SceneMove::DONE; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h index 908dcaa39c..c3d3e44593 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -13,6 +13,7 @@ #ifndef PokemonAutomation_Pokemon_SceneJudges_H #define PokemonAutomation_Pokemon_SceneJudges_H +#include #include #include "Common/Cpp/Time.h" #include "Pokemon_ScreenEvents.h" @@ -51,18 +52,17 @@ enum class SceneMove{ // What ends a talk-over, besides the quiet. struct TalkOverRule{ // A map change must come first: a fade or the banner. Only the quiet - // after it counts: r30's scene went quiet for 5 s before the fade home. + // after it counts: a scene can go quiet for 5 s before the fade home. bool warp = false; // False when a battle is to follow (a trainer's lines pause for more - // than 4 s before it, r210d): no quiet ends the talk then. + // than 4 s before it): no quiet ends the talk then. bool end_on_quiet = true; }; // The overworld with no box and a still screen this long ends it: a scene -// pauses while someone walks off (Dawn and Barry after Rowan leaves, r23), -// a scripted walk-in ran 5 s with no text before Mom spoke (r31), and -// Roark's badge speech pauses for the fanfare (lab-B 2026-10-31 09:45 and -// 2026-11-08 15:06). The clock is the last look that was not quiet. +// pauses while someone walks off, a scripted walk-in can run 5 s with no +// text before someone speaks, and a speech pauses for a fanfare. The clock +// is the last look that was not quiet. constexpr Milliseconds TALK_OVER_QUIET = Milliseconds(5000); // The overworld with no box this long ends it, still or not: wanderers or // grass can keep the screen from ever being still. @@ -80,7 +80,7 @@ class TalkOver{ : m_rule(rule) {} - SceneMove look(const ScreenEvents& look, WallClock now); + SceneMove look(const ScreenEvents& events, WallClock now); // Whether the warp the rule asks for has shown (true without one). bool warped() const; @@ -93,8 +93,9 @@ class TalkOver{ WarpFade m_fade = WarpFade::NONE; WarpFade m_fade_showing = WarpFade::NONE; bool m_banner = false; - WallClock m_quiet_since = WallClock::max(); - WallClock m_calm_since = WallClock::max(); + // Since when the screen has been quiet, and calm; none when it is not. + std::optional m_quiet_since; + std::optional m_calm_since; }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp index 33904b16f6..de8fdc5bc2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp @@ -7,13 +7,13 @@ */ #include -#include #include #include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_SceneJudges.h" #include "Pokemon_SceneJudges_Tests.h" +#include "Pokemon_TestExpect.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -22,13 +22,6 @@ namespace{ using namespace std::chrono_literals; -UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ - if (got == expected){ - return true; - } - return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); -} - UnitTestResult test_warp_seen(){ WarpSeen seen = note_warp({}, {ScreenEvent::DIALOG_BOX}, "Route 203"); @@ -93,9 +86,8 @@ UnitTestResult test_talk_over(){ SceneMove::DONE, 6}, {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, - // Mom's Running Shoes scene (lab-B 2026-11-09 14:33): quiet, then - // the scene's closing fade. It ended at the fade's start and the - // next step's input landed in the fade. + // Quiet, then the scene's closing fade: the scene must not end at + // the fade's start, or the next step's input lands in the fade. {"a closing fade starts the quiet over", {}, concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), SceneMove::DONE, 12}, @@ -116,7 +108,7 @@ UnitTestResult test_talk_over(){ struct SceneJudgesCase{ struct Input{ std::string name; - std::function body; + UnitTestResult (*body)(); }; struct Expectation{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h new file mode 100644 index 0000000000..6b8c6221ea --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h @@ -0,0 +1,31 @@ +/* Test Expect + * + * From: https://github.com/PokemonAutomation/ + * + * Checks the unit tests of the AutoStory judges share. + * + */ + +#ifndef PokemonAutomation_Pokemon_TestExpect_H +#define PokemonAutomation_Pokemon_TestExpect_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Passes when `got` is `expected`; else fails naming `what`. +inline UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp index 75baebe6c3..18ef603a22 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -9,6 +9,8 @@ */ #include +#include +#include #include #include #include @@ -181,9 +183,20 @@ struct CapturedCase{ std::string track_captured_case(const Filesystem::Path& folder, const FadeProfile& profile){ std::vector> frames; for (const Filesystem::Path& file : Filesystem::list_directory(folder)){ - if (file.extension().string() == ".png"){ - frames.emplace_back(std::stoi(file.stem().string()), file); + std::string extension = file.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c){ + return static_cast(std::tolower(c)); + }); + if (extension != ".png"){ + continue; } + const std::string stem = file.stem().string(); + int ms = 0; + const auto parsed = std::from_chars(stem.data(), stem.data() + stem.size(), ms); + if (parsed.ec != std::errc() || parsed.ptr != stem.data() + stem.size()){ + return std::format("frame {} is not named by its time in ms", file.filename().string()); + } + frames.emplace_back(ms, file); } std::sort(frames.begin(), frames.end(), [](const auto& a, const auto& b){ return a.first < b.first; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h index ab112a4362..c2b1eb594c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_Interrupts.h, unchanged; it includes this header. + * The warp judge: whether a fade was a warp, from a game's timing. Its + * definitions are in Pokemon_Interrupts.cpp. * */ diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index cdabb865d6..b96f9e31c0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1609,6 +1609,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Pokemon_TestExpect.h Source/Pokemon/AutoStory/Pokemon_Transitions.cpp Source/Pokemon/AutoStory/Pokemon_Transitions.h Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp From f89bc00eb33d506e7bd838ec3e88f911b29bf467 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:02:04 -0800 Subject: [PATCH 19/85] TestExpect.h: namespace-close comments Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h index 6b8c6221ea..203bed4d21 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h @@ -26,6 +26,6 @@ inline UnitTestResult expect_equal(const std::string& what, const std::string& g } -} -} +} // namespace Pokemon +} // namespace PokemonAutomation #endif From 8eb6f347ef066595d951c6b9b594d1b29978be25 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:02:58 -0800 Subject: [PATCH 20/85] StoryActions: tests for a handler that throws and the HOME menu after a failed step (red) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_StoryInterrupts_Tests.cpp | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index f02b59c42f..779fec7300 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -568,6 +568,78 @@ UnitTestResult test_home_menu_stops_the_segment(){ return true; } +// A handler that drives the console can lose it. That fails the step as +// interrupt_failed, like a handler that returns a failure: it must not +// escape the executor, and the step is not run. +UnitTestResult test_handler_throws(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_failed"){ + return std::format("Expected interrupt_failed, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return expect_trace(game, {"look", "clear dialog", "told dialog interrupt_failed: dialog: operation_failed: the console is gone"}); +} + +// The same loss after a step failed, while the executor looks for what +// explains the failure: the step's own failure is kept. +UnitTestResult test_handler_throws_after_a_failure(){ + FakeGame game; + game.screens = {quiet(), dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1}); + if (run.outcome.failure != "dialog"){ + return std::format("Expected the step's own failure, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return true; +} + +// A step that fails and then shows the HOME menu did not fail on its own: +// the game is not running, so the segment must stop instead of recovering +// or reloading with the game closed. +UnitTestResult test_home_menu_after_a_failed_step(){ + for (bool throws : {false, true}){ + FakeGame game; + game.screens = {quiet(), home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1, .throws = throws}); + if (run.outcome.failure != "game_not_running"){ + return std::format("Expected game_not_running after a step that {} and then showed HOME, got {}", + throws ? "threw" : "failed", to_string(run.outcome)); + } + const size_t runs = static_cast(std::count(game.trace.begin(), game.trace.end(), "run walk")); + if (runs != 1){ + return std::format("Expected the step run once, got {} runs", runs); + } + } + return true; +} + UnitTestResult test_settle_of_a_look(){ struct Row{ std::string name; @@ -717,6 +789,18 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, .expectation = {.description = "no recovery in place, no reload"}, }, + { + .input = {.name = "a handler that throws fails the step", .test = test_handler_throws}, + .expectation = {.description = "interrupt_failed, the step not run, nothing escapes"}, + }, + { + .input = {.name = "a handler that throws after a failed step", .test = test_handler_throws_after_a_failure}, + .expectation = {.description = "the step's own failure, nothing escapes"}, + }, + { + .input = {.name = "the HOME menu after a failed step", .test = test_home_menu_after_a_failed_step}, + .expectation = {.description = "game_not_running instead of the step's failure, run once"}, + }, }; } // namespace From 27f818676b8f06f931b2ccd9666ef74b1dad7730 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:04:42 -0800 Subject: [PATCH 21/85] Review fixes: a throwing interrupt handler fails the step, HOME after a failed step stops the segment; comment content, include order, named literals, optional frame colour Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 +- .../AutoStory/Pokemon_InterruptHandlers.h | 3 +- .../AutoStory/Pokemon_StoryActions.cpp | 28 +++++++++++++++---- .../Pokemon/AutoStory/Pokemon_StoryActions.h | 14 ++++++++-- .../AutoStory/Pokemon_StoryActions_Tests.h | 2 +- .../AutoStory/Pokemon_StoryInterrupts.cpp | 14 +++++++++- .../AutoStory/Pokemon_StoryInterrupts.h | 7 +---- .../Pokemon_StoryInterrupts_Tests.cpp | 7 ++--- .../AutoStory/Pokemon_StoryPreflight.cpp | 8 +++++- .../Pokemon/AutoStory/Pokemon_StoryRun.h | 4 +-- .../AutoStory/Pokemon_StoryRun_Tests.cpp | 11 ++++---- .../Pokemon_MoveMechanics_Tests.cpp | 4 +-- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 +- ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 11 ++++---- 14 files changed, 78 insertions(+), 39 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 906540637b..0e51776983 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,7 +19,6 @@ #include "Engine/Pokemon_StoryEngine_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" -#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" @@ -28,6 +27,7 @@ #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h index c574b2503f..ffe9602115 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_StoryInterrupts.h, unchanged; it includes this header. + * The table of a game's interrupt handlers and the screen look they read. + * Pokemon_StoryInterrupts.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 5ecbd69f35..2e7376990e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -107,13 +107,25 @@ Outcome TableExecutor::run(const StoryStep& step, RunState& state){ } try{ Outcome outcome = run_action(step, state); - if (outcome.succeeded() || !cleared_after_failure(step, state, cleared)){ + if (outcome.succeeded()){ + return outcome; + } + switch (look_after_failure(step, state, cleared)){ + case AfterFailure::RETRY: + continue; + case AfterFailure::GAME_NOT_RUNNING: + return outcome_game_not_running(); + case AfterFailure::KEEP: return outcome; } }catch (OperationFailedException& e){ - if (cleared_after_failure(step, state, cleared)){ + const AfterFailure after = look_after_failure(step, state, cleared); + if (after == AfterFailure::RETRY){ continue; } + if (after == AfterFailure::GAME_NOT_RUNNING){ + return outcome_game_not_running(); + } if (m_guard.stops_on_failure(step)){ throw; } @@ -153,11 +165,15 @@ std::optional TableExecutor::clear_interrupts(const StoryStep& step, Ru return std::nullopt; } -// Whether an interrupt explains the failure of `step`: one showed after -// it failed and is cleared, so the step runs again. -bool TableExecutor::cleared_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ +// What explains the failure of `step`, if anything: an interrupt that +// showed after it failed and is cleared, or the game not running. +AfterFailure TableExecutor::look_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ const size_t before = cleared; - return !clear_interrupts(step, state, cleared) && cleared > before; + const std::optional failed = clear_interrupts(step, state, cleared); + if (failed){ + return failed->failure == GAME_NOT_RUNNING ? AfterFailure::GAME_NOT_RUNNING : AfterFailure::KEEP; + } + return cleared > before ? AfterFailure::RETRY : AfterFailure::KEEP; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 3e2792a695..23711eb83c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -109,6 +108,17 @@ class StepGuard{ }; +// What a look at the screen after a step failed found. +enum class AfterFailure{ + // Nothing explains the failure: it is the step's own. + KEEP, + // An interrupt explains it and is cleared: the step runs again. + RETRY, + // The game is not running (the Switch's HOME menu): the failure is + // that, and the step is not run again. + GAME_NOT_RUNNING, +}; + // Runs each step with the table's action for it, inside `guard`. class TableExecutor : public StoryStepExecutor{ public: @@ -138,7 +148,7 @@ class TableExecutor : public StoryStepExecutor{ private: std::optional clear_interrupts(const StoryStep& step, RunState& state, size_t& cleared); - bool cleared_after_failure(const StoryStep& step, RunState& state, size_t& cleared); + AfterFailure look_after_failure(const StoryStep& step, RunState& state, size_t& cleared); const StoryActionTable& m_table; StepGuard& m_guard; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h index d3593d58f6..6f6f908d18 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h @@ -13,7 +13,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -// Registers unit tests for story action tables, the variant parser and the table executor. +// Registers unit tests for story action tables, checkpoint lint and the table executor. void add_tests_StoryActions(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 0012c5d2eb..8c50b18d37 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -10,6 +10,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryInterrupts.h" namespace PokemonAutomation{ @@ -146,6 +147,17 @@ std::string describe(const ScreenSettle& settle){ } +// The handler's outcome. A handler drives the console, which it can lose: +// that is a failed outcome too, not an exception for the executor's caller. +Outcome run_handler(const InterruptHandler& handler, const InterruptVerdict& verdict, RunState& state){ + try{ + return handler.handle(verdict, state); + }catch (OperationFailedException& e){ + return outcome_failed("operation_failed", e.message()); + } +} + + InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state){ InterruptCheck out; out.verdict = settled_verdict(interrupts, step.kind, out.screen); @@ -171,7 +183,7 @@ InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const St out.outcome = outcome_failed("unhandled_interrupt", std::format("{} before {}", interrupt_kind_name(kind), step.name)); return out; } - const Outcome handled = handler->handle(out.verdict, state); + const Outcome handled = run_handler(*handler, out.verdict, state); if (!handled.succeeded()){ out.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt_kind_name(kind), to_string(handled))); return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 2bceba34c6..61945b8459 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -34,17 +34,12 @@ #ifndef PokemonAutomation_Pokemon_StoryInterrupts_H #define PokemonAutomation_Pokemon_StoryInterrupts_H -#include -#include -#include -#include #include -#include +#include "Pokemon_InterruptHandlers.h" #include "Pokemon_Interrupts.h" #include "Pokemon_ScreenEvents.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_StoryStepExecutor.h" -#include "Pokemon_InterruptHandlers.h" namespace PokemonAutomation{ namespace Pokemon{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 779fec7300..e994e11745 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -347,8 +347,8 @@ UnitTestResult test_unsettled_before_a_battle(){ } // A battle's opening still playing when a walk step begins: the walk -// before it ended in grass or in a trainer's sight (BDSP fault sweep, 51 -// steps of 00.01-01.11). The looks wait for the battle, past max_looks, +// before it ended in grass or in a trainer's sight. The looks wait for the +// battle, past max_looks, // and its handler clears it before the step. UnitTestResult test_opening_before_a_walk(ScreenLook opening, ScreenLook battle, const std::string& kind, const std::string& handler){ FakeGame game; @@ -492,8 +492,7 @@ UnitTestResult test_screen_before_each_step(){ }); } -// The program started on the HOME menu (lab-B 2026-11-09 15:31: "before -// save: settled overworld", then X on HOME and a 22-tile walk on it). The +// The program started with the game closed and the HOME menu showing. The // screen is told as HOME and the step fails at once, before any input, // and before a step that starts on a battle's opening too. UnitTestResult test_home_menu_before_a_step(){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp index 2b56c6b435..5266a751e7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp @@ -26,6 +26,12 @@ namespace{ // Color bars are seven flat vertical stripes of different colors. constexpr size_t BAR_COUNT = 7; +// Each stripe is sampled in its middle, away from its edges: inset by this +// fraction of its width on each side, and from the top for this fraction of +// the frame's height. +constexpr double BAR_INSET = 0.25; +constexpr double BAR_TOP = 0.1; +constexpr double BAR_HEIGHT = 0.5; // A stripe flatter than this (stddev sum) is one solid color. constexpr double BAR_MAX_STDDEV = 30; // Two stripes this far apart (RGB distance) are different bars. @@ -37,7 +43,7 @@ bool shows_color_bars(const ImageViewRGB32& frame){ std::array bars; for (size_t c = 0; c < BAR_COUNT; c++){ const double width = 1.0 / BAR_COUNT; - const ImageFloatBox stripe(c * width + width * 0.25, 0.1, width * 0.5, 0.5); + const ImageFloatBox stripe(c * width + width * BAR_INSET, BAR_TOP, width * (1 - 2 * BAR_INSET), BAR_HEIGHT); const ImageStats stats = image_stats(extract_box_reference(frame, stripe)); if (stats.stddev.sum() > BAR_MAX_STDDEV){ return false; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 9215d63a1c..d888b9f73d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -19,8 +19,8 @@ * run before anything is saved. * - The first checkpoint's own save at its start runs only for a new * game: after a load the save is already there, and from the game as - * it is the place is unconfirmed (console B, 2026-11-11: a run on the - * HOME menu "saved" first). + * it is the place is unconfirmed (the game may be on the HOME + * menu). * - A failure leaves the game where it failed. Nothing here closes the * game; the user (or the next run from the save) resumes from there. * diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index 78a24e0399..b1c187331b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -134,8 +134,8 @@ class Test_StoryStart : public UnitTest{ }; const StartCase START_CASES[] = { - // Console B, 2026-11-11: a BDSP run started at 00.04b with the game - // left at 00.04d walked from 00.04d's position. + // A game left at a later checkpoint must not be walked from: a + // checkpoint with a save loads that save first. { .input = {.name = "a checkpoint with a save loads it first", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = READY}, .expectation = {.succeeds = true, .loads = 1, .rereads = 1, .save_loaded = true}, @@ -152,9 +152,8 @@ const StartCase START_CASES[] = { .input = {.name = "a live start loads nothing", .start = StoryStart::LIVE, .place_error = "", .preflight = READY}, .expectation = {.succeeds = true, .loads = 0, .rereads = 0, .save_loaded = false}, }, - // Console B, 2026-11-11 13:32: the game was on HOME; the run saved, - // pressed X/R/ZL on HOME, then "loaded" nothing. The preflight stops it - // before any press. + // The game is on the HOME menu: every press would go to the console's + // menus, so the preflight stops the run before any press. { .input = {.name = "the HOME menu stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = ON_HOME}, .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, @@ -222,7 +221,7 @@ const PreflightCase PREFLIGHT_CASES[] = { // Whether the first checkpoint saves at its start: only a new game's. After // a load the save is already there; from the game as it is the place is -// unconfirmed (console B, 2026-11-11: "save" ran first on HOME). +// unconfirmed (the game may be on the HOME menu). struct FirstSaveCase{ struct Input{ StoryStart start; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp index bf50a717ec..fced1d74eb 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -24,8 +24,8 @@ struct MoveMechanicsCase{ MoveMechanics mechanics; }; struct Expectation{ - // How the walker presses an open leg on foot (the user's pick, - // 2026-11-11: BDSP taps, FRLG timed holds). + // How the walker presses an open leg on foot (BDSP taps, FRLG + // timed holds). OpenLegPress open_legs_on_foot; }; Input input; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index aab4b660f9..f2fad841a4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -8,7 +8,6 @@ #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" -#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Inference/Box/PokemonFRLG_BoxCellOccupiedDetector.h" #include "Inference/Box/PokemonFRLG_BoxCellReader.h" #include "Inference/Box/PokemonFRLG_BoxGenderReader.h" @@ -28,6 +27,7 @@ #include "Inference/PokemonFRLG_StatsReader.h" #include "Inference/PokemonFRLG_TrainerIdReader.h" #include "Inference/PokemonFRLG_WildEncounterReader.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h" #include "Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.h" #include "Tests/TestUtils.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp index f71a8a3aae..d2a2d5d332 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -10,6 +10,7 @@ */ #include +#include #include #include #include "Common/Cpp/TestRunners/UnitTest.h" @@ -29,8 +30,8 @@ namespace{ struct ScreenEventsCase{ struct Input{ std::string name; - // The frame's colour; 0 for no frame. - uint32_t color; + // The frame's colour; none for no frame. + std::optional color; }; struct Expectation{ @@ -50,9 +51,9 @@ class Test_AutoStoryScreenEvents : public UnitTest{ virtual UnitTestResult run(Logger&, CancellableScope&) const override{ VideoSnapshot frame; - if (m_case.input.color != 0){ + if (m_case.input.color.has_value()){ ImageRGB32 image(1920, 1080); - image.fill(m_case.input.color); + image.fill(*m_case.input.color); frame = VideoSnapshot(std::move(image), WallClock()); } FrlgScreenObserver observer; @@ -72,7 +73,7 @@ class Test_AutoStoryScreenEvents : public UnitTest{ const ScreenEventsCase SCREEN_EVENTS_CASES[] = { { - .input = {"no frame shows nothing", 0}, + .input = {"no frame shows nothing", std::nullopt}, .expectation = {{}}, }, { From 047fd8a153b36c5b23bc0b8d3e69d6e100bbc828 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:05:38 -0800 Subject: [PATCH 22/85] Review fixes: first_golden_difference returns an optional, with_crlf is public and tested, Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimGolden.cpp | 42 +++++++++---------- .../Navigation/Simulation/Pokemon_SimGolden.h | 10 ++++- .../Simulation/Pokemon_SimGolden_Tests.cpp | 28 +++++++++++-- 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp index ea8b6fe80d..0ab221c99e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "Common/Cpp/Filesystem/FileIO.h" #include "Pokemon_SimGolden.h" @@ -16,22 +17,6 @@ namespace Pokemon{ namespace{ -// `text` with every "\n" made "\r\n" and no "\r" of its own. -std::string with_crlf(std::string_view text){ - std::string out; - out.reserve(text.size() + text.size() / 16); - for (char ch : text){ - if (ch == '\r'){ - continue; - } - if (ch == '\n'){ - out += '\r'; - } - out += ch; - } - return out; -} - // Line `begin` of `text` up to its "\n", without a "\r" at its end. std::string_view line_at(std::string_view text, size_t begin){ if (begin >= text.size()){ @@ -57,6 +42,21 @@ size_t next_line(std::string_view text, size_t begin){ } // namespace +std::string with_crlf(std::string_view text){ + std::string out; + out.reserve(text.size() + text.size() / 16); + for (char ch : text){ + if (ch == '\r'){ + continue; + } + if (ch == '\n'){ + out += '\r'; + } + out += ch; + } + return out; +} + bool sim_golden_update_requested(){ // code-health: allow char_pointer -- std::getenv returns a const char pointer const char* value = std::getenv(std::string(SIM_GOLDEN_UPDATE_VARIABLE).c_str()); @@ -81,7 +81,7 @@ std::string sim_golden_text(std::string_view about, const std::vector first_golden_difference(std::string_view golden, std::string_view actual){ size_t a = 0; size_t b = 0; for (size_t line = 1; a < golden.size() || b < actual.size(); line++){ @@ -99,7 +99,7 @@ std::string first_golden_difference(std::string_view golden, std::string_view ac a = next_line(golden, a); b = next_line(actual, b); } - return ""; + return std::nullopt; } UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const std::string& text){ @@ -116,11 +116,11 @@ UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const s if (!file_to_string(path, golden)){ return std::format("No golden at {}: run with {}=1 to write it.", path, SIM_GOLDEN_UPDATE_VARIABLE); } - const std::string difference = first_golden_difference(golden, text); - if (!difference.empty()){ + const std::optional difference = first_golden_difference(golden, text); + if (difference.has_value()){ return std::format( "{} differs from the simulation at {}\nRun with {}=1 to rewrite it if the change is meant.", - path, difference, SIM_GOLDEN_UPDATE_VARIABLE + path, *difference, SIM_GOLDEN_UPDATE_VARIABLE ); } return true; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h index 4d3210a1fc..23486fe72e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h @@ -18,6 +18,7 @@ #ifndef PokemonAutomation_Pokemon_SimGolden_H #define PokemonAutomation_Pokemon_SimGolden_H +#include #include #include #include @@ -41,9 +42,14 @@ std::string sim_golden_path(std::string_view source_file, std::string_view name) // ended by "\n". std::string sim_golden_text(std::string_view about, const std::vector& lines); +// `text` with every "\n" made "\r\n" and no "\r" of its own: the line +// endings the goldens are written with. +std::string with_crlf(std::string_view text); + // The first line where `golden` and `actual` differ, carriage returns -// ignored: "line N:\n--- golden: ...\n+++ actual: ...". "" if none. -std::string first_golden_difference(std::string_view golden, std::string_view actual); +// ignored: "line N:\n--- golden: ...\n+++ actual: ...". None if they are +// the same. +std::optional first_golden_difference(std::string_view golden, std::string_view actual); // Checks `text` against the golden file at `path`, or rewrites the file // with it when SIM_GOLDEN_UPDATE_VARIABLE is set. Fails with the first diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp index 06b48f2f5f..552dcd42cb 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -7,8 +7,10 @@ * */ +#include #include #include +#include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon_SimGolden.h" @@ -55,6 +57,11 @@ UnitTestResult expect_equal(std::string_view what, std::string_view actual, std: return std::string(what) + ": expected \"" + std::string(expected) + "\", got \"" + std::string(actual) + "\"."; } +// The difference as text for expect_equal(): "(none)" when the texts match. +std::string difference_of(std::string_view golden, std::string_view actual){ + return first_golden_difference(golden, actual).value_or("(none)"); +} + UnitTestResult test_path_beside_source(Logger&){ UnitTestResult result = expect_equal("posix", sim_golden_path("/a/b/Test.cpp", "x.golden.txt"), "/a/b/x.golden.txt"); if (result.result != UnitTestResult::PASSED){ @@ -72,30 +79,42 @@ UnitTestResult test_text(Logger&){ } UnitTestResult test_same_text_ignoring_crlf(Logger&){ - return expect_equal("difference", first_golden_difference("# x\r\na\r\nb\r\n", "# x\na\nb\n"), ""); + return expect_equal("difference", difference_of("# x\r\na\r\nb\r\n", "# x\na\nb\n"), "(none)"); } UnitTestResult test_first_differing_line(Logger&){ return expect_equal( - "difference", first_golden_difference("# x\r\na\r\nb\r\n", "# x\na\nc\n"), + "difference", difference_of("# x\r\na\r\nb\r\n", "# x\na\nc\n"), "line 3:\n--- golden: b\n+++ actual: c" ); } UnitTestResult test_extra_line(Logger&){ UnitTestResult result = expect_equal( - "longer actual", first_golden_difference("a\n", "a\nb\n"), + "longer actual", difference_of("a\n", "a\nb\n"), "line 2:\n--- golden: (end of file)\n+++ actual: b" ); if (result.result != UnitTestResult::PASSED){ return result; } return expect_equal( - "shorter actual", first_golden_difference("a\nb\n", "a\n"), + "shorter actual", difference_of("a\nb\n", "a\n"), "line 2:\n--- golden: b\n+++ actual: (end of file)" ); } +UnitTestResult test_with_crlf(Logger&){ + UnitTestResult result = expect_equal("bare LF", with_crlf("a\nb\n"), "a\r\nb\r\n"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("CRLF", with_crlf("a\r\nb\r\n"), "a\r\nb\r\n"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal("mixed and a stray CR", with_crlf("a\r\nb\rc\n"), "a\r\nbc\r\n"); +} + UnitTestResult test_missing_golden_fails(Logger& logger){ if (sim_golden_update_requested()){ return UnitTestResult(UnitTestResult::SKIPPED, "the goldens are being rewritten"); @@ -113,6 +132,7 @@ const SimGoldenTestCase SIM_GOLDEN_CASES[] = { {.input = {.name = "CRLF and LF text compare the same", .body = test_same_text_ignoring_crlf}, .expectation = {}}, {.input = {.name = "the first differing line is reported", .body = test_first_differing_line}, .expectation = {}}, {.input = {.name = "a line more or less is reported", .body = test_extra_line}, .expectation = {}}, + {.input = {.name = "goldens are written with exactly one CRLF a line", .body = test_with_crlf}, .expectation = {}}, {.input = {.name = "a missing golden fails", .body = test_missing_golden_fails}, .expectation = {}}, }; From 801c8bf75563b59f77c71382a27c0b5ed50f7ea8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:06:33 -0800 Subject: [PATCH 23/85] Review fixes: fault_classes() checked against the enum, plain separator, static_cast, Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/Pokemon_SimFaults_Tests.cpp | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp index 957a88e0bd..73b884ff6f 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" @@ -85,7 +86,10 @@ Counted count(const std::set& faulted, int chances){ std::string numbers_text(const std::vector& numbers){ std::string out; for (int number : numbers){ - out += out.empty() ? std::format("{}", number) : std::format(", {}", number); + if (!out.empty()){ + out += ", "; + } + out += std::format("{}", number); } return std::format("[{}]", out); } @@ -95,7 +99,7 @@ UnitTestResult expect_counted(const std::set& faulted, int chances, const s if (counted.faulted_at != faulted_at){ return std::format("Faulted chances {}, expected {}.", numbers_text(counted.faulted_at), numbers_text(faulted_at)); } - if (counted.chances != chances || counted.faulted != (int)faulted_at.size()){ + if (counted.chances != chances || counted.faulted != static_cast(faulted_at.size())){ return std::format("Counted {} chances, {} faulted; expected {}, {}.", counted.chances, counted.faulted, chances, faulted_at.size()); } if (counted.other_chances != chances || counted.other_faulted != 0){ @@ -134,12 +138,33 @@ UnitTestResult test_class_names(){ return true; } +// fault_classes() restates the enum, so it must list every value: the +// names stop at the first value past the enum's last (fault_class_name() +// is a switch, so a value with no name fails to build). +UnitTestResult test_classes_match_enum(){ + const std::vector& classes = fault_classes(); + size_t named = 0; + while (fault_class_name(static_cast(named)) != "?"){ + named++; + } + if (named != classes.size()){ + return std::format("The enum has {} classes, fault_classes() lists {}.", named, classes.size()); + } + for (size_t c = 0; c < classes.size(); c++){ + if (classes[c] != static_cast(c)){ + return std::format("fault_classes() lists {} at position {}, not in the enum's order.", static_cast(classes[c]), c); + } + } + return true; +} + const SimFaultsTestCase SIM_FAULTS_CASES[] = { {.input = {.name = "none named faults none", .body = test_none_named}, .expectation = {.description = "3 chances, none faulted"}}, {.input = {.name = "the named chances are faulted, from 1", .body = test_named_from_one}, .expectation = {.description = "1 and 3 of 4 faulted"}}, {.input = {.name = "a chance never reached is not faulted", .body = test_never_reached}, .expectation = {.description = "2 of 3 faulted, 9 never reached"}}, {.input = {.name = "no chances, nothing counted", .body = test_no_chances}, .expectation = {.description = "0 chances, none faulted"}}, {.input = {.name = "each class has its own name", .body = test_class_names}, .expectation = {.description = "no two classes share a name"}}, + {.input = {.name = "fault_classes() lists every class in order", .body = test_classes_match_enum}, .expectation = {.description = "the list is the enum's values, in order"}}, }; } // namespace From c2101fe5bd3b218992baeed42d2f2d3b48577cb9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 15:14:25 -0800 Subject: [PATCH 24/85] runtime-map tests: README passes the pinned publisher revision The README's prepare_parity.py command had no --publisher-revision, and the script's default pin was older than the workflow's, so following the README on the pinned checkout failed. The default now matches the workflow pin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- devtools/runtime-map-tests/README.md | 4 +++- devtools/runtime-map-tests/prepare_parity.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/devtools/runtime-map-tests/README.md b/devtools/runtime-map-tests/README.md index 77b34cd011..e1ae46d4b9 100644 --- a/devtools/runtime-map-tests/README.md +++ b/devtools/runtime-map-tests/README.md @@ -42,7 +42,9 @@ that `.github/workflows/runtime-map-reader.yml` pins (CI passes it as ```sh python3 devtools/runtime-map-tests/prepare_parity.py \ - --publisher /path/to/PokemonSimulation --out /tmp/runtime-map-pairs.json + --publisher /path/to/PokemonSimulation \ + --publisher-revision \ + --out /tmp/runtime-map-pairs.json /path/to/build/RuntimeMapTests /tmp/runtime-map-pairs.json ``` diff --git a/devtools/runtime-map-tests/prepare_parity.py b/devtools/runtime-map-tests/prepare_parity.py index fb1cdea9ef..80519e81ee 100644 --- a/devtools/runtime-map-tests/prepare_parity.py +++ b/devtools/runtime-map-tests/prepare_parity.py @@ -16,7 +16,7 @@ import sys -PUBLISHER_REVISION = '40717c7c809c415c751fd7a348dfc1895f7ec3d7' +PUBLISHER_REVISION = '906956e94fc912ae9adb0e44845da780f3bc7e4c' def main(): From 1836dd3713bbcf2dd202a4446a4c6b8d3597c80d Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:49:52 -0800 Subject: [PATCH 25/85] AutoStory: shared RNG handoff contract Moved unchanged from bdsp/autostory-starter-rng (7a46b79b4), so that BDSP and FRLG both build on it from the shared base. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../AutoStory/Pokemon_StoryRngHandoff.cpp | 38 ++++++ .../AutoStory/Pokemon_StoryRngHandoff.h | 64 ++++++++++ .../Pokemon_StoryRngHandoff_Tests.cpp | 113 ++++++++++++++++++ .../AutoStory/Pokemon_StoryRngHandoff_Tests.h | 23 ++++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 6 files changed, 244 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index fad5698fcc..a04e1a1c77 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -23,6 +23,7 @@ #include "Pokemon_ScreenEvents_Tests.h" #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRngHandoff_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" @@ -37,6 +38,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_AutoStorySelect(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); + add_tests_StoryRngHandoff(database); add_tests_StoryRangeOptions(database); add_tests_StoryEvents(database); add_tests_StorySegments(database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp new file mode 100644 index 0000000000..e23256397a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -0,0 +1,38 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +RngHandoffMode rng_handoff_mode(bool stop, bool run){ + if (run){ + return RngHandoffMode::RUN; + } + return stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; +} + +bool RngHandoffResult::succeeded() const{ + return failure.empty(); +} + +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ + const RngHandoffResult result = call(); + if (!result.succeeded()){ + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, result.failure); + } + logger.log(program + " succeeded: " + result.summary, COLOR_BLUE); + return outcome_ok(); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h new file mode 100644 index 0000000000..140d20e5ea --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -0,0 +1,64 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + * The part of an AutoStory run that hands the game to an RNG program (BDSP + * Starter RNG, FRLG Starter RNG and Gift RNG) and takes it back. A game + * supplies the program's call; the contract around it is shared: + * + * - A handoff row has a mode: OFF (the story plays it by hand), STOP (the run + * ends after the row's handoff save, for the user to run the RNG program) + * or RUN (the story calls the RNG program itself and continues). + * - The call ends in an RngHandoffResult: no failure means the game stands + * where the story goes on; a failure is the reason it does not. + * - A failed RUN stops the program. It never retries the row: the program's + * own reset loop is the retry, and a reload of the save would lose a + * shiny it caught. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_H + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class RngHandoffMode{ + OFF, + STOP, + RUN, +}; + +// The mode for a handoff's two options: RUN takes precedence over STOP. +RngHandoffMode rng_handoff_mode(bool stop, bool run); + + +// How an RNG program's call ended, as the story needs it. +struct RngHandoffResult{ + // Empty: the game stands where the story goes on. Otherwise why it does not. + std::string failure; + // What a success did, for the log: the resets used, the target hit. + std::string summary; + + bool succeeded() const; +}; + +// The call a handoff row runs in place of its steps. +using RngHandoffCall = std::function; + +// Runs `call` for the RNG program `program` ("Starter RNG"). A success is +// logged with its summary and returned as an ok Outcome. A failure throws +// OperationFailedException with an error report, so that no row retry +// reruns the program's reset loop. +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp new file mode 100644 index 0000000000..72a847d509 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -0,0 +1,113 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" +#include "Pokemon_StoryRngHandoff_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// rng_handoff_mode()'s two options. +struct ModeInput{ + bool stop; + bool run; +}; + +struct ModeCase{ + ModeInput input; + RngHandoffMode expected; +}; + +const ModeCase MODE_CASES[] = { + {.input = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, + {.input = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, + {.input = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, + {.input = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, +}; + +class Test_RngHandoffMode : public UnitTest{ +public: + Test_RngHandoffMode() + : UnitTest("Pokemon::StoryRngHandoff - RUN takes precedence over STOP") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + for (const ModeCase& item : MODE_CASES){ + if (rng_handoff_mode(item.input.stop, item.input.run) != item.expected){ + return std::format( + "stop={}, run={}: wrong mode", item.input.stop, item.input.run + ); + } + } + return true; + } +}; + +// A success is an ok Outcome and calls the program once. +class Test_RngHandoffSuccess : public UnitTest{ +public: + Test_RngHandoffSuccess() + : UnitTest("Pokemon::StoryRngHandoff - a success is ok") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.summary = "2 resets"}; + }); + if (!outcome.succeeded()){ + return "Expected an ok outcome"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } +}; + +// A failure throws, once: nothing reruns the program. +class Test_RngHandoffFailure : public UnitTest{ +public: + Test_RngHandoffFailure() + : UnitTest("Pokemon::StoryRngHandoff - a failure throws without a retry") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + try{ + run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.failure = "out of resets"}; + }); + }catch (OperationFailedException&){ + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } + return "Expected OperationFailedException"; + } +}; + +} // namespace + + +void add_tests_StoryRngHandoff(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h new file mode 100644 index 0000000000..aca6f82c1b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h @@ -0,0 +1,23 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared RNG handoff contract. +void add_tests_StoryRngHandoff(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 79a8c47dae..739b7096d0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1531,6 +1531,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp From 00624b4c3556b0968d83b68ea413dc40c7703e07 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:50:09 -0800 Subject: [PATCH 26/85] AutoStory RNG handoff: a program's end can be the user's turn FRLG's loop also ends where the user takes over (target hit but not shiny, attempts spent); that is a stop with a message, not an error. A shiny is a continuation whose rows the game builds, so the seam carries no rows. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRngHandoff.cpp | 17 ++++++++- .../AutoStory/Pokemon_StoryRngHandoff.h | 17 ++++++++- .../Pokemon_StoryRngHandoff_Tests.cpp | 38 +++++++++++++++++++ 3 files changed, 70 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp index e23256397a..1d0d290e1c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -24,12 +24,27 @@ bool RngHandoffResult::succeeded() const{ return failure.empty(); } -Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ +std::optional run_rng_handoff_or_user_turn( + Logger& logger, const std::string& program, const RngHandoffCall& call +){ const RngHandoffResult result = call(); if (!result.succeeded()){ throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, result.failure); } + if (!result.user_turn.empty()){ + logger.log(program + " stopped for the user: " + result.user_turn, COLOR_BLUE); + return result.user_turn; + } logger.log(program + " succeeded: " + result.summary, COLOR_BLUE); + return std::nullopt; +} + +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ + const std::optional user_turn = run_rng_handoff_or_user_turn(logger, program, call); + if (user_turn){ + // A story action has no stop to give the user's turn to. + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, *user_turn); + } return outcome_ok(); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h index 140d20e5ea..a3f14f1d38 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -10,7 +10,11 @@ * ends after the row's handoff save, for the user to run the RNG program) * or RUN (the story calls the RNG program itself and continues). * - The call ends in an RngHandoffResult: no failure means the game stands - * where the story goes on; a failure is the reason it does not. + * where the story goes on; a failure is the reason it does not. A game + * whose program can also end where the user takes over (FRLG: the target + * hit but not shiny, the attempts spent) gives that end a user_turn, which + * is a stop and not an error. What the story runs after a continuation + * (FRLG: the rows after a shiny) is the game's, built from the call. * - A failed RUN stops the program. It never retries the row: the program's * own reset loop is the retry, and a reload of the save would lose a * shiny it caught. @@ -21,6 +25,7 @@ #define PokemonAutomation_Pokemon_StoryRngHandoff_H #include +#include #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Pokemon_StoryOutcome.h" @@ -45,6 +50,9 @@ struct RngHandoffResult{ std::string failure; // What a success did, for the log: the resets used, the target hit. std::string summary; + // Not empty (and no failure): the program ended where the user takes + // over, with this for them. The run stops without an error report. + std::string user_turn; bool succeeded() const; }; @@ -58,6 +66,13 @@ using RngHandoffCall = std::function; // reruns the program's reset loop. Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call); +// As run_rng_handoff(), for a program whose call may end in the user's turn: +// returns that message, which is logged, and the run stops there. Returns +// nothing when the game stands where the story goes on. +std::optional run_rng_handoff_or_user_turn( + Logger& logger, const std::string& program, const RngHandoffCall& call +); + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp index 72a847d509..3608fb064b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" @@ -99,6 +100,42 @@ class Test_RngHandoffFailure : public UnitTest{ } }; +// The user's turn is returned, not thrown, once. +class Test_RngHandoffUserTurn : public UnitTest{ +public: + Test_RngHandoffUserTurn() + : UnitTest("Pokemon::StoryRngHandoff - a user's turn is returned, not an error") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + int calls = 0; + const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.user_turn = "save by hand"}; + }); + if (!turn || *turn != "save by hand"){ + return "Expected the user's turn"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.summary = "shiny"}; + }); + if (none){ + return "A success has no user's turn"; + } + try{ + run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; + }); + }catch (OperationFailedException&){ + return true; + } + return "A failure must throw even with a user's turn"; + } +}; + } // namespace @@ -106,6 +143,7 @@ void add_tests_StoryRngHandoff(UnitTestDatabase& database){ database.add(); database.add(); database.add(); + database.add(); } From eed3b65e0746a34cecb501affa9c9752d16075ae Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 12 Nov 2026 18:52:07 -0800 Subject: [PATCH 27/85] AutoStory RNG handoff: options struct for the mode, test table Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRngHandoff.cpp | 6 +- .../AutoStory/Pokemon_StoryRngHandoff.h | 9 +- .../Pokemon_StoryRngHandoff_Tests.cpp | 204 +++++++++--------- 3 files changed, 119 insertions(+), 100 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp index 1d0d290e1c..67fc164c82 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -13,11 +13,11 @@ namespace PokemonAutomation{ namespace Pokemon{ -RngHandoffMode rng_handoff_mode(bool stop, bool run){ - if (run){ +RngHandoffMode rng_handoff_mode(const RngHandoffOptions& options){ + if (options.run){ return RngHandoffMode::RUN; } - return stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; + return options.stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; } bool RngHandoffResult::succeeded() const{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h index a3f14f1d38..7887658546 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -34,14 +34,21 @@ namespace PokemonAutomation{ namespace Pokemon{ +// What a handoff row does with its RNG program. enum class RngHandoffMode{ OFF, STOP, RUN, }; +// A handoff's two options. +struct RngHandoffOptions{ + bool stop = false; + bool run = false; +}; + // The mode for a handoff's two options: RUN takes precedence over STOP. -RngHandoffMode rng_handoff_mode(bool stop, bool run); +RngHandoffMode rng_handoff_mode(const RngHandoffOptions& options); // How an RNG program's call ended, as the story needs it. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp index 3608fb064b..e6d72119a4 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryRngHandoff.h" @@ -17,133 +18,144 @@ namespace Pokemon{ namespace{ -// rng_handoff_mode()'s two options. -struct ModeInput{ - bool stop; - bool run; +struct RngHandoffInput{ + std::string_view name; + UnitTestResult (*body)(Logger& logger); }; -struct ModeCase{ - ModeInput input; - RngHandoffMode expected; +struct RngHandoffExpectation{ + std::string_view description; }; -const ModeCase MODE_CASES[] = { - {.input = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, - {.input = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, - {.input = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, - {.input = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, +struct RngHandoffTestCase{ + RngHandoffInput input; + RngHandoffExpectation expectation; }; -class Test_RngHandoffMode : public UnitTest{ +class Test_RngHandoff : public UnitTest{ public: - Test_RngHandoffMode() - : UnitTest("Pokemon::StoryRngHandoff - RUN takes precedence over STOP") + explicit Test_RngHandoff(RngHandoffTestCase scenario) + : UnitTest("Pokemon::StoryRngHandoff - " + std::string(scenario.input.name)) + , m_scenario(scenario) {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - for (const ModeCase& item : MODE_CASES){ - if (rng_handoff_mode(item.input.stop, item.input.run) != item.expected){ - return std::format( - "stop={}, run={}: wrong mode", item.input.stop, item.input.run - ); - } - } - return true; + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return m_scenario.input.body(logger); } + +private: + RngHandoffTestCase m_scenario; }; +// rng_handoff_mode()'s two options. +UnitTestResult test_mode(Logger&){ + struct Case{ + RngHandoffOptions options; + RngHandoffMode expected; + }; + const Case cases[] = { + {.options = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, + {.options = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, + {.options = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, + {.options = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, + }; + for (const Case& item : cases){ + if (rng_handoff_mode(item.options) != item.expected){ + return std::format("stop={}, run={}: wrong mode", item.options.stop, item.options.run); + } + } + return true; +} + // A success is an ok Outcome and calls the program once. -class Test_RngHandoffSuccess : public UnitTest{ -public: - Test_RngHandoffSuccess() - : UnitTest("Pokemon::StoryRngHandoff - a success is ok") - {} +UnitTestResult test_success(Logger& logger){ + int calls = 0; + const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.summary = "2 resets"}; + }); + if (!outcome.succeeded()){ + return "Expected an ok outcome"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; +} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - int calls = 0; - const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ +// A failure throws, once: nothing reruns the program. +UnitTestResult test_failure(Logger& logger){ + int calls = 0; + try{ + run_rng_handoff(logger, "Test RNG", [&]{ calls++; - return RngHandoffResult{.summary = "2 resets"}; + return RngHandoffResult{.failure = "out of resets"}; }); - if (!outcome.succeeded()){ - return "Expected an ok outcome"; - } + }catch (OperationFailedException&){ if (calls != 1){ return std::format("Expected 1 call, got {}", calls); } return true; } -}; - -// A failure throws, once: nothing reruns the program. -class Test_RngHandoffFailure : public UnitTest{ -public: - Test_RngHandoffFailure() - : UnitTest("Pokemon::StoryRngHandoff - a failure throws without a retry") - {} + return "Expected OperationFailedException"; +} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - int calls = 0; - try{ - run_rng_handoff(logger, "Test RNG", [&]{ - calls++; - return RngHandoffResult{.failure = "out of resets"}; - }); - }catch (OperationFailedException&){ - if (calls != 1){ - return std::format("Expected 1 call, got {}", calls); - } - return true; - } - return "Expected OperationFailedException"; +// The user's turn is returned, not thrown, once; a success has none; a +// failure throws even with one. +UnitTestResult test_user_turn(Logger& logger){ + int calls = 0; + const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.user_turn = "save by hand"}; + }); + if (!turn || *turn != "save by hand"){ + return "Expected the user's turn"; } -}; - -// The user's turn is returned, not thrown, once. -class Test_RngHandoffUserTurn : public UnitTest{ -public: - Test_RngHandoffUserTurn() - : UnitTest("Pokemon::StoryRngHandoff - a user's turn is returned, not an error") - {} - - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - int calls = 0; - const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ - calls++; - return RngHandoffResult{.user_turn = "save by hand"}; - }); - if (!turn || *turn != "save by hand"){ - return "Expected the user's turn"; - } - if (calls != 1){ - return std::format("Expected 1 call, got {}", calls); - } - const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ - return RngHandoffResult{.summary = "shiny"}; + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.summary = "shiny"}; + }); + if (none){ + return "A success has no user's turn"; + } + try{ + run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; }); - if (none){ - return "A success has no user's turn"; - } - try{ - run_rng_handoff_or_user_turn(logger, "Test RNG", []{ - return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; - }); - }catch (OperationFailedException&){ - return true; - } - return "A failure must throw even with a user's turn"; + }catch (OperationFailedException&){ + return true; } + return "A failure must throw even with a user's turn"; +} + +const RngHandoffTestCase RNG_HANDOFF_CASES[] = { + { + .input = {.name = "RUN takes precedence over STOP", .body = test_mode}, + .expectation = {.description = "RUN wins when both options are on"}, + }, + { + .input = {.name = "a success is ok", .body = test_success}, + .expectation = {.description = "an ok outcome after one call"}, + }, + { + .input = {.name = "a failure throws without a retry", .body = test_failure}, + .expectation = {.description = "OperationFailedException after one call"}, + }, + { + .input = {.name = "a user's turn is returned, not an error", .body = test_user_turn}, + .expectation = {.description = "the message comes back; a failure still throws"}, + }, }; } // namespace void add_tests_StoryRngHandoff(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); + for (const RngHandoffTestCase& scenario : RNG_HANDOFF_CASES){ + database.add(scenario); + } } From 8e0fa6397d64e607f6f0c57e6307ebd25d14e93f Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 00:06:10 -0800 Subject: [PATCH 28/85] Transitions: ignore samples with no stats An empty or dropped frame has count 0 and zero stats, which level_of() read as uniform and dark, so it could start or extend a black fade and give a false FADE_BLACK warp. push() now skips such samples. Tests mix empty frames into a scene and into a rise. Also: named bool args, optional beat in the talk-over test, no issue numbers in comments. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_Interrupts.h | 2 +- .../Pokemon/AutoStory/Pokemon_SceneJudges.h | 4 ++-- .../AutoStory/Pokemon_SceneJudges_Tests.cpp | 24 +++++++++++-------- .../Pokemon/AutoStory/Pokemon_Transitions.cpp | 12 ++++++---- .../AutoStory/Pokemon_Transitions_Tests.cpp | 18 ++++++++++++++ 5 files changed, 43 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h index b7637ad044..cb46ce18d4 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h @@ -6,7 +6,7 @@ * (ScreenEventLog), the same way for every game: a wild encounter, a * trainer's sight, a dialog, a warp. One frame cannot tell them apart; the * order can. A white flash then a battle is an encounter, a white fade with - * no battle after it a cave exit (BDSP's walk fled one as a battle, #268); + * no battle after it a cave exit (BDSP's walk once fled one as a battle); * a box then a flash then a battle is a trainer's lines; a flash then a box * then a battle is a wild battle's opening text. * diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h index c3d3e44593..785dfe6950 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -3,7 +3,7 @@ * From: https://github.com/PokemonAutomation/ * * Judgements a story step makes from screen events (Pokemon_ScreenEvents.h) - * over time, not from one look (#268's design note): a warp is a fade or + * over time, not from one look: a warp is a fade or * the banner of the map arrived on, and a talk or a scene is over when the * overworld has been quiet for a while. Pure: tests drive them with * scripted scenes, and every game shares them. @@ -22,7 +22,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -// What a walk or a step saw of a warp (#268): a fade or the location +// What a walk or a step saw of a warp: a fade or the location // banner of the map arrived on. Either one alone is the warp. struct WarpSeen{ WarpFade fade = WarpFade::NONE; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp index de8fdc5bc2..8c30c04b92 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -36,17 +37,17 @@ UnitTestResult test_warp_seen(){ // A scripted scene: a look per beat, a second apart. Returns the beat -// TalkOver first says `want` at, or -1. -int first_beat(const std::vector& beats, SceneMove want, TalkOver& judge){ +// TalkOver first says `want` at, if any. +std::optional first_beat(const std::vector& beats, SceneMove want, TalkOver& judge){ const Milliseconds every = 1000ms; WallClock now = WallClock(); for (size_t c = 0; c < beats.size(); c++){ if (judge.look(beats[c], now) == want){ - return (int)c; + return c; } now += every; } - return -1; + return std::nullopt; } const ScreenEvents QUIET{ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; @@ -70,7 +71,7 @@ UnitTestResult test_talk_over(){ TalkOverRule rule; std::vector beats; SceneMove want; - int beat; + std::optional beat; // Unset: never says `want`. }; const std::vector rows = { {"5 s of quiet ends it", {}, repeat(QUIET, 8), SceneMove::DONE, 5}, @@ -84,21 +85,24 @@ UnitTestResult test_talk_over(){ {"a banner is the warp too", {.warp = true}, concat({ScreenEvents{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}}, repeat(QUIET, 8)), SceneMove::DONE, 6}, - {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, + {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, std::nullopt}, {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, // Quiet, then the scene's closing fade: the scene must not end at // the fade's start, or the next step's input lands in the fade. {"a closing fade starts the quiet over", {}, concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), SceneMove::DONE, 12}, - {"a fade still down never ends it", {}, concat(repeat(QUIET, 3), repeat(FADED, 20)), SceneMove::DONE, -1}, - {"a fade is never calm", {}, concat(repeat(CALM, 10), repeat(CALM_FADED, 10)), SceneMove::DONE, -1}, + {"a fade still down never ends it", {}, concat(repeat(QUIET, 3), repeat(FADED, 20)), SceneMove::DONE, std::nullopt}, + {"a fade is never calm", {}, concat(repeat(CALM, 10), repeat(CALM_FADED, 10)), SceneMove::DONE, std::nullopt}, }; for (const Row& row : rows){ TalkOver judge(row.rule); - const int got = first_beat(row.beats, row.want, judge); + const std::optional got = first_beat(row.beats, row.want, judge); if (got != row.beat){ - return std::format("{}: expected beat {}, got {} ({})", row.name, row.beat, got, judge.describe()); + const auto show = [](const std::optional& beat){ + return beat ? std::to_string(*beat) : std::string("none"); + }; + return std::format("{}: expected beat {}, got {} ({})", row.name, show(row.beat), show(got), judge.describe()); } } return true; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp index e243313477..28de36ccf6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp @@ -130,18 +130,22 @@ TransitionTracker::Level TransitionTracker::level_of(const ImageStats& middle) c } std::optional TransitionTracker::push(const TransitionSample& sample){ + // No stats (an empty or dropped frame) would read as uniform and dark. + if (sample.middle.count == 0){ + return std::nullopt; + } switch (level_of(sample.middle)){ case Level::SCENE: return on_scene(sample); case Level::PARTIAL_DARK: - return on_partial(sample, false); + return on_partial(sample, /*white=*/false); case Level::PARTIAL_WHITE: - return on_partial(sample, true); + return on_partial(sample, /*white=*/true); case Level::DARK: - on_uniform(sample, false); + on_uniform(sample, /*white=*/false); return std::nullopt; case Level::WHITE: - on_uniform(sample, true); + on_uniform(sample, /*white=*/true); return std::nullopt; } return std::nullopt; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp index 18ef603a22..a91b6fa631 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -50,6 +50,8 @@ const ImageStats FALLING_DARK = stats(60, 60, 60, 10); const ImageStats DARK = stats(5, 5, 5, 1); const ImageStats FALLING_WHITE = stats(160, 160, 160, 10); const ImageStats WHITE = stats(250, 250, 250, 1); +// An empty or dropped frame: no stats at all. +const ImageStats EMPTY; SceneChange compare_means(const TransitionSample& before, const TransitionSample& after){ const FloatPixel& a = before.middle.average; @@ -344,6 +346,22 @@ const TrackCase TRACK_CASES[] = { {{0, 100, ROUTE}, {200, 500, DARK}, {600, 2500, DIM_FLOOR}}}, .expectation = {"black fade +200 ms, peak +200 ms, rise +600 ms, end +1700 ms, other scene", "warped"}, }, + { + .input = {"empty frames in a scene start no fade", + {{0, 100, ROUTE}, {200, 300, EMPTY}, {400, 500, ROUTE}}}, + .expectation = {"none"}, + }, + { + .input = {"an empty frame in a fall is skipped", + {{0, 100, ROUTE}, {200, 200, EMPTY}, {300, 300, FALLING_DARK}, {400, 600, DARK}}}, + .expectation = {"none", "fade still showing"}, + }, + { + .input = {"an empty frame in the rise does not move the rise", + {{0, 100, ROUTE}, {200, 200, FALLING_DARK}, {300, 500, DARK}, {600, 600, FALLING_DARK}, + {700, 700, EMPTY}, {800, 900, HOUSE}}}, + .expectation = {"black fade +200 ms, peak +300 ms, rise +600 ms, end +800 ms, other scene", "warped"}, + }, { .input = {"a fade in progress is still showing", {{0, 100, ROUTE}, {200, 200, FALLING_DARK}, {300, 600, DARK}}}, From 45a46f72505685ba0c2c1ce579aa935d9e867ffd Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 00:11:55 -0800 Subject: [PATCH 29/85] AutoStory RNG handoff: red test: a stop reports its message and lines Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryRngHandoff.cpp | 7 +++++ .../AutoStory/Pokemon_StoryRngHandoff.h | 10 +++++++ .../Pokemon_StoryRngHandoff_Tests.cpp | 26 +++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp index 67fc164c82..3e05133a3d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -48,6 +48,13 @@ Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHan return outcome_ok(); } +std::string report_rng_handoff_stop( + Logger& logger, const std::string& message, const std::vector& lines, + const std::function& show +){ + return std::string(); +} + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h index 7887658546..ddc21f3286 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -27,6 +27,7 @@ #include #include #include +#include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Pokemon_StoryOutcome.h" @@ -80,6 +81,15 @@ std::optional run_rng_handoff_or_user_turn( Logger& logger, const std::string& program, const RngHandoffCall& call ); +// A run that stops for the user to run an RNG program, as the game's program +// reports it: `message` (what to do) and then `lines` (the RNG plan's +// attempts), each logged and passed to `show` (the overlay's log). Returns +// the whole text, one line each, for the program's finish notification. +std::string report_rng_handoff_stop( + Logger& logger, const std::string& message, const std::vector& lines, + const std::function& show +); + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp index e6d72119a4..a5733d5bce 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryRngHandoff.h" @@ -130,11 +131,36 @@ UnitTestResult test_user_turn(Logger& logger){ return "A failure must throw even with a user's turn"; } +// A stop reports its message, then each line, to the log and to `show`; +// the notification text is one line each. +UnitTestResult test_stop_report(Logger& logger){ + std::vector shown; + const auto show = [&](const std::string& line){ + shown.push_back(line); + }; + const std::string text = report_rng_handoff_stop(logger, "Stopped for RNG.", {"Attempt 1", "Attempt 2"}, show); + if (text != "Stopped for RNG.\nAttempt 1\nAttempt 2"){ + return std::format("Wrong notification text: {}", text); + } + if (shown != std::vector{"Stopped for RNG.", "Attempt 1", "Attempt 2"}){ + return "The overlay must get the message and then each line"; + } + shown.clear(); + if (report_rng_handoff_stop(logger, "Stopped.", {}, show) != "Stopped." || shown.size() != 1){ + return "A stop without lines is its message alone"; + } + return true; +} + const RngHandoffTestCase RNG_HANDOFF_CASES[] = { { .input = {.name = "RUN takes precedence over STOP", .body = test_mode}, .expectation = {.description = "RUN wins when both options are on"}, }, + { + .input = {.name = "a stop reports its message and lines", .body = test_stop_report}, + .expectation = {.description = "log, overlay and notification text agree"}, + }, { .input = {.name = "a success is ok", .body = test_success}, .expectation = {.description = "an ok outcome after one call"}, From 0877430cfec4c7794de744825bc3b263b2b02b28 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 00:16:01 -0800 Subject: [PATCH 30/85] AutoStory RNG handoff: report_rng_handoff_stop, the stop's log, overlay and notification text Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp index 3e05133a3d..1890518dd4 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -52,7 +52,15 @@ std::string report_rng_handoff_stop( Logger& logger, const std::string& message, const std::vector& lines, const std::function& show ){ - return std::string(); + std::string text = message; + logger.log(message, COLOR_BLUE); + show(message); + for (const std::string& line : lines){ + logger.log(line, COLOR_BLUE); + show(line); + text += "\n" + line; + } + return text; } From 14cf7180b066833dbe89a5b92cd14a0a7a40f87f Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:11:25 -0800 Subject: [PATCH 31/85] Recover the boss from the summary when header read is not a boss (#1894) Prevent an OCR misread from making a non-boss as boss during boss battle. - Leave the boss empty in header read if not GlobalState::opponent_fits_stage() in process_header_read - Retry the OCR in summary read, which makes a valid boss string more likely - accept_opponent() then only records a valid boss - boss_if_caught() returns the boss only after the fourth win - If the boss is still empty, throw (same as before) Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss Co-authored-by: Claude Opus 5.5 --- .../Framework/PokemonSwSh_MaxLair_State.cpp | 31 +++--- .../Framework/PokemonSwSh_MaxLair_State.h | 13 ++- .../PokemonSwSh_MaxLair_State_Tests.cpp | 95 ++++++++++++++++--- .../PokemonSwSh_MaxLair_Run_Battle.cpp | 18 +--- 4 files changed, 117 insertions(+), 40 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp index 53150be1bf..b00840ef4a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp @@ -24,24 +24,33 @@ bool is_boss_battle(const GlobalState& state){ } // namespace -bool GlobalState::accept_opponent(){ +bool GlobalState::opponent_fits_stage() const{ const std::string opponent_slug = opponent.empty() ? "" : *opponent.begin(); - // A boss before the end means something is out-of-sync. - if (!is_boss_battle(*this) && is_boss(opponent_slug)){ - return false; + if (!is_boss_battle(*this)){ + return !is_boss(opponent_slug); + } + if (!boss.empty()){ + return opponent.size() == 1 && opponent_slug == boss; + } + // A rental read here is a misread (Kyurem read as Mimikyu, 2026-11-02). + return opponent.size() == 1 && is_boss(opponent_slug); +} + +bool GlobalState::accept_opponent(){ + const bool fits = opponent_fits_stage(); + if (!is_boss_battle(*this)){ + // A boss before the end means something is out-of-sync. + return fits; } - // Infer the boss if we don't know it. Only a single boss species counts: - // a rental read here is a misread (Kyurem read as Mimikyu, 2026-11-02) - // and must not become the boss. A later turn's read can still record it. - if (is_boss_battle(*this) && boss.empty() && opponent.size() == 1 && is_boss(opponent_slug)){ - boss = opponent_slug; + if (boss.empty() && fits){ + boss = *opponent.begin(); } return true; } std::string GlobalState::boss_if_caught() const{ - // The identified boss is reported whether or not it was caught. - return boss; + // The boss is caught only if the fourth battle was won. + return wins == 4 ? boss : ""; } std::string PlayerState::dump() const{ diff --git a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h index 4b34bfecec..e1ec843268 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h +++ b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h @@ -172,10 +172,14 @@ struct GlobalState{ size_t find_player_index(size_t console_id) const; void clear_battle_state(); - // Returns false when the opponent read doesn't fit this battle stage (a - // boss before the fourth battle), so the caller retries the read. On an - // accepted read at the fourth battle, records the boss if none is known - // and the read is a single boss species. + // Whether the opponent read fits this battle stage: before the fourth + // battle, any non-boss; at the fourth battle, exactly the known boss, or a + // single boss species when no boss is known yet. + bool opponent_fits_stage() const; + + // Returns false when the read doesn't fit a battle before the fourth (a + // boss there), so the caller retries the read. At the fourth battle, + // records the boss if none is known and the read fits. bool accept_opponent(); // The same boss, but only if the adventure caught it, else empty: for the @@ -183,7 +187,6 @@ struct GlobalState{ // the boss-caught rules after a loss. Decided from the battles won (the // boss is the fourth battle), not from how many Pokemon were caught, so it // stays right if non-boss catches are ever skipped. - // For now this returns boss whatever the battles won. std::string boss_if_caught() const; std::string dump() const; diff --git a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State_Tests.cpp index fbd162aa6e..fd6651d6ee 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State_Tests.cpp @@ -68,7 +68,6 @@ class Test_MaxLairBossState : public UnitTest{ BossStateTestCase m_scenario; }; -// Cases marked TODO record the current, wrong behaviour. const BossStateTestCase CASES[] = { { .input = {.name = "rental before three wins", .wins = 2, .opponent = {"mimikyu-disguised"}, .boss = "", .final_wins = 3}, @@ -86,12 +85,11 @@ const BossStateTestCase CASES[] = { // is already known is kept. { .input = {.name = "Kyurem after Mimikyu misidentification", .wins = 3, .opponent = {"kyurem"}, .boss = "mimikyu-disguised", .final_wins = 3}, - .expectation = {.accepted = true, .boss = "mimikyu-disguised", .boss_if_caught = "mimikyu-disguised"}, + .expectation = {.accepted = true, .boss = "mimikyu-disguised", .boss_if_caught = ""}, }, - // TODO: to be fixed: the boss is reported caught without a fourth win. { .input = {.name = "identified boss lost", .wins = 3, .opponent = {"kyurem"}, .boss = "kyurem", .final_wins = 3}, - .expectation = {.accepted = true, .boss = "kyurem", .boss_if_caught = "kyurem"}, + .expectation = {.accepted = true, .boss = "kyurem", .boss_if_caught = ""}, }, { .input = {.name = "identified boss caught", .wins = 3, .opponent = {"kyurem"}, .boss = "", .final_wins = 4}, @@ -101,7 +99,6 @@ const BossStateTestCase CASES[] = { .input = {.name = "boss before three wins must retry", .wins = 2, .opponent = {"kyurem"}, .boss = "", .final_wins = 2}, .expectation = {.accepted = false, .boss = "", .boss_if_caught = ""}, }, - // TODO: to be fixed: a boss stage with no opponent read is accepted. { .input = {.name = "empty boss-stage read", .wins = 3, .opponent = {}, .boss = "", .final_wins = 3}, .expectation = {.accepted = true, .boss = "", .boss_if_caught = ""}, @@ -110,24 +107,100 @@ const BossStateTestCase CASES[] = { .input = {.name = "ambiguous boss-stage read is not the boss", .wins = 3, .opponent = {"kyurem", "mimikyu-disguised"}, .boss = "", .final_wins = 3}, .expectation = {.accepted = true, .boss = "", .boss_if_caught = ""}, }, - // TODO: to be fixed: a rental read at the boss stage is accepted, and the boss is reported caught without a fourth win. { .input = {.name = "rental read after known boss", .wins = 3, .opponent = {"mimikyu-disguised"}, .boss = "kyurem", .final_wins = 3}, - .expectation = {.accepted = true, .boss = "kyurem", .boss_if_caught = "kyurem"}, + .expectation = {.accepted = true, .boss = "kyurem", .boss_if_caught = ""}, + }, +}; + +struct FitsStageTestCaseInput{ + std::string name; + uint8_t wins; + std::set opponent; + std::string boss; +}; + +struct FitsStageTestCaseExpectation{ + bool fits; +}; + +struct FitsStageTestCase{ + FitsStageTestCaseInput input; + FitsStageTestCaseExpectation expectation; +}; + +class Test_MaxLairFitsStage : public UnitTest{ +public: + explicit Test_MaxLairFitsStage(FitsStageTestCase scenario) + : UnitTest(std::format("PokemonSwSh::MaxLairFitsStage - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const FitsStageTestCaseInput& input = m_scenario.input; + const FitsStageTestCaseExpectation& expected = m_scenario.expectation; + GlobalState state; + state.wins = input.wins; + state.opponent = input.opponent; + state.boss = input.boss; + const bool fits = state.opponent_fits_stage(); + if (fits != expected.fits){ + return std::format("Expected fits={}, got {}", expected.fits, fits); + } + return true; + } + +private: + FitsStageTestCase m_scenario; +}; + +const FitsStageTestCase FITS_STAGE_CASES[] = { + { + .input = {.name = "rental before three wins", .wins = 2, .opponent = {"mimikyu-disguised"}, .boss = ""}, + .expectation = {.fits = true}, + }, + { + .input = {.name = "boss before three wins", .wins = 2, .opponent = {"kyurem"}, .boss = ""}, + .expectation = {.fits = false}, + }, + { + .input = {.name = "rental at boss stage with unknown boss", .wins = 3, .opponent = {"mimikyu-disguised"}, .boss = ""}, + .expectation = {.fits = false}, }, - // TODO: a rental boss recorded before this fix is still reported as caught. { - .input = {.name = "fourth win after rental boss", .wins = 3, .opponent = {"mimikyu-disguised"}, .boss = "mimikyu-disguised", .final_wins = 4}, - .expectation = {.accepted = true, .boss = "mimikyu-disguised", .boss_if_caught = "mimikyu-disguised"}, + .input = {.name = "empty read at boss stage with unknown boss", .wins = 3, .opponent = {}, .boss = ""}, + .expectation = {.fits = false}, + }, + { + .input = {.name = "ambiguous read at boss stage with unknown boss", .wins = 3, .opponent = {"kyurem", "mimikyu-disguised"}, .boss = ""}, + .expectation = {.fits = false}, + }, + { + .input = {.name = "boss at boss stage", .wins = 3, .opponent = {"kyurem"}, .boss = ""}, + .expectation = {.fits = true}, + }, + { + .input = {.name = "rental at boss stage with known boss", .wins = 3, .opponent = {"mimikyu-disguised"}, .boss = "kyurem"}, + .expectation = {.fits = false}, + }, + { + .input = {.name = "known boss at boss stage", .wins = 3, .opponent = {"kyurem"}, .boss = "kyurem"}, + .expectation = {.fits = true}, + }, + { + .input = {.name = "other boss at boss stage with known boss", .wins = 3, .opponent = {"zekrom"}, .boss = "kyurem"}, + .expectation = {.fits = false}, }, }; - } void add_tests_MaxLairBossState(UnitTestDatabase& database){ for (const BossStateTestCase& scenario : CASES){ database.add(scenario); } + for (const FitsStageTestCase& scenario : FITS_STAGE_CASES){ + database.add(scenario); + } } } diff --git a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp index 3685caa3a5..2715609322 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp @@ -32,7 +32,7 @@ bool process_header_read( ){ if (mon.size() == 1){ state.opponent = std::move(mon); - return true; + return state.opponent_fits_stage(); } if (mon.size() > 1){ logger.log("Ambiguous Read Result: " + set_to_str(mon), COLOR_PURPLE); @@ -41,7 +41,7 @@ bool process_header_read( "Using previous known value to disambiguate: " + set_to_str(mon), COLOR_PURPLE ); - return true; + return state.opponent_fits_stage(); } } if (state.opponent.size() == 1){ @@ -49,7 +49,7 @@ bool process_header_read( "Failed to read opponent from battle. Using previously known value: " + set_to_str(state.opponent), COLOR_ORANGE ); - return true; + return state.opponent_fits_stage(); } return false; @@ -75,14 +75,6 @@ bool read_battle_menu( std::set mon = reader.read_opponent(stream.logger(), context, stream.video()); bool retry = !process_header_read(stream.logger(), state, std::move(mon)); - std::string opponent = state.opponent.empty() - ? "" - : *state.opponent.begin(); - - // If we see a boss before the end. Something is wrong. Retry. - if (state.wins != 3 && is_boss(opponent)){ - retry = true; - } VideoSnapshot snapshot; if (retry){ @@ -363,14 +355,14 @@ StateMachineAction throw_balls( state.players[2].health.value.dead = 0; state.players[3].health.value.dead = 0; - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - std::string ball; bool boss = inferred.wins == 4; if (boss){ + // This will crash if `inferred.boss` is still empty after battle-screen + // and the fallback summary read (OCR misses). ball = decider.boss_ball(console_index, inferred.boss); }else{ ball = decider.normal_ball(console_index); From e5b317294af4956b94516508b64a6a1561bce43e Mon Sep 17 00:00:00 2001 From: Dalton <59972310+Dalton-V@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:33:44 -0600 Subject: [PATCH 32/85] Support different game languages (#1904) --- .../PokemonFRLG_BoxOrganization.cpp | 10 +++++----- .../PokemonFRLG_BoxOrganization.h | 3 ++- .../BoxOrganization/PokemonFRLG_BoxSorter.cpp | 20 ++++++++++++++++--- .../BoxOrganization/PokemonFRLG_BoxSorter.h | 2 ++ .../PokemonFRLG_BoxSorterLivingDex.cpp | 20 ++++++++++++++++--- .../PokemonFRLG_BoxSorterLivingDex.h | 2 ++ 6 files changed, 45 insertions(+), 12 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp index 20854d4936..bfdbfab3f4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp @@ -166,7 +166,7 @@ void open_summary_screen(SingleSwitchProgramEnvironment& env, ProControllerConte // Currently only reads shininess, but could be extended to read other summary information. void scan_box_summaries( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const BoxSelectionModeDetector& selection_detector, BoxCursor& cursor, + Language language, const BoxSelectionModeDetector& selection_detector, BoxCursor& cursor, std::vector>& boxes_data ){ const size_t box_start = cursor.box * BOX_ROWS * BOX_COLS; @@ -194,7 +194,7 @@ void scan_box_summaries( auto& pokemon = *boxes_data[index]; const VideoSnapshot screen = env.console.video().snapshot(); PokemonFRLG_Stats current_stats; - reader.read_page1(env.logger(), Language::English, screen, current_stats); + reader.read_page1(env.logger(), language, screen, current_stats); if (current_stats.name != pokemon.name_slug || current_stats.level != pokemon.level){ std::ostringstream ss; ss << "Box Sorter: Summary species mismatch at " << BoxCursor(index) @@ -421,7 +421,7 @@ std::string make_missing_living_dex_report( BoxOrganizationScan scan_box_data( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::vector& preferences, size_t num_boxes, bool read_shininess + Language language, const std::vector& preferences, size_t num_boxes, bool read_shininess ){ bool read_summary = read_shininess || std::any_of(preferences.begin(), preferences.end(), [](const SortingRule& rule){ return rule.sort_type == SortingRuleType::Shiny; @@ -496,7 +496,7 @@ BoxOrganizationScan scan_box_data( continue; } - const std::string name = cell_reader.read_name(env.logger(), Language::English, screen); + const std::string name = cell_reader.read_name(env.logger(), language, screen); const int level = cell_reader.read_level(env.logger(), screen); const auto& dex_numbers = SLUGS_TO_NATIONAL_DEX(); const auto dex = dex_numbers.find(name); @@ -521,7 +521,7 @@ BoxOrganizationScan scan_box_data( env.update_stats(); } if (read_summary){ - scan_box_summaries(env, context, selection_detector, cursor, boxes_data); + scan_box_summaries(env, context, language, selection_detector, cursor, boxes_data); } } return {std::move(boxes_data), cursor, scan_mode}; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h index 27dc430f2e..b2401191e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h @@ -11,6 +11,7 @@ #include #include #include +#include "CommonFramework/Language.h" #include "CommonFramework/ProgramStats/StatsTracking.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Pokemon_BoxCursor.h" @@ -77,7 +78,7 @@ struct BoxOrganizationScan{ // Detecting Shiny requires reading the summary screen, this is much slower than just reading the box data. BoxOrganizationScan scan_box_data( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::vector& preferences, size_t num_boxes, + Language language, const std::vector& preferences, size_t num_boxes, bool read_shininess = false ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp index fdf5b5f545..6c2f7edbf5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp @@ -32,7 +32,7 @@ BoxSorter_Descriptor::BoxSorter_Descriptor() Pokemon::STRING_POKEMON + " FRLG", "Box Sorter", "Programs/PokemonFRLG/BoxSorter.html", "Sort boxes of " + STRING_POKEMON + ". Start in Move " + STRING_POKEMON + - " with an empty hand in the first box to sort. Uses English species names.", + " with an empty hand in the first box to sort.", PanelQualityStanding::OFFICIAL_BETA, ProgramControllerClass::StandardController_NoRestrictions, FeedbackType::REQUIRED, @@ -46,7 +46,20 @@ std::unique_ptr BoxSorter_Descriptor::make_stats() const{ } BoxSorter::BoxSorter() - : NUM_BOXES( + : LANGUAGE( + "Game Language:
Select the language of your game so the program can read " + STRING_POKEMON + " species names.", + { + Language::English, + Language::Japanese, + Language::Spanish, + Language::French, + Language::German, + Language::Italian, + }, + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NUM_BOXES( "Number of Boxes to Sort:
Starting with the current box and continuing to the right.", LockMode::LOCK_WHILE_RUNNING, 1, 1, MAX_BOXES ) @@ -61,6 +74,7 @@ BoxSorter::BoxSorter() ) , NOTIFICATIONS({&NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_FATAL}) { + PA_ADD_OPTION(LANGUAGE); PA_ADD_OPTION(NUM_BOXES); PA_ADD_OPTION(SORT_TABLE); PA_ADD_OPTION(DRY_RUN); @@ -76,7 +90,7 @@ void BoxSorter::program(SingleSwitchProgramEnvironment& env, ProControllerContex } auto& stats = env.current_stats(); - BoxOrganizationScan scan = scan_box_data(env, context, preferences, (uint16_t)NUM_BOXES); + BoxOrganizationScan scan = scan_box_data(env, context, LANGUAGE, preferences, (uint16_t)NUM_BOXES); const auto& boxes_data = scan.boxes_data; // Stable ordering avoids unnecessary moves for Pokemon with identical sort keys. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.h index af5234576c..2e7882b466 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.h @@ -11,6 +11,7 @@ #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/SimpleIntegerOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_BoxSortingTable.h" @@ -39,6 +40,7 @@ class BoxSorter : public SingleSwitchProgramInstance{ private: + OCR::LanguageOCROption LANGUAGE; SimpleIntegerOption NUM_BOXES; Pokemon::BoxSortingTable SORT_TABLE; BooleanCheckBoxOption DRY_RUN; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp index ca0dd79326..aa48844633 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp @@ -28,7 +28,7 @@ BoxSorterLivingDex_Descriptor::BoxSorterLivingDex_Descriptor() STRING_POKEMON + " FRLG", "Box Sorter Living Dex", "Programs/PokemonFRLG/BoxSorterLivingDex.html", "Arrange boxes of " + STRING_POKEMON + " into living dex order. Start in Move " + STRING_POKEMON + - " with an empty hand in the first box to organize. Uses English species names.", + " with an empty hand in the first box to organize.", PanelQualityStanding::OFFICIAL_BETA, ProgramControllerClass::StandardController_NoRestrictions, FeedbackType::REQUIRED, @@ -41,7 +41,20 @@ std::unique_ptr BoxSorterLivingDex_Descriptor::make_stats() const{ } BoxSorterLivingDex::BoxSorterLivingDex() - : NUM_BOXES( + : LANGUAGE( + "Game Language:
Select the language of your game so the program can read " + STRING_POKEMON + " species names.", + { + Language::English, + Language::Japanese, + Language::Spanish, + Language::French, + Language::German, + Language::Italian, + }, + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NUM_BOXES( "Number of Boxes to Organize:
Starting with the current box and continuing to the right. " "Include room after the template for duplicates and other Pokemon.", LockMode::LOCK_WHILE_RUNNING, 8, 1, 14 @@ -63,6 +76,7 @@ BoxSorterLivingDex::BoxSorterLivingDex() ) , NOTIFICATIONS({&NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_FATAL}) { + PA_ADD_OPTION(LANGUAGE); PA_ADD_OPTION(NUM_BOXES); PA_ADD_OPTION(LIVING_DEX_TEMPLATE); PA_ADD_OPTION(SHINY_DEX); @@ -96,7 +110,7 @@ void BoxSorterLivingDex::program(SingleSwitchProgramEnvironment& env, ProControl const std::vector preferences{{SortingRuleType::DexNo, false}}; auto& stats = env.current_stats(); const bool shiny_dex = SHINY_DEX; - BoxOrganizationScan scan = scan_box_data(env, context, preferences, (uint16_t)NUM_BOXES, shiny_dex); + BoxOrganizationScan scan = scan_box_data(env, context, LANGUAGE, preferences, (uint16_t)NUM_BOXES, shiny_dex); const auto boxes_sorted = make_living_dex_order( env.logger(), scan.boxes_data, living_dex_order, obey_gender_differences, shiny_dex ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.h index 91bc2c9902..d60b6b456f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.h @@ -12,6 +12,7 @@ #include "Common/Cpp/Options/EnumDropdownOption.h" #include "Common/Cpp/Options/SimpleIntegerOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" namespace PokemonAutomation{ class Logger; } @@ -43,6 +44,7 @@ class BoxSorterLivingDex : public SingleSwitchProgramInstance{ Condensed, }; + OCR::LanguageOCROption LANGUAGE; SimpleIntegerOption NUM_BOXES; EnumDropdownOption LIVING_DEX_TEMPLATE; BooleanCheckBoxOption SHINY_DEX; From 8d67694a4797ba188eac0127ef66f36043b31011 Mon Sep 17 00:00:00 2001 From: Dalton <59972310+Dalton-V@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:35:44 -0600 Subject: [PATCH 33/85] Home - Detect Selection Hand (#1903) --- .../PokemonHome_SelectionArrowDetector.cpp | 239 +++++++++++++++--- 1 file changed, 210 insertions(+), 29 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_SelectionArrowDetector.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_SelectionArrowDetector.cpp index c7aad61df6..6c319c5a98 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_SelectionArrowDetector.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_SelectionArrowDetector.cpp @@ -9,6 +9,7 @@ #include "Kernels/Waterfill/Kernels_Waterfill_Types.h" #include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" #include "CommonTools/Images/WaterfillUtilities.h" @@ -20,11 +21,12 @@ namespace NintendoSwitch{ namespace PokemonHome{ namespace{ -const ImageFloatBox ARROW_SEARCH_BOX(0.02, 0.085, 0.47, 0.69); +const ImageFloatBox SELECTION_SEARCH_BOX(0.02, 0.085, 0.47, 0.69); +const ImageFloatBox MODE_ICON_BORDER(0.495, 0.005, 0.010, 0.006); -class SelectionArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +class SelectionCursorMatcher : public ImageMatch::WaterfillTemplateMatcher{ public: - SelectionArrowMatcher(const char* path, Color min_color, Color max_color) + SelectionCursorMatcher(const char* path, Color min_color, Color max_color) : WaterfillTemplateMatcher(path, min_color, max_color, 100) { m_aspect_ratio_lower = 0.8; @@ -35,7 +37,7 @@ class SelectionArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ }; struct ArrowStyle{ - SelectionArrowMatcher matcher; + SelectionCursorMatcher matcher; BoxSelectionMode mode; bool down; uint32_t min_color; @@ -60,38 +62,112 @@ const auto& arrow_styles(){ return styles; } +// Arrows have a slightly different starting Y compared to the hand. +std::optional grid_selection_at( + const ImageFloatBox& cursor, double first_row_y, BoxSelectionMode mode +){ + constexpr double FIRST_COLUMN_X = 0.075; + constexpr double COLUMN_SPACING = 0.072; + constexpr double ROW_SPACING = 0.1055; + const double center_x = cursor.x + cursor.width / 2; + const double center_y = cursor.y + cursor.height / 2; + const int column = (int)std::lround((center_x - FIRST_COLUMN_X) / COLUMN_SPACING); + const int row = (int)std::lround((center_y - first_row_y) / ROW_SPACING); + if (column < 0 || column >= 6 || row < 0 || row >= 5){ + return std::nullopt; + } + if (std::abs(center_x - (FIRST_COLUMN_X + column * COLUMN_SPACING)) > 0.015 + || std::abs(center_y - (first_row_y + row * ROW_SPACING)) > 0.025){ + return std::nullopt; + } + return BoxSelection{mode, BoxSelectionLocation::Grid, (size_t)row, (size_t)column}; +} + std::optional selection_at(const ImageFloatBox& arrow, const ArrowStyle& style){ + // Right arrows are used for buttons outside the grid. + if (style.down){ + constexpr double FIRST_COLUMN_Y = 0.16; + return grid_selection_at(arrow, FIRST_COLUMN_Y, style.mode); + } + const double center_x = arrow.x + arrow.width / 2; const double center_y = arrow.y + arrow.height / 2; - if (!style.down){ - if (std::abs(center_y - 0.123) < 0.025 && std::abs(center_x - 0.12) < 0.025){ - return BoxSelection{style.mode, BoxSelectionLocation::BoxName}; + if (std::abs(center_y - 0.123) < 0.025 && std::abs(center_x - 0.12) < 0.025){ + return BoxSelection{style.mode, BoxSelectionLocation::BoxName}; + } + if (std::abs(center_y - 0.738) < 0.025){ + if (std::abs(center_x - 0.18) < 0.025){ + return BoxSelection{style.mode, BoxSelectionLocation::BoxSpaces}; } - if (std::abs(center_y - 0.738) < 0.025){ - if (std::abs(center_x - 0.18) < 0.025){ - return BoxSelection{style.mode, BoxSelectionLocation::BoxSpaces}; - } - if (std::abs(center_x - 0.332) < 0.025){ - return BoxSelection{style.mode, BoxSelectionLocation::Newest30}; - } + if (std::abs(center_x - 0.332) < 0.025){ + return BoxSelection{style.mode, BoxSelectionLocation::Newest30}; } - return std::nullopt; } + return std::nullopt; +} - constexpr double FIRST_GRID_ARROW_X = 0.075; - constexpr double FIRST_GRID_ARROW_Y = 0.16; - constexpr double COLUMN_SPACING = 0.072; - constexpr double ROW_SPACING = 0.1055; - const int column = (int)std::lround((center_x - FIRST_GRID_ARROW_X) / COLUMN_SPACING); - const int row = (int)std::lround((center_y - FIRST_GRID_ARROW_Y) / ROW_SPACING); - if (column < 0 || column >= 6 || row < 0 || row >= 5){ - return std::nullopt; +std::optional hand_selection_mode(const ImageViewRGB32& screen){ + // The hand is white in every mode. The active toolbar icon has a colored border. + const FloatPixel color = image_average(extract_box_reference(screen, MODE_ICON_BORDER)); + if (color.r > 170 && color.g < 120 && color.b < 120){ + return BoxSelectionMode::Normal; + } + if (color.r < 125 && color.g > 90 && color.b > 170){ + return BoxSelectionMode::Relocate; + } + if (color.r < 125 && color.g > 145 && color.b < 140){ + return BoxSelectionMode::Multi; } - if (std::abs(center_x - (FIRST_GRID_ARROW_X + column * COLUMN_SPACING)) > 0.015 - || std::abs(center_y - (FIRST_GRID_ARROW_Y + row * ROW_SPACING)) > 0.025){ + return std::nullopt; +} + +std::optional detect_hand( + const ImageViewRGB32& screen, const ImageViewRGB32& region, double screen_rel_size +){ + const auto mode = hand_selection_mode(screen); + if (!mode){ return std::nullopt; } - return BoxSelection{style.mode, BoxSelectionLocation::Grid, (size_t)row, (size_t)column}; + + constexpr double FIRST_COLUMN_Y = 0.174; + constexpr uint32_t MIN_WHITE = 0xffdcdcdc; + static const SelectionCursorMatcher matcher( + "PokemonHome/SelectionArrows/SelectionHand.png", Color(MIN_WHITE), COLOR_WHITE + ); + const double area_scale = screen_rel_size * screen_rel_size; + const size_t min_area = std::max(1, size_t(area_scale * 700)); + const size_t max_area = std::max(min_area, size_t(area_scale * 2200)); + double best_rmsd = 40; + std::optional best; + match_template_by_waterfill( + screen.size(), region, matcher, {{MIN_WHITE, 0xffffffff}}, {min_area, max_area}, best_rmsd, + [&](Kernels::Waterfill::WaterfillObject& object){ + const ImageFloatBox hand = translate_to_parent(screen, SELECTION_SEARCH_BOX, object); + if (hand.width < 0.017 || hand.width > 0.029 || hand.height < 0.034 || hand.height > 0.057){ + return false; + } + const auto selection = grid_selection_at(hand, FIRST_COLUMN_Y, *mode); + if (!selection){ + return false; + } + + // Verify black pixels at the wrist. Ensuring we don't detect a blob of white pixels. + const ImageFloatBox wrist_outline( + hand.x + hand.width * 0.4, hand.y - hand.height * 0.065, + hand.width * 0.2, hand.height * 0.04 + ); + if (image_average(extract_box_reference(screen, wrist_outline)).sum() > 300){ + return false; + } + const double rmsd = matcher.rmsd_original(screen.size(), region, object); + if (rmsd < best_rmsd){ + best_rmsd = rmsd; + best = selection; + } + return false; + } + ); + return best; } std::string selection_string(const std::optional& selection){ @@ -126,12 +202,17 @@ std::string selection_string(const std::optional& selection){ } void SelectionArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, ARROW_SEARCH_BOX); + items.add(m_color, SELECTION_SEARCH_BOX); + items.add(m_color, MODE_ICON_BORDER); } std::optional SelectionArrowDetector::detect(const ImageViewRGB32& screen) const{ - const ImageViewRGB32 region = extract_box_reference(screen, ARROW_SEARCH_BOX); + const ImageViewRGB32 region = extract_box_reference(screen, SELECTION_SEARCH_BOX); const double screen_rel_size = screen.height() / 1080.0; + if (auto hand = detect_hand(screen, region, screen_rel_size)){ + return hand; + } + const size_t min_area = std::max(1, size_t(screen_rel_size * screen_rel_size * 500)); double best_rmsd = 80; std::optional best; @@ -140,7 +221,7 @@ std::optional SelectionArrowDetector::detect(const ImageViewRGB32& screen.size(), region, style.matcher, {{style.min_color, style.max_color}}, {min_area, SIZE_MAX}, best_rmsd, [&](Kernels::Waterfill::WaterfillObject& object){ - const ImageFloatBox arrow = translate_to_parent(screen, ARROW_SEARCH_BOX, object); + const ImageFloatBox arrow = translate_to_parent(screen, SELECTION_SEARCH_BOX, object); if (arrow.width < 0.01 || arrow.width > 0.035 || arrow.height < 0.015 || arrow.height > 0.065){ return false; } @@ -262,6 +343,106 @@ void add_tests_SelectionArrowDetector(UnitTestDatabase& database){ database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_11.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::BoxSpaces, 0, 0}); database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxName_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::BoxName, 0, 0}); database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxName_02.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::BoxName, 0, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row1_Column5_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row4_Column0_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 4, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row0_Column5_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 0, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row0_Column4_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row0_Column0_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row3_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 3, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column5_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 5}); + database.add("PokemonHome/BoxView/SelectionArrow_None_01.png", std::nullopt); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row1_Column3_03.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column0_02.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column2_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxName_03.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::BoxName, 0, 0}); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxName_06.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::BoxName, 0, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row1_Column5_02.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row1_Column3_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row4_Column1_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 4, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row4_Column4_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 4, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row3_Column5_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 3, 5}); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row0_Column4_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 0, 4}); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row0_Column4_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row0_Column1_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column0_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column4_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column4_02.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column3_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column0_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row1_Column0_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 1, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row0_Column2_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row0_Column3_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 3}); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row0_Column4_02.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 4}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row0_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 4}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row3_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 3, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row3_Column5_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 3, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column5_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column5_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row0_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row0_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_10.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::BoxSpaces, 0, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column3_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 3}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Newest30_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Newest30, 0, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column5_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row0_Column5_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row0_Column5_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row0_Column1_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row1_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row1_Column2_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row1_Column2_03.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column4_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column5_03.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row0_Column1_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 0, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column1_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 1}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row1_Column2_04.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column3_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 3}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column3_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column4_03.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column4_04.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column3_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column2_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row4_Column2_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 4, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column2_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row1_Column5_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row0_Column5_02.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 0, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row0_Column5_03.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 0, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row3_Column1_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 3, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row3_Column2_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 3, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row1_Column3_02.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 3}); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row2_Column1_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 2, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column1_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row3_Column5_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 3, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column4_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row3_Column4_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 3, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column3_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row1_Column3_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 1, 3}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row0_Column0_02.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row0_Column0_03.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 0, 0}); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row4_Column0_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column0_03.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column0_04.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 0}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row4_Column1_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 4, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column1_02.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row2_Column1_03.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Relocate_Grid_Row1_Column2_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row2_Column2_01.png", BoxSelection{BoxSelectionMode::Relocate, BoxSelectionLocation::Grid, 2, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row2_Column4_05.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column4_02.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 4}); + database.add("PokemonHome/BoxView/SelectionHand_Multi_Grid_Row1_Column4_03.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 1, 4}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column4_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 4}); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column5_01.png", BoxSelection{BoxSelectionMode::Multi, BoxSelectionLocation::Grid, 2, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row2_Column5_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 2, 5}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row3_Column1_02.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 3, 1}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row4_Column2_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 4, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row4_Column2_02.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 4, 2}); + database.add("PokemonHome/BoxView/SelectionHand_Normal_Grid_Row1_Column2_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 1, 2}); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row3_Column2_01.png", BoxSelection{BoxSelectionMode::Normal, BoxSelectionLocation::Grid, 3, 2}); database.add("PokemonHome/SummaryScreen/annihilape_Regular.png", std::nullopt); database.add("PokemonHome/SummaryScreen/bidoof_Regular.png", std::nullopt); database.add("PokemonHome/SummaryScreen/bulbasaur_Regular.png", std::nullopt); From 5d80115640d9a86dd16aa7b9cb522cbf1081a8c8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 08:24:43 -0800 Subject: [PATCH 34/85] System keyboard: read every key, robust detector and field checks, checked typing Review of #62: - The cursor reader covers the right column (backspace, Return, OK) and the bottom row; the typer steps back onto the character grid from there. - The detector's key-panel check uses two strips (rows 0/1 and 2/3), so a cursor anywhere can only spoil one of them. - system_keyboard_field_has_text() reads the backspace key (dark with text), not the field over the game's background. - The typer checks every character before the first press (UserSetupError), logs the cursor read and the moves of each try, names the last cursor and the target in its error, and checks that each key press adds white pixels to the field. - Presses use the code entry hold for Switch 1; the read-back waits stay fixed. - read_system_keyboard_cursor() returns std::optional. - Tests derive ImageUnitTest, add six Legends: Z-A frames (en/fr/de/it/ja/es) and list the screens still to capture, which are added once their file exists. - Headers state the supported keyboards (Latin QWERTY/AZERTY), Korean and Chinese out of scope, Switch 2 untested. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../NintendoSwitch_SystemKeyboardDetector.cpp | 244 +++++++++++++----- .../NintendoSwitch_SystemKeyboardDetector.h | 57 +++- .../NintendoSwitch_KeyboardCodeEntry.h | 2 +- .../NintendoSwitch_SystemKeyboardTyping.cpp | 225 +++++++++++++--- .../NintendoSwitch_SystemKeyboardTyping.h | 36 ++- 5 files changed, 432 insertions(+), 132 deletions(-) diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp index 428abbafa3..4f0e37dedf 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp @@ -5,137 +5,249 @@ */ #include +#include +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Images/SolidColorTest.h" +#include "Tests/ImageUnitTest.h" #include "NintendoSwitch_SystemKeyboardDetector.h" namespace PokemonAutomation{ namespace NintendoSwitch{ -// Centres of the four rows of character keys, and of the first column and the -// spacing between columns, as fractions of the screen. -static constexpr double KEY_ROW_Y[] = {0.500, 0.593, 0.681, 0.770}; -static constexpr double KEY_COL_X0 = 0.077; -static constexpr double KEY_COL_STEP = 0.075; +namespace{ + +// Centres of the five rows of keys, and of the first column and the spacing +// between columns, as fractions of the screen. +constexpr double KEY_ROW_Y[] = {0.500, 0.593, 0.681, 0.770, 0.858}; +constexpr double KEY_COL_X0 = 0.077; +constexpr double KEY_COL_STEP = 0.075; + +// In the right column, Return spans rows 1-2 and OK rows 3-4. These are the +// gaps between those keys. +constexpr double RIGHT_COLUMN_RETURN_TOP = 0.548; +constexpr double RIGHT_COLUMN_OK_TOP = 0.725; + +// The cursor border and everything else the reader looks at, from the top of the +// digit row to the bottom of the bottom row. +const ImageFloatBox KEYS_AREA(0.0, 0.43, 1.0, 0.49); + +// The cursor border is cyan (about 80, 230, 210). +bool is_cursor_pixel(uint32_t pixel){ + const int red = (pixel >> 16) & 0xff; + const int green = (pixel >> 8) & 0xff; + const int blue = pixel & 0xff; + return red < 150 && green > 200 && blue > 190; +} + +uint8_t nearest_row(double y){ + uint8_t row = 0; + for (uint8_t r = 1; r < 5; r++){ + if (std::abs(KEY_ROW_Y[r] - y) < std::abs(KEY_ROW_Y[row] - y)){ + row = r; + } + } + return row; +} + +// The key whose cursor border has its centre at (x, y), or nothing if that is +// off the keyboard. +std::optional key_at(double x, double y){ + const long col = std::lround((x - KEY_COL_X0) / KEY_COL_STEP); + if (col < 0 || col > 11){ + return std::nullopt; + } + if (col < 11){ + return SystemKeyboardKey{nearest_row(y), (uint8_t)col}; + } + if (y < RIGHT_COLUMN_RETURN_TOP){ + return SystemKeyboardKey{0, 11}; + } + if (y < RIGHT_COLUMN_OK_TOP){ + return SystemKeyboardKey{1, 11}; + } + return SystemKeyboardKey{3, 11}; +} + +} // namespace + SystemKeyboardDetector::SystemKeyboardDetector(Color color) : m_color(color) - , m_key_panel(0.15, 0.555, 0.65, 0.020) + , m_key_panel_upper(0.15, 0.532, 0.65, 0.036) + , m_key_panel_lower(0.15, 0.715, 0.65, 0.032) , m_bottom_bar(0.10, 0.935, 0.35, 0.030) , m_ok_button(0.875, 0.760, 0.045, 0.020) {} void SystemKeyboardDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_key_panel); + items.add(m_color, m_key_panel_upper); + items.add(m_color, m_key_panel_lower); items.add(m_color, m_bottom_bar); items.add(m_color, m_ok_button); } bool SystemKeyboardDetector::detect(const ImageViewRGB32& screen){ - if (!is_white(extract_box_reference(screen, m_key_panel)) || - !is_white(extract_box_reference(screen, m_bottom_bar)) - ){ + // Each strip crosses white keys and the slightly brighter gaps between them, + // which gives a stddev sum of about 11 (measured on BDSP and Legends: Z-A). + const double max_panel_stddev = 20; + const bool panel = + is_white(extract_box_reference(screen, m_key_panel_upper), 500, max_panel_stddev) || + is_white(extract_box_reference(screen, m_key_panel_lower), 500, max_panel_stddev); + if (!panel || !is_white(extract_box_reference(screen, m_bottom_bar))){ return false; } - // OK is blue, or flat grey while the field is empty (disabled). + // OK is blue (40, 93, 255), or flat grey (221, 221, 221) while the field is + // empty (disabled). Measured on BDSP and Legends: Z-A. const ImageStats ok = image_stats(extract_box_reference(screen, m_ok_button)); - return is_solid(ok, {0.172, 0.276, 0.552}) || is_grey(ok, 600, 690); + return is_solid(ok, {0.103, 0.240, 0.657}) || is_grey(ok, 600, 690); } -bool find_system_keyboard_cursor(const ImageViewRGB32& screen, int& row, int& col){ +std::optional read_system_keyboard_cursor(const ImageViewRGB32& screen){ // The cursor is a cyan border around one key. Neighbouring keys overlap that border, // so take the centroid of all cyan pixels and map it to the nearest key. - const ImageFloatBox area(0.02, 0.44, 0.84, 0.38); - ImageViewRGB32 keys = extract_box_reference(screen, area); + const ImageViewRGB32 keys = extract_box_reference(screen, KEYS_AREA); double count = 0, sum_x = 0, sum_y = 0; for (size_t y = 0; y < keys.height(); y++){ for (size_t x = 0; x < keys.width(); x++){ - const uint32_t pixel = keys.pixel(x, y); - const int red = (pixel >> 16) & 0xff; - const int green = (pixel >> 8) & 0xff; - const int blue = pixel & 0xff; - if (red < 150 && green > 200 && blue > 190){ + if (is_cursor_pixel(keys.pixel(x, y))){ count++; sum_x += (double)x; sum_y += (double)y; } } } - // The border is about 0.15% of the screen; a few stray pixels are not a cursor. + // The border is about 0.18% of the screen; a few stray pixels are not a cursor. if (count < 0.0005 * screen.width() * screen.height()){ - return false; + return std::nullopt; } - const double cx = area.x + sum_x / count / keys.width() * area.width; - const double cy = area.y + sum_y / count / keys.height() * area.height; - col = (int)std::lround((cx - KEY_COL_X0) / KEY_COL_STEP); - row = 0; - for (int r = 1; r < 4; r++){ - if (std::abs(KEY_ROW_Y[r] - cy) < std::abs(KEY_ROW_Y[row] - cy)){ - row = r; - } - } - return 0 <= col && col < 11; + return key_at( + KEYS_AREA.x + sum_x / count / keys.width() * KEYS_AREA.width, + KEYS_AREA.y + sum_y / count / keys.height() * KEYS_AREA.height + ); } bool system_keyboard_field_has_text(const ImageViewRGB32& screen){ - // Left part of the field, after the caret's position on an empty field. - const ImageStats stats = image_stats(extract_box_reference(screen, ImageFloatBox(0.11, 0.235, 0.19, 0.030))); - return stats.stddev.sum() > 30; + // Left part of the backspace key, clear of its icon and of the cursor border. + // Light grey (221) with an empty field, dark grey (52) with text. + const ImageStats stats = image_stats(extract_box_reference(screen, ImageFloatBox(0.878, 0.470, 0.008, 0.060))); + return stats.average.sum() < 400; +} + +size_t system_keyboard_text_pixels(const ImageViewRGB32& screen){ + // The field, above its underline, which is white in some games. + const ImageViewRGB32 field = extract_box_reference(screen, ImageFloatBox(0.03, 0.17, 0.87, 0.105)); + size_t count = 0; + for (size_t y = 0; y < field.height(); y++){ + for (size_t x = 0; x < field.width(); x++){ + const uint32_t pixel = field.pixel(x, y); + if (((pixel >> 16) & 0xff) > 190 && ((pixel >> 8) & 0xff) > 190 && (pixel & 0xff) > 190){ + count++; + } + } + } + return count; } + +namespace{ + // One screenshot and what each function should read from it. -class Test_SystemKeyboardDetector : public UnitTest{ +class Test_SystemKeyboardDetector : public ImageUnitTest{ public: - // cursor_row/col: -1 for a screen without the keyboard. - Test_SystemKeyboardDetector(const std::string& image, bool keyboard, int cursor_row, int cursor_col, bool has_text) - : UnitTest("NintendoSwitch::SystemKeyboardDetector - " + image) - , m_image(UNIT_TEST_RESOURCE_PATH() + image) - , m_keyboard(keyboard) - , m_cursor_row(cursor_row) - , m_cursor_col(cursor_col) + // `cursor`: the key under the cursor, or nothing for a screen without the keyboard. + Test_SystemKeyboardDetector(const std::string& image, std::optional cursor, bool has_text) + : ImageUnitTest(std::format("NintendoSwitch::SystemKeyboardDetector - {}", image), {image}) + , m_cursor(cursor) , m_has_text(has_text) {} - virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ - ImageRGB32 image(m_image); - if (SystemKeyboardDetector().detect(image) != m_keyboard){ - return false; + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + const ImageRGB32& image = images[0]; + const bool keyboard = SystemKeyboardDetector().detect(image); + if (keyboard != m_cursor.has_value()){ + return std::format("detect() returned {}.", keyboard); } - if (!m_keyboard){ + if (!keyboard){ return true; } - int row = -1; - int col = -1; - return find_system_keyboard_cursor(image, row, col) - && row == m_cursor_row && col == m_cursor_col - && system_keyboard_field_has_text(image) == m_has_text; + const std::optional cursor = read_system_keyboard_cursor(image); + if (cursor != m_cursor){ + return cursor + ? std::format("Read the cursor at ({}, {}).", cursor->row, cursor->col) + : std::format("Read no cursor."); + } + const bool has_text = system_keyboard_field_has_text(image); + if (has_text != m_has_text){ + return std::format("system_keyboard_field_has_text() returned {}.", has_text); + } + // An empty field has no white text pixels; one typed character has many. + const size_t text_pixels = system_keyboard_text_pixels(image); + if ((text_pixels >= 20) != m_has_text){ + return std::format("system_keyboard_text_pixels() returned {}.", text_pixels); + } + return true; } private: - std::string m_image; - bool m_keyboard; - int m_cursor_row; - int m_cursor_col; + std::optional m_cursor; bool m_has_text; }; +} // namespace + void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ - const std::string folder = "NintendoSwitch/SystemKeyboardDetector/"; + const auto path = [](std::string_view image){ + return std::format("NintendoSwitch/SystemKeyboardDetector/{}", image); + }; + const SystemKeyboardKey key_1{0, 0}; // The OK button is blue with text in the field and grey without. - database.add(folder + "BDSP-PlayerName-Empty.png", true, 0, 0, false); - database.add(folder + "BDSP-FriendName-Typed.png", true, 0, 0, true); - database.add(folder + "BDSP-Dialog.png", false, -1, -1, false); - database.add(folder + "HomeMenu.png", false, -1, -1, false); - database.add(folder + "HomeMenu-OnlineLicensePopup.png", false, -1, -1, false); - database.add(folder + "UserSelect.png", false, -1, -1, false); + database.add(path("BDSP-PlayerName-Empty.png"), key_1, false); + database.add(path("BDSP-FriendName-Typed.png"), key_1, true); + for (std::string_view language : {"English", "French", "German", "Italian", "Japanese", "Spanish"}){ + database.add(path(std::format("PLZA-{}-Empty.png", language)), key_1, false); + } + for (std::string_view image : {"BDSP-Dialog.png", "HomeMenu.png", "HomeMenu-OnlineLicensePopup.png", "UserSelect.png"}){ + database.add(path(image), std::nullopt, false); + } + + // Screens still to be captured. Each test is added once its image is in the + // test repo. + struct Planned{ + std::string_view image; + std::optional cursor; + bool has_text; + }; + const Planned planned[] = { + {"PLZA-Cursor-3.png", SystemKeyboardKey{0, 2}, false}, + {"PLZA-Cursor-T.png", SystemKeyboardKey{1, 4}, false}, + {"PLZA-Cursor-Minus.png", SystemKeyboardKey{0, 10}, false}, + {"PLZA-Cursor-Backspace.png", SystemKeyboardKey{0, 11}, true}, + {"PLZA-Cursor-OK.png", SystemKeyboardKey{3, 11}, true}, + {"PLZA-Cursor-Space.png", SystemKeyboardKey{4, 8}, false}, + {"AZERTY-Empty.png", key_1, false}, + {"PLZA-Korean.png", std::nullopt, false}, + }; + for (const Planned& test : planned){ + const std::string image = path(test.image); + if (Filesystem::exists(std::format("{}{}", UNIT_TEST_RESOURCE_PATH(), image))){ + database.add(image, test.cursor, test.has_text); + } + } } -} -} +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h index 7a2952a2ce..5c7e837eaf 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h @@ -3,18 +3,24 @@ * From: https://github.com/PokemonAutomation/ * * The Switch's own on-screen keyboard, which games open for names (e.g. the - * player's name in BDSP): detect it, find the key under its cursor, and tell - * whether its text field is empty. Typing with it is in + * player's name in BDSP and in Legends: Z-A): detect it, read the key under its + * cursor, and tell whether its text field is empty. Typing with it is in * Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h. * - * Measured on 1920x1080 captures of the QWERTY layout. + * Supported: the Latin keyboard (QWERTY; AZERTY shares the key grid but has no + * test screenshot yet). Measured on 1920x1080 Switch 1 captures of BDSP's and + * Legends: Z-A's name entry, the latter in English, Spanish, German, Italian, + * French and Japanese. Not supported: the Korean keyboard, whose candidate strip + * moves the keys down (the detector returns false on it), and probably the + * Chinese ones (not tested). Switch 2 is not tested. * */ #ifndef PokemonAutomation_NintendoSwitch_SystemKeyboardDetector_H #define PokemonAutomation_NintendoSwitch_SystemKeyboardDetector_H -#include +#include +#include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonTools/VisualDetector.h" @@ -23,8 +29,8 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ -// White key panel and bottom bar, and the OK button (blue, or grey while the -// field is empty). +// The white key panel, the white bar below it, and the OK button (blue, or grey +// while the field is empty). Works wherever the cursor is. class SystemKeyboardDetector : public StaticScreenDetector{ public: SystemKeyboardDetector(Color color = COLOR_CYAN); @@ -34,10 +40,16 @@ class SystemKeyboardDetector : public StaticScreenDetector{ private: Color m_color; - ImageFloatBox m_key_panel; + // Two strips across the key panel, one over the gap between rows 0 and 1 and + // one over the gap between rows 2 and 3. The cursor's border reaches into at + // most one of them, so the panel is white if either is. + ImageFloatBox m_key_panel_upper; + ImageFloatBox m_key_panel_lower; ImageFloatBox m_bottom_bar; ImageFloatBox m_ok_button; }; + +// Finds SystemKeyboardDetector on the video, checking every 250 ms. class SystemKeyboardWatcher : public DetectorToFinder{ public: SystemKeyboardWatcher(Color color = COLOR_CYAN) @@ -46,21 +58,40 @@ class SystemKeyboardWatcher : public DetectorToFinder{ }; -// The key under the cursor, as row (0: digits .. 3: "zxcv") and column (0..10). +// A key of the keyboard. +// Rows 0-3 are the character rows (0: digits .. 3: "zxcv"), row 4 is the bottom +// row (globe, Shift, ABC, #+=, the accent pages and Space). +// Columns 0-10 are the character columns. Column 11 is the right column, whose +// keys are taller: backspace is (0, 11), Return (1, 11) and OK (3, 11). +// A row-4 key reports the character column nearest its centre (Space: 8). +struct SystemKeyboardKey{ + uint8_t row; + uint8_t col; + + bool operator==(const SystemKeyboardKey&) const = default; +}; + +// The key under the cursor, or nothing if no cursor border is visible. // The keyboard remembers the cursor between uses, so read it, don't assume it. -// Returns false if no cursor border is visible. -bool find_system_keyboard_cursor(const ImageViewRGB32& screen, int& row, int& col); +std::optional read_system_keyboard_cursor(const ImageViewRGB32& screen); -// Whether the text field holds any text. Pressing B on an empty field closes the +// Whether the text field holds any text: the backspace key is dark then and light +// grey while the field is empty. Pressing B on an empty field closes the // keyboard, so delete only while this is true. bool system_keyboard_field_has_text(const ImageViewRGB32& screen); +// The number of white pixels in the text field. Each typed character adds some +// (a "1" adds about 110 at 1920x1080), so comparing two counts tells whether a +// key press reached the field. +size_t system_keyboard_text_pixels(const ImageViewRGB32& screen); + +// Register the tests of this file. void add_tests_SystemKeyboardDetector(UnitTestDatabase& database); -} -} +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h index 38f4f4d841..1aa290cdc1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h @@ -13,7 +13,7 @@ #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardEntryMappings.h" -#include "NintendoSwitch_CodeEntryTools.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h" namespace PokemonAutomation{ namespace NintendoSwitch{ diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp index 43a3329df5..511e36ecad 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.cpp @@ -5,11 +5,19 @@ */ #include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h" -#include "NintendoSwitch_KeyboardCodeEntry.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h" #include "NintendoSwitch_SystemKeyboardTyping.h" namespace PokemonAutomation{ @@ -21,58 +29,202 @@ using namespace std::chrono_literals; namespace{ -constexpr Milliseconds MOVE_HOLD = 100ms; // One key per press, without auto-repeat. +// Waits after each press. They are longer than the code entry delays because +// the next step reads the screen: the cursor animation and the capture latency +// must be over first. constexpr Milliseconds MOVE_RELEASE = 200ms; constexpr Milliseconds WRAP_RELEASE = 400ms; // Wrapping around a side animates for longer. constexpr Milliseconds SETTLE = 300ms; // Before reading the cursor after moving it. -constexpr Milliseconds KEY_HOLD = 80ms; +constexpr Milliseconds SHIFT_RELEASE = 250ms; constexpr Milliseconds KEY_RELEASE = 300ms; // A press made while the keyboard is still sliding in is ignored, so the // cursor is read again after each try until it is on the target. constexpr size_t MAX_MOVE_TRIES = 10; +// Reads of the text field after a key press, SETTLE apart, before giving up. +constexpr size_t MAX_FIELD_READS = 3; -bool read_cursor(VideoStream& stream, ProControllerContext& context, KeyboardEntryPosition& position){ +// The fewest white pixels a typed character adds to the field ("." or "'"). +constexpr size_t MIN_CHARACTER_PIXELS = 10; + + +// The key of each character of `text`. Throws UserSetupError, listing every +// character that has no key, before anything is typed. +std::vector text_keys(Logger& logger, const std::string& text, KeyboardLayout layout){ + const std::map& positions = KEYBOARD_POSITIONS(layout); + std::vector keys; + std::string missing; + for (char ch : text){ + // Letters are listed under their uppercase key. + auto iter = positions.find((char)std::toupper((unsigned char)ch)); + if (iter == positions.end()){ + missing += ch; + }else{ + keys.emplace_back(iter->second); + } + } + if (!missing.empty()){ + throw UserSetupError( + logger, + std::format("System keyboard: \"{}\" has characters with no key on the keyboard: \"{}\".", text, missing) + ); + } + return keys; +} + +// How long to hold each button: the hold of the code entry timings for Switch 1. +Milliseconds button_hold(ProControllerContext& context){ + const ConsoleSettings& settings = ConsoleSettings::instance(); + const CodeEntryDelays delays = context->performance_class() == ControllerPerformanceClass::SerialPABotBase_Wired + ? CodeEntryDelays(settings.CODEBOARD_ENTRY_SWITCH1_WIRED) + : CodeEntryDelays(settings.CODEBOARD_ENTRY_SWITCH1_WIRELESS); + return delays.hold; +} + +// The D-pad direction of a move. +DpadPosition move_direction(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::NORM_MOVE_UP: + case CodeEntryAction::WRAP_MOVE_UP: + return DpadPosition::DPAD_UP; + case CodeEntryAction::NORM_MOVE_RIGHT: + case CodeEntryAction::WRAP_MOVE_RIGHT: + return DpadPosition::DPAD_RIGHT; + case CodeEntryAction::NORM_MOVE_DOWN: + case CodeEntryAction::WRAP_MOVE_DOWN: + return DpadPosition::DPAD_DOWN; + case CodeEntryAction::NORM_MOVE_LEFT: + case CodeEntryAction::WRAP_MOVE_LEFT: + return DpadPosition::DPAD_LEFT; + default: + return DpadPosition::DPAD_NONE; + } +} + +// The moves toward `target`. Off the character grid (the right column or the +// bottom row), one step back onto it, after which the cursor is read again. +std::vector path_toward(SystemKeyboardKey cursor, KeyboardEntryPosition target){ + if (cursor.col == 11){ + return {CodeEntryAction::NORM_MOVE_LEFT}; + } + if (cursor.row == 4){ + return {CodeEntryAction::NORM_MOVE_UP}; + } + std::vector path = keyboard_get_path({cursor.row, cursor.col}, target); + std::erase_if(path, [](CodeEntryAction action){ return !is_move(action); }); + return path; +} + +// The moves as letters for the log, e.g. "DLL" or "R*" for a wrap to the right. +std::string path_to_string(const std::vector& path){ + std::string ret; + for (CodeEntryAction action : path){ + switch (move_direction(action)){ + case DpadPosition::DPAD_UP: + ret += 'U'; + break; + case DpadPosition::DPAD_RIGHT: + ret += 'R'; + break; + case DpadPosition::DPAD_DOWN: + ret += 'D'; + break; + case DpadPosition::DPAD_LEFT: + ret += 'L'; + break; + default: + ret += '?'; + break; + } + if (is_wrap(action)){ + ret += '*'; + } + } + return ret; +} + +std::optional read_cursor(VideoStream& stream, ProControllerContext& context){ context.wait_for_all_requests(); VideoSnapshot screen = stream.video().snapshot(); - int row = -1; - int col = -1; - if (!screen || !find_system_keyboard_cursor(screen, row, col)){ - return false; + if (!screen){ + return std::nullopt; } - position = {(uint8_t)row, (uint8_t)col}; - return true; + return read_system_keyboard_cursor(screen); +} + +[[noreturn]] void throw_cursor_failure( + VideoStream& stream, + std::optional last, KeyboardEntryPosition target, char ch +){ + std::string message = last + ? std::format("the cursor is at ({}, {}), not on '{}' at ({}, {})", last->row, last->col, ch, target.row, target.col) + : std::format("the cursor could not be read while moving to '{}' at ({}, {})", ch, target.row, target.col); + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("System keyboard: {}, after {} tries.", message, MAX_MOVE_TRIES), + stream + ); } -void move_cursor(VideoStream& stream, ProControllerContext& context, KeyboardEntryPosition target, char ch){ +void move_cursor( + VideoStream& stream, ProControllerContext& context, Milliseconds hold, + KeyboardEntryPosition target, char ch +){ + std::optional last; for (size_t attempt = 0; attempt < MAX_MOVE_TRIES; attempt++){ - KeyboardEntryPosition cursor; - if (!read_cursor(stream, context, cursor)){ + const std::optional cursor = read_cursor(stream, context); + if (!cursor){ + stream.logger().log(std::format("System keyboard: no cursor seen, try {}.", attempt + 1)); pbf_wait(context, SETTLE); continue; } - if (cursor.row == target.row && cursor.col == target.col){ + last = cursor; + if (cursor->row == target.row && cursor->col == target.col){ return; } - for (CodeEntryAction action : keyboard_get_path(cursor, target)){ - if (!is_move(action)){ - continue; - } - const bool wrap = ((uint8_t)action & 0x80) != 0; - const DpadPosition direction = (DpadPosition)((uint8_t)action & 0x7f); - pbf_press_dpad(context, direction, MOVE_HOLD, wrap ? WRAP_RELEASE : MOVE_RELEASE); + const std::vector path = path_toward(*cursor, target); + stream.logger().log(std::format( + "System keyboard: cursor ({}, {}) -> '{}' ({}, {}): {}, try {}.", + cursor->row, cursor->col, ch, target.row, target.col, path_to_string(path), attempt + 1 + )); + for (CodeEntryAction action : path){ + pbf_press_dpad(context, move_direction(action), hold, is_wrap(action) ? WRAP_RELEASE : MOVE_RELEASE); + } + pbf_wait(context, SETTLE); + } + throw_cursor_failure(stream, last, target, ch); +} + +size_t read_text_pixels(VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + return screen ? system_keyboard_text_pixels(screen) : 0; +} + +// Types `ch` with the cursor on its key, and checks that the text field grew. +void press_key(VideoStream& stream, ProControllerContext& context, Milliseconds hold, char ch){ + const size_t before = read_text_pixels(stream, context); + if (std::isupper((unsigned char)ch)){ + pbf_press_button(context, BUTTON_LCLICK, hold, SHIFT_RELEASE); + } + pbf_press_button(context, BUTTON_A, hold, KEY_RELEASE); + size_t after = 0; + for (size_t read = 0; read < MAX_FIELD_READS; read++){ + after = read_text_pixels(stream, context); + if (after >= before + MIN_CHARACTER_PIXELS){ + return; } pbf_wait(context, SETTLE); } OperationFailedExceptionWithScreenshot::fire( ErrorReportMode::SEND_ERROR_REPORT, - std::string("System keyboard: the cursor did not reach '") + ch + "'.", + std::format("System keyboard: pressed '{}', but the text field did not change ({} -> {} white pixels).", ch, before, after), stream ); } -} +} // namespace @@ -81,28 +233,17 @@ void type_on_system_keyboard( const std::string& text, KeyboardLayout layout ){ - const std::map& positions = KEYBOARD_POSITIONS(layout); - for (char ch : text){ - // Letters are listed under their uppercase key. - auto iter = positions.find((char)std::toupper((unsigned char)ch)); - if (iter == positions.end()){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - std::string("System keyboard: no key for '") + ch + "'.", - stream - ); - } - move_cursor(stream, context, iter->second, ch); - if (std::isupper((unsigned char)ch)){ - pbf_press_button(context, BUTTON_LCLICK, 100ms, 250ms); - } - pbf_press_button(context, BUTTON_A, KEY_HOLD, KEY_RELEASE); + const std::vector keys = text_keys(stream.logger(), text, layout); + const Milliseconds hold = button_hold(context); + for (size_t c = 0; c < text.size(); c++){ + move_cursor(stream, context, hold, keys[c], text[c]); + press_key(stream, context, hold, text[c]); } context.wait_for_all_requests(); } -} -} -} +} // namespace FastCodeEntry +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h index b0ec331111..2fe1497e4c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h @@ -4,8 +4,14 @@ * * Types text on the Switch's on-screen keyboard with a Pro Controller, reading * the cursor from the video before each key. Unlike keyboard_enter_code(), - * which moves blind from an assumed starting key, it works wherever the - * keyboard left its cursor and catches presses the keyboard ignored. + * which moves blind from an assumed starting key, it starts wherever the + * keyboard left its cursor and corrects moves the keyboard ignored. + * + * Supported keyboards are those of NintendoSwitch_SystemKeyboardDetector.h: the + * Latin keyboard, QWERTY or AZERTY. Console-tested on Switch 1 (2026-11-13): + * the player's name in Legends: Z-A in English, Spanish, German, Italian, French + * and Japanese, and earlier the player's and rival's names in BDSP. Not + * supported: the Korean and Chinese keyboards. Switch 2 is not tested. * */ @@ -15,17 +21,27 @@ #include #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "NintendoSwitch_KeyboardEntryMappings.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardEntryMappings.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace FastCodeEntry{ -// Types `text` (letters, digits and the symbols on the keyboard's first page) -// on the open keyboard. An uppercase letter is typed with Shift (left stick -// click). Throws, with a screenshot, for a character that has no key, or if -// the cursor can't be read or doesn't reach a key. +// Types `text` on the open keyboard: letters, digits and the symbols on the +// keyboard's first page. An uppercase letter is typed with Shift (left stick +// click), which assumes the keyboard opened with Shift off, as BDSP's and +// Legends: Z-A's do. +// +// Before the first press, throws UserSetupError if `text` has a character with +// no key. While typing, throws OperationFailedException, with a screenshot, if +// the cursor can't be read or doesn't reach a key, or if a key press doesn't +// add to the text field. The check counts the field's white pixels, so it +// catches a dropped press but not a wrong case. +// +// Presses are held for the "Fast Code Entry Timings" hold of Switch 1 with the +// controller's connection type, as keyboard_enter_code() does. The waits after +// them are fixed, since each move is read back from the video. void type_on_system_keyboard( VideoStream& stream, ProControllerContext& context, const std::string& text, @@ -33,7 +49,7 @@ void type_on_system_keyboard( ); -} -} -} +} // namespace FastCodeEntry +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif From c44b908bef4c3aa143f8b3dd31dc2c6fb8faed4d Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 08:29:56 -0800 Subject: [PATCH 35/85] System keyboard: read the cursor in its dark phase; tests on real cursor frames The cursor border pulses between bright cyan and a darker teal (0, 185, 210); the reader only matched the bright phase, so a cursor on '/' read as nothing. Widen the colour test (red < 130, green > 160, blue > 170, green - red > 60), which still leaves out the OK button and ABC underline blue. Add tests on Legends: Z-A console frames with the cursor on T, /, !, 0, -, backspace, Return, OK, globe, the N-accent key and Space. AZERTY and Korean stay planned: the layout follows the system language, not the game's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../NintendoSwitch_SystemKeyboardDetector.cpp | 41 +++++++++++++------ .../NintendoSwitch_SystemKeyboardDetector.h | 8 ++-- .../NintendoSwitch_SystemKeyboardTyping.h | 5 ++- 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp index 4f0e37dedf..00600fdf64 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/GlobalAutoPaths.h" @@ -38,12 +39,14 @@ constexpr double RIGHT_COLUMN_OK_TOP = 0.725; // digit row to the bottom of the bottom row. const ImageFloatBox KEYS_AREA(0.0, 0.43, 1.0, 0.49); -// The cursor border is cyan (about 80, 230, 210). +// The cursor border pulses between bright cyan (about 50, 240, 220) and a darker +// teal (about 0, 185, 210), measured on Legends: Z-A. The blue of the OK button +// and of the ABC underline (40, 90, 250) is not green enough to match. bool is_cursor_pixel(uint32_t pixel){ const int red = (pixel >> 16) & 0xff; const int green = (pixel >> 8) & 0xff; const int blue = pixel & 0xff; - return red < 150 && green > 200 && blue > 190; + return red < 130 && green > 160 && blue > 170 && green - red > 60; } uint8_t nearest_row(double y){ @@ -222,22 +225,36 @@ void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ database.add(path(image), std::nullopt, false); } - // Screens still to be captured. Each test is added once its image is in the - // test repo. + // The cursor on other keys (Legends: Z-A, English and Spanish prompts). The + // border pulses between bright cyan and a darker teal; T, / and ! are dark. + const std::pair cursors[] = { + {"PLZA-Cursor-T.png", {1, 4}}, + {"PLZA-Cursor-Slash.png", {1, 10}}, + {"PLZA-Cursor-Exclamation.png", {3, 10}}, + {"PLZA-Cursor-0.png", {0, 9}}, + {"PLZA-Cursor-Minus.png", {0, 10}}, + {"PLZA-Cursor-Backspace.png", {0, 11}}, + {"PLZA-Cursor-Return.png", {1, 11}}, + {"PLZA-Cursor-OK.png", {3, 11}}, + {"PLZA-Cursor-Globe.png", {4, 0}}, + {"PLZA-Cursor-NTilde.png", {4, 5}}, + {"PLZA-Cursor-Space.png", {4, 8}}, + }; + for (const auto& [image, cursor] : cursors){ + database.add(path(image), cursor, false); + } + + // Screens still to be captured: AZERTY needs a console whose system language + // uses it (the layout follows the system, not the game). Each test is added + // once its image is in the test repo. struct Planned{ std::string_view image; std::optional cursor; bool has_text; }; const Planned planned[] = { - {"PLZA-Cursor-3.png", SystemKeyboardKey{0, 2}, false}, - {"PLZA-Cursor-T.png", SystemKeyboardKey{1, 4}, false}, - {"PLZA-Cursor-Minus.png", SystemKeyboardKey{0, 10}, false}, - {"PLZA-Cursor-Backspace.png", SystemKeyboardKey{0, 11}, true}, - {"PLZA-Cursor-OK.png", SystemKeyboardKey{3, 11}, true}, - {"PLZA-Cursor-Space.png", SystemKeyboardKey{4, 8}, false}, - {"AZERTY-Empty.png", key_1, false}, - {"PLZA-Korean.png", std::nullopt, false}, + {"AZERTY-Empty.png", key_1, false}, + {"PLZA-Korean.png", std::nullopt, false}, }; for (const Planned& test : planned){ const std::string image = path(test.image); diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h index 5c7e837eaf..3a5bbf7f03 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.h @@ -8,9 +8,11 @@ * Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h. * * Supported: the Latin keyboard (QWERTY; AZERTY shares the key grid but has no - * test screenshot yet). Measured on 1920x1080 Switch 1 captures of BDSP's and - * Legends: Z-A's name entry, the latter in English, Spanish, German, Italian, - * French and Japanese. Not supported: the Korean keyboard, whose candidate strip + * test screenshot yet). Its layout follows the console's system language, not + * the game's. Measured on 1920x1080 Switch 1 captures of BDSP's and Legends: + * Z-A's name entry, the latter with the game in English, Spanish, German, + * Italian, French and Japanese (all QWERTY on an English console). Not + * supported: the Korean keyboard, whose candidate strip * moves the keys down (the detector returns false on it), and probably the * Chinese ones (not tested). Switch 2 is not tested. * diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h index 2fe1497e4c..3d2e2dcc2f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_SystemKeyboardTyping.h @@ -9,8 +9,9 @@ * * Supported keyboards are those of NintendoSwitch_SystemKeyboardDetector.h: the * Latin keyboard, QWERTY or AZERTY. Console-tested on Switch 1 (2026-11-13): - * the player's name in Legends: Z-A in English, Spanish, German, Italian, French - * and Japanese, and earlier the player's and rival's names in BDSP. Not + * the player's name in Legends: Z-A with the game in English, Spanish, German, + * Italian, French and Japanese (QWERTY, English system language), and earlier + * the player's and rival's names in BDSP. AZERTY is not tested. Not * supported: the Korean and Chinese keyboards. Switch 2 is not tested. * */ From c9058545c2722eea40af36dcedbd643d2ebdb66d Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 08:30:39 -0800 Subject: [PATCH 36/85] System keyboard tests: split add_tests into cursor and planned helpers (function length) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../NintendoSwitch_SystemKeyboardDetector.cpp | 50 +++++++++++-------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp index 00600fdf64..b08bee33a4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SystemKeyboardDetector.cpp @@ -207,25 +207,13 @@ class Test_SystemKeyboardDetector : public ImageUnitTest{ bool m_has_text; }; -} // namespace - - -void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ - const auto path = [](std::string_view image){ - return std::format("NintendoSwitch/SystemKeyboardDetector/{}", image); - }; - const SystemKeyboardKey key_1{0, 0}; - // The OK button is blue with text in the field and grey without. - database.add(path("BDSP-PlayerName-Empty.png"), key_1, false); - database.add(path("BDSP-FriendName-Typed.png"), key_1, true); - for (std::string_view language : {"English", "French", "German", "Italian", "Japanese", "Spanish"}){ - database.add(path(std::format("PLZA-{}-Empty.png", language)), key_1, false); - } - for (std::string_view image : {"BDSP-Dialog.png", "HomeMenu.png", "HomeMenu-OnlineLicensePopup.png", "UserSelect.png"}){ - database.add(path(image), std::nullopt, false); - } +std::string test_image_path(std::string_view image){ + return std::format("NintendoSwitch/SystemKeyboardDetector/{}", image); +} - // The cursor on other keys (Legends: Z-A, English and Spanish prompts). The +// The cursor on keys other than "1". +void add_cursor_tests(UnitTestDatabase& database){ + // Legends: Z-A, English and Spanish prompts. The // border pulses between bright cyan and a darker teal; T, / and ! are dark. const std::pair cursors[] = { {"PLZA-Cursor-T.png", {1, 4}}, @@ -241,9 +229,13 @@ void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ {"PLZA-Cursor-Space.png", {4, 8}}, }; for (const auto& [image, cursor] : cursors){ - database.add(path(image), cursor, false); + database.add(test_image_path(image), cursor, false); } +} +// Tests whose screen is not captured yet. +void add_planned_tests(UnitTestDatabase& database){ + const SystemKeyboardKey key_1{0, 0}; // Screens still to be captured: AZERTY needs a console whose system language // uses it (the layout follows the system, not the game). Each test is added // once its image is in the test repo. @@ -257,13 +249,31 @@ void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ {"PLZA-Korean.png", std::nullopt, false}, }; for (const Planned& test : planned){ - const std::string image = path(test.image); + const std::string image = test_image_path(test.image); if (Filesystem::exists(std::format("{}{}", UNIT_TEST_RESOURCE_PATH(), image))){ database.add(image, test.cursor, test.has_text); } } } +} // namespace + + +void add_tests_SystemKeyboardDetector(UnitTestDatabase& database){ + const SystemKeyboardKey key_1{0, 0}; + // The OK button is blue with text in the field and grey without. + database.add(test_image_path("BDSP-PlayerName-Empty.png"), key_1, false); + database.add(test_image_path("BDSP-FriendName-Typed.png"), key_1, true); + for (std::string_view language : {"English", "French", "German", "Italian", "Japanese", "Spanish"}){ + database.add(test_image_path(std::format("PLZA-{}-Empty.png", language)), key_1, false); + } + for (std::string_view image : {"BDSP-Dialog.png", "HomeMenu.png", "HomeMenu-OnlineLicensePopup.png", "UserSelect.png"}){ + database.add(test_image_path(image), std::nullopt, false); + } + add_cursor_tests(database); + add_planned_tests(database); +} + } // namespace NintendoSwitch From 72de561cf831917d9ce9e070caf7f5e6f5083af9 Mon Sep 17 00:00:00 2001 From: Pokemon Automation Dev Bot Date: Fri, 13 Nov 2026 09:58:35 -0800 Subject: [PATCH 37/85] Sockets: add a per-connection id to server socket sends (#1910) * Sockets: add a per-connection id to server socket sends send() can now be given the connection_id() the caller captured when it started writing. The id increments on every accept, under the socket's lock, and send() compares it against the current id at transport selection and on every loop iteration (queue time and run time in the Qt backend). A write that outlived its connection - the peer disconnected and a new client was accepted in the meantime - is refused instead of being delivered into the new client's socket. Motivated by the in-app HTTP server: its per-connection task may be inside a long handler call when the client disconnects, and a fast reconnect can be accepted before the task notices; without the id, its final response could be written into the new client's stream. Default argument (0 = no check) keeps existing callers unchanged. Test: Sockets - A send for a replaced connection is refused (runs on the Qt, POSIX, and WinSocket backends). * Sockets: report connection_id() as 0 when no connection is active The documented contract ("0 when no connection is active") now holds in all three backends: the accessor reports 0 whenever the socket is not CONNECTED. The stored counter stays monotonic - resetting it on close would let a queued write from the previous connection match the id of the next one - and send() compares against the counter, so the stale-send refusal is unaffected. Test_Sockets_StaleSend now also checks the idle state before and after the first connection. * Sockets: move the connection_id() monotonicity note to the base class Suggested by review: the note explaining why the counter is never reset was duplicated in all three backends; it now lives once in the abstract class next to the connection_id() contract. Comment-only change. --------- Co-authored-by: PA Dev Bot <344001113+pa-devbot@users.noreply.github.com> --- Common/Cpp/Sockets/AbstractServerSocket.h | 18 ++- Common/Cpp/Sockets/ServerSocket_POSIX.cpp | 30 +++-- Common/Cpp/Sockets/ServerSocket_POSIX.h | 14 ++- Common/Cpp/Sockets/ServerSocket_Qt.cpp | 35 +++++- Common/Cpp/Sockets/ServerSocket_Qt.h | 20 ++- Common/Cpp/Sockets/ServerSocket_WinSocket.cpp | 27 ++++- Common/Cpp/Sockets/ServerSocket_WinSocket.h | 14 ++- Common/Cpp/Sockets/Sockets_Tests.cpp | 114 ++++++++++++++++++ 8 files changed, 249 insertions(+), 23 deletions(-) diff --git a/Common/Cpp/Sockets/AbstractServerSocket.h b/Common/Cpp/Sockets/AbstractServerSocket.h index 4139a0f120..1c2da259ef 100644 --- a/Common/Cpp/Sockets/AbstractServerSocket.h +++ b/Common/Cpp/Sockets/AbstractServerSocket.h @@ -13,6 +13,7 @@ #define PokemonAutomation_Sockets_AbstractServerSocket_H #include +#include #include #include "Common/Cpp/ListenerSet.h" @@ -58,6 +59,18 @@ class AbstractServerSocket{ return m_state.load(std::memory_order_relaxed); } + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. Capture it when a write + // starts and pass it to "send()", so that a write that outlives its + // connection (the peer disconnected and a new client was accepted + // in the meantime) refuses to reach the new client's socket. + // Implementations keep the underlying counter monotonic (never + // reset it when a connection closes, or a queued write for the old + // connection could match the next connection's id); 0 is only the + // "no connection is active" report, never a counter value. + virtual uint64_t connection_id() = 0; + // Binds to "address" and listens on "port". // Use "0.0.0.0" to accept connections on all interfaces. virtual void start(const std::string& address, uint16_t port) = 0; @@ -69,7 +82,10 @@ class AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + // The connection_id() captured when this write started. 0 skips + // the check: the call applies to whatever connection is active. + uint64_t connection = 0 ) = 0; diff --git a/Common/Cpp/Sockets/ServerSocket_POSIX.cpp b/Common/Cpp/Sockets/ServerSocket_POSIX.cpp index 75b2a14ead..ad38549eb6 100644 --- a/Common/Cpp/Sockets/ServerSocket_POSIX.cpp +++ b/Common/Cpp/Sockets/ServerSocket_POSIX.cpp @@ -83,6 +83,14 @@ void ServerSocket_POSIX::start(const std::string& address, uint16_t port){ } } +uint64_t ServerSocket_POSIX::connection_id(){ + std::lock_guard lg(m_lock); + return m_state.load(std::memory_order_relaxed) == State::CONNECTED + ? m_connection_id + : 0; +} + + void ServerSocket_POSIX::close_connection(){ int socket; { @@ -159,16 +167,16 @@ void ServerSocket_POSIX::close_and_wait() noexcept{ } } -size_t ServerSocket_POSIX::send(const void* data, size_t bytes, std::chrono::milliseconds timeout){ +size_t ServerSocket_POSIX::send(const void* data, size_t bytes, std::chrono::milliseconds timeout, uint64_t connection){ int socket; { std::lock_guard lg(m_lock); - socket = m_state.load(std::memory_order_relaxed) == State::CONNECTED - ? m_client - : -1; - } - if (socket == -1){ - return 0; + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ + return 0; + } + socket = m_client; } const char* ptr = (const char*)data; @@ -184,7 +192,12 @@ size_t ServerSocket_POSIX::send(const void* data, size_t bytes, std::chrono::mil while (bytes > 0){ { std::lock_guard lg(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::CONNECTED){ + // The connection may have been replaced (or closed) since the + // last iteration: in that case this write must stop rather + // than reach the new client's socket. + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ return sent; } } @@ -359,6 +372,7 @@ void ServerSocket_POSIX::accept_thread_loop(std::string address, uint16_t port, fcntl(client_socket, F_SETFL, O_NONBLOCK); m_client = client_socket; m_close_requested = false; + m_connection_id++; m_state.store(State::CONNECTED, std::memory_order_release); accepted = true; } diff --git a/Common/Cpp/Sockets/ServerSocket_POSIX.h b/Common/Cpp/Sockets/ServerSocket_POSIX.h index 6786a631fc..f08b83ca68 100644 --- a/Common/Cpp/Sockets/ServerSocket_POSIX.h +++ b/Common/Cpp/Sockets/ServerSocket_POSIX.h @@ -42,9 +42,15 @@ class ServerSocket_POSIX final : public AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + uint64_t connection = 0 ) override; + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. + virtual uint64_t connection_id() override; + private: @@ -87,6 +93,12 @@ class ServerSocket_POSIX final : public AbstractServerSocket{ int m_client = -1; bool m_close_requested = false; + // A connection token, incremented (under m_lock) on every accept. + // send() compares it against the token the caller captured, so a + // write that outlived its connection cannot reach the client that + // replaced it. 0 means no connection is active. + uint64_t m_connection_id = 0; + // One task per start() call. start() must never destroy the previous // task's AsyncTask here: its destructor blocks until the task has // finished, and a task from an earlier attempt may still be running diff --git a/Common/Cpp/Sockets/ServerSocket_Qt.cpp b/Common/Cpp/Sockets/ServerSocket_Qt.cpp index fd48c72001..359a45b1f1 100644 --- a/Common/Cpp/Sockets/ServerSocket_Qt.cpp +++ b/Common/Cpp/Sockets/ServerSocket_Qt.cpp @@ -174,13 +174,16 @@ void ServerSocket_Qt::close_and_wait() noexcept{ m_close_requested = false; } -size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::milliseconds timeout){ +size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::milliseconds timeout, uint64_t connection){ QTcpSocket* socket; { std::lock_guard lg(m_lock); - socket = m_state.load(std::memory_order_relaxed) == State::CONNECTED - ? m_socket - : nullptr; + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ + return 0; + } + socket = m_socket; } if (socket == nullptr){ return 0; @@ -188,6 +191,7 @@ size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::millis QSharedPointer send_data = QSharedPointer::create(); send_data->packet.assign((const char*)data, bytes); + send_data->connection = connection; // "time_point::max()" (the infinite default) is never reached; using // it also avoids overflowing "now() + timeout". send_data->deadline = @@ -213,7 +217,8 @@ size_t ServerSocket_Qt::send(const void* data, size_t bytes, std::chrono::millis std::lock_guard lg(m_lock); registered = m_state.load(std::memory_order_relaxed) == State::CONNECTED - && m_socket != nullptr; + && m_socket != nullptr + && (connection == 0 || m_connection_id == connection); if (registered){ m_inflight_sends.push_back(send_data); } @@ -310,6 +315,7 @@ void ServerSocket_Qt::on_new_connection(){ }else{ m_socket = sock; m_close_requested = false; + m_connection_id++; m_state.store(State::CONNECTED, std::memory_order_release); accepted = true; rejected = false; @@ -434,11 +440,28 @@ void ServerSocket_Qt::on_close_connection(QSharedPointer comple completion->cv.notify_all(); } +uint64_t ServerSocket_Qt::connection_id(){ + std::lock_guard lg(m_lock); + return m_state.load(std::memory_order_relaxed) == State::CONNECTED + ? m_connection_id + : 0; +} + + void ServerSocket_Qt::on_send(QSharedPointer send_data){ QTcpSocket* sock; { std::lock_guard lg(m_lock); - sock = m_socket; + if (send_data->connection != 0 + && m_connection_id != send_data->connection + ){ + // The connection this send was queued for was replaced (or + // torn down) while it was waiting in the queue: the write + // loop must not reach into the new connection's socket. + sock = nullptr; + }else{ + sock = m_socket; + } } { diff --git a/Common/Cpp/Sockets/ServerSocket_Qt.h b/Common/Cpp/Sockets/ServerSocket_Qt.h index 0bcf70c0a6..370152e98c 100644 --- a/Common/Cpp/Sockets/ServerSocket_Qt.h +++ b/Common/Cpp/Sockets/ServerSocket_Qt.h @@ -54,6 +54,12 @@ class ServerSocket_Qt final : public QObject, public AbstractServerSocket{ // "close_and_wait()"/"close_connection()" cancel the send. bool done = false; + // The connection_id() the send was queued for; 0 skips the + // check. "on_send" refuses to write if the connection was + // replaced while the send was queued, so it cannot reach the + // new client's socket. + uint64_t connection = 0; + Mutex lock; ConditionVariable cv; }; @@ -86,9 +92,15 @@ class ServerSocket_Qt final : public QObject, public AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + uint64_t connection = 0 ) override; + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. + virtual uint64_t connection_id() override; + signals: void internal_send(QSharedPointer send_data); @@ -142,6 +154,12 @@ class ServerSocket_Qt final : public QObject, public AbstractServerSocket{ bool m_close_requested = false; bool m_starting = false; + // A connection token, incremented (under m_lock) on every accept. + // "send()" compares it against the token the caller captured, so a + // write that outlived its connection cannot reach the client that + // replaced it. 0 means no connection is active. + uint64_t m_connection_id = 0; + // The "send()" calls that are queued on the event thread but not // finished yet, so that "close_and_wait()"/"close_connection()" can // cancel diff --git a/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp b/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp index 55889f4b38..066a76ab24 100644 --- a/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp +++ b/Common/Cpp/Sockets/ServerSocket_WinSocket.cpp @@ -94,6 +94,14 @@ void ServerSocket_WinSocket::start(const std::string& address, uint16_t port){ } } +uint64_t ServerSocket_WinSocket::connection_id(){ + std::lock_guard lg(m_lock); + return m_state.load(std::memory_order_relaxed) == State::CONNECTED + ? m_connection_id + : 0; +} + + void ServerSocket_WinSocket::close_connection(){ SOCKET socket; { @@ -170,13 +178,16 @@ void ServerSocket_WinSocket::close_and_wait() noexcept{ } } -size_t ServerSocket_WinSocket::send(const void* data, size_t bytes, std::chrono::milliseconds timeout){ +size_t ServerSocket_WinSocket::send(const void* data, size_t bytes, std::chrono::milliseconds timeout, uint64_t connection){ SOCKET socket; { std::lock_guard lg(m_lock); - socket = m_state.load(std::memory_order_relaxed) == State::CONNECTED - ? m_client - : INVALID_SOCKET; + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ + return 0; + } + socket = m_client; } if (socket == INVALID_SOCKET){ return 0; @@ -195,7 +206,12 @@ size_t ServerSocket_WinSocket::send(const void* data, size_t bytes, std::chrono: while (bytes > 0){ { std::lock_guard lg(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::CONNECTED){ + // The connection may have been replaced (or closed) since the + // last iteration: in that case this write must stop rather + // than reach the new client's socket. + if (m_state.load(std::memory_order_relaxed) != State::CONNECTED + || (connection != 0 && m_connection_id != connection) + ){ return sent; } } @@ -379,6 +395,7 @@ void ServerSocket_WinSocket::accept_thread_loop(std::string address, uint16_t po ioctlsocket(client_socket, FIONBIO, &client_non_blocking); m_client = client_socket; m_close_requested = false; + m_connection_id++; m_state.store(State::CONNECTED, std::memory_order_release); accepted = true; } diff --git a/Common/Cpp/Sockets/ServerSocket_WinSocket.h b/Common/Cpp/Sockets/ServerSocket_WinSocket.h index 6b68519ab8..f478e69b46 100644 --- a/Common/Cpp/Sockets/ServerSocket_WinSocket.h +++ b/Common/Cpp/Sockets/ServerSocket_WinSocket.h @@ -45,9 +45,15 @@ class ServerSocket_WinSocket final : public AbstractServerSocket{ virtual size_t send( const void* data, size_t bytes, - std::chrono::milliseconds timeout = std::chrono::milliseconds::max() + std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), + uint64_t connection = 0 ) override; + // A token identifying the connection the socket is currently + // serving. It changes every time a new client is accepted, and it + // is 0 when no connection is active. + virtual uint64_t connection_id() override; + private: // Winsock has to be started before any of its functions can be used, and @@ -96,6 +102,12 @@ class ServerSocket_WinSocket final : public AbstractServerSocket{ SOCKET m_client = INVALID_SOCKET; bool m_close_requested = false; + // A connection token, incremented (under m_lock) on every accept. + // send() compares it against the token the caller captured, so a + // write that outlived its connection cannot reach the client that + // replaced it. 0 means no connection is active. + uint64_t m_connection_id = 0; + // One task per start() call. start() must never destroy the previous // task's AsyncTask here: its destructor blocks until the task has // finished, and a task from an earlier attempt may still be running diff --git a/Common/Cpp/Sockets/Sockets_Tests.cpp b/Common/Cpp/Sockets/Sockets_Tests.cpp index 7864a7d34a..3fe3bd915d 100644 --- a/Common/Cpp/Sockets/Sockets_Tests.cpp +++ b/Common/Cpp/Sockets/Sockets_Tests.cpp @@ -822,6 +822,117 @@ class Test_Sockets_RejectSecondClient : public TestSockets +class Test_Sockets_StaleSend : public TestSockets{ +public: + using TestSockets::TestSockets; + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + ServerListener server_listener; + ServerSocketType server(this->m_thread_pool); + server.add_listener(server_listener); + + uint16_t port; + if (!this->start_server(server, server_listener, port)){ + return "Failed to start the server"; + } + + std::string error; + if (server.connection_id() != 0){ + error = "connection_id() was not 0 before any connection"; + } + + uint64_t first_id = 0; + { + ClientListener client_listener; + ClientSocketType client(this->m_thread_pool); + client.add_listener(client_listener); + + if (!this->connect_client(client, client_listener, port, 1)){ + error = "The first client did not finish connecting"; + }else if (!server_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 1; } + )){ + error = "The server did not call on_connect"; + }else{ + first_id = server.connection_id(); + if (first_id == 0){ + error = "The server did not assign a connection id"; + } + client.close(); + } + } + + if (error.empty() && !server_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&server_listener]{ return server_listener.disconnected.load() >= 1; } + )){ + error = "The server did not call on_disconnect"; + } + + // The counter is monotonic and not reset, but with no active + // connection the id must report 0. + if (error.empty() && server.connection_id() != 0){ + error = "connection_id() was not 0 while no connection was active"; + } + + uint64_t second_id = 0; + { + ClientListener client_listener; + ClientSocketType client(this->m_thread_pool); + client.add_listener(client_listener); + + if (!this->connect_client(client, client_listener, port, 1)){ + error = "The second client did not finish connecting"; + }else if (!server_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&server_listener]{ return server_listener.connected.load() >= 2; } + )){ + error = "The server did not call on_connect for the second client"; + }else{ + second_id = server.connection_id(); + if (second_id == first_id){ + error = "The connection id did not change after reconnect"; + } + // A send for the replaced connection must be refused, + // not delivered into the new client's socket. + if (error.empty() && + server.send("stale", 5, std::chrono::milliseconds::max(), first_id) != 0 + ){ + error = "A send for a replaced connection was not refused"; + } + // A send for the current connection still goes through. + if (error.empty() && + server.send("hello", 5, std::chrono::milliseconds::max(), second_id) != 5 + ){ + error = "The send for the current connection was not delivered"; + } + if (error.empty() && !client_listener.waiter.wait_for( + SOCKET_TEST_WAIT, + [&client_listener]{ return client_listener.received.size() >= 5; } + )){ + error = "The second client did not receive the data"; + }else if (error.empty() && + std::memcmp(client_listener.received.data(), "hello", 5) != 0 + ){ + error = "The second client received the wrong data"; + } + client.close(); + } + } + + if (!error.empty()){ + return error; + } + return true; + } +}; + + // Starting a second server on an already-bound port must fail through // on_listen_finished and leave the server not running. template @@ -2676,6 +2787,9 @@ void add_socket_tests(UnitTestDatabase& database, ThreadPool& thread_pool, const database.add>( thread_pool, prefix + "Reject a second client" ); + database.add>( + thread_pool, prefix + "A send for a replaced connection is refused" + ); database.add>( thread_pool, prefix + "Port in use" ); From 1e49c4f46cbbebc798bd41b6c19b87ab7a18fa94 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 12:30:58 -0800 Subject: [PATCH 38/85] SV AutoStory: write the shared checkpoint log lines SV's checkpoint loops and its start line use Pokemon_StoryLog's format (moved here from #325, as asked in review). The log header is included from the .cpp files, not AutoStoryTools.h. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp | 3 ++- .../Programs/AutoStory/PokemonSV_AutoStoryTools.cpp | 9 +++++---- .../Programs/AutoStory/PokemonSV_AutoStoryTools.h | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp index 130271139b..6895a9e8b3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -28,6 +28,7 @@ #include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "Pokemon/Pokemon_Strings.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" #include "VideoGames/PokemonSV/PokemonSV_Settings.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" @@ -1230,7 +1231,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex require_player(env.console, context, BUTTON_L); if (ENABLE_ADVANCED_MODE){ - env.console.log("Start Checkpoint " + ALL_AUTO_STORY_CHECKPOINT_LIST()[get_start_checkpoint_index()]->name(), COLOR_ORANGE); + env.console.log(Pokemon::checkpoint_start_line(ALL_AUTO_STORY_CHECKPOINT_LIST()[get_start_checkpoint_index()]->name()), COLOR_ORANGE); }else{ env.console.log("Start Segment " + ALL_AUTO_STORY_SEGMENT_LIST()[get_start_segment_index()]->name(), COLOR_ORANGE); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index c2d61152df..b87996958d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -14,6 +14,7 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" #include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" @@ -1445,7 +1446,7 @@ void checkpoint_reattempt_loop( save_game_from_overworld(env.program_info(), env.console, context); } - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); + env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); context.wait_for_all_requests(); action(i); @@ -1479,7 +1480,7 @@ void checkpoint_reattempt_loop( ); } context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); + env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); @@ -1507,7 +1508,7 @@ void checkpoint_reattempt_loop_tutorial( send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); } - env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); + env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); context.wait_for_all_requests(); action(i); @@ -1538,7 +1539,7 @@ void checkpoint_reattempt_loop_tutorial( ); } context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); + env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index e39d8a47da..8583c68c42 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -7,6 +7,7 @@ #ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H #define PokemonAutomation_PokemonSV_AutoStoryTools_H +#include #include #include "CommonFramework/Language.h" #include "CommonFramework/ImageTools/ImageBoxes.h" @@ -108,7 +109,7 @@ class AutoStory_Checkpoint { AutoStoryStats& stats) const = 0; std::string checkpoint_text() const { - return "Checkpoint:: " + name() + ". Start point: " + start_text(); + return std::format("{}. Start point: {}", name(), start_text()); } }; From 1b5aaf01d0aadf3f9d33572effbea030058af9c2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 12:32:12 -0800 Subject: [PATCH 39/85] SV AutoStory: keep the legacy file line counts (code health) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp | 1 - .../PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp | 1 - 2 files changed, 2 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp index 6895a9e8b3..9aca6582cc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -5,7 +5,6 @@ */ - #if 0 #include "CommonFramework/Exceptions/UnexpectedBattleException.h" #include "CommonTools/Async/InferenceRoutines.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index b87996958d..63a8e80523 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -44,7 +44,6 @@ namespace PokemonSV{ - void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout){ bool seen_tutorial = false; while (true){ From d24b86d1a04b0c1bfea2c9ea8f75c8e0116f7bb2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 12:34:14 -0800 Subject: [PATCH 40/85] SV AutoStory: drop the log header include, now in the .cpp files via #45 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h | 1 - 1 file changed, 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index 312533cde7..8583c68c42 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -16,7 +16,6 @@ #include "ML/Inference/ML_YOLONavigation.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" -#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" namespace PokemonAutomation{ From 7cdde2d723cc33b13a3897900007a4502e1aa408 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 13:03:49 -0800 Subject: [PATCH 41/85] AutoStory: review fixes for the shared log lines SV keeps its checkpoint_text() and its own attempt/reset lines: they only know the full "Checkpoint:: name. Start point: ..." text, which does not fit the shared "[Checkpoint] : ..." lines. SV writes only the shared start line, from name(). Drop checkpoint_pass_line()'s unused in_place count, nest the test case's Input and Expectation in StoryLogTestCase, and say who reads the lines in the header comment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_StoryLog.cpp | 8 +--- .../Pokemon/AutoStory/Pokemon_StoryLog.h | 16 ++++---- .../AutoStory/Pokemon_StoryLog_Tests.cpp | 40 +++++++++---------- .../AutoStory/PokemonSV_AutoStoryTools.cpp | 10 ++--- .../AutoStory/PokemonSV_AutoStoryTools.h | 3 +- 5 files changed, 36 insertions(+), 41 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp index f931e3bd51..63684e54f8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -41,12 +41,8 @@ std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt, return std::format("[Checkpoint] {}: attempt {}/{}", checkpoint, attempt, *attempts); } -std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, size_t in_place){ - return std::format( - "[Checkpoint] {}: passed on attempt {} ({}){}", - checkpoint, attempt, resets_text(attempt), - in_place == 0 ? "" : std::format(", {} in place", in_place) - ); +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt){ + return std::format("[Checkpoint] {}: passed on attempt {} ({})", checkpoint, attempt, resets_text(attempt)); } std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h index 539a3d3424..7d1d5b5edc 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -4,10 +4,10 @@ * * The log lines an AutoStory program writes around its checkpoints, in * one format for every game: the story engine (Pokemon_StoryEvents.h, - * Pokemon_StorySegments.h) writes them, and a game with its own checkpoint - * loop (SV's) writes the same lines, so the lab watcher and whoever reads - * a log find each checkpoint's start, attempts, resets and pass the same - * way. Nothing here runs a story. + * Pokemon_StorySegments.h) writes them, and SV's AutoStory writes the same + * checkpoint start line, so the program developer and user find each + * checkpoint's start, attempts, resets and pass the same way in any game's + * log. Nothing here runs a story. * */ @@ -41,11 +41,11 @@ std::string checkpoint_attempt_line( std::string_view checkpoint, size_t attempt, std::optional attempts = std::nullopt ); -// A checkpoint passed on attempt `attempt`, after `in_place` recoveries in -// place: +// A checkpoint passed on attempt `attempt`, counting from 1; every attempt +// before it ended in a reset: // [Checkpoint] 00.03: passed on attempt 1 (one-shot) -// [Checkpoint] 00.04: passed on attempt 3 (2 resets), 1 in place -std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, size_t in_place = 0); +// [Checkpoint] 00.04: passed on attempt 3 (2 resets) +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt); // An attempt failed and the game resets to the checkpoint's save for // attempt `next_attempt`: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp index 1cc32c258b..7c705d7d74 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -16,26 +16,26 @@ namespace Pokemon{ namespace{ -// A formatter's line, made when the table is built. -struct StoryLogInput{ - std::string name; - std::string line; -}; - -// The exact line: the lab watcher and the engine tests read these. -struct StoryLogExpectation{ - std::string line; -}; - // One formatter call and the line it must make. -struct StoryLogCase{ - StoryLogInput input; - StoryLogExpectation expectation; +struct StoryLogTestCase{ + // A formatter's line, made when the table is built. + struct Input{ + std::string name; + std::string line; + }; + + // The exact line: the lab watcher and the engine tests read these. + struct Expectation{ + std::string line; + }; + + Input input; + Expectation expectation; }; class Test_StoryLog : public UnitTest{ public: - Test_StoryLog(StoryLogCase test_case) + Test_StoryLog(StoryLogTestCase test_case) : UnitTest(std::format("Pokemon::StoryLog - {}", test_case.input.name)) , m_case(std::move(test_case)) {} @@ -48,10 +48,10 @@ class Test_StoryLog : public UnitTest{ } private: - const StoryLogCase m_case; + const StoryLogTestCase m_case; }; -const StoryLogCase STORY_LOG_CASES[] = { +const StoryLogTestCase STORY_LOG_CASES[] = { { .input = {.name = "event", .line = event_log_line("00.04", 3, "talk_mom", "start")}, .expectation = {.line = "[Event] 00.04/3 talk_mom: start"}, @@ -81,8 +81,8 @@ const StoryLogCase STORY_LOG_CASES[] = { .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 2 (1 reset)"}, }, { - .input = {.name = "pass after resets and recoveries in place", .line = checkpoint_pass_line("00.04", 3, 1)}, - .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 3 (2 resets), 1 in place"}, + .input = {.name = "pass after resets", .line = checkpoint_pass_line("00.04", 3)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 3 (2 resets)"}, }, { .input = {.name = "reset", .line = checkpoint_reset_line("00.04", 2)}, @@ -99,7 +99,7 @@ const StoryLogCase STORY_LOG_CASES[] = { void add_tests_StoryLog(UnitTestDatabase& database){ - for (const StoryLogCase& test_case : STORY_LOG_CASES){ + for (const StoryLogTestCase& test_case : STORY_LOG_CASES){ database.add(test_case); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index 63a8e80523..c2d61152df 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -14,7 +14,6 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/AutoStory/Pokemon_StoryLog.h" #include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" #include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" #include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" @@ -44,6 +43,7 @@ namespace PokemonSV{ + void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout){ bool seen_tutorial = false; while (true){ @@ -1445,7 +1445,7 @@ void checkpoint_reattempt_loop( save_game_from_overworld(env.program_info(), env.console, context); } - env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); + env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); context.wait_for_all_requests(); action(i); @@ -1479,7 +1479,7 @@ void checkpoint_reattempt_loop( ); } context.wait_for_all_requests(); - env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); + env.console.log("Resetting from checkpoint."); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); @@ -1507,7 +1507,7 @@ void checkpoint_reattempt_loop_tutorial( send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); } - env.console.log(Pokemon::checkpoint_attempt_line(checkpoint_text, i + 1)); + env.console.log(checkpoint_text + " Num attempts: " + std::to_string(i)); context.wait_for_all_requests(); action(i); @@ -1538,7 +1538,7 @@ void checkpoint_reattempt_loop_tutorial( ); } context.wait_for_all_requests(); - env.console.log(Pokemon::checkpoint_reset_line(checkpoint_text, i + 2)); + env.console.log("Resetting from checkpoint."); reset_game(env.program_info(), env.console, context); stats.m_reset++; env.update_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index 8583c68c42..e39d8a47da 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -7,7 +7,6 @@ #ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H #define PokemonAutomation_PokemonSV_AutoStoryTools_H -#include #include #include "CommonFramework/Language.h" #include "CommonFramework/ImageTools/ImageBoxes.h" @@ -109,7 +108,7 @@ class AutoStory_Checkpoint { AutoStoryStats& stats) const = 0; std::string checkpoint_text() const { - return std::format("{}. Start point: {}", name(), start_text()); + return "Checkpoint:: " + name() + ". Start point: " + start_text(); } }; From 7b7ef1dc17f3ab5e58e4d1a77a2779e94d124042 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 13:37:25 -0800 Subject: [PATCH 42/85] AutoStory: nest the stats test case's Input and Expectation Same test style as StoryLogTestCase: StoryCountsCase becomes StoryCountsTestCase with nested Input and Expectation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_AutoStoryStats_Tests.cpp | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp index 453a975516..b427cd6d22 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp @@ -18,28 +18,28 @@ namespace Pokemon{ namespace{ -// Counts added to fresh stats, in order. -struct StoryCountsInput{ - std::string name; - std::vector added; -}; - -// The stats after them: counts add up rather than replace. -struct StoryCountsExpectation{ - uint64_t segments; - uint64_t checkpoints; - uint64_t resets; -}; - // Counts recorded into the AutoStory stats and the totals they must reach. -struct StoryCountsCase{ - StoryCountsInput input; - StoryCountsExpectation expectation; +struct StoryCountsTestCase{ + // Counts added to fresh stats, in order. + struct Input{ + std::string name; + std::vector added; + }; + + // The stats after them: counts add up rather than replace. + struct Expectation{ + uint64_t segments; + uint64_t checkpoints; + uint64_t resets; + }; + + Input input; + Expectation expectation; }; class Test_StoryCounts : public UnitTest{ public: - Test_StoryCounts(StoryCountsCase test_case) + Test_StoryCounts(StoryCountsTestCase test_case) : UnitTest(std::format("Pokemon::AutoStoryStats - {}", test_case.input.name)) , m_case(std::move(test_case)) {} @@ -49,7 +49,7 @@ class Test_StoryCounts : public UnitTest{ for (const StoryRunCounts& counts : m_case.input.added){ record_story_counts(counts, stats); } - const StoryCountsExpectation& expected = m_case.expectation; + const StoryCountsTestCase::Expectation& expected = m_case.expectation; if (stats.m_segment != expected.segments || stats.m_checkpoint != expected.checkpoints || stats.m_reset != expected.resets){ return std::format( "Expected {} segments, {} checkpoints and {} resets, got {}, {} and {}", @@ -61,10 +61,10 @@ class Test_StoryCounts : public UnitTest{ } private: - const StoryCountsCase m_case; + const StoryCountsTestCase m_case; }; -const StoryCountsCase STORY_COUNTS_CASES[] = { +const StoryCountsTestCase STORY_COUNTS_CASES[] = { { .input = {.name = "a segment's counts in the stats", .added = {{.segments = 1, .checkpoints = 2, .resets = 3}}}, .expectation = {.segments = 1, .checkpoints = 2, .resets = 3}, @@ -82,7 +82,7 @@ const StoryCountsCase STORY_COUNTS_CASES[] = { void add_tests_AutoStoryStats(UnitTestDatabase& database){ - for (const StoryCountsCase& test_case : STORY_COUNTS_CASES){ + for (const StoryCountsTestCase& test_case : STORY_COUNTS_CASES){ database.add(test_case); } } From cc99e64ad4f1fd17a4593d8f0b5199c0c028e707 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 13:52:22 -0800 Subject: [PATCH 43/85] Pokemon AutoStory: one checkpoint retry loop for every AutoStory run_checkpoint_attempts() is the loop without exceptions: an attempt passes, fails, or fails in a way another attempt repeats, and the game's reset may fail. The story segments and the story engine run their checkpoints through it; SV's run_checkpoint_with_retries() is now its throwing adapter, with the same lines and counts as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_CheckpointAttempts.cpp | 36 +++++++ .../AutoStory/Pokemon_CheckpointAttempts.h | 70 ++++++++++++ .../AutoStory/Pokemon_CheckpointRetry.cpp | 38 ++++--- .../AutoStory/Pokemon_CheckpointRetry.h | 21 ++-- .../Pokemon_CheckpointRetry_Tests.cpp | 101 ++++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 6 files changed, 243 insertions(+), 25 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp new file mode 100644 index 0000000000..7a87749188 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp @@ -0,0 +1,36 @@ +/* Checkpoint Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryLog.h" +#include "Pokemon_CheckpointAttempts.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +CheckpointAttemptsResult run_checkpoint_attempts(std::string_view checkpoint, const CheckpointAttempts& attempts){ + CheckpointAttemptsResult result; + for (size_t attempt = 1;; attempt++){ + result.attempts = attempt; + const AttemptResult outcome = attempts.run(attempt); + if (outcome == AttemptResult::PASSED){ + result.passed = true; + attempts.log(checkpoint_pass_line(checkpoint, attempt)); + return result; + } + if (outcome == AttemptResult::FINAL || attempt >= attempts.max_attempts){ + return result; + } + if (!attempts.reset(attempt + 1)){ + return result; + } + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h new file mode 100644 index 0000000000..813fad9db4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h @@ -0,0 +1,70 @@ +/* Checkpoint Attempts + * + * From: https://github.com/PokemonAutomation/ + * + * The retry loop every AutoStory runs a checkpoint in: run an attempt, and + * when it fails go back to the checkpoint's start save and try again, + * until an attempt passes, fails in a way another attempt would repeat, + * the last attempt fails, or a reset fails. SV's loop + * (Pokemon_CheckpointRetry.h), the story segments and the story engine all + * run their checkpoints through it, so each writes the same pass line + * (Pokemon_StoryLog.h) and counts attempts the same way. The game supplies + * the attempt and the reset. + * + */ + +#ifndef PokemonAutomation_Pokemon_CheckpointAttempts_H +#define PokemonAutomation_Pokemon_CheckpointAttempts_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How one attempt at a checkpoint ended. +enum class AttemptResult{ + PASSED, + // Failed; another attempt from the start save may pass. + FAILED, + // Failed in a way another attempt would repeat (the game is not + // running): no more attempts. + FINAL, +}; + +// Writes one log line. +using CheckpointLogger = std::function; + +// What the game does at each step of the retry loop. +struct CheckpointAttempts{ + // Attempts before the loop gives up. + size_t max_attempts; + // Runs attempt `attempt`, counting from 1. + std::function run; + // Goes back to the checkpoint's start save before attempt + // `next_attempt`, writing its own log line. Returns false when it could + // not, which ends the loop. + std::function reset; + CheckpointLogger log; +}; + +// What the loop came to. +struct CheckpointAttemptsResult{ + bool passed = false; + // Attempts run, counting the last one. + size_t attempts = 0; +}; + +// Runs `checkpoint` until an attempt passes, an attempt is FINAL, +// `max_attempts` attempts failed, or a reset failed. Writes the pass line. +// Exceptions from `run` and `reset` pass through. +CheckpointAttemptsResult run_checkpoint_attempts(std::string_view checkpoint, const CheckpointAttempts& attempts); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp index 3f30be451d..bf5505cf7b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp @@ -18,26 +18,34 @@ size_t run_checkpoint_with_retries( AutoStoryStats& stats ){ actions.log(checkpoint_start_line(checkpoint)); - for (size_t attempt = 1;; attempt++){ - try{ + const CheckpointAttempts attempts{ + .max_attempts = policy.max_attempts, + .run = [&](size_t attempt){ actions.log(checkpoint_attempt_line(checkpoint, attempt, policy.max_attempts)); - actions.run(attempt); - actions.log(checkpoint_pass_line(checkpoint, attempt)); - return attempt; - }catch (OperationFailedException& e){ - if (attempt == policy.report_at_failure){ - actions.report(e); + try{ + actions.run(attempt); + return AttemptResult::PASSED; + }catch (OperationFailedException& e){ + if (attempt == policy.report_at_failure){ + actions.report(e); + } + if (attempt >= policy.max_attempts){ + actions.give_up(e); + throw; + } + return AttemptResult::FAILED; } - if (attempt >= policy.max_attempts){ - actions.give_up(e); - throw; - } - actions.log(checkpoint_reset_line(checkpoint, attempt + 1)); + }, + .reset = [&](size_t next_attempt){ + actions.log(checkpoint_reset_line(checkpoint, next_attempt)); actions.reset(); stats.m_reset++; actions.update_stats(); - } - } + return true; + }, + .log = actions.log, + }; + return run_checkpoint_attempts(checkpoint, attempts).attempts; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h index 05ac68e781..bab3477f7f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h @@ -2,10 +2,10 @@ * * From: https://github.com/PokemonAutomation/ * - * The retry policy of a game whose AutoStory runs each checkpoint in its - * own loop (SV's): run the checkpoint, and on an operation failure reset - * the game to the checkpoint's save and try again, report once for - * debugging after some failures, and give up after the last attempt. + * SV's checkpoint retry policy on the shared loop (Pokemon_CheckpointAttempts.h): + * an attempt fails by throwing OperationFailedException; on a failure SV + * resets the game to the checkpoint's save and tries again, reports once + * for debugging after some failures, and gives up after the last attempt. * The game supplies what it does at each step; the policy, the counters * and the log lines (Pokemon_StoryLog.h) live here. * @@ -20,12 +20,13 @@ #include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_AutoStoryStats.h" +#include "Pokemon_CheckpointAttempts.h" namespace PokemonAutomation{ namespace Pokemon{ -// How often a checkpoint retries and when it reports. +// SV's policy: how often a checkpoint retries and when it reports. struct CheckpointRetryPolicy{ // Attempts before the checkpoint gives up. size_t max_attempts; @@ -37,10 +38,8 @@ struct CheckpointRetryPolicy{ using CheckpointStep = std::function; // A game step on the failure that reached a policy count. using CheckpointFailureStep = std::function; -// Writes one log line. -using CheckpointLogger = std::function; -// What the game does at each step of the loop. +// What SV does at each step of the loop, where a failed attempt throws. struct CheckpointRetryActions{ // Runs attempt `attempt`, counting from 1. Throws // OperationFailedException when the attempt fails. @@ -57,8 +56,10 @@ struct CheckpointRetryActions{ CheckpointLogger log; }; -// Runs `checkpoint` until an attempt passes, and returns that attempt's -// number. Each reset adds to `stats.m_reset`. +// Runs `checkpoint` through run_checkpoint_attempts() with the start, +// attempt and reset lines, until an attempt passes, and returns that +// attempt's number. After the last attempt fails it calls `give_up` and +// rethrows. Each reset adds to `stats.m_reset`. size_t run_checkpoint_with_retries( std::string_view checkpoint, const CheckpointRetryPolicy& policy, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp index 3d1015cbc2..f15024a653 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp @@ -182,6 +182,104 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { }; +// A checkpoint whose attempts end as `results` says, in order, and whose +// resets fail from `reset_fails_at` on (0: never). +struct CheckpointAttemptsInput{ + std::string name; + size_t max_attempts; + std::vector results; + size_t reset_fails_at = 0; +}; + +struct CheckpointAttemptsExpectation{ + bool passed; + size_t attempts; + // The attempt each reset was for. + std::vector resets; + std::vector log; +}; + +// One run of the shared loop and what it must do. +struct CheckpointAttemptsCase{ + CheckpointAttemptsInput input; + CheckpointAttemptsExpectation expectation; +}; + +class Test_CheckpointAttempts : public UnitTest{ +public: + Test_CheckpointAttempts(CheckpointAttemptsCase test_case) + : UnitTest(std::format("Pokemon::CheckpointRetry - attempts: {}", test_case.input.name)) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const CheckpointAttemptsInput& input = m_case.input; + std::vector resets; + std::vector log; + const CheckpointAttempts attempts{ + .max_attempts = input.max_attempts, + .run = [&](size_t attempt){ + return attempt <= input.results.size() ? input.results[attempt - 1] : AttemptResult::FINAL; + }, + .reset = [&](size_t next_attempt){ + resets.push_back(next_attempt); + return input.reset_fails_at == 0 || next_attempt < input.reset_fails_at; + }, + .log = [&](const std::string& line){ + log.push_back(line); + }, + }; + const CheckpointAttemptsResult result = run_checkpoint_attempts("01", attempts); + const CheckpointAttemptsExpectation& expected = m_case.expectation; + if (result.passed != expected.passed || result.attempts != expected.attempts){ + return std::format( + "Expected passed {} after {} attempts, got {} after {}", + expected.passed, expected.attempts, result.passed, result.attempts + ); + } + if (resets != expected.resets){ + return std::format("Expected {} resets, got {}", expected.resets.size(), resets.size()); + } + if (log != expected.log){ + return std::format("Expected {} log lines, got {}", expected.log.size(), log.size()); + } + return true; + } + +private: + const CheckpointAttemptsCase m_case; +}; + +const CheckpointAttemptsCase CHECKPOINT_ATTEMPTS_CASES[] = { + { + .input = {.name = "pass after a reset", .max_attempts = 3, .results = {AttemptResult::FAILED, AttemptResult::PASSED}}, + .expectation = { + .passed = true, + .attempts = 2, + .resets = {2}, + .log = {"[Checkpoint] 01: passed on attempt 2 (1 reset)"}, + }, + }, + { + .input = {.name = "a final failure stops without a reset", .max_attempts = 3, .results = {AttemptResult::FINAL}}, + .expectation = {.passed = false, .attempts = 1, .resets = {}, .log = {}}, + }, + { + .input = {.name = "no reset after the last attempt", .max_attempts = 2, .results = {AttemptResult::FAILED, AttemptResult::FAILED}}, + .expectation = {.passed = false, .attempts = 2, .resets = {2}, .log = {}}, + }, + { + .input = { + .name = "a failed reset stops", + .max_attempts = 3, + .results = {AttemptResult::FAILED, AttemptResult::FAILED}, + .reset_fails_at = 3, + }, + .expectation = {.passed = false, .attempts = 2, .resets = {2, 3}, .log = {}}, + }, +}; + + // `saves` checkpoint saves in a row. struct CheckpointSavedInput{ std::string name; @@ -251,6 +349,9 @@ const CheckpointSavedCase CHECKPOINT_SAVED_CASES[] = { void add_tests_CheckpointRetry(UnitTestDatabase& database){ + for (const CheckpointAttemptsCase& test_case : CHECKPOINT_ATTEMPTS_CASES){ + database.add(test_case); + } for (const CheckpointRetryCase& test_case : CHECKPOINT_RETRY_CASES){ database.add(test_case); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5181f64ebb..fabfc70afb 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1492,6 +1492,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h + Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp + Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp From 9ad520ea43a8820f1be03d968df47937678c32e8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 13:55:05 -0800 Subject: [PATCH 44/85] AutoStory: [Checkpoint] lines take an optional display text A game whose checkpoints carry their own text that already says it is a checkpoint (SV's "Checkpoint:: 004 - 02 ...") passes it as display_text, and the line starts with it in place of "[Checkpoint] ", so the word is not doubled. The default, empty, keeps the current lines. StoryLog cases for both forms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_StoryLog.cpp | 38 ++++++++++++++----- .../Pokemon/AutoStory/Pokemon_StoryLog.h | 17 +++++++-- .../AutoStory/Pokemon_StoryLog_Tests.cpp | 21 ++++++++++ 3 files changed, 62 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp index 63684e54f8..2d002518ff 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -20,6 +20,14 @@ std::string resets_text(size_t attempt){ return std::format("{} reset{}", attempt - 1, attempt == 2 ? "" : "s"); } +// "[Checkpoint] 00.04", or the game's own display text. +std::string checkpoint_head(std::string_view checkpoint, std::string_view display_text){ + if (!display_text.empty()){ + return std::string(display_text); + } + return std::format("[Checkpoint] {}", checkpoint); +} + } // namespace @@ -27,26 +35,36 @@ std::string event_log_line(std::string_view checkpoint, size_t number, std::stri return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); } -std::string checkpoint_start_line(std::string_view checkpoint, std::optional events){ +std::string checkpoint_start_line( + std::string_view checkpoint, std::optional events, std::string_view display_text +){ + const std::string head = checkpoint_head(checkpoint, display_text); if (!events){ - return std::format("[Checkpoint] {}: start", checkpoint); + return std::format("{}: start", head); } - return std::format("[Checkpoint] {}: start, {} events", checkpoint, *events); + return std::format("{}: start, {} events", head, *events); } -std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt, std::optional attempts){ +std::string checkpoint_attempt_line( + std::string_view checkpoint, size_t attempt, std::optional attempts, std::string_view display_text +){ + const std::string head = checkpoint_head(checkpoint, display_text); if (!attempts){ - return std::format("[Checkpoint] {}: attempt {}", checkpoint, attempt); + return std::format("{}: attempt {}", head, attempt); } - return std::format("[Checkpoint] {}: attempt {}/{}", checkpoint, attempt, *attempts); + return std::format("{}: attempt {}/{}", head, attempt, *attempts); } -std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt){ - return std::format("[Checkpoint] {}: passed on attempt {} ({})", checkpoint, attempt, resets_text(attempt)); +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, std::string_view display_text){ + return std::format( + "{}: passed on attempt {} ({})", checkpoint_head(checkpoint, display_text), attempt, resets_text(attempt) + ); } -std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt){ - return std::format("[Checkpoint] {}: failed, resetting for attempt {}", checkpoint, next_attempt); +std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt, std::string_view display_text){ + return std::format( + "{}: failed, resetting for attempt {}", checkpoint_head(checkpoint, display_text), next_attempt + ); } std::string segment_reload_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h index 7d1d5b5edc..9b0f368a18 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -28,29 +28,38 @@ namespace Pokemon{ // [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status); +// The [Checkpoint] lines below name a checkpoint by its id. A game whose +// checkpoints have their own text that already says it is a checkpoint +// (SV's "Checkpoint:: 004 - 02 ...") passes that as `display_text`, and +// the line starts with it in place of "[Checkpoint] ": +// Checkpoint:: 004 - 02 ...: start + // A checkpoint starts; the story engine also says it has `events` events: // [Checkpoint] 00.04: start // [Checkpoint] 00.04: start, 3 events -std::string checkpoint_start_line(std::string_view checkpoint, std::optional events = std::nullopt); +std::string checkpoint_start_line( + std::string_view checkpoint, std::optional events = std::nullopt, std::string_view display_text = "" +); // An attempt at a checkpoint starts, counting from 1, out of the // program's limit of `attempts` if it has one: // [Checkpoint] 00.04: attempt 2 // [Checkpoint] 00.04: attempt 2/3 std::string checkpoint_attempt_line( - std::string_view checkpoint, size_t attempt, std::optional attempts = std::nullopt + std::string_view checkpoint, size_t attempt, std::optional attempts = std::nullopt, + std::string_view display_text = "" ); // A checkpoint passed on attempt `attempt`, counting from 1; every attempt // before it ended in a reset: // [Checkpoint] 00.03: passed on attempt 1 (one-shot) // [Checkpoint] 00.04: passed on attempt 3 (2 resets) -std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt); +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, std::string_view display_text = ""); // An attempt failed and the game resets to the checkpoint's save for // attempt `next_attempt`: // [Checkpoint] 00.04: failed, resetting for attempt 2 -std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt); +std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt, std::string_view display_text = ""); // The story engine reloads within segment `segment`, out of `attempts`: // [Segment] 00: 00.02 failed, reloading for attempt 2/3 diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp index 7c705d7d74..f8063b7a2f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -5,7 +5,9 @@ */ #include +#include #include +#include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_StoryLog.h" @@ -51,6 +53,9 @@ class Test_StoryLog : public UnitTest{ const StoryLogTestCase m_case; }; +// SV's display text for a checkpoint, which already says "Checkpoint::". +constexpr std::string_view SV_TEXT = "Checkpoint:: 004 - 02. Start point: X"; + const StoryLogTestCase STORY_LOG_CASES[] = { { .input = {.name = "event", .line = event_log_line("00.04", 3, "talk_mom", "start")}, @@ -88,6 +93,22 @@ const StoryLogTestCase STORY_LOG_CASES[] = { .input = {.name = "reset", .line = checkpoint_reset_line("00.04", 2)}, .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2"}, }, + { + .input = {.name = "start with display text", .line = checkpoint_start_line("004", std::nullopt, SV_TEXT)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: start"}, + }, + { + .input = {.name = "attempt with display text", .line = checkpoint_attempt_line("004", 2, 100, SV_TEXT)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: attempt 2/100"}, + }, + { + .input = {.name = "pass with display text", .line = checkpoint_pass_line("004", 2, SV_TEXT)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: passed on attempt 2 (1 reset)"}, + }, + { + .input = {.name = "reset with display text", .line = checkpoint_reset_line("004", 2, SV_TEXT)}, + .expectation = {.line = "Checkpoint:: 004 - 02. Start point: X: failed, resetting for attempt 2"}, + }, { .input = {.name = "reload within a segment", .line = segment_reload_line("00", "00.02", 2, 3)}, .expectation = {.line = "[Segment] 00: 00.02 failed, reloading for attempt 2/3"}, From 86034a257e00d96200d547e35d87a3e3d2153ab6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 13:56:18 -0800 Subject: [PATCH 45/85] Pokemon AutoStory: SV's retry lines use its checkpoint text as display text run_checkpoint_with_retries() passes SV's "Checkpoint:: ..." text as the [Checkpoint] lines' display text (#45), so the lines read "Checkpoint:: 004 - 02 ...: start" without the word doubled, and SV keeps passing the text it has. CheckpointAttempts carries the display text for the pass line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_CheckpointAttempts.cpp | 2 +- .../AutoStory/Pokemon_CheckpointAttempts.h | 3 ++ .../AutoStory/Pokemon_CheckpointRetry.cpp | 11 ++--- .../AutoStory/Pokemon_CheckpointRetry.h | 9 ++-- .../Pokemon_CheckpointRetry_Tests.cpp | 44 +++++++++---------- 5 files changed, 37 insertions(+), 32 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp index 7a87749188..5f9df065b6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.cpp @@ -18,7 +18,7 @@ CheckpointAttemptsResult run_checkpoint_attempts(std::string_view checkpoint, co const AttemptResult outcome = attempts.run(attempt); if (outcome == AttemptResult::PASSED){ result.passed = true; - attempts.log(checkpoint_pass_line(checkpoint, attempt)); + attempts.log(checkpoint_pass_line(checkpoint, attempt, attempts.display_text)); return result; } if (outcome == AttemptResult::FINAL || attempt >= attempts.max_attempts){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h index 813fad9db4..795655a996 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointAttempts.h @@ -49,6 +49,9 @@ struct CheckpointAttempts{ // not, which ends the loop. std::function reset; CheckpointLogger log; + // The game's own text for the checkpoint, if its lines use one + // (checkpoint_start_line()). + std::string_view display_text = ""; }; // What the loop came to. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp index bf5505cf7b..31f0cce4b7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.cpp @@ -12,16 +12,16 @@ namespace Pokemon{ size_t run_checkpoint_with_retries( - std::string_view checkpoint, + std::string_view checkpoint_text, const CheckpointRetryPolicy& policy, const CheckpointRetryActions& actions, AutoStoryStats& stats ){ - actions.log(checkpoint_start_line(checkpoint)); + actions.log(checkpoint_start_line(checkpoint_text, std::nullopt, checkpoint_text)); const CheckpointAttempts attempts{ .max_attempts = policy.max_attempts, .run = [&](size_t attempt){ - actions.log(checkpoint_attempt_line(checkpoint, attempt, policy.max_attempts)); + actions.log(checkpoint_attempt_line(checkpoint_text, attempt, policy.max_attempts, checkpoint_text)); try{ actions.run(attempt); return AttemptResult::PASSED; @@ -37,15 +37,16 @@ size_t run_checkpoint_with_retries( } }, .reset = [&](size_t next_attempt){ - actions.log(checkpoint_reset_line(checkpoint, next_attempt)); + actions.log(checkpoint_reset_line(checkpoint_text, next_attempt, checkpoint_text)); actions.reset(); stats.m_reset++; actions.update_stats(); return true; }, .log = actions.log, + .display_text = checkpoint_text, }; - return run_checkpoint_attempts(checkpoint, attempts).attempts; + return run_checkpoint_attempts(checkpoint_text, attempts).attempts; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h index bab3477f7f..35afade804 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry.h @@ -56,12 +56,13 @@ struct CheckpointRetryActions{ CheckpointLogger log; }; -// Runs `checkpoint` through run_checkpoint_attempts() with the start, +// Runs the checkpoint through run_checkpoint_attempts() with the start, // attempt and reset lines, until an attempt passes, and returns that -// attempt's number. After the last attempt fails it calls `give_up` and -// rethrows. Each reset adds to `stats.m_reset`. +// attempt's number. SV's lines name the checkpoint by `checkpoint_text` +// ("Checkpoint:: 004 - 02 ..."), its display text. After the last attempt +// fails it calls `give_up` and rethrows. Each reset adds to `stats.m_reset`. size_t run_checkpoint_with_retries( - std::string_view checkpoint, + std::string_view checkpoint_text, const CheckpointRetryPolicy& policy, const CheckpointRetryActions& actions, AutoStoryStats& stats diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp index f15024a653..948c522412 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_CheckpointRetry_Tests.cpp @@ -77,7 +77,7 @@ CheckpointRetryRecord run_case(const CheckpointRetryInput& input, AutoStoryStats }, }; try{ - record.passed_on = run_checkpoint_with_retries("01", input.policy, actions, stats); + record.passed_on = run_checkpoint_with_retries("Checkpoint:: 01", input.policy, actions, stats); }catch (GaveUp&){ record.passed_on = 0; } @@ -125,9 +125,9 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { .reports = {}, .resets = 0, .log = { - "[Checkpoint] 01: start", - "[Checkpoint] 01: attempt 1/3", - "[Checkpoint] 01: passed on attempt 1 (one-shot)", + "Checkpoint:: 01: start", + "Checkpoint:: 01: attempt 1/3", + "Checkpoint:: 01: passed on attempt 1 (one-shot)", }, }, }, @@ -138,11 +138,11 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { .reports = {}, .resets = 1, .log = { - "[Checkpoint] 01: start", - "[Checkpoint] 01: attempt 1/3", - "[Checkpoint] 01: failed, resetting for attempt 2", - "[Checkpoint] 01: attempt 2/3", - "[Checkpoint] 01: passed on attempt 2 (1 reset)", + "Checkpoint:: 01: start", + "Checkpoint:: 01: attempt 1/3", + "Checkpoint:: 01: failed, resetting for attempt 2", + "Checkpoint:: 01: attempt 2/3", + "Checkpoint:: 01: passed on attempt 2 (1 reset)", }, }, }, @@ -153,15 +153,15 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { .reports = {2}, .resets = 3, .log = { - "[Checkpoint] 01: start", - "[Checkpoint] 01: attempt 1/5", - "[Checkpoint] 01: failed, resetting for attempt 2", - "[Checkpoint] 01: attempt 2/5", - "[Checkpoint] 01: failed, resetting for attempt 3", - "[Checkpoint] 01: attempt 3/5", - "[Checkpoint] 01: failed, resetting for attempt 4", - "[Checkpoint] 01: attempt 4/5", - "[Checkpoint] 01: passed on attempt 4 (3 resets)", + "Checkpoint:: 01: start", + "Checkpoint:: 01: attempt 1/5", + "Checkpoint:: 01: failed, resetting for attempt 2", + "Checkpoint:: 01: attempt 2/5", + "Checkpoint:: 01: failed, resetting for attempt 3", + "Checkpoint:: 01: attempt 3/5", + "Checkpoint:: 01: failed, resetting for attempt 4", + "Checkpoint:: 01: attempt 4/5", + "Checkpoint:: 01: passed on attempt 4 (3 resets)", }, }, }, @@ -172,10 +172,10 @@ const CheckpointRetryCase CHECKPOINT_RETRY_CASES[] = { .reports = {2}, .resets = 1, .log = { - "[Checkpoint] 01: start", - "[Checkpoint] 01: attempt 1/2", - "[Checkpoint] 01: failed, resetting for attempt 2", - "[Checkpoint] 01: attempt 2/2", + "Checkpoint:: 01: start", + "Checkpoint:: 01: attempt 1/2", + "Checkpoint:: 01: failed, resetting for attempt 2", + "Checkpoint:: 01: attempt 2/2", }, }, }, From f72260e0f38413ad0997c74e16b0226b5181c9b5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 13:56:56 -0800 Subject: [PATCH 46/85] Pokemon AutoStory: story segments retry through run_checkpoint_attempts() run_row() keeps its lines and counts (pass line, the game-not-running stop, the segment reload line, report.reloads) and hands the loop to the shared retry loop from #391. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StorySegments.cpp | 72 ++++++++++--------- 1 file changed, 40 insertions(+), 32 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index c6cd802e00..4c5b37e14e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -6,6 +6,7 @@ #include #include +#include "Pokemon_CheckpointAttempts.h" #include "Pokemon_StoryLog.h" #include "Pokemon_StorySegments.h" @@ -103,42 +104,49 @@ Outcome reload(RunState& state, SegmentHooks& hooks){ return outcome_ok(); } -// One row to success, reloading and rebuilding after each failed attempt. -// Returns the last attempt's report, or the reload's failure; `run` says -// how many attempts it took. +// One row to success through run_checkpoint_attempts(), reloading and +// rebuilding after each failed attempt. Returns the last attempt's report, +// or the reload's failure; `run` says how many attempts it took. CheckpointReport run_row( const Segment& segment, const SegmentPolicy& policy, CheckpointSpec& spec, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run, RunState& state ){ - for (size_t attempt = 1; ; attempt++){ - run.attempts = attempt; - Checkpoint checkpoint = spec.build(); - if (spec.saves && !checkpoint.save){ - checkpoint.save = [&hooks](RunState& state){ - return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); - }; - } - EventLogger log = [&hooks](const std::string& line){ say(line, hooks); }; - CheckpointReport result = run_checkpoint(state, checkpoint, log); - if (result.completed){ - run.passed = true; - say(checkpoint_pass_line(spec.id, attempt), hooks); - return result; - } - if (result.failure.failure == GAME_NOT_RUNNING){ - say(std::format("[Segment] {}: {} failed; the game is not running, so no reload", segment.id, spec.id), hooks); - return result; - } - if (attempt >= policy.attempts_per_checkpoint){ - return result; - } - say(segment_reload_line(segment.id, spec.id, attempt + 1, policy.attempts_per_checkpoint), hooks); - report.reloads++; - Outcome reloaded = reload(state, hooks); - if (!reloaded.succeeded()){ - return failed_report(std::move(reloaded)); - } - } + CheckpointReport result; + const CheckpointAttempts attempts{ + .max_attempts = policy.attempts_per_checkpoint, + .run = [&](size_t attempt){ + run.attempts = attempt; + Checkpoint checkpoint = spec.build(); + if (spec.saves && !checkpoint.save){ + checkpoint.save = [&hooks](RunState& state){ + return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); + }; + } + EventLogger log = [&hooks](const std::string& line){ say(line, hooks); }; + result = run_checkpoint(state, checkpoint, log); + if (result.completed){ + return AttemptResult::PASSED; + } + if (result.failure.failure == GAME_NOT_RUNNING){ + say(std::format("[Segment] {}: {} failed; the game is not running, so no reload", segment.id, spec.id), hooks); + return AttemptResult::FINAL; + } + return AttemptResult::FAILED; + }, + .reset = [&](size_t next_attempt){ + say(segment_reload_line(segment.id, spec.id, next_attempt, policy.attempts_per_checkpoint), hooks); + report.reloads++; + Outcome reloaded = reload(state, hooks); + if (!reloaded.succeeded()){ + result = failed_report(std::move(reloaded)); + return false; + } + return true; + }, + .log = [&hooks](const std::string& line){ say(line, hooks); }, + }; + run.passed = run_checkpoint_attempts(spec.id, attempts).passed; + return result; } SegmentReport stop_segment(const std::string& id, Outcome failure, SegmentHooks& hooks, SegmentReport& report){ From a76f816394d9785bbd1668305b6dc407da359ea7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 14:00:40 -0800 Subject: [PATCH 47/85] AutoStory engine: retries through run_checkpoint_attempts() run_with_retries() keeps its lines and counts (the reload line, the pass line, no reload for a failure every attempt repeats, a failed reload ends the checkpoint) and hands the loop to the shared retry loop from #391. StoryEngine retry cases pin the lines and attempt counts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Engine/Pokemon_StoryEngine.cpp | 49 +++++++----- .../Engine/Pokemon_StoryEngineRuns_Tests.cpp | 74 +++++++++++++++++++ 2 files changed, 103 insertions(+), 20 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp index e215a54d82..f86281cee6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine.cpp @@ -9,6 +9,7 @@ #include #include #include +#include "Pokemon/AutoStory/Pokemon_CheckpointAttempts.h" #include "Pokemon/AutoStory/Pokemon_StoryEvents.h" #include "Pokemon_StoryEngine.h" @@ -234,26 +235,34 @@ template StoryEngineReport StoryEngine::run_with_retries( const StoryCheckpoint& checkpoint, SavePoint point, size_t attempts, RunState& state, CheckpointRun& run ){ - for (size_t attempt = 1; ; attempt++){ - run.attempts = attempt; - StoryEngineReport report = run_checkpoint(checkpoint, point, state); - if (report.verdict == CheckpointVerdict::PASSED){ - run.passed = true; - m_backend.log(checkpoint_pass_line(checkpoint.id, attempt)); - return report; - } - if (attempt >= attempts || repeats_on_reload(report.run.failure)){ - return report; - } - m_backend.log(std::format("[Segment] {}: failed, reloading for attempt {}/{}", checkpoint.id, attempt + 1, attempts)); - const Outcome reloaded = reload(state); - if (!reloaded.succeeded()){ - report.run.completed = false; - report.run.failed_name.clear(); - report.run.failure = reloaded; - return report; - } - } + StoryEngineReport report; + const CheckpointAttempts loop{ + .max_attempts = attempts, + .run = [&](size_t attempt){ + run.attempts = attempt; + report = run_checkpoint(checkpoint, point, state); + if (report.verdict == CheckpointVerdict::PASSED){ + return AttemptResult::PASSED; + } + return repeats_on_reload(report.run.failure) ? AttemptResult::FINAL : AttemptResult::FAILED; + }, + .reset = [&](size_t next_attempt){ + m_backend.log(std::format("[Segment] {}: failed, reloading for attempt {}/{}", checkpoint.id, next_attempt, attempts)); + const Outcome reloaded = reload(state); + if (!reloaded.succeeded()){ + report.run.completed = false; + report.run.failed_name.clear(); + report.run.failure = reloaded; + return false; + } + return true; + }, + .log = [this](const std::string& line){ + m_backend.log(line); + }, + }; + run.passed = run_checkpoint_attempts(checkpoint.id, loop).passed; + return report; } template diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp index e15bd54774..9e5f141d09 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp @@ -651,6 +651,77 @@ class StorySegmentTest : public UnitTest{ SegmentCase m_case; }; +// The engine's retries run through run_checkpoint_attempts(): the same +// reload and pass lines and attempt counts as its own loop had. +struct RetryCase{ + struct Input{ + std::string_view name; + // Calls of the checkpoint's action that fail before one passes. + size_t failures = 0; + size_t attempts = 0; + }; + + struct Expectation{ + bool passed = false; + size_t attempts = 0; + // Lines the run writes once each. + std::vector lines; + }; + + Input input; + Expectation expectation; +}; + +const RetryCase RETRY_CASES[] = { + {.input = {.name = "pass after a reload", .failures = 1, .attempts = 3}, + .expectation = {.passed = true, .attempts = 2, .lines = { + "[Segment] 01: failed, reloading for attempt 2/3", + "[Test] reload", + "[Checkpoint] 01: passed on attempt 2 (1 reset)", + }}}, + {.input = {.name = "stop after the last attempt", .failures = 5, .attempts = 2}, + .expectation = {.passed = false, .attempts = 2, .lines = { + "[Segment] 01: failed, reloading for attempt 2/2", + "[Test] reload", + }}}, +}; + +std::string check_retry(const RetryCase& test, CancellableScope& scope){ + const StoryGame game = flaky_game(test.input.failures); + FakeStoryBackend backend({.looks = {look({ScreenEvent::CAN_MOVE})}}, scope); + StoryEngine engine(game, backend); + const std::vector checkpoints{checkpoint_of("01", {game_step("walk", "flaky")})}; + RunState state; + const SegmentReport report = engine.run_segment("seg", checkpoints, test.input.attempts, state); + const CheckpointRun& run = report.runs.at(0); + if (run.passed != test.expectation.passed || run.attempts != test.expectation.attempts){ + return std::format( + "expected passed {} after {} attempts, got {} after {}: {}", + test.expectation.passed, test.expectation.attempts, run.passed, run.attempts, joined(backend.lines()) + ); + } + for (std::string_view line : test.expectation.lines){ + if (count_lines(backend, line) != 1){ + return std::format("expected \"{}\" once: {}", line, joined(backend.lines())); + } + } + return ""; +} + +class StoryRetryTest : public UnitTest{ +public: + explicit StoryRetryTest(RetryCase test) + : UnitTest(std::format("Pokemon::StoryEngine retry - {}", test.input.name)) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope& scope) const override{ + const std::string error = check_retry(m_case, scope); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + RetryCase m_case; +}; + // Gap 7: verify runs a checkpoint 3 times from one save, saving only at // the end of the last, and only when every run passed. std::string verify_saves_after_all_passed(CancellableScope& scope){ @@ -735,6 +806,9 @@ void add_tests_StoryEngineRuns(UnitTestDatabase& database){ for (const SegmentCase& test : SEGMENT_CASES){ database.add(test); } + for (const RetryCase& test : RETRY_CASES){ + database.add(test); + } } From 73fecab6efc236e94360d4d07a240b660f94c790 Mon Sep 17 00:00:00 2001 From: Dalton <59972310+Dalton-V@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:38:18 -0600 Subject: [PATCH 48/85] FRLG Box Sorter - BallReader (#1908) --- .../Inference/PokemonFRLG_BallReader.cpp | 138 ++++++++++++++++++ .../Inference/PokemonFRLG_BallReader.h | 40 +++++ .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../PokemonFRLG_BoxOrganization.cpp | 35 ++++- .../PokemonFRLG_BoxOrganization.h | 4 +- .../BoxOrganization/PokemonFRLG_BoxSorter.cpp | 8 +- .../PokemonFRLG_BoxSorterLivingDex.cpp | 1 - .../PokemonFRLG_BoxSorter_Tests.cpp | 26 ++++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 9 files changed, 246 insertions(+), 10 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.cpp new file mode 100644 index 0000000000..ae9d4c111c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.cpp @@ -0,0 +1,138 @@ +/* Ball Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "CommonTools/Resources/SpriteDatabase.h" +#include "Tests/ImageUnitTest.h" +#include "Tests/TestUtils.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_BallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +namespace{ + +constexpr double MAX_ALPHA = 0.40; +constexpr double ALPHA_SPREAD = 0.02; +constexpr double MIN_BACKGROUND_DISTANCE = 100; +const ImageFloatBox BALL_BOX(0.410, 0.507, 0.063, 0.084); + +class PokeballSpriteMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ +public: + PokeballSpriteMatcher() + : CroppedImageDictionaryMatcher({1, 128}) + { + const SpriteDatabase sprites("PokemonFRLG/PokeballSprites.png", "PokemonFRLG/PokeballSprites.json"); + for (const auto& item : sprites){ + add(item.first, item.second.sprite); + } + } + +private: + std::vector get_crop_candidates(const ImageViewRGB32& image) const override{ + const FloatPixel background = image_border_stats(image).average; + const ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + image, + [&](Color pixel){ + double r = (double)pixel.red() - background.r; + double g = (double)pixel.green() - background.g; + double b = (double)pixel.blue() - background.b; + return r*r + g*g + b*b >= MIN_BACKGROUND_DISTANCE * MIN_BACKGROUND_DISTANCE; + } + ); + return {extract_box_reference(image, box)}; + } +}; + +} + + +BallReader::BallReader(VideoStream& stream) + : m_stream(stream) + , m_box_sprite(stream.overlay(), GameSettings::instance().GAME_BOX.inner_to_outer(BALL_BOX)) +{} + +std::string BallReader::read_ball(const ImageViewRGB32& screen) const{ + if (!screen){ + return ""; + } + + static const PokeballSpriteMatcher matcher; + const ImageViewRGB32 image = extract_box_reference(screen, m_box_sprite); + ImageMatch::ImageMatchResult result = matcher.match(image, ALPHA_SPREAD); + result.log(m_stream.logger(), MAX_ALPHA); + result.clear_beyond_alpha(MAX_ALPHA); + + if (result.results.size() != 1){ + dump_image(m_stream.logger(), ProgramInfo(), "FRLG-BallReader", screen); + } + if (result.results.empty()){ + return ""; + } + return result.results.begin()->second; +} + + +class Test_BallReader : public ImageUnitTest{ +public: + Test_BallReader(const std::string& image, std::string expected) + : ImageUnitTest("PokemonFRLG::BallReader - " + image, {"PokemonFRLG/StatsReader/Page1/" + image}) + , m_expected(std::move(expected)) + {} + +private: + UnitTestResult run_on_images( + Logger& logger, CancellableScope&, + const std::vector& images + ) const override{ + DummyAudioFeed audio_feed; + DummyVideoFeed video_feed; + StreamHistorySession history(logger); + DummyVideoOverlay overlay; + VideoStream stream(logger, audio_feed, video_feed, history, overlay); + BallReader reader(stream); + std::string result = reader.read_ball(images[0]); + if (result == m_expected){ + return true; + } + return "Expected: " + m_expected + ", received: " + result; + } + + std::string m_expected; +}; + +void add_tests_BallReader(UnitTestDatabase& database){ + database.add("abra_1_deu.png", "master-ball"); + database.add("bulbasaur_1_eng.png", "poke-ball"); + database.add("bulbasaur_1_fra.png", "poke-ball"); + database.add("bulbasaur_1_jpn.png", "poke-ball"); + database.add("bulbasaur_2_eng.png", "poke-ball"); + database.add("bulbasaur_3_eng.png", "poke-ball"); + database.add("bulbasaur_4_eng.png", "poke-ball"); + database.add("deoxys_1_jpn.png", "master-ball"); + database.add("horsea_1_deu.png", "master-ball"); + database.add("horsea_2_deu.png", "master-ball"); + database.add("horsea_3_deu.png", "master-ball"); + database.add("magikarp_1_spa.png", "poke-ball"); + database.add("moltres_1_eng.png", "master-ball"); + database.add("nidoran_m_eng.png", "ultra-ball"); + database.add("pidgey_1_ita.png", "poke-ball"); + database.add("venonat_4k_eng.png", "master-ball"); +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.h new file mode 100644 index 0000000000..f7e38d75c4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.h @@ -0,0 +1,40 @@ +/* Ball Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_BallReader_H +#define PokemonAutomation_PokemonFRLG_BallReader_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ + +class UnitTestDatabase; +class VideoStream; + +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +class BallReader{ +public: + BallReader(VideoStream& stream); + + // Read the ball slug from the first summary page. Return an empty string if no match is found. + std::string read_ball(const ImageViewRGB32& screen) const; + +private: + VideoStream& m_stream; + OverlayBoxScope m_box_sprite; +}; + +void add_tests_BallReader(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 94dc41dd85..31746134b7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -20,6 +20,7 @@ #include "Inference/Menus/PokemonFRLG_PartyEmptySlotDetector.h" #include "Inference/Menus/PokemonFRLG_PartyHeldItemDetector.h" #include "Inference/Menus/PokemonFRLG_PartyMenuDetector.h" +#include "Inference/PokemonFRLG_BallReader.h" #include "Inference/PokemonFRLG_BattleLevelUpReader.h" #include "Inference/PokemonFRLG_BattleSelectionArrowDetector.h" #include "Inference/PokemonFRLG_PartyLevelUpReader.h" @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AdvanceWhiteDialogDetector(database); add_tests_AdvanceBattleDialogDetector(database); add_tests_BagDetector(database); + add_tests_BallReader(database); add_tests_BattleLevelUpReader(database); add_tests_BattleMenuDetector(database); add_tests_BattleMoveSelectionArrow(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp index bfdbfab3f4..99847df668 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.cpp @@ -23,6 +23,7 @@ #include "VideoGames/PokemonFRLG/Inference/Box/PokemonFRLG_BoxGenderReader.h" #include "VideoGames/PokemonFRLG/Inference/Box/PokemonFRLG_BoxSelectionModeDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_SelectionArrowDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_ShinySymbolDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_StatsReader.h" @@ -162,8 +163,7 @@ void open_summary_screen(SingleSwitchProgramEnvironment& env, ProControllerConte wait_for_summary_animation(env, context); } -// Scroll through the detected pokemon and read their summary screens. -// Currently only reads shininess, but could be extended to read other summary information. +// Scroll through the detected Pokemon and read their shininess and ball type. void scan_box_summaries( SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, const BoxSelectionModeDetector& selection_detector, BoxCursor& cursor, @@ -180,7 +180,7 @@ void scan_box_summaries( return; } - env.log("Reading shininess in box " + std::to_string(cursor.box + 1)); + env.log("Reading summaries in box " + std::to_string(cursor.box + 1)); move_cursor_to(env, context, selection_detector, cursor, BoxCursor(occupied.back()), BoxSelectionMode::Normal); open_summary_screen(env, context); @@ -189,6 +189,8 @@ void scan_box_summaries( ShinySymbolDetector shiny_detector(COLOR_YELLOW); VideoOverlaySet overlays(env.console.overlay()); shiny_detector.make_overlays(overlays); + BallReader ball_reader(env.console); + for (size_t remaining = occupied.size(); remaining > 0; remaining--){ const size_t index = occupied[remaining - 1]; auto& pokemon = *boxes_data[index]; @@ -203,6 +205,21 @@ void scan_box_summaries( OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, ss.str(), env.console); } pokemon.shiny = shiny_detector.read(env.logger(), screen); + pokemon.ball_slug = ball_reader.read_ball(screen); + if (pokemon.ball_slug.empty()){ + std::ostringstream ss; + ss << "Box Sorter: Unable to read the ball type at " << BoxCursor(index) << "."; + env.log(ss.str(), COLOR_RED); + } + + std::ostringstream overview; + overview << "index:" << index + << ", name:" << pokemon.name_slug + << ", lvl:" << level_str(pokemon.level) + << ", shiny:" << (pokemon.shiny ? "True" : "False") + << ", ball:" << pokemon.ball_slug; + env.log(overview.str()); + pbf_press_dpad(context, DPAD_UP, 80ms, 300ms); context.wait_for_all_requests(); wait_for_summary_animation(env, context); @@ -421,10 +438,16 @@ std::string make_missing_living_dex_report( BoxOrganizationScan scan_box_data( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - Language language, const std::vector& preferences, size_t num_boxes, bool read_shininess + Language language, const std::vector& preferences, size_t num_boxes, bool force_summary_scan ){ - bool read_summary = read_shininess || std::any_of(preferences.begin(), preferences.end(), [](const SortingRule& rule){ - return rule.sort_type == SortingRuleType::Shiny; + const bool read_summary = force_summary_scan || std::any_of(preferences.begin(), preferences.end(), [](const SortingRule& rule){ + switch (rule.sort_type){ + case SortingRuleType::Shiny: + case SortingRuleType::Ball_Slug: + return true; + default: + return false; + } }); auto& stats = env.current_stats(); const size_t slot_count = num_boxes * BOX_ROWS * BOX_COLS; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h index b2401191e6..6c2e90348c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxOrganization.h @@ -75,11 +75,11 @@ struct BoxOrganizationScan{ BoxSelectionMode mode; }; -// Detecting Shiny requires reading the summary screen, this is much slower than just reading the box data. +// Scan summaries for rules that need summary data or when the caller requests a summary scan. BoxOrganizationScan scan_box_data( SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, const std::vector& preferences, size_t num_boxes, - bool read_shininess = false + bool force_summary_scan = false ); void execute_box_sorting_plan( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp index 6c2f7edbf5..dd725ec99d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter.cpp @@ -65,7 +65,13 @@ BoxSorter::BoxSorter() ) , SORT_TABLE( "Sort Order Rules:
Sort order rules will be applied top to bottom.", - {SortingRuleType::DexNo, SortingRuleType::Level, SortingRuleType::Gender, SortingRuleType::Shiny} + { + SortingRuleType::DexNo, + SortingRuleType::Level, + SortingRuleType::Gender, + SortingRuleType::Shiny, + SortingRuleType::Ball_Slug, + } ) , DRY_RUN( "Dry Run:
Scan boxes and write frlg-box_order.json and " diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp index aa48844633..6035c5c36e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorterLivingDex.cpp @@ -12,7 +12,6 @@ #include "CommonTools/StartupChecks/StartProgramChecks.h" #include "Pokemon/Pokemon_Strings.h" #include "PokemonFRLG_BoxOrganization.h" -#include "PokemonFRLG_BoxSorterLivingDex.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_BoxSorterLivingDex.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.cpp index f529d86d53..e63660ec33 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.cpp @@ -7,11 +7,14 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/GlobalAutoPaths.h" #include "Pokemon/Resources/Pokemon_PokemonSlugs.h" #include "PokemonFRLG_BoxOrganization.h" +#include "PokemonFRLG_BoxSorter.h" #include "PokemonFRLG_BoxSorter_Tests.h" namespace PokemonAutomation{ @@ -73,6 +76,29 @@ class Test_BoxSorter_Ordering : public UnitTest{ if (slots != std::vector>{low, high, shiny, std::nullopt}){ return "Reversed shiny sorting must put non-shinies first and empty slots last."; } + auto poke_ball = low; + poke_ball->ball_slug = "poke-ball"; + auto master_ball = poke_ball; + master_ball->ball_slug = "master-ball"; + auto high_poke_ball = high; + high_poke_ball->ball_slug = "poke-ball"; + rules = {{SortingRuleType::Ball_Slug, false}, {SortingRuleType::Level, false}}; + const std::vector> original{ + poke_ball, master_ball, high_poke_ball, std::nullopt + }; + slots = {high_poke_ball, std::nullopt, poke_ball, master_ball}; + std::stable_sort(slots.begin(), slots.end()); + if (slots != std::vector>{master_ball, poke_ball, high_poke_ball, std::nullopt}){ + return "Ball Type sorting must group balls alphabetically and break ties by level."; + } + if (make_box_sorting_plan(original, slots).chains != std::vector>{{0, 1, 0}}){ + return "The swap plan must distinguish Pokemon that differ only by ball type."; + } + rules[0].reverse = true; + std::stable_sort(slots.begin(), slots.end()); + if (slots != std::vector>{poke_ball, high_poke_ball, master_ball, std::nullopt}){ + return "Reversing Ball Type must leave the level tie-breaker and empty slots in order."; + } if (SLUGS_TO_NATIONAL_DEX().at("bulbasaur") != 1 || SLUGS_TO_NATIONAL_DEX().at("deoxys") != 386){ return "Species conversion must use National Dex numbers."; } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 03a76d8719..eb81069fbd 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1731,6 +1731,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryDetector.h Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.h + Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.cpp + Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BallReader.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.cpp Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.h Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattlePokemonDetector.cpp From 33fccf14156dcf5317eec60296ce0a2f8008494e Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 14:55:14 -0800 Subject: [PATCH 49/85] Leg planner: optional open_stop_risk() and tap_stop_risk() on the step model Moved from the FRLG stack, where they were edited in a game PR: open_stop_risk() from 3fc691772 (trainer sight as a route cost) and tap_stop_risk() from 9411b936a (a single step from where a hold to a wall ended can't stop part-way). Both are optional: a model without them plans as before. The LegPlanner header is taken unchanged from 9411b936a. (cherry picked from commit 3fc691772 and 9411b936a, Pokemon_LegPlanner.h only) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_LegPlanner.h | 50 ++++++++++++++++--- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h index 4ebb84e9c2..043b7e5306 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h @@ -25,6 +25,24 @@ * is whether holding `direction` keeps the player on this tile: a wall, but * not a person who may walk off or an edge to a map that isn't loaded. * + * A model may also have + * + * int open_stop_risk(const State& state, Direction direction) const; + * + * the extra cost of a leg that ends on `state` walking `direction` where + * the player could keep going: what a tile past the stop would cost, e.g. + * a tile a trainer may see, and + * + * std::optional tap_stop_risk(const State& state, Direction direction) const; + * + * for such a leg of one step from where a hold to a wall ended, the extra + * cost to weigh instead of open_stop_risk() and LegCosts::per_open_wild_stop, + * or nothing to weigh those. A step can't stop part-way, so where an + * interruption stopping it would leave the player is no guess: e.g. on + * open water, a hold to a wall and a tile on starts a leg down a column + * with no wall of its own. Once a route: a run of them, wall to wall, + * would weave round the open stops it can't avoid. + * */ #ifndef PokemonAutomation_Pokemon_LegPlanner_H @@ -128,14 +146,18 @@ std::optional>> plan_legs( namespace LegPlannerInternal{ // A search node: the player, the way they face (4: not known), whether -// they are in the middle of a leg that could go on, and whether that leg -// had a wild step. +// they are in the middle of a leg that could go on, whether that leg had a +// wild step, whether it is one step from where a hold to a wall ended, and +// whether such a step was stopped after earlier (see tap_stop_risk() at +// the top of this file). template struct Node{ State state; int facing = 4; bool moving = false; bool wild = false; + bool tap_from_wall = false; + bool tapped = false; bool operator==(const Node& other) const = default; }; @@ -144,7 +166,8 @@ struct Node{ template struct NodeHash{ size_t operator()(const Node& node) const{ - return StateHash()(node.state) * 20 + node.facing * 4 + (node.moving ? 2 : 0) + (node.wild ? 1 : 0); + return StateHash()(node.state) * 80 + node.facing * 16 + (node.moving ? 8 : 0) + (node.wild ? 4 : 0) + + (node.tap_from_wall ? 2 : 0) + (node.tapped ? 1 : 0); } }; @@ -162,7 +185,18 @@ int stop_cost(const Model& model, const Node& node, const LegCosts& costs if (!node.moving || model.held_at(node.state, (Direction)node.facing)){ return 0; } - return costs.per_open_stop + (node.wild ? costs.per_open_wild_stop : 0); + if constexpr (requires { model.tap_stop_risk(node.state, Direction::NORTH); }){ + if (node.tap_from_wall && !node.tapped){ + if (const std::optional risk = model.tap_stop_risk(node.state, (Direction)node.facing)){ + return costs.per_open_stop + *risk; + } + } + } + int cost = costs.per_open_stop + (node.wild ? costs.per_open_wild_stop : 0); + if constexpr (requires { model.open_stop_risk(node.state, Direction::NORTH); }){ + cost += model.open_stop_risk(node.state, (Direction)node.facing); + } + return cost; } // Combines atomic movement steps into contiguous legs. @@ -246,7 +280,11 @@ void expand( const bool continues = step->action == 0 && !step->ends_leg; const bool extends = current.moving && current.facing == (int)direction && step->action == 0 && !step->starts_leg; - const Node next{step->next, (int)step->facing, continues, (extends && current.wild) || step->wild}; + const bool from_wall = current.moving && model.held_at(current.state, (Direction)current.facing); + const Node next{ + step->next, (int)step->facing, continues, (extends && current.wild) || step->wild, + !extends && from_wall, current.tapped || (!extends && current.tap_from_wall) + }; int step_cost = costs.per_tile + step->extra_cost; if (current.facing != (int)direction){ step_cost += costs.per_turn + stop_cost(model, current, costs); @@ -344,7 +382,7 @@ std::optional>> plan_legs( using State = typename Model::State; using Node = LegPlannerInternal::Node; - const Node first{start, start_facing ? (int)*start_facing : 4, false, false}; + const Node first{start, start_facing ? (int)*start_facing : 4, false, false, false, false}; LegPlannerInternal::Search search; const std::optional end = LegPlannerInternal::search_goal(model, first, at_goal, goal_facing, costs, search); if (!end){ From 941b6762583cf6c7ebadd94c2b689659e65a1650 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 13 Nov 2026 14:56:13 -0800 Subject: [PATCH 50/85] Story events: Event::when_skipped runs when skip_if skips the event A skipped event's effect is already so, but what it leaves in the run state (a door it opens, a flag it sets) was lost. Moved from the FRLG stack, where bc6a55867 added it inside a game PR; StoryStepExecutor uses it for a skipped step's gates_after there. (cherry picked from commit bc6a55867, Pokemon_StoryEvent.h and Pokemon_StoryEvents.cpp only) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h | 4 ++++ .../Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 3 +++ 2 files changed, 7 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h index 48f20e317e..ffda3cee12 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h @@ -10,6 +10,7 @@ #define PokemonAutomation_Pokemon_StoryEvent_H #include +#include #include #include #include @@ -66,6 +67,9 @@ struct Event{ std::string why; // Skipped when all of these hold (and there is at least one). std::vector skip_if; + // Run when the event is skipped: what the event leaves in the run + // state that is already so (a door it opens, a flag it sets). + std::function when_skipped; // Must hold before `act`; a failure is "require_failed". std::vector require; Act act; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index 8afcdfe404..deb4003d8f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -412,6 +412,9 @@ CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLo EventRun run{checkpoint, c + 1, event, state, log, std::vector(event.recoveries.size(), 0), 0}; if (already_done(event, state)){ log_status("skipped", run); + if (event.when_skipped){ + event.when_skipped(state); + } report.events_skipped++; continue; } From 39f94a99f93dcff18b73ad3a1d78b305867eb46c Mon Sep 17 00:00:00 2001 From: theAstroGoth <52220914+theastrogoth@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:07:19 -0600 Subject: [PATCH 51/85] FRLG SpriteReader fixes and tests (#1913) * FRLG SpriteReader fixes and tests * allow for mirroring sprites left to right in SpriteDatabase --- .../CommonTools/Resources/SpriteDatabase.cpp | 16 +- .../CommonTools/Resources/SpriteDatabase.h | 10 +- .../Source/Pokemon/Pokemon_AdvRng.cpp | 14 +- .../Source/Pokemon/Pokemon_AdvRng.h | 9 +- .../PokemonFRLG_PokemonSpriteReader.cpp | 308 +++++++++++++++--- .../PokemonFRLG_PokemonSpriteReader.h | 76 ++++- .../Inference/PokemonFRLG_StatsReader.cpp | 7 + .../PokemonFRLG_WildEncounterReader.cpp | 28 +- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 3 + .../PokemonFRLG_RngCalibration.cpp | 2 +- .../PokemonFRLG_RngDisplays.cpp | 24 +- .../PokemonFRLG_RngNavigation.cpp | 10 +- .../Resources/PokemonFRLG_PokemonSprites.cpp | 63 +++- .../Resources/PokemonFRLG_PokemonSprites.h | 21 ++ 14 files changed, 501 insertions(+), 90 deletions(-) diff --git a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp index 9a615e8b4c..abf5aae895 100644 --- a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp +++ b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp @@ -4,6 +4,7 @@ * */ +#include #include "Common/Cpp/Json/JsonValue.h" #include "Common/Cpp/Json/JsonObject.h" #include "CommonFramework/GlobalAutoPaths.h" @@ -15,7 +16,10 @@ namespace PokemonAutomation{ -SpriteDatabase::SpriteDatabase(const char* sprite_path, const char* json_path) +SpriteDatabase::SpriteDatabase( + const char* sprite_path, const char* json_path, + const std::function& mirror_horizontally +) : m_backing_image(RESOURCE_PATH() + sprite_path) { std::string path = RESOURCE_PATH() + json_path; @@ -37,6 +41,16 @@ SpriteDatabase::SpriteDatabase(const char* sprite_path, const char* json_path) JsonObject& obj = item.second.to_object_throw(path); int y = (int)obj.get_integer_throw("top", path); int x = (int)obj.get_integer_throw("left", path); + if (mirror_horizontally && mirror_horizontally(slug)){ + if (x < 0 || y < 0 || (size_t)(x + width) > m_backing_image.width() || (size_t)(y + height) > m_backing_image.height()){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Sprite out of bounds: " + slug, path); + } + for (int r = y; r < y + (int)height; r++){ + for (int c0 = x, c1 = x + (int)width - 1; c0 < c1; c0++, c1--){ + std::swap(m_backing_image.pixel(c0, r), m_backing_image.pixel(c1, r)); + } + } + } ImageViewRGB32 sprite = extract_box_reference(m_backing_image, ImagePixelBox(x, y, x + width, y + height)); m_database.emplace( diff --git a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h index 3136ffd6ec..3213479227 100644 --- a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h +++ b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h @@ -7,6 +7,7 @@ #ifndef PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H #define PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H +#include #include #include "CommonFramework/ImageTypes/ImageRGB32.h" @@ -32,7 +33,14 @@ class SpriteDatabase{ // (next pokemon) ... // } // } - SpriteDatabase(const char* sprite_path, const char* json_path); + // + // If "mirror_horizontally" is set, each sprite for which it returns true + // is flipped left-to-right in place. This avoids storing a separate + // flipped copy of the image. + SpriteDatabase( + const char* sprite_path, const char* json_path, + const std::function& mirror_horizontally = nullptr + ); public: struct Sprite{ diff --git a/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.cpp b/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.cpp index aef20552e7..4f888bd9d1 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.cpp @@ -270,6 +270,18 @@ std::string base_species_slug(const std::string& species){ return species; } +bool species_matches(const std::string& observed, const std::string& candidate){ + const std::string base = base_species_slug(observed); + if (base != base_species_slug(candidate)){ + return false; + } + // Accept matches with the base slug in case form couldn't be read + if (observed == base || candidate == base){ + return true; + } + return observed == candidate; +} + int slot_to_unownform(AdvEncounterSlot slot){ if (slot.species.find("unown") == std::string::npos){ return -1; @@ -521,7 +533,7 @@ bool check_for_match(AdvPokemonResult res, AdvRngFilters target, int16_t gender_ } bool check_for_match(AdvWildPokemonResult res, AdvRngFilters target, int16_t gender_threshold, uint16_t tid_xor_sid){ - return (base_species_slug(target.species) == base_species_slug(res.species)) + return species_matches(target.species, res.species) && (target.level == res.level) && (target.nature == AdvNature::Any || (res.nature == target.nature)) && (target.ability == AdvAbility::Any || (res.ability == target.ability)) diff --git a/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.h b/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.h index 85a3ad8707..616063c46d 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_AdvRng.h @@ -202,11 +202,14 @@ Pokemon::NatureAdjustments nature_to_adjustment(AdvNature nature); Pokemon::AdvNature string_to_nature(const std::string& nature_string); std::string nature_to_string(const AdvNature& nature); -// Forms that cannot be told apart from an observation (e.g. Unown letters) share a base slug. -// Encounter slots carry the form-specific slug, while an observed species only ever carries -// the base slug, so both sides must be folded before they are compared. +// Forms of the same species (e.g. Unown letters) share a base slug. +// Encounter slots carry the form-specific slug (e.g. "unown-b"). std::string base_species_slug(const std::string& species); +// Return true if an observed species is consistent with a candidate species. +// Species with forms match by base slug, unless both sides name a specific form +bool species_matches(const std::string& observed, const std::string& candidate); + std::string gender_to_string(const AdvGender& gender); AdvGender gender_from_gender_value(uint8_t gender_value, int16_t threshold); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_PokemonSpriteReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_PokemonSpriteReader.cpp index 6e2c516038..f4e05933ce 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_PokemonSpriteReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_PokemonSpriteReader.cpp @@ -4,10 +4,14 @@ * */ +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonTools/ImageMatch/ImageCropper.h" +#include "Tests/ImageUnitTest.h" +#include "PokemonFRLG_ShinySymbolDetector.h" #include "VideoGames/PokemonFRLG/Resources/PokemonFRLG_PokemonSprites.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "PokemonFRLG_PokemonSpriteReader.h" @@ -17,78 +21,286 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -PokemonSpriteMatcherExact::PokemonSpriteMatcherExact(const std::set* subset, bool flipped) - : ExactImageDictionaryMatcher({1, 256}) +namespace{ + +// Positions are in GBA pixels. The GBA screen is 240 x 160. +constexpr int GBA_WIDTH = 240; +constexpr int GBA_HEIGHT = 160; +constexpr int SPRITE_SIZE = 64; + +ImageFloatBox sprite_box(int x, int y){ + return ImageFloatBox( + (double)x / GBA_WIDTH, (double)y / GBA_HEIGHT, + (double)SPRITE_SIZE / GBA_WIDTH, (double)SPRITE_SIZE / GBA_HEIGHT + ); +} + +// When the summary is opened, the sprite bounces up by as much as 9 pixels. +// the following allow 1 extra pixel of slack in each direction. +constexpr int SUMMARY_X_MIN = 27; +constexpr int SUMMARY_X_MAX = 31; +constexpr int SUMMARY_Y_MIN = 23; +constexpr int SUMMARY_Y_MAX = 34; + +// In battle, the sprite's top edge depends on the species and whether it floats. +constexpr int BATTLE_X = 144; +constexpr int BATTLE_Y_MIN = 0; +constexpr int BATTLE_Y_MAX = 36; + +} + + + +PositionedSpriteMatcher::PositionedSpriteMatcher( + const std::set* subset, + bool flipped, // most sprites are flipped on the summary screen + const std::vector& shiny_variants, // {false, true} to match against both normal and shiny sprites + int x_min, int x_max, int y_min, int y_max +) + : m_x_min(x_min), m_x_max(x_max) + , m_y_min(y_min), m_y_max(y_max) { - for (const auto& item : (flipped ? FLIPPED_POKEMON_SPRITES() : ALL_POKEMON_SPRITES())){ - if (subset == nullptr || subset->find(item.first) != subset->end()){ - add(item.first, item.second.sprite.copy()); + for (bool shiny : shiny_variants){ + for (const auto& item : POKEMON_SPRITES(shiny, flipped)){ + if (subset != nullptr && !sprite_in_species_subset(item.first, *subset)){ + continue; + } + m_templates.emplace_back(new Template{ + sprite_slug_to_species(item.first), + shiny, + ImageMatch::WeightedExactImageMatcher(item.second.sprite.copy(), {1, 256}) + }); } } } +ImageFloatBox PositionedSpriteMatcher::search_box() const{ + return ImageFloatBox( + (double)m_x_min / GBA_WIDTH, (double)m_y_min / GBA_HEIGHT, + (double)(m_x_max - m_x_min + SPRITE_SIZE) / GBA_WIDTH, + (double)(m_y_max - m_y_min + SPRITE_SIZE) / GBA_HEIGHT + ); +} -PokemonSpriteMatcherCropped::PokemonSpriteMatcherCropped(const std::set* subset, double min_euclidean_distance, bool flipped) - : CroppedImageDictionaryMatcher({1, 256}) - , m_min_euclidean_distance_squared(min_euclidean_distance * min_euclidean_distance) -{ - for (const auto& item : (flipped ? FLIPPED_POKEMON_SPRITES() : ALL_POKEMON_SPRITES())){ - if (subset == nullptr || subset->find(item.first) != subset->end()){ - add(item.first, item.second.sprite); +PositionedSpriteMatcher::Result PositionedSpriteMatcher::match( + const ImageViewRGB32& game_screen, double alpha_spread +) const{ + Result ret; + if (!game_screen || m_templates.empty()){ + return ret; + } + + // Every possible sprite position scaled to the template size + std::vector candidates; + for (int y = m_y_min; y <= m_y_max; y++){ + for (int x = m_x_min; x <= m_x_max; x++){ + candidates.emplace_back( + extract_box_reference(game_screen, sprite_box(x, y)).scale_to(SPRITE_SIZE, SPRITE_SIZE) + ); } } -} -auto PokemonSpriteMatcherCropped::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ - ImageStats border = image_border_stats(image); - ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( - image, - [&](Color pixel){ - double r = (double)pixel.red() - border.average.r; - double g = (double)pixel.green() - border.average.g; - double b = (double)pixel.blue() - border.average.b; - bool stop = r*r + g*g + b*b >= m_min_euclidean_distance_squared; - return stop; + std::map species_best; + double best_alpha = 10000; + for (const std::unique_ptr