From 326daebe7758771293904a259a18217b57559341 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 09:28:24 -0800 Subject: [PATCH 01/13] FRLG AutoStory stage 2: player name, SID Helper and Starter RNG Squash of fork PRs #177, #178, #179, #182, #183, #184 and frlg/rng-plan-base (frlg/autostory-rng-loop at 07819f4d0). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Inference/PokemonFRLG_TrainerIdReader.cpp | 18 +- .../Inference/PokemonFRLG_TrainerIdReader.h | 8 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 410 +++++++++ .../AutoStory/PokemonFRLG_AutoStory.cpp | 464 +++++++++- .../AutoStory/PokemonFRLG_AutoStory.h | 27 + .../PokemonFRLG_AutoStoryActions.cpp | 97 +- .../AutoStory/PokemonFRLG_AutoStoryActions.h | 19 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 57 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.h | 53 ++ .../PokemonFRLG_AutoStoryRngLoop.cpp | 119 +++ .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 73 ++ .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 207 +++++ .../PokemonFRLG_AutoStoryRngOptions.cpp | 199 +++++ .../PokemonFRLG_AutoStoryRngOptions.h | 100 +++ .../PokemonFRLG_AutoStorySimulation_Tests.cpp | 15 +- .../AutoStory/PokemonFRLG_AutoStoryTable.cpp | 45 +- .../AutoStory/PokemonFRLG_AutoStoryTable.h | 4 +- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 173 +++- .../Programs/PokemonFRLG_NamingScreen.cpp | 106 +++ .../Programs/PokemonFRLG_NamingScreen.h | 43 + .../PokemonFRLG_NamingScreenKeyboard.cpp | 348 ++++++++ .../PokemonFRLG_NamingScreenKeyboard.h | 140 +++ .../Programs/PokemonFRLG_TrainerCard.cpp | 105 +++ .../Programs/PokemonFRLG_TrainerCard.h | 41 + .../RngManipulation/PokemonFRLG_RngPlan.cpp | 159 ++++ .../RngManipulation/PokemonFRLG_RngPlan.h | 121 +++ .../PokemonFRLG_RngPlanInputs.cpp | 106 +++ .../PokemonFRLG_RngPlanInputs.h | 39 + .../PokemonFRLG_RngPlanInputs_Tests.cpp | 137 +++ .../PokemonFRLG_RngPlanInputs_Tests.h | 23 + .../PokemonFRLG_RngPlanLog.cpp | 137 +++ .../RngManipulation/PokemonFRLG_RngPlanLog.h | 77 ++ .../PokemonFRLG_RngPlanLog_Tests.cpp | 109 +++ .../PokemonFRLG_RngPlanLog_Tests.h | 23 + .../PokemonFRLG_RngPlanTestTargets.cpp | 61 ++ .../PokemonFRLG_RngPlanTestTargets.h | 46 + .../PokemonFRLG_RngPlanTracker.cpp | 134 +++ .../PokemonFRLG_RngPlanTracker.h | 119 +++ .../PokemonFRLG_RngPlanTracker_Tests.cpp | 262 ++++++ .../PokemonFRLG_RngPlanTracker_Tests.h | 23 + .../PokemonFRLG_RngPlan_Tests.cpp | 287 ++++++ .../PokemonFRLG_RngPlan_Tests.h | 23 + .../PokemonFRLG_RngSteps_Tests.cpp | 283 ++++++ .../PokemonFRLG_RngSteps_Tests.h | 24 + .../PokemonFRLG_RngTargetSearch.cpp | 417 +++++++++ .../PokemonFRLG_RngTargetSearch.h | 150 ++++ .../PokemonFRLG_RngTargetSearch_Tests.cpp | 446 +++++++++ .../PokemonFRLG_RngTargetSearch_Tests.h | 23 + .../PokemonFRLG_SeedsDatabase.h | 13 +- .../RngManipulation/PokemonFRLG_SidHelper.cpp | 175 +--- .../RngManipulation/PokemonFRLG_SidSteps.cpp | 124 +++ .../RngManipulation/PokemonFRLG_SidSteps.h | 50 ++ .../PokemonFRLG_StarterRng.cpp | 685 +------------- .../RngManipulation/PokemonFRLG_StarterRng.h | 30 +- .../PokemonFRLG_StarterRngAttempts.cpp | 845 ++++++++++++++++++ .../PokemonFRLG_StarterRngAttempts.h | 263 ++++++ .../PokemonFRLG_StarterRngConsoleSteps.cpp | 117 +++ .../PokemonFRLG_StarterRngConsoleSteps.h | 93 ++ .../PokemonFRLG_StarterRngLoop.cpp | 337 +++++++ .../PokemonFRLG_StarterRngLoop.h | 182 ++++ .../PokemonFRLG_StarterRngLoop_Tests.cpp | 516 +++++++++++ .../PokemonFRLG_StarterRngLoop_Tests.h | 23 + SerialPrograms/cmake/SourceFiles.cmake | 47 +- 63 files changed, 8681 insertions(+), 919 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.cpp index f505088994..7569dcab12 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.cpp @@ -40,6 +40,22 @@ void TrainerIdReader::make_overlays(VideoOverlaySet &items) const { uint16_t TrainerIdReader::read_tid( Logger& logger, Language language, const ImageViewRGB32& frame +){ + return uint16_t(read_tid_digits(logger, language, frame)); +} + +std::optional TrainerIdReader::try_read_tid( + Logger& logger, Language language, const ImageViewRGB32& frame +){ + const int tid = read_tid_digits(logger, language, frame); + if (tid < 0 || tid > 0xffff){ + return std::nullopt; + } + return uint16_t(tid); +} + +int TrainerIdReader::read_tid_digits( + Logger& logger, Language language, const ImageViewRGB32& frame ){ ImageViewRGB32 game_screen = extract_box_reference(frame, GameSettings::instance().GAME_BOX); @@ -52,7 +68,7 @@ uint16_t TrainerIdReader::read_tid( // waterfill segmentation + template matching // against the PokemonFRLG/Digits/0-9.png templates. - return uint16_t(read_digits_waterfill_template(logger, tid_region, DigitTemplateType::DialogBox)); + return read_digits_waterfill_template(logger, tid_region, DigitTemplateType::DialogBox); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h index c763913704..87be48324e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h @@ -34,8 +34,16 @@ class TrainerIdReader { uint16_t read_tid( Logger& logger, Language language, const ImageViewRGB32& frame ); + // As read_tid(), but nothing when the digits can't be read or are more + // than a TID can be, instead of a wrapped-around number. + std::optional try_read_tid( + Logger& logger, Language language, const ImageViewRGB32& frame + ); private: + // The digits read, or -1. + int read_tid_digits(Logger& logger, Language language, const ImageViewRGB32& frame); + Color m_color; ImageFloatBox m_box_tid; ImageFloatBox m_box_tid_spa; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 1973dbe3e4..4ccaa6a0d7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -5,6 +5,7 @@ */ #include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" @@ -37,9 +38,18 @@ #include "Overworld/PokemonFRLG_OverworldRoute.h" #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" +#include "Programs/PokemonFRLG_NamingScreenKeyboard.h" #include "PokemonFRLG_Navigation.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -272,6 +282,394 @@ void add_tests_ExitWildBattle(UnitTestDatabase& database){ } } + +// Naming screen keyboard: cursor moves, plans and text checks, against pokefirered's +// src/naming_screen.c. + +struct NamingCursorScenario{ + std::string name = ""; + NamingCursor start = {}; + std::vector actions = {}; + NamingCursor expected = {}; +}; + +class Test_NamingCursor : public UnitTest{ +public: + Test_NamingCursor(NamingCursorScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen cursor - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + NamingCursor cursor = m_scenario.start; + for (NamingAction action : m_scenario.actions){ + cursor = apply_naming_action(cursor, action); + } + if (cursor != m_scenario.expected){ + return "After " + to_string(m_scenario.actions) + ": expected " + to_string(m_scenario.expected) + + ", got " + to_string(cursor); + } + return true; + } + +private: + const NamingCursorScenario m_scenario; +}; + +// Crossing and moving on the button column. +std::vector naming_cursor_button_column_scenarios(){ + using enum NamingAction; + using enum NamingScreenPage; + return { + { + .name = "left from A goes to the page button", + .actions = {LEFT}, + .expected = {.page = UPPER, .row = 0, .column = 8, .remembered_row = 1}, + }, + { + .name = "left and right return to A", + .actions = {LEFT, RIGHT}, + .expected = {.page = UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + { + // Rows 1 and 2 share the back button; the game remembers which one it came from. + .name = "row 1 crosses the button column", + .start = {.page = UPPER, .row = 1, .column = 0}, + .actions = {LEFT, RIGHT}, + .expected = {.page = UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + { + .name = "row 2 crosses the button column", + .start = {.page = UPPER, .row = 2, .column = 0}, + .actions = {LEFT, RIGHT}, + .expected = {.page = UPPER, .row = 2, .column = 0, .remembered_row = 2}, + }, + { + .name = "row 3 crosses the OK button", + .start = {.page = UPPER, .row = 3, .column = 0}, + .actions = {LEFT, RIGHT}, + .expected = {.page = UPPER, .row = 3, .column = 0, .remembered_row = 2}, + }, + { + .name = "right from the last column wraps through the buttons", + .start = {.page = UPPER, .row = 0, .column = 7}, + .actions = {RIGHT, RIGHT}, + .expected = {.page = UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + { + // Moving on the button column overwrites the remembered row with BACK. + .name = "moving on the button column forgets row 2", + .start = {.page = UPPER, .row = 2, .column = 0}, + .actions = {LEFT, UP, DOWN, RIGHT}, + .expected = {.page = UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }; +} +// Wrap-around on the keys and the button column. +std::vector naming_cursor_wrap_scenarios(){ + using enum NamingAction; + using enum NamingScreenPage; + return { + { + .name = "button column wraps over three buttons", + .start = {.page = UPPER, .row = 0, .column = 8, .remembered_row = 1}, + .actions = {UP}, + .expected = {.page = UPPER, .row = 2, .column = 8, .remembered_row = 2}, + }, + { + .name = "rows wrap up", + .actions = {UP}, + .expected = {.page = UPPER, .row = 3, .column = 0}, + }, + { + .name = "rows wrap down", + .start = {.page = UPPER, .row = 3, .column = 0}, + .actions = {DOWN}, + .expected = {.page = UPPER, .row = 0, .column = 0}, + }, + { + .name = "symbols page has six key columns", + .start = {.page = SYMBOLS, .row = 0, .column = 0}, + .actions = {LEFT, LEFT}, + .expected = {.page = SYMBOLS, .row = 0, .column = 5, .remembered_row = 1}, + }, + }; +} +// SELECT and START. +std::vector naming_cursor_page_scenarios(){ + using enum NamingAction; + using enum NamingScreenPage; + return { + { + .name = "SELECT goes to lower case", + .actions = {SELECT}, + .expected = {.page = LOWER, .row = 0, .column = 0}, + }, + { + .name = "SELECT twice goes to symbols", + .actions = {SELECT, SELECT}, + .expected = {.page = SYMBOLS, .row = 0, .column = 0}, + }, + { + .name = "SELECT three times returns to upper case", + .actions = {SELECT, SELECT, SELECT}, + .expected = {.page = UPPER, .row = 0, .column = 0}, + }, + { + .name = "SELECT moves the cursor into the symbols columns", + .start = {.page = UPPER, .row = 0, .column = 7}, + .actions = {SELECT, SELECT, SELECT}, + .expected = {.page = UPPER, .row = 0, .column = 5}, + }, + { + .name = "SELECT keeps the cursor on the button column", + .start = {.page = UPPER, .row = 1, .column = 8, .remembered_row = 1}, + .actions = {SELECT, SELECT}, + .expected = {.page = SYMBOLS, .row = 1, .column = 6, .remembered_row = 1}, + }, + { + .name = "START goes to OK", + .start = {.page = LOWER, .row = 1, .column = 3}, + .actions = {START}, + .expected = {.page = LOWER, .row = 2, .column = 8}, + }, + { + .name = "START goes to OK on symbols", + .start = {.page = SYMBOLS, .row = 0, .column = 0}, + .actions = {START}, + .expected = {.page = SYMBOLS, .row = 2, .column = 6}, + }, + }; +} +void add_tests_NamingCursor(UnitTestDatabase& database){ + for (auto scenarios : { + naming_cursor_button_column_scenarios(), + naming_cursor_wrap_scenarios(), + naming_cursor_page_scenarios(), + }){ + for (const NamingCursorScenario& scenario : scenarios){ + database.add(scenario); + } + } +} + + +struct NamingPlanScenario{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; + // What the game shows when it differs from `text` (another spelling of a key). + std::string typed = ""; + // The exact plan, when the shortest one is unique; "" to skip. + std::string expected_actions = ""; + // The number of presses, including A and the final START A; 0 to skip. + size_t expected_presses = 0; +}; + +class Test_NamingPlan : public UnitTest{ +public: + Test_NamingPlan(NamingPlanScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen plan - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector actions = plan_naming_input(m_scenario.text, m_scenario.kind); + const std::string plan = to_string(actions); + if (!m_scenario.expected_actions.empty() && plan != m_scenario.expected_actions){ + return "Expected plan: " + m_scenario.expected_actions + "\nActual plan: " + plan; + } + if (m_scenario.expected_presses != 0 && actions.size() != m_scenario.expected_presses){ + return "Expected " + std::to_string(m_scenario.expected_presses) + " presses, got " + + std::to_string(actions.size()) + ": " + plan; + } + + // Replay the plan: every A but the last types the key under the cursor, and the last + // presses OK. + std::string typed; + NamingCursor cursor; + for (size_t i = 0; i < actions.size(); i++){ + cursor = apply_naming_action(cursor, actions[i]); + if (actions[i] != NamingAction::A){ + continue; + } + const uint8_t columns = NAMING_SCREEN_KEY_COLUMNS[(size_t)cursor.page]; + if (i + 1 == actions.size()){ + if (cursor.column != columns || cursor.row != NAMING_SCREEN_BUTTON_OK){ + return "The last A is not on OK but on " + to_string(cursor) + ": " + plan; + } + break; + } + if (cursor.column >= columns){ + return "A pressed on the button column at " + to_string(cursor) + ": " + plan; + } + typed += NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; + } + const std::string& expected = m_scenario.typed.empty() ? m_scenario.text : m_scenario.typed; + if (typed != expected){ + return "Expected the plan to type \"" + expected + "\", it types \"" + typed + "\": " + plan; + } + return true; + } + +private: + const NamingPlanScenario m_scenario; +}; + +void add_tests_NamingPlan(UnitTestDatabase& database){ + using enum NamingScreenKind; + const NamingPlanScenario scenarios[] = { + {.name = "starts on A", .text = "A", .expected_actions = "A START A"}, + {.name = "next key", .text = "AB", .expected_actions = "A RIGHT A START A"}, + {.name = "next row", .text = "AG", .expected_actions = "A DOWN A START A"}, + {.name = "rows wrap", .text = "T", .expected_actions = "UP A START A"}, + { + .name = "columns wrap through the button column", + .text = ".", + .expected_actions = "LEFT LEFT A START A", + }, + {.name = "lower case page", .text = "a", .expected_actions = "SELECT A START A"}, + {.name = "symbols page", .text = "0", .expected_actions = "SELECT SELECT A START A"}, + { + // The cursor moves from column 7 to the symbols page's last column, 5. + .name = "page change moves the cursor into the symbols columns", + .text = ".4", + .expected_actions = "LEFT LEFT A SELECT SELECT LEFT A START A", + }, + {.name = "both ways round", .text = "Z", .expected_presses = 7}, + {.name = "male sign", .text = "\xE2\x99\x82", .expected_presses = 9}, + {.name = "full player name", .text = "ABCDEFG", .expected_presses = 19}, + {.name = "mixed case", .text = "Gary", .expected_presses = 16}, + {.name = "space", .text = "A B", .expected_presses = 12}, + {.name = "full nickname", .text = "BULBASAURS", .kind = POKEMON}, + {.name = "female sign", .text = "NIDORAN\xE2\x99\x80", .kind = POKEMON}, + {.name = "box name", .text = "BOX 1-2!", .kind = BOX}, + {.name = "rival", .text = "Blue?", .kind = RIVAL}, + { + .name = "symbols row 4", + .text = "\xE2\x80\xA6\xE2\x80\x9C\xE2\x80\x9D\xE2\x80\x98'", + .kind = POKEMON, + }, + {.name = "curly apostrophe", .text = "IT\xE2\x80\x99S", .typed = "IT'S"}, + }; + for (const NamingPlanScenario& scenario : scenarios){ + database.add(scenario); + } +} + + +struct NamingKeysScenario{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; + // The exact plan, when the shortest one is unique; "" to skip. + std::string expected_actions = ""; +}; + +// plan_naming_keys() stops before OK: it is plan_naming_input() without the final START A. +class Test_NamingKeys : public UnitTest{ +public: + Test_NamingKeys(NamingKeysScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen keys only - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string keys = to_string(plan_naming_keys(m_scenario.text, m_scenario.kind)); + if (!m_scenario.expected_actions.empty() && keys != m_scenario.expected_actions){ + return "Expected keys: " + m_scenario.expected_actions + "\nActual keys: " + keys; + } + const std::string input = to_string(plan_naming_input(m_scenario.text, m_scenario.kind)); + if (input != keys + " START A"){ + return "Expected the confirmed plan to be \"" + keys + " START A\", got \"" + input + "\""; + } + return true; + } + +private: + const NamingKeysScenario m_scenario; +}; + +void add_tests_NamingKeys(UnitTestDatabase& database){ + using enum NamingScreenKind; + const NamingKeysScenario scenarios[] = { + {.name = "one key", .text = "A", .expected_actions = "A"}, + {.name = "next key", .text = "AB", .expected_actions = "A RIGHT A"}, + {.name = "lower case page", .text = "a", .expected_actions = "SELECT A"}, + // A full name: the game moves the cursor to OK by itself, but nothing presses it. + {.name = "full player name", .text = "ABCDEFG"}, + {.name = "mixed case", .text = "Kosmos"}, + }; + for (const NamingKeysScenario& scenario : scenarios){ + database.add(scenario); + } +} + + +struct NamingTextScenario{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; + // A part of the expected error; "" if the text is fine. + std::string expected_error = ""; +}; + +class Test_NamingText : public UnitTest{ +public: + Test_NamingText(NamingTextScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen text - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = naming_text_error(m_scenario.text, m_scenario.kind); + if (m_scenario.expected_error.empty()){ + if (!error.empty()){ + return "Expected \"" + m_scenario.text + "\" to be accepted, got: " + error; + } + return true; + } + if (error.find(m_scenario.expected_error) == std::string::npos){ + return "Expected an error containing \"" + m_scenario.expected_error + "\", got: \"" + error + "\""; + } + try{ + plan_naming_input(m_scenario.text, m_scenario.kind); + }catch (InternalProgramError&){ + return true; + } + return "Expected plan_naming_input() to throw for \"" + m_scenario.text + "\""; + } + +private: + const NamingTextScenario m_scenario; +}; + +void add_tests_NamingText(UnitTestDatabase& database){ + using enum NamingScreenKind; + const NamingTextScenario scenarios[] = { + {.name = "player name of 7", .text = "ABCDEFG", .kind = PLAYER}, + {.name = "player name of 8", .text = "ABCDEFGH", .kind = PLAYER, .expected_error = "at most 7"}, + {.name = "rival name of 7", .text = "ABCDEFG", .kind = RIVAL}, + {.name = "rival name of 8", .text = "ABCDEFGH", .kind = RIVAL, .expected_error = "at most 7"}, + {.name = "box name of 8", .text = "ABCDEFGH", .kind = BOX}, + {.name = "box name of 9", .text = "ABCDEFGHI", .kind = BOX, .expected_error = "at most 8"}, + {.name = "nickname of 10", .text = "ABCDEFGHIJ", .kind = POKEMON}, + {.name = "nickname of 11", .text = "ABCDEFGHIJK", .kind = POKEMON, .expected_error = "at most 10"}, + { + // Seven characters, 21 bytes. + .name = "symbols count as one character", + .text = "\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82", + }, + {.name = "unknown character", .text = "Ash@", .expected_error = "type: \"@\""}, + {.name = "unknown accented character", .text = "Jos\xC3\xA9", .expected_error = "type: \"\xC3\xA9\""}, + {.name = "empty", .text = "", .expected_error = "empty"}, + {.name = "only spaces", .text = " ", .expected_error = "only spaces"}, + }; + for (const NamingTextScenario& scenario : scenarios){ + database.add(scenario); + } +} + } @@ -319,6 +717,18 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory(database); add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); + add_tests_AutoStoryRngLoop(database); + add_tests_NamingCursor(database); + add_tests_NamingPlan(database); + add_tests_NamingKeys(database); + add_tests_NamingText(database); + add_tests_RngTargetSearch(database); + add_tests_RngPlanInputs(database); + add_tests_RngPlan(database); + add_tests_RngPlanTracker(database); + add_tests_RngPlanLog(database); + add_tests_RngSteps(database); + add_tests_StarterRngLoop(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index fb400f1e09..a57983b637 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -5,16 +5,27 @@ */ #include +#include #include #include "Common/Cpp/Exceptions.h" #include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/Pokemon_Strings.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStory.h" @@ -52,6 +63,13 @@ const StringSelectDatabase& checkpoint_database(){ } +const char* const RUN_STARTER_RNG_TEXT = + "Run Starter RNG in AutoStory:
Off by default. Instead of stopping for them, run SID Helper's steps on the " + "new game's keyboard when the RNG plan has no SID, and Starter RNG's attempts from a save south of the table at the " + "end of 00.04, as the RNG plan lists them. A shiny Squirtle goes on to the rival's battle, saves after it and the run " + "goes on; otherwise the run stops with the save south of the table.
" + "SID Helper's timing needs the text speed and button settings already saved, as with Stop for SID Helper."; + AutoStory::AutoStory() : RUN(checkpoint_database()) , NEW_GAME_FROM_TITLE( @@ -60,13 +78,42 @@ AutoStory::AutoStory() LockMode::LOCK_WHILE_RUNNING, true ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) + , PLAYER_NAME( + false, + "Player name:
Typed on the new game's keyboard (00.01). Empty keeps the game's default name. " + "The rival always keeps the default name.", + LockMode::LOCK_WHILE_RUNNING, + "Kosmos", "" + ) + , STOP_FOR_SID_HELPER( + "Stop for SID Helper:
Off by default. At 00.01, stop on the player's keyboard with the name typed and OK not pressed, " + "where the SID Helper program starts. After SID Helper, start AutoStory at 00.01b, with the game as SID Helper left it " + "(the Trainer Card, or HOME): it closes the card, sets the options and saves in the bedroom.
" + "SID Helper needs the text speed and button settings already saved. On a cartridge with that save, choose NEW GAME " + "by hand and start AutoStory on the first message.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , STOP_FOR_STARTER_RNG( + "Stop for Starter RNG:
Off by default. At the end of 00.04, save south of the table facing Squirtle's ball " + "and stop, where the Starter RNG program starts. After Starter RNG, save right after the rival's battle without moving " + "and start AutoStory at 00.05, listing the targets to try from the RNG plan.
" + "With this off, 00.04 and 00.04b run as one checkpoint, as before.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , RUN_STARTER_RNG(RUN_STARTER_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) + , NOTIFICATION_SHINY("Shiny found", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({&NOTIFICATION_SHINY, &NOTIFICATION_STATUS_UPDATE, &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_FATAL}) { PA_ADD_OPTION(RUN); PA_ADD_OPTION(NEW_GAME_FROM_TITLE); + PA_ADD_OPTION(PLAYER_NAME); + PA_ADD_OPTION(STOP_FOR_SID_HELPER); + PA_ADD_OPTION(STOP_FOR_STARTER_RNG); + PA_ADD_OPTION(RUN_STARTER_RNG); + PA_ADD_OPTION(RNG_PLAN); PA_ADD_OPTION(NOTIFICATIONS); } @@ -89,6 +136,17 @@ static void check_start_save( namespace{ +// Before the new game starts: a name the keyboard can't type is the user's to fix. +void check_player_name(ConsoleHandle& console, const std::string& name){ + if (name.empty()){ + return; + } + const std::string error = naming_text_error(name, NamingScreenKind::PLAYER); + if (!error.empty()){ + throw UserSetupError(console, "Player name: " + error); + } +} + // A failed attempt reloads the last save, with the supplies it had, read // from its bag again; the engine's lines go to the console's log. Pokemon::SegmentHooks story_hooks(SingleSwitchProgramEnvironment& env, StoryEnv& story){ @@ -136,6 +194,11 @@ void load_verify_save( "Verify mode reloads the checkpoint's save between runs: " + checkpoint.id + " starts a new game and has none." ); } + if (checkpoint.live_start){ + throw UserSetupError(env.console, + "Verify mode reloads the checkpoint's save between runs: " + checkpoint.id + " starts from the game as it is, with no save." + ); + } env.console.log("Verify mode: loading the save for " + checkpoint.id + "."); soft_reset(env.console, context); story.has_save = true; @@ -176,56 +239,385 @@ void verify_story_checkpoint( } -void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (const std::optional verify = RUN.VERIFY.policy()){ - verify_story_checkpoint(env, context, RUN, *verify, NOTIFICATION_PROGRAM_FINISH); +// The options' problems, before anything is pressed. +static void check_setup( + ConsoleHandle& console, const std::vector& checkpoints, size_t first, size_t last, + bool new_game_from_title, const std::string& player_name +){ + if (first > last || last >= checkpoints.size()){ + throw UserSetupError(console, "The start checkpoint must not come after the end checkpoint."); + } + if (first == 0 && !new_game_from_title){ + throw UserSetupError(console, "Checkpoint 00.01 starts a new game: start on the title screen with no save."); + } + if (first == 0){ + check_player_name(console, player_name); + } +} + +static void throw_if_failed(const Pokemon::SegmentReport& report){ + if (report.completed){ return; } - const std::vector& checkpoints = story_checkpoints(); - const size_t first = RUN.start_index(); - const size_t last = RUN.end_index(); - if (first > last || last >= checkpoints.size()){ - throw UserSetupError(env.console, "The start checkpoint must not come after the end checkpoint."); + throw OperationFailedException( + ErrorReportMode::NO_ERROR_REPORT, + std::format( + "AutoStory stopped at {} {}: {}", + report.failed_checkpoint, report.failed_event, Pokemon::to_string(report.failure) + ) + ); +} + +// Gets the game to where checkpoint `first` starts: a new game from the +// title screen, the game as another program left it, or the checkpoint's +// save loaded. +static void prepare_start( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::vector& checkpoints, size_t first, StoryEnv& story +){ + const StoryCheckpoint& checkpoint = checkpoints[first]; + if (!checkpoint.start){ + return; } - if (first == 0 && !NEW_GAME_FROM_TITLE){ - throw UserSetupError(env.console, "Checkpoint 00.01 starts a new game: start on the title screen with no save."); + if (checkpoint.live_start){ + env.console.log(checkpoint.id + " starts from the game as it is: no save to load."); + return; } + env.console.log("Loading the save for " + checkpoint.id + "."); + soft_reset(env.console, context); + story.has_save = true; + check_start_save(env, story, checkpoints[first]); + read_lead_moves(story, checkpoints[first].menu); + read_bag_supplies(story, checkpoints[first].menu); +} - StoryEnv story{env.console, context, checkpoints[first].supplies, checkpoints[first].supplies, false, RUN.checks()}; - if (!(first == 0 && NEW_GAME_FROM_TITLE)){ - env.console.log("Loading the save for " + checkpoints[first].id + "."); - soft_reset(env.console, context); - story.has_save = true; - check_start_save(env, story, checkpoints[first]); - read_lead_moves(story, checkpoints[first].menu); - read_bag_supplies(story, checkpoints[first].menu); +// The run stopped for an RNG program, as its option asked: the user's +// turn, with what to do next, and the lines that go with it (the RNG +// plan's attempts). +static void stop_for_handoff( + SingleSwitchProgramEnvironment& env, EventNotificationOption& notification, + const std::string& message, const std::vector& lines = {} +){ + env.console.log(message, COLOR_BLUE); + env.console.overlay().add_log(message); + std::string full = message; + for (const std::string& line : lines){ + env.console.log(line, COLOR_BLUE); + env.console.overlay().add_log(line); + full += "\n" + line; } + send_program_finished_notification(env, notification, full); +} - StoryExecutor executor(story); - executor.set_checks(RUN.checks()); - executor.set_language(RUN.language()); - Pokemon::Segment segment = make_story_segment(checkpoints, executor); +static void stop_for_sid_helper( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + EventNotificationOption& notification, const std::string& player_name +){ + play_new_game_to_player_name(env.console, context, player_name); + stop_for_handoff(env, notification, + "Stopped for SID Helper: the player's name is typed and OK is not pressed. Run SID Helper now, " + "enter its Target Advances and # Candidate SIDs in the RNG plan, then start AutoStory at 00.01b." + ); +} + +// The TID for the Starter RNG plan: the RNG plan's, or read off the +// Trainer Card (START, the player's entry), which is then closed again. +// Before the first Pokemon, as under the ball, the player's entry is second. +static uint16_t starter_rng_tid( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanOptions& options, Language language +){ + std::optional tid = options.tid_override(env.console); + if (tid){ + env.console.log(rng_log_tid(*tid, false)); + return *tid; + } + navigate_to_trainer_card(env.console, context); + tid = try_read_trainer_card_tid(env.console, context, language); + if (!tid){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "Couldn't read the TID on the Trainer Card, so there is no Starter RNG plan. Nothing was saved: " + "type the TID into the RNG plan's TID option and start AutoStory at 00.04 again.", + env.console + ); + } + close_trainer_card(env.console, context); + env.console.log(rng_log_tid(*tid, true)); + return *tid; +} + +// The Starter RNG attempts. Run under the ball before 00.04 saves there, so +// a failure ends the run with 00.03's save kept. +static StarterRngPlanned plan_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanOptions& options, Language language +){ + const uint16_t tid = starter_rng_tid(env, context, options, language); + try{ + return StarterRngPlanned{.tid = tid, .attempts = options.plan(env.console, language, tid)}; + }catch (UserSetupError& e){ + throw UserSetupError(env.console, e.message() + " Nothing was saved: fix the RNG plan and start AutoStory at 00.04 again."); + } +} + +// Has the last checkpoint of `segment` call `before` just before it saves. +static void before_last_save(Pokemon::Segment& segment, std::function before){ + Pokemon::CheckpointSpec& spec = segment.checkpoints.back(); + spec.build = [build = std::move(spec.build), before]() mutable{ + Pokemon::Checkpoint checkpoint = build(); + checkpoint.save = [save = std::move(checkpoint.save), before](Pokemon::RunState& state) mutable{ + before(); + return save(state); + }; + return checkpoint; + }; +} + +// The attempts are the user's to run, with Run Starter RNG in AutoStory off. +// TODO: LeafGreen and Bulbasaur/Charmander, with AutoStory's starter choice. +static void stop_for_starter_rng( + SingleSwitchProgramEnvironment& env, EventNotificationOption& notification, + const std::string& sound, const std::vector& attempts +){ + stop_for_handoff(env, notification, + "Stopped for Starter RNG: saved south of the table, facing Squirtle's ball. " + "Run Starter RNG (Squirtle, FireRed, Sound " + sound + ") with attempt 1's Target Seed and Advances. " + "If it hits the target and it isn't shiny, load this save and run the next attempt. If it is shiny, " + "its SID is the one listed (or one of them): enter it as the RNG plan's SID. " + "Then save right after the rival's battle, without moving, and start AutoStory at 00.05.", + attempts + ); +} + +static size_t checkpoint_index(const std::vector& checkpoints, const std::string& id){ + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == id){ + return c; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint " + id + "."); +} + +// Runs `rows` as one segment, calling `before` (if set) just before the +// last row saves. Throws if a checkpoint fails for good. +static void run_story_rows( + SingleSwitchProgramEnvironment& env, StoryEnv& story, StoryExecutor& executor, + const std::vector& rows, const Pokemon::SegmentPolicy& policy, + std::function before +){ + Pokemon::Segment segment = make_story_segment(rows, executor); + if (before){ + before_last_save(segment, std::move(before)); + } Pokemon::SegmentHooks hooks = story_hooks(env, story); Pokemon::RunState state; const Pokemon::SegmentReport report = run_segment( - state, segment, Pokemon::SegmentRange{checkpoints[first].id, checkpoints[last].id}, RUN.policy(), hooks + state, segment, Pokemon::SegmentRange{rows.front().id, rows.back().id}, policy, hooks ); Pokemon::record_story_stats(env.current_stats(), report); env.update_stats(); - if (!report.completed){ - throw OperationFailedException( - ErrorReportMode::NO_ERROR_REPORT, - std::format( - "AutoStory stopped at {} {}: {}", - report.failed_checkpoint, report.failed_event, Pokemon::to_string(report.failure) - ) + throw_if_failed(report); +} + +// SID Helper's steps in the program, from the player's keyboard: the name +// typed, then the intro at SID Helper's timing into the bedroom, and the +// Trainer Card opened to read the TID. Ends on the card, where 00.01b +// starts. +static void set_sid_in_program( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& player_name, const StarterRngPlanOptions& options, Language language +){ + const uint32_t target_advances = options.SID_HELPER_ADVANCES; + if (target_advances % 2 == 0){ + throw UserSetupError(env.console, "RNG plan: SID Helper's Target Advances must be odd."); + } + play_new_game_to_player_name(env.console, context, player_name); + const SidTiming timing = sid_timing(language, target_advances); + env.log("SID Helper's steps: delay " + std::to_string(timing.delay_ms) + "ms"); + set_sid_from_name_screen(context, timing); + finish_intro_animations(env, context); + + navigate_to_trainer_card(env.console, context); + const std::optional tid = try_read_trainer_card_tid(env.console, context, language); + if (!tid){ + env.console.log("Couldn't read the TID on the Trainer Card; 00.04 reads it again.", COLOR_ORANGE); + return; + } + env.console.log(rng_log_tid(*tid, true)); + env.console.log(rng_log_sid_helper(*tid, target_advances, options.helper_candidates(*tid))); +} + +namespace{ + +// Run Starter RNG in AutoStory: the time caps, Starter RNG's default Max +// Resets per try, and an attempt's misses before the run stops. +const StarterRngLoopLimits STARTER_RNG_LIMITS{ + .attempt_time = std::chrono::hours(3), + .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, +}; + +} + +// Starter RNG's attempts in the program, from the save south of the table. +// Returns true for a shiny Squirtle, on the target or not, the game on its +// summary; otherwise the run has stopped with what to do next. A shiny that +// confirms the SID writes it into the RNG plan's SID option. +static bool run_starter_rng_in_program( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanned& planned, StarterRngPlanOptions& options, Language language, + const StarterRngNotifications& notifications, EventNotificationOption& finished +){ + RngPlanTracker tracker( + planned.attempts, options.plan_candidates(env.console, planned.tid), options.SHINY_REQUIRED, STARTER_RNG_LIMITS.max_retries + ); + // The settings file gets the calibration saved after each reset when + // the program's panel is closed or the app quits. + RngStopCalibrationOptions& calibration = options.CALIBRATION; + ConsoleStarterRngSteps console_steps(env, context, StarterRngConsoleSettings{ + .language = language, .sound = options.SOUND, .calibration = calibration.calibration(calibration.STARTER_INGAME), + }, notifications); + CalibrationSavingSteps steps(console_steps, calibration, calibration.STARTER_INGAME); + RngPlanLogger logger(env.console); + const StarterRngLoopResult result = run_starter_rng_plan( + logger, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) + ); + const std::string confirmed_sid = result.sid ? std::to_string(*result.sid) : ""; + if (result.end == StarterRngLoopEnd::SHINY && result.sid && static_cast(options.SID) != confirmed_sid){ + // Kept in AutoStory's settings, so the next run plans for it and skips SID + // Helper's steps. Deferred: a per-save record keyed by TID (e.g. UserSettings/ + // FRLG-Saves.json: TID -> SID, version, language) that any FRLG RNG program + // could read, once a second program needs the SID. + options.SID.set(confirmed_sid); + env.console.log( + "AutoStory: set the RNG plan's SID to " + confirmed_sid + ". The settings file gets it " + "when the program's panel is closed or the app quits.", COLOR_BLUE + ); + } + const std::string message = starter_rng_loop_message(result); + if (result.end != StarterRngLoopEnd::SHINY && result.end != StarterRngLoopEnd::SHINY_OFF_TARGET){ + stop_for_handoff(env, finished, message); + return false; + } + env.console.log(message, COLOR_BLUE); + env.console.overlay().add_log(message); + return true; +} + +// After a shiny Squirtle: off its summary, then the rival's battle, which +// saves (00.04b), and the rows after it to `last`. Until that save, a +// reload would load the save under the ball and lose the shiny, so a +// failure stops the run instead. Returns the last row's id. +static std::string run_after_shiny_starter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const Pokemon::SegmentPolicy& policy, size_t ball_row, size_t last +){ + const std::vector rows = rows_after_starter_rng(story_checkpoints(), ball_row, last); + // As Starter RNG leaves the summary for the overworld. + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + env.console.log("The shiny Squirtle isn't saved until " + rows.front().id + " saves after the rival's battle. " + "If it fails before then, the run stops without reloading: save by hand.", COLOR_BLUE); + story.has_save = false; + run_story_rows(env, story, executor, rows, policy, nullptr); + return rows.back().id; +} + +// The run is done through `done_through`. The finish message also gives +// the SID when Starter RNG set it, from `sid_before` to `sid_after`. +static void send_story_finished( + SingleSwitchProgramEnvironment& env, EventNotificationOption& finished, + const std::string& done_through, const std::string& sid_before, const std::string& sid_after +){ + std::string message = "AutoStory: done through " + done_through + "."; + if (sid_after != sid_before){ + message += " Starter RNG confirmed the SID, " + sid_after + ", and saved it as the RNG plan's SID."; + } + env.console.log(message); + send_program_finished_notification(env, finished, message); +} + +StoryHandoffs AutoStory::story_handoffs() const{ + // Running Starter RNG here splits 00.04 at the ball as its stop does, + // and sets the SID at 00.01 when it isn't known. + return StoryHandoffs{ + .sid_helper = RUN_STARTER_RNG ? static_cast(RNG_PLAN.SID).empty() : bool(STOP_FOR_SID_HELPER), + .starter_rng = STOP_FOR_STARTER_RNG || RUN_STARTER_RNG, + }; +} + +void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (const std::optional verify = RUN.VERIFY.policy()){ + verify_story_checkpoint(env, context, RUN, *verify, NOTIFICATION_PROGRAM_FINISH); + return; + } + const std::vector& checkpoints = story_checkpoints(); + size_t first = RUN.start_index(); + const size_t last = RUN.end_index(); + const std::string player_name = PLAYER_NAME; + check_setup(env.console, checkpoints, first, last, NEW_GAME_FROM_TITLE, player_name); + const StoryHandoffs handoffs = story_handoffs(); + const std::string sid_before = RNG_PLAN.SID; + StoryRunPlan plan = plan_story_run(checkpoints, first, last, handoffs); + if (plan.stop == StoryHandoff::SID_HELPER && !RUN_STARTER_RNG){ + stop_for_sid_helper(env, context, NOTIFICATION_PROGRAM_FINISH, player_name); + return; + } + if (plan.stop != StoryHandoff::NONE){ + // The options' text, before anything is pressed. + RNG_PLAN.check(env.console); + } + if (plan.stop == StoryHandoff::SID_HELPER){ + set_sid_in_program(env, context, player_name, RNG_PLAN, RUN.language()); + first = checkpoint_index(checkpoints, "00.01b"); + plan = plan_story_run(checkpoints, first, last, handoffs); + } + StoryEnv story{env.console, context, checkpoints[first].supplies, checkpoints[first].supplies, false, RUN.checks()}; + story.player_name = player_name; + prepare_start(env, context, checkpoints, first, story); + StoryExecutor executor(story); + executor.set_checks(RUN.checks()); + executor.set_language(RUN.language()); + StarterRngPlanned planned; + std::function before; + if (plan.stop == StoryHandoff::STARTER_RNG){ + before = [&]{ planned = plan_starter_rng_attempts(env, context, RNG_PLAN, RUN.language()); }; + } + run_story_rows(env, story, executor, plan.rows, RUN.policy(), std::move(before)); + std::string done_through = plan.rows.back().id; + if (plan.stop == StoryHandoff::STARTER_RNG){ + std::optional done = after_starter_ball( + env, context, story, executor, planned, checkpoint_index(checkpoints, done_through) ); + if (!done){ + return; + } + done_through = *done; } - env.console.log("AutoStory: done through " + checkpoints[last].id + "."); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + send_story_finished(env, NOTIFICATION_PROGRAM_FINISH, done_through, sid_before, RNG_PLAN.SID); } +std::optional AutoStory::after_starter_ball( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const StarterRngPlanned& planned, size_t ball_row +){ + if (!RUN_STARTER_RNG){ + stop_for_starter_rng(env, NOTIFICATION_PROGRAM_FINISH, RNG_PLAN.sound_name(), rng_attempt_lines(planned.attempts)); + return std::nullopt; + } + const StarterRngNotifications notifications{ + .shiny = NOTIFICATION_SHINY, .status_update = NOTIFICATION_STATUS_UPDATE, .error_recoverable = NOTIFICATION_ERROR_RECOVERABLE, + }; + if (!run_starter_rng_in_program(env, context, planned, RNG_PLAN, RUN.language(), notifications, NOTIFICATION_PROGRAM_FINISH)){ + return std::nullopt; + } + return run_after_shiny_starter(env, context, story, executor, RUN.policy(), ball_row, RUN.end_index()); +} + + } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h index e92eb74549..c25edad269 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h @@ -12,12 +12,18 @@ #ifndef PokemonAutomation_PokemonFRLG_AutoStory_H #define PokemonAutomation_PokemonFRLG_AutoStory_H +#include +#include #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/StringOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -41,10 +47,31 @@ class AutoStory : public SingleSwitchProgramInstance{ ) override{} private: + // The RNG programs' handoffs the run takes, from the options. + StoryHandoffs story_handoffs() const; + // After 00.04 saved under Squirtle's ball (row `ball_row`): the stop + // for Starter RNG, or its attempts run here and, for a shiny, the run + // on to the end checkpoint. Returns the last checkpoint run, or nothing + // once the run has stopped. + std::optional after_starter_ball( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const StarterRngPlanned& planned, size_t ball_row + ); + // The start and end checkpoints, attempts, checks and language, as in // every game's AutoStory. Pokemon::StoryRunOptions RUN; BooleanCheckBoxOption NEW_GAME_FROM_TITLE; + StringOption PLAYER_NAME; + // The RNG programs the run stops for (StoryHandoff). + BooleanCheckBoxOption STOP_FOR_SID_HELPER; + BooleanCheckBoxOption STOP_FOR_STARTER_RNG; + // Runs SID Helper's steps and Starter RNG's attempts in the program + // instead of stopping for them. + BooleanCheckBoxOption RUN_STARTER_RNG; + StarterRngPlanOptions RNG_PLAN; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index a67e107e31..c3c5d3461c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -16,6 +16,8 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/Images/SolidColorTest.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" @@ -26,6 +28,7 @@ #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_SelectionArrowDetector.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" #include "PokemonFRLG_AutoStoryActions.h" @@ -168,18 +171,28 @@ void open_start_menu_row(ConsoleHandle& console, ProControllerContext& context, // without an arrow, and the arrow at the end of Oak's lines may be missed, // so a message box gets A every 1.5 s whatever it shows. The player's name // is asked on the keyboard straight away: B deletes whatever a stray A -// typed and START jumps to OK, which confirms the empty name as the -// default. The rival's is asked on a list with NEW NAME first, where A -// would open the keyboard: the cursor goes to the first preset name (the -// game's default rival, GREEN in FireRed, RED in LeafGreen) and A picks -// it, then YES confirms it (pokefirered oak_speech.c). If the keyboard -// opens anyway, the list was missed, and the empty name is confirmed -// there instead, which also names the rival GREEN. +// typed, then the name is typed, or START jumps to OK, which confirms the +// empty name as the default. The rival's is asked on a list with NEW NAME +// first, where A would open the keyboard: the cursor goes to the first +// preset name (the game's default rival, GREEN in FireRed, RED in +// LeafGreen) and A picks it, then YES confirms it (pokefirered +// oak_speech.c). If the keyboard opens anyway, the list was missed, and +// the empty name is confirmed there instead, which also names the rival +// GREEN. class NewGameIntro{ public: - NewGameIntro(ConsoleHandle& console, ProControllerContext& context) + // Where the intro stops: the bedroom, or the player's keyboard with the + // name typed and OK not pressed (for SID Helper). + enum class End{ + BEDROOM, + PLAYER_NAME_TYPED, + }; + + NewGameIntro(ConsoleHandle& console, ProControllerContext& context, std::string player_name, End end) : m_console(console) , m_context(context) + , m_player_name(std::move(player_name)) + , m_end(end) {} void run(){ @@ -189,7 +202,7 @@ class NewGameIntro{ m_last_press = m_last_dialog; while (current_time() < deadline){ if (step()){ - m_console.log("New game: the bedroom."); + m_console.log(m_end == End::BEDROOM ? "New game: the bedroom." : "New game: the player's name is typed, OK not pressed."); return; } } @@ -228,6 +241,12 @@ class NewGameIntro{ pbf_wait(m_context, POLL); return false; } + if (m_end == End::PLAYER_NAME_TYPED && m_keyboards_seen == 0 && NamingScreenDetector(COLOR_RED).detect(screen)){ + m_keyboards_seen++; + clear_stray_keys(); + type_player_name(false); + return true; + } if (names(screen)){ m_last_dialog = current_time(); m_last_press = m_last_dialog; @@ -262,12 +281,12 @@ class NewGameIntro{ switch (intro_name_step(shown, m_keyboards_seen, m_presets_picked)){ case IntroNameStep::PLAYER_KEYBOARD: m_keyboards_seen++; - enter_empty_name(); + enter_name(true); return true; case IntroNameStep::RIVAL_KEYBOARD: m_keyboards_seen++; m_console.log("New game: the rival's keyboard opened, so the name list was missed.", COLOR_ORANGE); - enter_empty_name(); + enter_name(false); return true; case IntroNameStep::RIVAL_PRESET: pick_rival_preset(*list_row); @@ -317,18 +336,46 @@ class NewGameIntro{ return false; } - void enter_empty_name(){ - m_console.log("New game: the keyboard, confirming an empty name."); + // B deletes whatever a stray A typed; the cursor stays on its key. + void clear_stray_keys(){ for (int c = 0; c < 8; c++){ press(m_context, BUTTON_B, 340ms); } - press(m_context, BUTTON_PLUS, 500ms); - press(m_context, BUTTON_A, 2000ms); + } + + void enter_name(bool player){ + clear_stray_keys(); + if (!player || m_player_name.empty()){ + m_console.log("New game: the keyboard, confirming an empty name."); + press(m_context, BUTTON_PLUS, 500ms); + press(m_context, BUTTON_A, 2000ms); + m_context.wait_for_all_requests(); + return; + } + type_player_name(true); + // Past the keyboard's fade, so it isn't taken for the rival's. + pbf_wait(m_context, 2000ms); m_context.wait_for_all_requests(); } + void type_player_name(bool confirm){ + if (m_player_name.empty()){ + return; + } + const bool typed = confirm + ? type_name(m_console, m_context, m_player_name, NamingScreenKind::PLAYER) + : type_name_without_confirming(m_console, m_context, m_player_name, NamingScreenKind::PLAYER); + if (!typed){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "play_new_game_intro(): the keyboard closed before the name was typed.", m_console + ); + } + } + ConsoleHandle& m_console; ProControllerContext& m_context; + const std::string m_player_name; + const End m_end; WallClock m_last_dialog; WallClock m_last_press; bool m_dialog_seen = false; @@ -834,9 +881,25 @@ void buy_items( mash_until_overworld(console, context, 20000ms); } -void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context){ +void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name){ console.log("New game: from the title screen."); - NewGameIntro(console, context).run(); + NewGameIntro(console, context, player_name, NewGameIntro::End::BEDROOM).run(); +} + +void play_new_game_to_player_name(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name){ + console.log("New game: from the title screen to the player's keyboard, for SID Helper."); + NewGameIntro(console, context, player_name, NewGameIntro::End::PLAYER_NAME_TYPED).run(); +} + +void close_trainer_card(ConsoleHandle& console, ProControllerContext& context){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (screen && HomeMenuDetector(console, COLOR_RED).detect(screen)){ + console.log("After SID Helper: on HOME, back to the game."); + resume_game_from_home(console, context); + } + // B closes the card, then the START menu. + mash_until_overworld(console, context, 20000ms); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index 78d88a0d14..7065c8e1f7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -212,10 +212,21 @@ void buy_items( ); // From the title screen of a game with no save, to the bedroom: the -// controls pages, Oak's speech, BOY, the default name for the player (an -// empty name confirmed) and the rival's first preset name. Returns on the -// overworld. -void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context); +// controls pages, Oak's speech, BOY, `player_name` typed on the player's +// keyboard, and the rival's first preset name. An empty `player_name` +// keeps the player's default name (an empty name confirmed). Returns on +// the overworld. Throws UserSetupError if the game can't take the name +// (naming_text_error()). +void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name); + +// play_new_game_intro() up to the player's keyboard: `player_name` typed, +// OK not pressed, which is where SID Helper starts. Empty types nothing. +void play_new_game_to_player_name(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name); + +// From the Trainer Card SID Helper leaves open, or from HOME (its "go +// home when done"): back to the game, the card and the START menu closed. +// Returns on the overworld. +void close_trainer_card(ConsoleHandle& console, ProControllerContext& context); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 4c205cbb49..a39e555328 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -389,7 +389,7 @@ Outcome StoryExecutor::run(RunState& state, const StoryStep& step){ } Outcome StoryExecutor::new_game(RunState&, const StoryStep&){ - play_new_game_intro(m_env.console, m_env.context); + play_new_game_intro(m_env.console, m_env.context, m_env.player_name); return Pokemon::outcome_ok(); } @@ -443,6 +443,61 @@ Outcome StoryExecutor::ready(RunState& state, const StoryStep& step){ return get_ready(m_env, state, step); } +Outcome StoryExecutor::game(RunState&, const StoryStep& step){ + if (step.variant == CLOSE_TRAINER_CARD){ + close_trainer_card(m_env.console, m_env.context); + return Pokemon::outcome_ok(); + } + return Pokemon::unsupported_step(step); +} + + +namespace{ + +// `first` and `second` as one checkpoint: `first`'s id, start and +// supplies, `second`'s title and START menu, both rows' steps. +StoryCheckpoint joined_rows(const StoryCheckpoint& first, const StoryCheckpoint& second){ + StoryCheckpoint row = second; + row.id = first.id; + row.start = first.start; + row.supplies = first.supplies; + row.live_start = first.live_start; + row.steps = first.steps; + row.steps.insert(row.steps.end(), second.steps.begin(), second.steps.end()); + return row; +} + +} + +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs +){ + StoryRunPlan plan; + for (size_t c = first; c <= last && c < checkpoints.size(); c++){ + const StoryCheckpoint& row = checkpoints[c]; + if (row.live_start && c != first){ + continue; + } + if (row.handoff == StoryHandoff::SID_HELPER && handoffs.sid_helper){ + plan.rows.clear(); + plan.stop = StoryHandoff::SID_HELPER; + return plan; + } + if (row.handoff == StoryHandoff::STARTER_RNG && handoffs.starter_rng){ + plan.rows.emplace_back(row); + plan.stop = StoryHandoff::STARTER_RNG; + return plan; + } + if (row.handoff == StoryHandoff::STARTER_RNG && c + 1 < checkpoints.size()){ + plan.rows.emplace_back(joined_rows(row, checkpoints[c + 1])); + c++; + continue; + } + plan.rows.emplace_back(row); + } + return plan; +} + std::string check_save_place(StoryEnv& env, const std::string& start_map){ if (save_card_place(start_map).empty()){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index 887ca363b6..b716973374 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -56,18 +56,66 @@ struct StoryPose{ // has the Running Shoes (00.10 on). inline const std::string RUN_VARIANT = "run"; +// The GAME step that closes the Trainer Card SID Helper leaves open. +inline const std::string CLOSE_TRAINER_CARD = "close_trainer_card"; + // How `step`, a ROUTE or LEGS, moves the player: RUN_VARIANT runs. MoveSpeed move_speed(const StoryStep& step); +// An upstream RNG program the user may run part-way through the story. +// Each is off unless its option is on. +enum class StoryHandoff{ + NONE, + // The checkpoint's new game stops on the player's keyboard, the name + // typed and OK not pressed, which is where SID Helper starts. + SID_HELPER, + // The checkpoint saves south of the table, facing the starter's ball, + // which is where Starter RNG starts. With the handoff off, it runs on + // into the next checkpoint as one, as the story did before the split. + STARTER_RNG, +}; + // A shared checkpoint with what FRLG adds to it. struct StoryCheckpoint : public Pokemon::StoryCheckpoint{ // The healing items at its start, for a run that loads its save. Supplies supplies; // The START menu at its end, when it saves. StartMenu menu = StartMenu::FULL; + // Starts from the game as another program left it, loading no save: + // the way back into the story after an RNG program. A run that starts + // before it passes over it. + bool live_start = false; + // The RNG program the user may run at this checkpoint. + StoryHandoff handoff = StoryHandoff::NONE; +}; + +// The handoffs a run stops for (AutoStory's options). +struct StoryHandoffs{ + bool sid_helper = false; + bool starter_rng = false; }; +// What a run from table row `first` to `last` does. +struct StoryRunPlan{ + // The checkpoints to run, in order. + std::vector rows; + // NONE: the run ends after `rows`. SID_HELPER: `rows` is empty; the run + // plays the new game to the player's keyboard and stops there. + // STARTER_RNG: the run stops after `rows`, the last of which saves at + // the starter's ball. + StoryHandoff stop = StoryHandoff::NONE; +}; + +// The rows of `checkpoints` from `first` to `last`, both inclusive, as a +// run with `handoffs` takes them: live-start rows only when the run +// starts there, a run that reaches a handoff that is on stops for it, and +// a STARTER_RNG row whose handoff is off is joined with the row after it, +// under its own id. +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs +); + // The maps the story plans on: every map to Brock, with the objects the // game hides after the Hall of Fame removed, as the lab's frlg_route does. @@ -117,6 +165,9 @@ struct StoryEnv{ // The game's language, for reading item names. In one the readers have // no names for, the checks fall back to positions and counts. Language language = Language::English; + // The name the new game's intro types for the player; empty keeps the + // game's default name. + std::string player_name = {}; // The map the checkpoint under way starts on, where its save is: a // reload checks the save card against it. std::string start_map = {}; @@ -172,6 +223,8 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ // The Viridian Mart, before the Boulder Badge: Potions, Antidotes and Parlyz Heals. virtual Pokemon::Outcome shop(Pokemon::RunState& state, const StoryStep& step) override; virtual Pokemon::Outcome ready(Pokemon::RunState& state, const StoryStep& step) override; + // CLOSE_TRAINER_CARD: back from SID Helper (close_trainer_card()). + virtual Pokemon::Outcome game(Pokemon::RunState& state, const StoryStep& step) override; private: StoryEnv& m_env; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp new file mode 100644 index 0000000000..f6c1f5d3c9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -0,0 +1,119 @@ +/* AutoStory RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// "-" for none. +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text.empty() ? "-" : text; +} + +} + +std::string starter_rng_loop_message(const StarterRngLoopResult& result){ + const std::string sids = join_sids(result.remaining_sids); + switch (result.end){ + case StarterRngLoopEnd::SHINY: + if (result.sid){ + return std::format("Starter RNG: shiny Squirtle. The SID is {}: saved as the RNG plan's SID, so AutoStory skips SID Helper's steps next time.", *result.sid); + } + if (result.remaining_sids.empty()){ + return "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates."; + } + return std::format("Starter RNG: shiny Squirtle. The SID is one of {}.", sids); + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return std::format( + "Starter RNG: shiny Squirtle, but not the planned target, so it doesn't tell the SID. SIDs left: {}.", sids + ); + case StarterRngLoopEnd::TARGET: + return "Starter RNG hit the target (shiny not required). Nothing was saved after it: the game is where " + "Starter RNG's calibration left it. Play to the rival's battle and save by hand, then start AutoStory at 00.05."; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return std::format( + "Starter RNG: every planned attempt hit its target and none was shiny. SIDs left: {}. " + "The save is still south of the table: raise the RNG plan's max attempts and start AutoStory at 00.04 again.", sids + ); + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "Starter RNG: every attempt left missed its target more often than the retries allow, or Starter RNG " + "refused its timings (see the log). The save is still south of the table: check the RNG plan's sound setting " + "and start AutoStory at 00.04 again."; + case StarterRngLoopEnd::OUT_OF_TIME: + return std::format( + "Starter RNG: out of time after {} attempts. The save is still south of the table: start AutoStory at 00.04 again.", + result.attempts_run + ); + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG loop end."); +} + + +CalibrationSavingSteps::CalibrationSavingSteps( + StarterRngLoopSteps& steps, RngStopCalibrationOptions& calibration, FloatingPointOption& ingame +) + : m_steps(steps) + , m_calibration(calibration) + , m_ingame(ingame) +{} + +WallClock CalibrationSavingSteps::now(){ + return m_steps.now(); +} + +StarterRngResult CalibrationSavingSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ + StarterRngAttemptCall saving = call; + saving.on_reset = [&](const StarterRngProgress& progress){ + m_calibration.save(progress.calibrations, m_ingame); + if (call.on_reset){ + call.on_reset(progress); + } + }; + return m_steps.run_attempt(attempt, saving); +} + + +std::vector rows_after_starter_rng( + const std::vector& checkpoints, size_t ball_row, size_t last +){ + if (ball_row + 1 >= checkpoints.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint after the starter's ball."); + } + StoryCheckpoint row = checkpoints[ball_row + 1]; + auto taken = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ + return step.name == "rival_takes_bulbasaur"; + }); + if (taken == row.steps.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, row.id + " has no rival_takes_bulbasaur step."); + } + row.steps.erase(row.steps.begin(), taken + 1); + row.title = "after Starter RNG in AutoStory: the rival's battle"; + + std::vector rows{std::move(row)}; + if (last > ball_row + 1){ + StoryRunPlan rest = plan_story_run(checkpoints, ball_row + 2, last, StoryHandoffs{}); + rows.insert(rows.end(), rest.rows.begin(), rest.rows.end()); + } + return rows; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h new file mode 100644 index 0000000000..a6c0f248af --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -0,0 +1,73 @@ +/* AutoStory RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + * AutoStory's Starter RNG stop, run in the program with the Starter RNG + * loop (RngManipulation/PokemonFRLG_StarterRngLoop.h) from the save under + * Squirtle's ball: the plan it runs, what the run says when the loop + * ends, and the rows it takes after a shiny. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The Starter RNG plan, for the TID it was made for. +struct StarterRngPlanned{ + uint16_t tid = 0; + std::vector attempts; +}; + +// What the run says when the loop ends with `result`. +std::string starter_rng_loop_message(const StarterRngLoopResult& result); + + +// `steps`, with the calibration of each reset also kept in the RNG plan's +// calibration, with `ingame` as the stop's in-game advances offset, so the +// next run starts from it. +class CalibrationSavingSteps : public StarterRngLoopSteps{ +public: + CalibrationSavingSteps(StarterRngLoopSteps& steps, RngStopCalibrationOptions& calibration, FloatingPointOption& ingame); + + virtual WallClock now() override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; + +private: + StarterRngLoopSteps& m_steps; + RngStopCalibrationOptions& m_calibration; + FloatingPointOption& m_ingame; +}; + + +// The rows a run takes after a shiny from the loop, which leaves the player +// under Squirtle's ball with the rival's ball taken: the row after +// `ball_row` (00.04b) from its step after "rival_takes_bulbasaur", then +// the rows after it to `last` as plan_story_run() takes them. Throws +// InternalProgramError for a table without that row or step. +std::vector rows_after_starter_rng( + const std::vector& checkpoints, size_t ball_row, size_t last +); + + +void add_tests_AutoStoryRngLoop(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp new file mode 100644 index 0000000000..f042a5349c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -0,0 +1,207 @@ +/* AutoStory RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + * What the run says after a shiny, and the rows it takes then. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class Test_AutoStoryRngLoop : public UnitTest{ +public: + Test_AutoStoryRngLoop(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryRngLoop - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + + +// What the run says after a shiny, by what it tells of the SID. +UnitTestResult test_shiny_messages(){ + struct Case{ + StarterRngLoopResult result; + std::string expected; + }; + const std::vector cases = { + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 2, .remaining_sids = {300}, .sid = uint16_t(300)}, + .expected = "Starter RNG: shiny Squirtle. The SID is 300: saved as the RNG plan's SID, so AutoStory skips SID Helper's steps next time.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle. The SID is one of 100,200.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle, but not the planned target, so it doesn't tell the SID. " + "SIDs left: 100,200.", + }, + }; + for (const Case& item : cases){ + const std::string got = starter_rng_loop_message(item.result); + if (got != item.expected){ + return "Expected \"" + item.expected + "\", got \"" + got + "\"."; + } + } + return true; +} + + +// After a shiny, 00.04b picks up at the rival's trigger and runs on. +UnitTestResult test_rows_after_shiny(){ + const std::vector& checkpoints = story_checkpoints(); + size_t ball_row = 0; + size_t parcel_row = 0; + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == "00.04"){ + ball_row = c; + } + if (checkpoints[c].id == "00.05"){ + parcel_row = c; + } + } + struct Case{ + size_t last; + std::string ids; + }; + const std::vector cases = { + {.last = ball_row, .ids = "00.04b"}, + {.last = ball_row + 1, .ids = "00.04b"}, + {.last = parcel_row, .ids = "00.04b,00.05"}, + }; + for (const Case& item : cases){ + const std::vector rows = rows_after_starter_rng(checkpoints, ball_row, item.last); + std::string ids; + for (const StoryCheckpoint& row : rows){ + ids += (ids.empty() ? "" : ",") + row.id; + } + const std::string first_step = rows.front().steps.empty() ? "" : rows.front().steps.front().name; + if (ids != item.ids || first_step != "above_rival_trigger"){ + return std::format( + "Expected rows {} starting at above_rival_trigger; got {} starting at {}", item.ids, ids, first_step + ); + } + } + return true; +} + + +std::string calibration_text(const RngCalibrations& calibration){ + return std::format("{}/{}/{}", calibration.seed_offset, calibration.csf_offset, calibration.ingame_offset); +} + +// Starter RNG starts from the RNG plan's calibration: the console's seed +// and Continue Screen Frames offsets, and Starter RNG's in-game offset. +UnitTestResult test_starter_calibration_from_options(){ + StarterRngPlanOptions options; + RngStopCalibrationOptions& calibration = options.CALIBRATION; + const RngCalibrations zero{.seed_offset = 0, .csf_offset = 0, .ingame_offset = 0}; + if (calibration.calibration(calibration.STARTER_INGAME) != zero){ + return "Expected no calibration by default; got " + calibration_text(calibration.calibration(calibration.STARTER_INGAME)); + } + calibration.SEED.set(17); + calibration.CSF.set(0.5); + calibration.STARTER_INGAME.set(-1.2); + const RngCalibrations expected{.seed_offset = 17 / FRLG_FRAME_DURATION, .csf_offset = 0.5, .ingame_offset = -1.2}; + const RngCalibrations got = calibration.calibration(calibration.STARTER_INGAME); + if (got != expected){ + return std::format("Expected calibration {}; got {}", calibration_text(expected), calibration_text(got)); + } + return true; +} + +// Steps whose one try resets once for each calibration in `resets`. +class ResettingSteps : public StarterRngLoopSteps{ +public: + explicit ResettingSteps(std::vector resets) : m_resets(std::move(resets)) {} + virtual WallClock now() override{ return WallClock{}; } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ + for (size_t c = 0; c < m_resets.size(); c++){ + call.on_reset(StarterRngProgress{.resets = c + 1, .calibrations = m_resets[c]}); + } + return StarterRngResult{.outcome = StarterRngOutcome::out_of_resets, .pokemon = std::nullopt}; + } + +private: + std::vector m_resets; +}; + +// Each reset's calibration is kept in the RNG plan before the loop hears +// of the reset, so a run stopped after it keeps it. +UnitTestResult test_starter_calibration_saved(){ + StarterRngPlanOptions options; + RngStopCalibrationOptions& calibration = options.CALIBRATION; + ResettingSteps resetting({ + {.seed_offset = 0.5, .csf_offset = 0.25, .ingame_offset = -0.5}, + {.seed_offset = 1.0, .csf_offset = 0.5, .ingame_offset = -1.2}, + }); + CalibrationSavingSteps steps(resetting, calibration, calibration.STARTER_INGAME); + std::vector csf_at_reset; + steps.run_attempt(RngAttempt{}, StarterRngAttemptCall{ + .index = 0, .deadline = WallClock{}, .max_resets = 2, + .on_reset = [&](const StarterRngProgress&){ csf_at_reset.emplace_back(calibration.CSF); }, + }); + if (csf_at_reset != std::vector{0.25, 0.5}){ + std::string got; + for (double csf : csf_at_reset){ + got += std::format(" {}", csf); + } + return "Expected the CSF offset saved at each reset as 0.25 0.5; got" + got; + } + // The seed offset is kept in ms: 1.0 frame is 16.7 ms. + if (int64_t(calibration.SEED) != 17 || double(calibration.STARTER_INGAME) != -1.2){ + return std::format( + "Expected seed 17 ms and Starter RNG in-game -1.2 saved; got {} ms and {}", + int64_t(calibration.SEED), double(calibration.STARTER_INGAME) + ); + } + return true; +} + +} + + +void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ + database.add("shiny messages", test_shiny_messages); + database.add("rows after a shiny", test_rows_after_shiny); + database.add("Starter RNG starts from the RNG plan's calibration", test_starter_calibration_from_options); + database.add("Starter RNG saves its calibration after each reset", test_starter_calibration_saved); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp new file mode 100644 index 0000000000..57943c2dcd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp @@ -0,0 +1,199 @@ +/* AutoStory RNG Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngStopCalibrationOptions::RngStopCalibrationOptions() + : GroupOption("RNG Calibration (this console)", LockMode::LOCK_WHILE_RUNNING) + , SEED( + "Seed Calibration (ms):
As in Starter RNG's RNG Calibration. Each RNG stop starts from it, " + "and saves what it learns after every reset.", + LockMode::LOCK_WHILE_RUNNING, 0 + ) + , CSF( + "Continue Screen Frames Calibration:
As in Starter RNG's RNG Calibration, kept as the seed's is.", + LockMode::LOCK_WHILE_RUNNING, 0.0 + ) + , STARTER_INGAME( + "Starter RNG's In-Game Advances Calibration:
As in Starter RNG's RNG Calibration, " + "for Squirtle only: each RNG stop keeps its own.", + LockMode::LOCK_WHILE_RUNNING, 0.0 + ) +{ + PA_ADD_OPTION(SEED); + PA_ADD_OPTION(CSF); + PA_ADD_OPTION(STARTER_INGAME); +} + +RngCalibrations RngStopCalibrationOptions::calibration(const FloatingPointOption& ingame) const{ + return RngCalibrations{ + .seed_offset = double(int64_t(SEED)) / FRLG_FRAME_DURATION, + .csf_offset = CSF, + .ingame_offset = ingame, + }; +} + +void RngStopCalibrationOptions::save(const RngCalibrations& calibration, FloatingPointOption& ingame){ + // In ms, as RngCalibrationDisplay::set_calibrations() shows it. + SEED.set(int64_t(std::round(calibration.seed_offset * FRLG_FRAME_DURATION))); + CSF.set(calibration.csf_offset); + ingame.set(calibration.ingame_offset); +} + + +StarterRngPlanOptions::StarterRngPlanOptions() + : GroupOption("RNG Plan (Stop for Starter RNG)", LockMode::LOCK_WHILE_RUNNING) + , SOUND( + "Sound:
The in-game sound setting, as in Starter RNG. It picks the seeds.", + {{SoundSetting::Mono, "mono", "Mono"}, {SoundSetting::Stereo, "stereo", "Stereo"}}, + LockMode::LOCK_WHILE_RUNNING, SoundSetting::Mono + ) + , TID( + false, "TID:
Empty: read from the Trainer Card at the stop. Set it only if that read fails.", + LockMode::LOCK_WHILE_RUNNING, "", "" + ) + , SID( + false, + "SID:
The SID, once known. Empty: plan for the SIDs SID Helper lists, from the two options below. " + "Run Starter RNG in AutoStory fills it in when a shiny Squirtle confirms the SID.", + LockMode::LOCK_WHILE_RUNNING, "", "" + ) + , SID_HELPER_ADVANCES( + "SID Helper's Target Advances:
As set in SID Helper.", + LockMode::LOCK_WHILE_RUNNING, 3001, 2275 + ) + , SID_HELPER_CANDIDATES( + "SID Helper's # Candidate SIDs:
As set in SID Helper. The middle one counts as the likeliest.", + LockMode::LOCK_WHILE_RUNNING, 5, 1, 11 + ) + , SHINY_REQUIRED( + "Shiny required:
Only targets shiny for a SID candidate, tried until one comes out shiny. " + "Off: the quickest target that passes the natures and IVs.", + LockMode::LOCK_WHILE_RUNNING, true + ) + , NATURES(false, "Natures:
Separated by commas. Empty: any nature.", LockMode::LOCK_WHILE_RUNNING, "", "Modest, Timid") + , MIN_IVS( + false, "Minimum IVs:
HP/Atk/Def/SpA/SpD/Spe.", + LockMode::LOCK_WHILE_RUNNING, "0/0/0/0/0/0", "0/0/0/0/0/0" + ) + , MAX_ATTEMPTS("Max attempts:
The most targets to list.", LockMode::LOCK_WHILE_RUNNING, 5, 1, 20) +{ + PA_ADD_OPTION(SOUND); + PA_ADD_OPTION(TID); + PA_ADD_OPTION(SID); + PA_ADD_OPTION(SID_HELPER_ADVANCES); + PA_ADD_OPTION(SID_HELPER_CANDIDATES); + PA_ADD_OPTION(SHINY_REQUIRED); + PA_ADD_OPTION(NATURES); + PA_ADD_OPTION(MIN_IVS); + PA_ADD_OPTION(MAX_ATTEMPTS); + PA_ADD_OPTION(CALIBRATION); +} + +std::string StarterRngPlanOptions::sound_name() const{ + return SOUND == SoundSetting::Stereo ? "Stereo" : "Mono"; +} + +std::optional StarterRngPlanOptions::tid_override(Logger& logger) const{ + const std::string text = TID; + if (text.empty()){ + return std::nullopt; + } + const std::optional tid = parse_trainer_id(text); + if (!tid){ + throw UserSetupError(logger, "RNG plan: the TID must be a number from 0 to 65535, or empty."); + } + return tid; +} + +std::optional StarterRngPlanOptions::sid(Logger& logger) const{ + const std::string text = SID; + if (text.empty()){ + return std::nullopt; + } + const std::optional sid = parse_trainer_id(text); + if (!sid){ + throw UserSetupError(logger, "RNG plan: the SID must be a number from 0 to 65535, or empty."); + } + return sid; +} + +RngTargetFilters StarterRngPlanOptions::filters(Logger& logger) const{ + const std::optional> natures = parse_natures(NATURES); + if (!natures){ + throw UserSetupError(logger, "RNG plan: natures must be nature names separated by commas, e.g. \"Modest, Timid\"."); + } + const std::optional min_ivs = parse_ivs(MIN_IVS); + if (!min_ivs){ + throw UserSetupError(logger, "RNG plan: minimum IVs must be six numbers from 0 to 31, e.g. \"0/0/0/31/0/31\"."); + } + RngTargetFilters filters; + filters.natures = *natures; + filters.min_ivs = *min_ivs; + filters.shiny_required = SHINY_REQUIRED; + return filters; +} + +void StarterRngPlanOptions::check(Logger& logger) const{ + tid_override(logger); + sid(logger); + filters(logger); +} + +std::vector StarterRngPlanOptions::helper_candidates(uint16_t tid) const{ + return sid_helper_candidates(tid, SID_HELPER_ADVANCES, SID_HELPER_CANDIDATES); +} + +std::vector StarterRngPlanOptions::plan_candidates(Logger& logger, uint16_t tid) const{ + const std::optional known = sid(logger); + return known ? std::vector{{*known, 1}} : helper_candidates(tid); +} + +std::vector StarterRngPlanOptions::plan(Logger& logger, Language language, uint16_t tid) const{ + // SID Helper's candidates are logged even with the SID known, to place + // it among them (rng_log_confirmed()). + const std::vector helper = helper_candidates(tid); + logger.log(rng_log_sid_helper(tid, SID_HELPER_ADVANCES, helper)); + const std::optional known = sid(logger); + if (known){ + logger.log(rng_log_confirmed(tid, *known, helper)); + } + + const std::vector attempts = plan_starter_rng(StarterRngPlanInputs{ + // TODO: LeafGreen, once AutoStory plays it. + .firered = true, + .language = language, + .sound = SOUND, + .tid = tid, + .candidates = plan_candidates(logger, tid), + .filters = filters(logger), + .max_attempts = MAX_ATTEMPTS, + }); + if (attempts.empty()){ + throw UserSetupError(logger, + "RNG plan: no Starter RNG target passes the natures, minimum IVs and shiny options for TID " + std::to_string(tid) + "." + ); + } + for (size_t c = 0; c < attempts.size(); c++){ + logger.log(rng_log_attempt(c, attempts[c])); + } + return attempts; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h new file mode 100644 index 0000000000..dc0a8e1343 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h @@ -0,0 +1,100 @@ +/* AutoStory RNG Options + * + * From: https://github.com/PokemonAutomation/ + * + * The RNG plan options: what AutoStory's Starter RNG stop searches targets + * with (RngManipulation/PokemonFRLG_RngPlan.h). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRngOptions_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRngOptions_H + +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Language.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// This console's RNG calibration, as Starter RNG's RNG Calibration shows +// it, for AutoStory's RNG stops to start from: the seed and Continue +// Screen Frames offsets, the same for every stop, and an in-game advances +// offset for each stop. +class RngStopCalibrationOptions : public GroupOption{ +public: + RngStopCalibrationOptions(); + + // The calibration in frames for the stop whose in-game advances offset + // `ingame` keeps. + RngCalibrations calibration(const FloatingPointOption& ingame) const; + // Keeps `calibration` as calibration() returns it. Called after each + // reset, so a stopped run keeps what it learned. + void save(const RngCalibrations& calibration, FloatingPointOption& ingame); + +public: + SimpleIntegerOption SEED; + FloatingPointOption CSF; + // Starter RNG's in-game advances offset. + FloatingPointOption STARTER_INGAME; +}; + + +class StarterRngPlanOptions : public GroupOption{ +public: + StarterRngPlanOptions(); + + // Throws UserSetupError for a TID, SID, natures or IVs it can't read, + // before the run presses anything. + void check(Logger& logger) const; + // The TID typed in, or nothing to read it from the Trainer Card. + std::optional tid_override(Logger& logger) const; + + // The attempts these options ask for, for TID "tid" in a FireRed game + // in "language", logged as "RngPlan:" lines. Throws UserSetupError + // when no target passes. + std::vector plan(Logger& logger, Language language, uint16_t tid) const; + // SID Helper's candidates for "tid", from the two SID Helper options. + std::vector helper_candidates(uint16_t tid) const; + // The SIDs plan() plans for: the SID if set, else helper_candidates(). + std::vector plan_candidates(Logger& logger, uint16_t tid) const; + // The sound setting as Starter RNG's dropdown shows it. + std::string sound_name() const; + +public: + EnumDropdownOption SOUND; + StringOption TID; + StringOption SID; + SimpleIntegerOption SID_HELPER_ADVANCES; + SimpleIntegerOption SID_HELPER_CANDIDATES; + BooleanCheckBoxOption SHINY_REQUIRED; + StringOption NATURES; + StringOption MIN_IVS; + SimpleIntegerOption MAX_ATTEMPTS; + RngStopCalibrationOptions CALIBRATION; + +private: + RngTargetFilters filters(Logger& logger) const; + std::optional sid(Logger& logger) const; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp index 6410a0710c..53b2da73ad 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -166,6 +166,7 @@ class FakeGame : public Pokemon::StoryStepExecutor{ virtual Outcome mash(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } virtual Outcome battle(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } virtual Outcome heal(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } + virtual Outcome game(RunState&, const StoryStep&) override{ return Pokemon::outcome_ok(); } // The Viridian Mart's list as the game shows it. After a purchase the // cursor stays on the row bought (console B, 2026-11-01), so each // order moves it from there, as buy_items() does since ad5d40885. @@ -220,9 +221,11 @@ class FakeGame : public Pokemon::StoryStepExecutor{ }; -// One simulated run, segment built as the program builds it: each -// checkpoint saves at its end (hooks.save stands for save_game()). +// One simulated run, segment built as the program builds it: the rows a +// run takes with every handoff off, each saving at its end (hooks.save +// stands for save_game()). struct Simulation{ + std::vector rows = plan_story_run(story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{}).rows; FakeGame game; std::vector lines; // Where each save stood: the end of its checkpoint. @@ -234,7 +237,7 @@ struct Simulation{ game.set_language(Language::Japanese); Pokemon::Segment segment; segment.id = "00"; - for (const StoryCheckpoint& data : story_checkpoints()){ + for (const StoryCheckpoint& data : rows){ segment.checkpoints.push_back(Pokemon::CheckpointSpec{ .id = data.id, .title = data.title, .saves = true, .build = [this, &data]{ return Pokemon::build_story_checkpoint(data, game); }, @@ -303,15 +306,15 @@ UnitTestResult test_whole_story(){ return "Expected the whole story through:" + joined(sim.lines); } std::vector ids; - for (const StoryCheckpoint& data : story_checkpoints()){ + for (const StoryCheckpoint& data : sim.rows){ ids.push_back(data.id); } if (sim.begun() != ids || sim.saves.size() != ids.size()){ return "Expected each checkpoint once, in order, each saving at its end:" + joined(sim.game.trace); } // Each checkpoint starts where the save before it stands. - for (size_t c = 1; c < story_checkpoints().size(); c++){ - const StoryCheckpoint& data = story_checkpoints()[c]; + for (size_t c = 1; c < sim.rows.size(); c++){ + const StoryCheckpoint& data = sim.rows[c]; const std::optional start = story_pose(*data.start); const std::optional saved = story_pose(sim.saves[c - 1].second); const bool same = start && saved && start->map == saved->map && start->tile == saved->tile diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 7db4cec429..eb29f6d463 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -146,12 +146,37 @@ StoryStep shop(std::string name, std::vector items, std::str } +StoryStep game_step(std::string variant, Pokemon::Pose pose_after, std::string why){ + StoryStep step = make(StoryStepKind::GAME, variant, std::move(why)); + step.variant = std::move(variant); + step.pose_after = std::move(pose_after); + return step; +} + +StoryStep options_step(){ + return make(StoryStepKind::OPTIONS, "options", "fast text; no switch prompt between a trainer's Pokemon"); +} + + StoryCheckpoint new_game(){ - return row("00.01", "new game to the bedroom", std::nullopt, {}, StartMenu::BEFORE_POKEMON, { + StoryCheckpoint checkpoint = row("00.01", "new game to the bedroom", std::nullopt, {}, StartMenu::BEFORE_POKEMON, { // new_game.c: the bedroom at (6, 6), facing the TV. - new_game_intro(at(BEDROOM, 6, 6, NORTH), "Oak's speech, BOY, default names, rival GREEN"), - make(StoryStepKind::OPTIONS, "options", "fast text; no switch prompt between a trainer's Pokemon"), + new_game_intro(at(BEDROOM, 6, 6, NORTH), "Oak's speech, BOY, the player's name (default if none is set), rival GREEN"), + options_step(), + }); + checkpoint.handoff = StoryHandoff::SID_HELPER; + return checkpoint; +} + +// SID Helper confirms the name, finishes the intro and reads the Trainer +// Card from the START menu, without moving the player or saving. +StoryCheckpoint after_sid_helper(){ + StoryCheckpoint checkpoint = row("00.01b", "after SID Helper: close the Trainer Card, save in the bedroom", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { + game_step(CLOSE_TRAINER_CARD, at(BEDROOM, 6, 6, NORTH), "the Trainer Card SID Helper left open, or HOME"), + options_step(), }); + checkpoint.live_start = true; + return checkpoint; } StoryCheckpoint leave_house(){ @@ -169,9 +194,17 @@ StoryCheckpoint oaks_trigger(){ }); } -StoryCheckpoint starter(){ - return row("00.04", "Squirtle, then the rival's battle", at(LAB, 6, 4, NORTH), {}, StartMenu::BEFORE_POKEDEX, { +// Starter RNG starts from a save south of the table, facing the ball. +StoryCheckpoint to_starter_ball(){ + StoryCheckpoint checkpoint = row("00.04", "to Squirtle's ball, south of the table", at(LAB, 6, 4, NORTH), {}, StartMenu::BEFORE_POKEMON, { route("below_squirtle", at(LAB, 9, 5, NORTH), "under Squirtle's ball (9, 4)"), + }); + checkpoint.handoff = StoryHandoff::STARTER_RNG; + return checkpoint; +} + +StoryCheckpoint starter(){ + return row("00.04b", "Squirtle, then the rival's battle", at(LAB, 9, 5, NORTH), {}, StartMenu::BEFORE_POKEDEX, { talk("squirtle_ball", "\"So, you want the WATER POKEMON SQUIRTLE?\""), answer("choose_squirtle", true, "take Squirtle"), answer("no_nickname", false, "\"give a nickname?\" NO"), @@ -284,7 +317,7 @@ StoryCheckpoint running_shoes(){ const std::vector& story_checkpoints(){ static const std::vector checkpoints{ - new_game(), leave_house(), oaks_trigger(), starter(), parcel(), pokedex(), shopping(), forest(), brock(), + new_game(), after_sid_helper(), leave_house(), oaks_trigger(), to_starter_ball(), starter(), parcel(), pokedex(), shopping(), forest(), brock(), running_shoes(), }; return checkpoints; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index d8a3f8b15d..e93c6058f9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -21,7 +21,9 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Checkpoints 00.01 to 00.10, in order. +// Checkpoints 00.01 to 00.10, in order, with 00.01b, the way back in after +// SID Helper, after 00.01, and 00.04 split in two at Squirtle's ball for +// Starter RNG: 00.04 and 00.04b. const std::vector& story_checkpoints(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index fa4b926b71..d282fd40bd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -211,8 +212,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po UnitTestResult test_routes_and_chain(){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 10 || checkpoints[0].start){ - return "Expected 10 checkpoints, the first from a new game."; + if (checkpoints.size() != 12 || checkpoints[0].start){ + return "Expected 12 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -527,6 +528,171 @@ UnitTestResult test_intro_names(){ return true; } + +size_t row_index(std::string_view id){ + const std::vector& checkpoints = story_checkpoints(); + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == id){ + return c; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint " + std::string(id)); +} + +std::string joined_ids(const std::vector& rows){ + std::string text; + for (const StoryCheckpoint& row : rows){ + text += (text.empty() ? "" : " ") + row.id; + } + return text; +} + +const char* handoff_name(StoryHandoff handoff){ + switch (handoff){ + case StoryHandoff::NONE: + return "none"; + case StoryHandoff::SID_HELPER: + return "SID Helper"; + case StoryHandoff::STARTER_RNG: + return "Starter RNG"; + } + return "?"; +} + +struct RunPlanScenario{ + std::string name = ""; + std::string first = ""; + // The table's last row if empty. + std::string last = ""; + StoryHandoffs handoffs = {}; + std::string expected_ids = ""; + StoryHandoff expected_stop = StoryHandoff::NONE; +}; + +class Test_RunPlan : public UnitTest{ +public: + Test_RunPlan(RunPlanScenario scenario) + : UnitTest("PokemonFRLG::AutoStory - run plan: " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + const size_t last = m_scenario.last.empty() ? story_checkpoints().size() - 1 : row_index(m_scenario.last); + const StoryRunPlan plan = plan_story_run(story_checkpoints(), row_index(m_scenario.first), last, m_scenario.handoffs); + const std::string ids = joined_ids(plan.rows); + if (ids != m_scenario.expected_ids || plan.stop != m_scenario.expected_stop){ + return "Expected rows \"" + m_scenario.expected_ids + "\", stop " + handoff_name(m_scenario.expected_stop) + + "; got \"" + ids + "\", stop " + handoff_name(plan.stop) + "."; + } + return true; + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + const RunPlanScenario m_scenario; +}; + +void add_tests_RunPlan(UnitTestDatabase& database){ + const std::string TODAY = "00.01 00.02 00.03 00.04 00.05 00.06 00.07 00.08 00.09 00.10"; + const RunPlanScenario scenarios[] = { + {.name = "handoffs off: the story as before", .first = "00.01", .expected_ids = TODAY}, + {.name = "handoffs off: a range", .first = "00.02", .last = "00.04", .expected_ids = "00.02 00.03 00.04"}, + { + .name = "SID Helper: 00.01 stops on the keyboard", + .first = "00.01", + .handoffs = {.sid_helper = true}, + .expected_ids = "", + .expected_stop = StoryHandoff::SID_HELPER, + }, + { + .name = "SID Helper: back in at 00.01b", + .first = "00.01b", + .last = "00.03", + .handoffs = {.sid_helper = true}, + .expected_ids = "00.01b 00.02 00.03", + }, + {.name = "00.01b runs when started at, option off", .first = "00.01b", .last = "00.02", .expected_ids = "00.01b 00.02"}, + {.name = "SID Helper: a later start passes over it", .first = "00.02", .last = "00.03", .handoffs = {.sid_helper = true}, .expected_ids = "00.02 00.03"}, + {.name = "handoffs off: an end at 00.04 still takes the rival's battle", .first = "00.03", .last = "00.04", .expected_ids = "00.03 00.04"}, + { + .name = "Starter RNG: stops after 00.04's save", + .first = "00.02", + .handoffs = {.starter_rng = true}, + .expected_ids = "00.02 00.03 00.04", + .expected_stop = StoryHandoff::STARTER_RNG, + }, + {.name = "00.04b runs from its own save", .first = "00.04b", .last = "00.05", .expected_ids = "00.04b 00.05"}, + {.name = "Starter RNG: a later start doesn't stop", .first = "00.05", .last = "00.06", .handoffs = {.starter_rng = true}, .expected_ids = "00.05 00.06"}, + { + .name = "both handoffs, back in after SID Helper", + .first = "00.01b", + .handoffs = {.sid_helper = true, .starter_rng = true}, + .expected_ids = "00.01b 00.02 00.03 00.04", + .expected_stop = StoryHandoff::STARTER_RNG, + }, + }; + for (const RunPlanScenario& scenario : scenarios){ + database.add(scenario); + } +} + +std::string step_names(const StoryCheckpoint& checkpoint){ + std::string text; + for (const StoryStep& step : checkpoint.steps){ + text += (text.empty() ? "" : " ") + step.name; + } + return text; +} + +// With Starter RNG's handoff off, 00.04 and 00.04b run as the one 00.04 +// the story had before the split: from the lab's table to the rival's +// battle, saving once with the starter's START menu. +UnitTestResult test_starter_rows_joined(){ + const std::vector& checkpoints = story_checkpoints(); + const StoryRunPlan plan = plan_story_run(checkpoints, row_index("00.04"), row_index("00.04b"), StoryHandoffs{}); + const std::string expected_steps = + "below_squirtle squirtle_ball choose_squirtle no_nickname rival_takes_bulbasaur above_rival_trigger rival_trigger rival_battle"; + if (plan.rows.size() != 1){ + return "Expected one checkpoint, got \"" + joined_ids(plan.rows) + "\"."; + } + const StoryCheckpoint& row = plan.rows[0]; + if (row.id != "00.04" || row.title != "Squirtle, then the rival's battle" || step_names(row) != expected_steps){ + return "Expected 00.04 \"Squirtle, then the rival's battle\": " + expected_steps + + "; got " + row.id + " \"" + row.title + "\": " + step_names(row); + } + const std::optional start = story_pose(*row.start); + if (!start || start->map != "PalletTown_ProfessorOaksLab" || !(start->tile == TilePos{6, 4}) || row.menu != StartMenu::BEFORE_POKEDEX){ + return "Expected the joined 00.04 to start at the table (6, 4) and save with the starter's START menu."; + } + // Split, 00.04 saves under the ball facing it, before the starter. + const StoryCheckpoint& to_ball = checkpoints[row_index("00.04")]; + const std::optional ball = story_pose(*checkpoints[row_index("00.04b")].start); + if (to_ball.handoff != StoryHandoff::STARTER_RNG || to_ball.menu != StartMenu::BEFORE_POKEMON + || !ball || !(ball->tile == TilePos{9, 5}) || ball->facing != Direction::NORTH + ){ + return "Expected 00.04 to end under Squirtle's ball (9, 5) facing north, saving before the starter."; + } + return true; +} + +// The way back in after SID Helper loads no save and starts where 00.01 +// leaves the player, so 00.02 follows it unchanged. +UnitTestResult test_after_sid_helper_row(){ + const StoryCheckpoint& sid = story_checkpoints()[row_index("00.01b")]; + if (!sid.live_start || story_checkpoints()[0].handoff != StoryHandoff::SID_HELPER){ + return "Expected 00.01 to be SID Helper's handoff and 00.01b to start from the live game."; + } + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + if (checkpoint.live_start != (checkpoint.id == "00.01b")){ + return checkpoint.id + ": only 00.01b starts from the live game."; + } + } + return true; +} + // set_options()'s RIGHT presses from each value an old save can leave: // on console B a save with FAST and SET became SLOW and SHIFT when the // presses assumed MID and SHIFT. @@ -571,6 +737,9 @@ UnitTestResult test_option_presses(){ void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_RunPlan(database); + database.add("00.01b: back in after SID Helper", test_after_sid_helper_row); + database.add("00.04 and 00.04b: one checkpoint with Starter RNG off", test_starter_rows_joined); database.add("every route plans, and checkpoints chain", test_routes_and_chain); database.add("step names are unique per checkpoint", test_unique_names); database.add("every save has a place on the save card", test_save_places); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp new file mode 100644 index 0000000000..974acd42c9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp @@ -0,0 +1,106 @@ +/* Naming Screen + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_NamingScreenDetector.h" +#include "PokemonFRLG_NamingScreen.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// The game reads new presses once per frame and starts repeating a held direction after +// about 40 frames, so a short hold with a release of several frames is one press each. +constexpr Milliseconds PRESS_HOLD = 80ms; +constexpr Milliseconds MOVE_RELEASE = 120ms; +constexpr Milliseconds KEY_RELEASE = 200ms; +// The page swap animation runs 32 frames (about 530 ms) with input disabled. +constexpr Milliseconds PAGE_SWAP_RELEASE = 900ms; +// After the last character fits, the cursor animates to OK with input disabled. +constexpr Milliseconds START_RELEASE = 500ms; + +void press(ProControllerContext& context, NamingAction action){ + switch (action){ + case NamingAction::UP: + pbf_press_dpad(context, DPAD_UP, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::DOWN: + pbf_press_dpad(context, DPAD_DOWN, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::LEFT: + pbf_press_dpad(context, DPAD_LEFT, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::RIGHT: + pbf_press_dpad(context, DPAD_RIGHT, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::A: + pbf_press_button(context, BUTTON_A, PRESS_HOLD, KEY_RELEASE); + return; + case NamingAction::SELECT: + pbf_press_button(context, BUTTON_MINUS, PRESS_HOLD, PAGE_SWAP_RELEASE); + return; + case NamingAction::START: + pbf_press_button(context, BUTTON_PLUS, PRESS_HOLD, START_RELEASE); + return; + } +} + +void check_name(ConsoleHandle& console, const std::string& text, NamingScreenKind kind){ + const std::string error = naming_text_error(text, kind); + if (!error.empty()){ + throw UserSetupError(console, error); + } +} + +bool press_on_naming_screen( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind, const std::vector& actions +){ + NamingScreenWatcher naming_screen(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, std::chrono::seconds(5), {naming_screen}) < 0){ + console.log("Naming screen not found. Not typing \"" + text + "\".", COLOR_RED); + return false; + } + + console.log("Typing " + std::string(naming_screen_kind_name(kind)) + " name \"" + text + "\": " + to_string(actions)); + for (NamingAction action : actions){ + press(context, action); + } + context.wait_for_all_requests(); + return true; +} + +} + + +bool type_name( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +){ + check_name(console, text, kind); + return press_on_naming_screen(console, context, text, kind, plan_naming_input(text, kind)); +} + +bool type_name_without_confirming( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +){ + check_name(console, text, kind); + return press_on_naming_screen(console, context, text, kind, plan_naming_keys(text, kind)); +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h new file mode 100644 index 0000000000..65acefc8f4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h @@ -0,0 +1,43 @@ +/* Naming Screen + * + * From: https://github.com/PokemonAutomation/ + * + * Types a name on the in-game naming screen (player, rival, box, Pokemon nickname). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreen_H +#define PokemonAutomation_PokemonFRLG_NamingScreen_H + +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_NamingScreenKeyboard.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Types `text` on a naming screen that was just opened (cursor on "A", nothing typed) and +// presses OK. Returns once OK is pressed; what follows (e.g. "So your name is ...?") is up to +// the caller. +// Returns false, without pressing anything, if the naming screen is not on screen. +// Throws UserSetupError if the game can't take `text` (see naming_text_error()). +bool type_name( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +); + +// Like type_name(), but leaves the name on screen with OK not pressed, for a program that +// confirms the name itself (SID Helper presses PLUS then A on its own timing). +bool type_name_without_confirming( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp new file mode 100644 index 0000000000..c148871808 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp @@ -0,0 +1,348 @@ +/* Naming Screen Keyboard + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_NamingScreenKeyboard.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +size_t naming_screen_max_chars(NamingScreenKind kind){ + switch (kind){ + case NamingScreenKind::PLAYER: return 7; + case NamingScreenKind::RIVAL: return 7; + case NamingScreenKind::BOX: return 8; + case NamingScreenKind::POKEMON: return 10; + } + return 0; +} +const char* naming_screen_kind_name(NamingScreenKind kind){ + switch (kind){ + case NamingScreenKind::PLAYER: return "player"; + case NamingScreenKind::RIVAL: return "rival"; + case NamingScreenKind::BOX: return "box"; + case NamingScreenKind::POKEMON: return "Pokemon"; + } + return "?"; +} + +std::string to_string(const NamingCursor& cursor){ + static const char* const PAGE_NAMES[] = {"UPPER", "LOWER", "SYMBOLS"}; + return std::string(PAGE_NAMES[(size_t)cursor.page]) + + " row " + std::to_string(cursor.row) + + " column " + std::to_string(cursor.column) + + " (remembered row " + std::to_string(cursor.remembered_row) + ")"; +} + +const char* naming_action_name(NamingAction action){ + switch (action){ + case NamingAction::UP: return "UP"; + case NamingAction::DOWN: return "DOWN"; + case NamingAction::LEFT: return "LEFT"; + case NamingAction::RIGHT: return "RIGHT"; + case NamingAction::A: return "A"; + case NamingAction::SELECT: return "SELECT"; + case NamingAction::START: return "START"; + } + return "?"; +} +std::string to_string(const std::vector& actions){ + std::string ret; + for (NamingAction action : actions){ + if (!ret.empty()){ + ret += ' '; + } + ret += naming_action_name(action); + } + return ret; +} + + +namespace{ + +constexpr uint8_t BUTTON_COUNT = 3; +// sKeyRowToButtonRow and sButtonRowToKeyRow in HandleDpadMovement(). +constexpr uint8_t KEY_ROW_TO_BUTTON[NAMING_SCREEN_KEY_ROWS] = {0, 1, 1, 2}; +constexpr uint8_t BUTTON_TO_KEY_ROW[BUTTON_COUNT] = {0, 0, 3}; + +uint8_t key_columns(NamingScreenPage page){ + return NAMING_SCREEN_KEY_COLUMNS[(size_t)page]; +} + +// Wraps the row after a move: three buttons on the button column, four key rows elsewhere. +void wrap_row(NamingCursor& cursor, bool on_button_column, int y){ + if (on_button_column){ + if (y < 0){ + y = BUTTON_COUNT - 1; + } + if (y >= BUTTON_COUNT){ + y = 0; + } + // The game reuses tButtonId here, so the middle button can return to row 1 or 2. + if (y == 0){ + cursor.remembered_row = NAMING_SCREEN_BUTTON_BACK; + }else if (y == BUTTON_COUNT - 1){ + cursor.remembered_row = NAMING_SCREEN_BUTTON_OK; + } + }else{ + if (y < 0){ + y = NAMING_SCREEN_KEY_ROWS - 1; + } + if (y >= (int)NAMING_SCREEN_KEY_ROWS){ + y = 0; + } + } + cursor.row = (uint8_t)y; +} + +NamingCursor move(NamingCursor cursor, int dx, int dy){ + const int columns = key_columns(cursor.page); + const int previous_x = cursor.column; + int x = cursor.column + dx; + int y = cursor.row + dy; + + // Wrap X. The button column is part of the ring. + if (x < 0){ + x = columns; + } + if (x > columns){ + x = 0; + } + + // Moving onto or off the button column. + if (dx != 0){ + if (x == columns){ + cursor.remembered_row = (uint8_t)y; + y = KEY_ROW_TO_BUTTON[y]; + }else if (previous_x == columns){ + y = y == BUTTON_COUNT / 2 ? cursor.remembered_row : BUTTON_TO_KEY_ROW[y]; + } + } + + cursor.column = (uint8_t)x; + wrap_row(cursor, x == columns, y); + return cursor; +} + +NamingCursor next_page(NamingCursor cursor){ + const bool on_button_column = cursor.column == key_columns(cursor.page); + cursor.page = (NamingScreenPage)(((size_t)cursor.page + 1) % NAMING_SCREEN_PAGES); + const uint8_t columns = key_columns(cursor.page); + if (on_button_column || cursor.column >= columns){ + cursor.column = on_button_column ? columns : columns - 1; + } + return cursor; +} + +const char* key_at(const NamingCursor& cursor){ + if (cursor.column >= key_columns(cursor.page)){ + return nullptr; + } + return NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; +} + + +struct KeyAlias{ + const char* typed; + const char* key; +}; +// Other spellings of a key's character. +constexpr KeyAlias KEY_ALIASES[] = { + {"\xE2\x80\x99", "'"}, // right single quote: the apostrophe key types it +}; + +bool text_has_at(const std::string& text, size_t position, const char* str){ + return text.compare(position, strlen(str), str) == 0; +} + +// The key text at `position` in `text`, or nullptr if no key types it. +const char* key_text_at(const std::string& text, size_t position, size_t& length){ + const char* best = nullptr; + length = 0; + for (const auto& page : NAMING_SCREEN_KEYS){ + for (const auto& row : page){ + for (const char* key : row){ + if (key != nullptr && strlen(key) > length && text_has_at(text, position, key)){ + best = key; + length = strlen(key); + } + } + } + } + for (const KeyAlias& alias : KEY_ALIASES){ + if (strlen(alias.typed) > length && text_has_at(text, position, alias.typed)){ + best = alias.key; + length = strlen(alias.typed); + } + } + return best; +} + +// The UTF-8 character at `position`, for error messages. +std::string utf8_char_at(const std::string& text, size_t position){ + const unsigned char lead = (unsigned char)text[position]; + size_t length = 1; + if (lead >= 0xF0){ + length = 4; + }else if (lead >= 0xE0){ + length = 3; + }else if (lead >= 0xC0){ + length = 2; + } + return text.substr(position, length); +} + +// Splits `text` into the keys that type it. Returns the error, or "" on success. +std::string split_into_keys(const std::string& text, std::vector& keys){ + keys.clear(); + for (size_t position = 0; position < text.size();){ + size_t length; + const char* key = key_text_at(text, position, length); + if (key == nullptr){ + return "\"" + text + "\" has a character the naming screen can't type: \"" + + utf8_char_at(text, position) + "\" (byte " + std::to_string(position) + "). " + "It types A-Z, a-z, 0-9, space and . , ! ? / - ' and the game's " + "male/female signs, ellipsis and curly quotes."; + } + keys.emplace_back(key); + position += length; + } + return ""; +} + + +size_t state_index(const NamingCursor& cursor){ + return (((size_t)cursor.page * (NAMING_SCREEN_MAX_KEY_COLUMNS + 1) + cursor.column) + * NAMING_SCREEN_KEY_ROWS + cursor.row) * NAMING_SCREEN_KEY_ROWS + cursor.remembered_row; +} +constexpr size_t STATE_COUNT = + NAMING_SCREEN_PAGES * (NAMING_SCREEN_MAX_KEY_COLUMNS + 1) * NAMING_SCREEN_KEY_ROWS * NAMING_SCREEN_KEY_ROWS; + +// Breadth-first search over cursor states for the fewest presses that reach a key typing `key`. +// Appends the moves and returns the cursor on that key. +NamingCursor append_moves_to_key(const NamingCursor& start, const char* key, std::vector& actions){ + // START is left out: it only jumps to OK, which the plan uses once at the end. + static const NamingAction MOVES[] = { + NamingAction::UP, NamingAction::DOWN, NamingAction::LEFT, NamingAction::RIGHT, NamingAction::SELECT, + }; + struct Visit{ + bool seen = false; + size_t parent = 0; + NamingAction action = NamingAction::A; + }; + std::vector visits(STATE_COUNT); + std::vector queue{start}; + visits[state_index(start)].seen = true; + + for (size_t head = 0; head < queue.size(); head++){ + const NamingCursor cursor = queue[head]; + const char* here = key_at(cursor); + if (here != nullptr && strcmp(here, key) == 0){ + std::vector path; + for (size_t index = state_index(cursor); index != state_index(start); index = visits[index].parent){ + path.emplace_back(visits[index].action); + } + actions.insert(actions.end(), path.rbegin(), path.rend()); + return cursor; + } + for (NamingAction action : MOVES){ + const NamingCursor next = apply_naming_action(cursor, action); + Visit& visit = visits[state_index(next)]; + if (!visit.seen){ + visit.seen = true; + visit.parent = state_index(cursor); + visit.action = action; + queue.emplace_back(next); + } + } + } + // Every key is reachable, so this is a bug. + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string("No path to naming screen key: ") + key); +} + +} + + +NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action){ + switch (action){ + case NamingAction::UP: return move(cursor, 0, -1); + case NamingAction::DOWN: return move(cursor, 0, 1); + case NamingAction::LEFT: return move(cursor, -1, 0); + case NamingAction::RIGHT: return move(cursor, 1, 0); + case NamingAction::SELECT: return next_page(cursor); + case NamingAction::START:{ + NamingCursor ret = cursor; + ret.column = key_columns(cursor.page); + ret.row = NAMING_SCREEN_BUTTON_OK; + return ret; + } + case NamingAction::A: + return cursor; + } + return cursor; +} + + +std::string naming_text_error(const std::string& text, NamingScreenKind kind){ + std::vector keys; + std::string error = split_into_keys(text, keys); + if (!error.empty()){ + return error; + } + bool only_spaces = true; + for (const char* key : keys){ + only_spaces &= strcmp(key, " ") == 0; + } + if (only_spaces){ + return "The name \"" + text + "\" is empty or only spaces, so the game would not keep it."; + } + const size_t max_chars = naming_screen_max_chars(kind); + if (keys.size() > max_chars){ + return "\"" + text + "\" is " + std::to_string(keys.size()) + " characters, but a " + + naming_screen_kind_name(kind) + " name holds at most " + std::to_string(max_chars) + "."; + } + return ""; +} + +std::vector plan_naming_keys( + const std::string& text, NamingScreenKind kind, const NamingCursor& start +){ + const std::string error = naming_text_error(text, kind); + if (!error.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, error); + } + std::vector keys; + split_into_keys(text, keys); + + std::vector actions; + NamingCursor cursor = start; + for (const char* key : keys){ + cursor = append_moves_to_key(cursor, key, actions); + actions.emplace_back(NamingAction::A); + } + return actions; +} + +std::vector plan_naming_input( + const std::string& text, NamingScreenKind kind, const NamingCursor& start +){ + std::vector actions = plan_naming_keys(text, kind, start); + // When the last key fills the name, the game moves the cursor to OK by itself; START is + // then harmless. + actions.emplace_back(NamingAction::START); + actions.emplace_back(NamingAction::A); + return actions; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h new file mode 100644 index 0000000000..496c46df63 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h @@ -0,0 +1,140 @@ +/* Naming Screen Keyboard + * + * From: https://github.com/PokemonAutomation/ + * + * The in-game keyboard used to name the player, the rival, PC boxes and Pokemon, and a + * planner that turns a name into button presses. Pure data and logic: no console needed. + * + * Everything here follows pret/pokefirered src/naming_screen.c at commit + * ce6406d8c2eaf46d543c8a2606de0c3cb1951982 (English game). The decomp includes the Switch + * revision (REVISION >= 0xA), so the layout is the one on the Switch release. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_H +#define PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The keyboard pages, in the order SELECT cycles through them. The screen opens on UPPER. +enum class NamingScreenPage : uint8_t{ + UPPER, + LOWER, + SYMBOLS, +}; +constexpr size_t NAMING_SCREEN_PAGES = 3; +constexpr size_t NAMING_SCREEN_KEY_ROWS = 4; +constexpr size_t NAMING_SCREEN_MAX_KEY_COLUMNS = 8; + +// Key columns on each page (sPageColumnCounts). The button column (page / back / OK) comes +// right after the last key column, so on a page with N key columns it is column N. +constexpr uint8_t NAMING_SCREEN_KEY_COLUMNS[NAMING_SCREEN_PAGES] = {8, 8, 6}; + +// The text each key types, in UTF-8 (sKeyboardChars), indexed [page][row][column]. +// nullptr: no key (past the page's last column). +// The decomp pads each row with byte 0x00, which is a space in the game's charmap, and the +// keyboard labels draw a blank there: those cells type a space just like the spaces in rows 0-1. +// The apostrophe key types the game's right single quote (charmap 0xB4). +constexpr const char* NAMING_SCREEN_KEYS + [NAMING_SCREEN_PAGES][NAMING_SCREEN_KEY_ROWS][NAMING_SCREEN_MAX_KEY_COLUMNS] = { + { // UPPER + {"A", "B", "C", "D", "E", "F", " ", "."}, + {"G", "H", "I", "J", "K", "L", " ", ","}, + {"M", "N", "O", "P", "Q", "R", "S", " "}, + {"T", "U", "V", "W", "X", "Y", "Z", " "}, + }, + { // LOWER + {"a", "b", "c", "d", "e", "f", " ", "."}, + {"g", "h", "i", "j", "k", "l", " ", ","}, + {"m", "n", "o", "p", "q", "r", "s", " "}, + {"t", "u", "v", "w", "x", "y", "z", " "}, + }, + { // SYMBOLS + {"0", "1", "2", "3", "4", " ", nullptr, nullptr}, + {"5", "6", "7", "8", "9", " ", nullptr, nullptr}, + {"!", "?", "\xE2\x99\x82", "\xE2\x99\x80", "/", "-", nullptr, nullptr}, // ! ? male female / - + {"\xE2\x80\xA6", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x98", "'", " ", nullptr, nullptr}, // ellipsis, double quotes, left single quote, ' + }, +}; + +// The three buttons in the button column, top to bottom. +constexpr uint8_t NAMING_SCREEN_BUTTON_PAGE = 0; +constexpr uint8_t NAMING_SCREEN_BUTTON_BACK = 1; +constexpr uint8_t NAMING_SCREEN_BUTTON_OK = 2; + + +// Which naming screen is open; it sets how many characters fit (NamingScreenTemplate.maxChars). +enum class NamingScreenKind : uint8_t{ + PLAYER, // PLAYER_NAME_LENGTH + RIVAL, // PLAYER_NAME_LENGTH + BOX, // BOX_NAME_LENGTH + POKEMON, // POKEMON_NAME_LENGTH, for caught Pokemon and the nickname rater +}; +size_t naming_screen_max_chars(NamingScreenKind kind); +const char* naming_screen_kind_name(NamingScreenKind kind); + + +// The cursor, as the game tracks it. +struct NamingCursor{ + NamingScreenPage page = NamingScreenPage::UPPER; + // Key row (0-3), or button (0-2) when on the button column. + uint8_t row = 0; + // Key column, or NAMING_SCREEN_KEY_COLUMNS[page] for the button column. + uint8_t column = 0; + // The game's tButtonId: the key row to return to when leaving the middle button. + uint8_t remembered_row = 0; + + bool operator==(const NamingCursor& other) const = default; +}; +std::string to_string(const NamingCursor& cursor); + + +enum class NamingAction : uint8_t{ + UP, + DOWN, + LEFT, + RIGHT, + A, + SELECT, // next page + START, // move the cursor to OK +}; +const char* naming_action_name(NamingAction action); +// Space-separated action names, e.g. "LEFT LEFT A START A". +std::string to_string(const std::vector& actions); + + +// Where the cursor ends up after one press (HandleDpadMovement, MainState_WaitPageSwap, +// MoveCursorToOKButton). A leaves the cursor in place. +NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action); + +// Why the game can't take `text` as a name of this kind, or "" if it can: a character with +// no key, more characters than fit, or nothing but spaces (the game then keeps no name). +std::string naming_text_error(const std::string& text, NamingScreenKind kind); + +// The presses that type `text` from `start` without confirming it: the shortest moves to +// each character's key, then A. The name stays on screen with OK not pressed, which is where +// SID Helper starts. +// Throws InternalProgramError if naming_text_error() rejects `text`; check that first. +std::vector plan_naming_keys( + const std::string& text, NamingScreenKind kind, const NamingCursor& start = NamingCursor() +); + +// plan_naming_keys(), then START and A to press OK. +std::vector plan_naming_input( + const std::string& text, NamingScreenKind kind, const NamingCursor& start = NamingCursor() +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp new file mode 100644 index 0000000000..54af553f9b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp @@ -0,0 +1,105 @@ +/* Trainer Card + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h" +#include "PokemonFRLG_StartMenuNavigation.h" +#include "PokemonFRLG_TrainerCard.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void navigate_to_trainer_card(ConsoleHandle& console, ProControllerContext& context){ + int errors = 0; + while (true){ + if (errors >= 5){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "navigate_to_trainer_card(): failed 5 times to navigate to the Trainer Card", console + ); + } + + open_start_menu(console, context); + + // the positions are different before recieving a Pokemon and Pokedex + bool cursor = move_cursor_to_position( + console, context, SelectionArrowPositionStartMenu(1) + ); + if (!cursor){ + errors++; + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + } + + TrainerCardWatcher trainer_card(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + }, + { trainer_card } + ); + + if (ret < 0){ + console.log("navigate_to_trainer_card(): failed to detect Trainer Card"); + errors++; + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + } + + break; + } +} + +namespace{ + +template +auto read_on_card(ConsoleHandle& console, ProControllerContext& context, Read read){ + TrainerIdReader reader; + VideoOverlaySet overlays(console.overlay()); + reader.make_overlays(overlays); + + VideoSnapshot screen = console.video().snapshot(); + console.log("Trainer Card detected."); + console.log("Reading TID..."); + auto tid = read(reader, screen); + + context.wait_for_all_requests(); + + return tid; +} + +} + +uint16_t read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language){ + uint16_t tid = read_on_card(console, context, [&](TrainerIdReader& reader, const VideoSnapshot& screen){ + return reader.read_tid(console.logger(), language, screen); + }); + console.log("TID: " + std::to_string(tid)); + return tid; +} + +std::optional try_read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language){ + std::optional tid = read_on_card(console, context, [&](TrainerIdReader& reader, const VideoSnapshot& screen){ + return reader.try_read_tid(console.logger(), language, screen); + }); + console.log(tid ? "TID: " + std::to_string(*tid) : std::string("TID: not read")); + return tid; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h new file mode 100644 index 0000000000..c52c212cba --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h @@ -0,0 +1,41 @@ +/* Trainer Card + * + * From: https://github.com/PokemonAutomation/ + * + * Opening the Trainer Card from the overworld and reading the TID on it, + * as SID Helper does. Shared with AutoStory, which reads the TID for its + * Starter RNG plan. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_TrainerCard_H +#define PokemonAutomation_PokemonFRLG_TrainerCard_H + +#include +#include +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// From the overworld, START then the player's entry, until the card shows. +// The entry is second only before the first Pokemon and the Pokedex. +// Throws OperationFailedException after 5 failed tries. +void navigate_to_trainer_card(ConsoleHandle& console, ProControllerContext& context); + +// The TID on the Trainer Card on screen. An unreadable TID comes back as +// TrainerIdReader::read_tid() returns it. +uint16_t read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language); +// Nothing when the TID can't be read. +std::optional try_read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp new file mode 100644 index 0000000000..b462362ec9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp @@ -0,0 +1,159 @@ +/* RNG Plan + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_BlindNavigation.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +std::vector sid_helper_candidates(uint16_t tid, uint32_t target_advances, uint8_t count){ + // As SidHelper's get_sid_messages(): from "count / 2" steps before the target. + const int start = -int(count) / 2; + const int end = start + int(count); + const int farthest = std::max(-start, end - 1); + + std::vector candidates; + AdvRngSearcher searcher(tid, uint64_t(int64_t(target_advances) + 2 * start)); + for (int i = start; i < end; i++){ + candidates.push_back({uint16_t(searcher.state.s0 >> 16), double(farthest + 1 - std::abs(i))}); + searcher.advance_state(); + searcher.advance_state(); + } + return candidates; +} + + +namespace{ + +// "targets" with only the shiny candidates still "left", and their share of +// the weight left. +std::vector rescore( + const std::vector& targets, + const std::vector& candidates, + const std::vector& left +){ + double total = 0; + for (size_t c = 0; c < candidates.size(); c++){ + if (left[c]){ + total += candidates[c].weight; + } + } + std::vector scored; + scored.reserve(targets.size()); + for (const RngTarget& target : targets){ + RngTarget copy = target; + copy.shiny_for.clear(); + double weight = 0; + for (const ShinyCandidate& shiny : target.shiny_for){ + if (left[shiny.candidate]){ + copy.shiny_for.push_back(shiny); + weight += candidates[shiny.candidate].weight; + } + } + copy.shiny_probability = total > 0 ? weight / total : 0; + scored.emplace_back(std::move(copy)); + } + return scored; +} + +RngAttempt make_attempt(const RngTarget& target, const std::vector& candidates){ + RngAttempt attempt{target, {}}; + for (const ShinyCandidate& shiny : target.shiny_for){ + attempt.sids.push_back(candidates[shiny.candidate].sid); + } + return attempt; +} + +} + + +std::vector plan_rng_attempts( + const std::vector& targets, + const std::vector& candidates, + bool shiny_required, + size_t max_attempts +){ + std::vector attempts; + if (targets.empty() || max_attempts == 0){ + return attempts; + } + std::vector left(candidates.size(), true); + + if (!shiny_required){ + // With no shiny chance, rank_rng_targets() sorts by time alone. + std::vector by_time = targets; + for (RngTarget& target : by_time){ + target.shiny_probability = 0; + } + rank_rng_targets(by_time); + const uint32_t quickest = by_time.front().state; + for (const RngTarget& target : rescore(targets, candidates, left)){ + if (target.state == quickest){ + attempts.push_back(make_attempt(target, candidates)); + break; + } + } + return attempts; + } + + while (attempts.size() < max_attempts){ + std::vector scored = rescore(targets, candidates, left); + rank_rng_targets(scored); + const RngTarget& best = scored.front(); + if (best.shiny_for.empty()){ + break; + } + for (const ShinyCandidate& shiny : best.shiny_for){ + left[shiny.candidate] = false; + } + attempts.push_back(make_attempt(best, candidates)); + if (std::find(left.begin(), left.end(), true) == left.end()){ + break; + } + } + return attempts; +} + + +int64_t starter_rng_seed_wait_ms(const InitialSeedEntry& seed){ + return int64_t(seed.seed_time_ms) + STARTER_RNG_FIXED_SEED_OFFSET_MS; +} + +bool starter_rng_can_wait_for(const InitialSeedEntry& seed){ + return starter_rng_seed_wait_ms(seed) >= STARTER_RNG_MIN_SEED_WAIT_MS; +} + +int64_t starter_rng_ingame_ms(uint64_t advances){ + const int64_t frames = int64_t(advances) - int64_t(STARTER_RNG_CONTINUE_SCREEN_FRAMES) + + fixed_advances_offset(PokemonFRLG_RngTarget::starters); + return int64_t(frames * FRLG_FRAME_DURATION / 2); +} + +std::vector plan_starter_rng(const StarterRngPlanInputs& inputs){ + const SeedsDatabase database(seeds_json_path(inputs.firered, inputs.language)); + // Only the English lists hold the blackout button's seeds (initial_seed_entries()). + const bool english_list = inputs.language != Language::Japanese; + std::vector seeds = initial_seed_entries(database, inputs.sound, "Help", english_list); + std::erase_if(seeds, [](const InitialSeedEntry& seed){ return !starter_rng_can_wait_for(seed); }); + + RngTargetFilters filters = inputs.filters; + filters.min_advances = std::max(filters.min_advances, STARTER_RNG_PLAN_MIN_ADVANCES); + const std::vector targets = search_rng_targets(seeds, inputs.tid, inputs.candidates, filters); + return plan_rng_attempts(targets, inputs.candidates, filters.shiny_required, inputs.max_attempts); +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h new file mode 100644 index 0000000000..3cc5276748 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h @@ -0,0 +1,121 @@ +/* RNG Plan + * + * From: https://github.com/PokemonAutomation/ + * + * Which Starter RNG targets to ask for, in order, when the SID is + * only narrowed down to SID Helper's candidates, and what to do after each + * one. The loop is the one PokemonFRLG_RngTargetSearch.h describes: + * - Shiny, and the target was hit: the SID is one of those the target is + * shiny for. With one left, it is confirmed and later targets can be + * searched with it alone. + * - Shiny, but not the target (another advance): it says nothing about + * the SID. The plan ends with the shiny. + * - Nature and IVs match, but not shiny: the target was hit, so the SIDs it + * is shiny for are wrong. Go on to the next attempt. + * - Nature or IVs differ: the target was missed. Run it again, up to the + * retries, then go on to the next attempt. + * + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlan_H +#define PokemonAutomation_PokemonFRLG_RngPlan_H + +#include +#include +#include +#include "CommonFramework/Language.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The SIDs SID Helper lists for "tid": "count" of them, 2 advances apart, +// centered on "target_advances", as its get_sid_messages() lists them. The +// middle one, where SID Helper aims, weighs the most, and each step away one +// less, so the outermost weigh 1. +std::vector sid_helper_candidates(uint16_t tid, uint32_t target_advances, uint8_t count); + + +struct RngAttempt{ + RngTarget target; + // The SIDs the target is shiny for, of those the attempts before it + // leave. Empty when the target isn't shiny for any of them. + std::vector sids; +}; + +// The attempts to make, in order, for SID candidates "candidates" (the ones +// "targets" were searched with). Each is the best target by +// rank_rng_targets() over the candidates the attempts before it leave, so a +// target shiny for several candidates comes before one shiny for one, unless +// it takes much longer. Stops after "max_attempts", or once no target is +// shiny for a candidate left. +// +// With "shiny_required" off, a hit ends the plan whether it is shiny or not, +// so the plan is the one quickest target. +std::vector plan_rng_attempts( + const std::vector& targets, + const std::vector& candidates, + bool shiny_required, + size_t max_attempts +); + + +// What Starter RNG's targets are searched with. +struct StarterRngPlanInputs{ + bool firered; + Language language; + SoundSetting sound; + uint16_t tid; + std::vector candidates; + RngTargetFilters filters; + size_t max_attempts; +}; + +// Starter RNG's smallest Advances setting. +inline constexpr uint64_t STARTER_RNG_MIN_ADVANCES = 940; + +// Starter RNG's title screen wait, before calibration: the seed list's +// delay plus this (FIXED_SEED_OFFSET in StarterRng's attempts). +inline constexpr int64_t STARTER_RNG_FIXED_SEED_OFFSET_MS = -845; +// The shortest title screen wait the plan uses. Starter RNG refuses waits +// under 29,650 ms, and its docs (pokemonautomation.github.io, +// docs/Programs/PokemonFRLG/StarterRng.md, "Avoid low seed delays when +// possible") warn that waits near 30,500 ms can miss the title screen +// press. 31,500 ms keeps a second clear of that for the seed calibration. +inline constexpr int64_t STARTER_RNG_MIN_SEED_WAIT_MS = 31500; +// Starter RNG's title screen wait for `seed`, as prepare_timings() makes it +// before calibration. +int64_t starter_rng_seed_wait_ms(const InitialSeedEntry& seed); +// Whether the wait is at least STARTER_RNG_MIN_SEED_WAIT_MS. (Console B, +// 2026-11-02, FireRed English: seeds 11A3 and 405C, at 30,473 and +// 30,488 ms in the table, are 29,628 and 29,643 ms waits, which Starter +// RNG refuses.) +bool starter_rng_can_wait_for(const InitialSeedEntry& seed); + +// Starter RNG's Continue Screen frames, taken off the advances before the +// in-game wait (CONTINUE_SCREEN_FRAMES in StarterRng's attempts). +inline constexpr uint64_t STARTER_RNG_CONTINUE_SCREEN_FRAMES = 200; +// Starter RNG's in-game wait for `advances`, before calibration. It +// refuses one under 7,500 ms, which STARTER_RNG_MIN_ADVANCES just makes. +int64_t starter_rng_ingame_ms(uint64_t advances); +// Room for the in-game calibration, in advances (2 per frame of wait): the +// calibration moves the wait, and it went to -720 after one miss on console +// B (2026-11-02, seed B579 at 967 advances: an 8 s wait cut to 1.7 s). The +// plan's targets are at least this many advances past Starter RNG's +// minimum. To tune from the logs' calibrations. +inline constexpr uint64_t STARTER_RNG_INGAME_MARGIN_ADVANCES = 720; +inline constexpr uint64_t STARTER_RNG_PLAN_MIN_ADVANCES = STARTER_RNG_MIN_ADVANCES + STARTER_RNG_INGAME_MARGIN_ADVANCES; + +// The attempts for Starter RNG, from the seed list of the version and +// language in Help button mode, the one Starter RNG uses. +std::vector plan_starter_rng(const StarterRngPlanInputs& inputs); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp new file mode 100644 index 0000000000..9e0d1a087f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp @@ -0,0 +1,106 @@ +/* RNG Plan Inputs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonFRLG_RngPlanInputs.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +std::string trim(const std::string& text){ + const size_t first = text.find_first_not_of(' '); + if (first == std::string::npos){ + return ""; + } + const size_t last = text.find_last_not_of(' '); + return text.substr(first, last - first + 1); +} + +std::vector split(const std::string& text, char separator){ + std::vector parts; + size_t start = 0; + while (true){ + const size_t next = text.find(separator, start); + parts.push_back(trim(text.substr(start, next == std::string::npos ? std::string::npos : next - start))); + if (next == std::string::npos){ + return parts; + } + start = next + 1; + } +} + +} + + +std::optional parse_trainer_id(const std::string& text){ + const std::string digits = trim(text); + if (digits.empty() || digits.size() > 5 || !std::all_of(digits.begin(), digits.end(), [](char ch){ return ch >= '0' && ch <= '9'; })){ + return std::nullopt; + } + const int value = std::stoi(digits); + if (value > 0xffff){ + return std::nullopt; + } + return uint16_t(value); +} + +std::optional parse_ivs(const std::string& text){ + const std::vector parts = split(text, '/'); + if (parts.size() != 6){ + return std::nullopt; + } + uint8_t values[6]; + for (size_t c = 0; c < 6; c++){ + const std::string& part = parts[c]; + if (part.empty() || part.size() > 2 || !std::all_of(part.begin(), part.end(), [](char ch){ return ch >= '0' && ch <= '9'; })){ + return std::nullopt; + } + const int value = std::stoi(part); + if (value > 31){ + return std::nullopt; + } + values[c] = uint8_t(value); + } + AdvIVs ivs; + ivs.hp = values[0]; + ivs.attack = values[1]; + ivs.defense = values[2]; + ivs.spatk = values[3]; + ivs.spdef = values[4]; + ivs.speed = values[5]; + return ivs; +} + +std::string ivs_to_string(const AdvIVs& ivs){ + return std::format("{}/{}/{}/{}/{}/{}", ivs.hp, ivs.attack, ivs.defense, ivs.spatk, ivs.spdef, ivs.speed); +} + +std::optional> parse_natures(const std::string& text){ + std::vector natures; + if (trim(text).empty()){ + return natures; + } + for (const std::string& name : split(text, ',')){ + const AdvNature nature = string_to_nature(name); + if (nature == AdvNature::Any){ + return std::nullopt; + } + natures.push_back(nature); + } + return natures; +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h new file mode 100644 index 0000000000..da7fe44525 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h @@ -0,0 +1,39 @@ +/* RNG Plan Inputs + * + * From: https://github.com/PokemonAutomation/ + * + * The TID, IVs and natures an RNG plan is typed in with, as text. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanInputs_H +#define PokemonAutomation_PokemonFRLG_RngPlanInputs_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A TID or SID typed as a number from 0 to 65535. Nothing for any other text. +std::optional parse_trainer_id(const std::string& text); + +// "HP/Atk/Def/SpA/SpD/Spe", as Ten Lines and the RNG programs list IVs. +// Nothing for text that isn't six numbers from 0 to 31. +std::optional parse_ivs(const std::string& text); +std::string ivs_to_string(const Pokemon::AdvIVs& ivs); + +// Natures separated by commas ("Modest, Timid"). Empty text is any nature +// (no entries). Nothing for a name that isn't a nature. +std::optional> parse_natures(const std::string& text); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp new file mode 100644 index 0000000000..6cf8e40bde --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp @@ -0,0 +1,137 @@ +/* RNG Plan Inputs Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanInputs.h" +#include "PokemonFRLG_RngPlanInputs_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +class Test_RngPlanInputs : public UnitTest{ +public: + Test_RngPlanInputs(std::string name, std::function body) + : UnitTest("PokemonFRLG::RngPlanInputs - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +UnitTestResult test_parse_trainer_id(Logger&){ + struct Case{ + std::string text; + std::string expected; + }; + const Case cases[] = { + {.text = "64694", .expected = "64694"}, + {.text = " 0 ", .expected = "0"}, + {.text = "65535", .expected = "65535"}, + {.text = "65536", .expected = "none"}, + {.text = "", .expected = "none"}, + {.text = "-1", .expected = "none"}, + {.text = "12a", .expected = "none"}, + }; + for (const Case& item : cases){ + const std::optional sid = parse_trainer_id(item.text); + const std::string got = sid ? std::to_string(*sid) : "none"; + if (got != item.expected){ + return std::format("SID \"{}\": expected {}, got {}.", item.text, item.expected, got); + } + } + return true; +} + +UnitTestResult test_parse_ivs(Logger&){ + struct Case{ + std::string text; + std::string expected; + }; + const Case cases[] = { + {.text = "31/14/7/29/1/27", .expected = "31/14/7/29/1/27"}, + {.text = " 0 / 0/0/0/0/31 ", .expected = "0/0/0/0/0/31"}, + {.text = "31/0/0", .expected = "none"}, + {.text = "32/0/0/0/0/0", .expected = "none"}, + {.text = "a/0/0/0/0/0", .expected = "none"}, + {.text = "-1/0/0/0/0/0", .expected = "none"}, + {.text = "", .expected = "none"}, + }; + for (const Case& item : cases){ + const std::optional ivs = parse_ivs(item.text); + const std::string got = ivs ? ivs_to_string(*ivs) : "none"; + if (got != item.expected){ + return std::format("IVs \"{}\": expected {}, got {}.", item.text, item.expected, got); + } + } + return true; +} + +UnitTestResult test_parse_natures(Logger&){ + struct Case{ + std::string text; + std::string expected; + }; + const Case cases[] = { + {.text = "", .expected = "any"}, + {.text = " ", .expected = "any"}, + {.text = "Modest", .expected = "Modest"}, + {.text = "Modest, Timid", .expected = "Modest Timid"}, + {.text = "Modset", .expected = "none"}, + {.text = "Modest,", .expected = "none"}, + }; + for (const Case& item : cases){ + const std::optional> natures = parse_natures(item.text); + std::string got; + if (!natures){ + got = "none"; + }else if (natures->empty()){ + got = "any"; + }else{ + for (AdvNature nature : *natures){ + got += (got.empty() ? "" : " ") + nature_to_string(nature); + } + } + if (got != item.expected){ + return std::format("Natures \"{}\": expected {}, got {}.", item.text, item.expected, got); + } + } + return true; +} + +} + + +void add_tests_RngPlanInputs(UnitTestDatabase& database){ + database.add("TID and SID text", test_parse_trainer_id); + database.add("IVs text", test_parse_ivs); + database.add("natures text", test_parse_natures); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h new file mode 100644 index 0000000000..5da86a73d4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h @@ -0,0 +1,23 @@ +/* RNG Plan Inputs Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanInputs_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlanInputs_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_RngPlanInputs(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp new file mode 100644 index 0000000000..a10f229e73 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp @@ -0,0 +1,137 @@ +/* RNG Plan Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h" +#include "PokemonFRLG_RngPlanLog.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text; +} + +} + +std::string rng_log_tid(uint16_t tid, bool from_card){ + return std::format("RngPlan: tid={} source={}", tid, from_card ? "card" : "option"); +} + +std::string rng_log_sid_helper(uint16_t tid, uint32_t target_advances, const std::vector& candidates){ + std::vector sids; + for (const SidCandidate& candidate : candidates){ + sids.push_back(candidate.sid); + } + return std::format("RngPlan: sid_helper tid={} target_advances={} candidates={}", tid, target_advances, join_sids(sids)); +} + +std::string rng_log_attempt(size_t index, const RngAttempt& attempt){ + return std::format( + "RngPlan: attempt={} seed={:04X} advances={} sids={} seed_wait_ms={} ingame_ms={}", + index + 1, attempt.target.seed.seed, attempt.target.advances, join_sids(attempt.sids), + starter_rng_seed_wait_ms(attempt.target.seed), starter_rng_ingame_ms(attempt.target.advances) + ); +} + +namespace{ + +const char* outcome_name(RngAttemptOutcome outcome){ + switch (outcome){ + case RngAttemptOutcome::SHINY: + return "shiny"; + case RngAttemptOutcome::SHINY_OFF_TARGET: + return "shiny_off_target"; + case RngAttemptOutcome::HIT_NOT_SHINY: + return "hit_not_shiny"; + case RngAttemptOutcome::MISSED: + return "missed"; + case RngAttemptOutcome::UNUSABLE: + return "unusable"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngAttemptOutcome."); +} + +const char* next_name(RngPlanNext next){ + switch (next){ + case RngPlanNext::RETRY: + return "retry"; + case RngPlanNext::NEXT_ATTEMPT: + return "next_attempt"; + case RngPlanNext::CONFIRM: + return "confirm"; + case RngPlanNext::STOP: + return "stop"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanNext."); +} + +} + +std::string rng_log_result(const RngResultLog& result){ + const std::optional& pokemon = result.pokemon; + return std::format( + "RngPlan: result attempt={} try={} outcome={} starter_rng={} nature={} ivs={} pid={} next={}", + result.index + 1, result.try_number, outcome_name(result.outcome), + result.detail.empty() ? "-" : result.detail, + pokemon ? nature_to_string(pokemon->nature) : "-", + pokemon ? ivs_to_string(pokemon->ivs) : "-", + pokemon ? std::format("{:08X}", pokemon->pid) : "-", + next_name(result.next) + ); +} + +std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates){ + size_t k = 0; + for (size_t c = 0; c < sid_helper_candidates.size(); c++){ + if (sid_helper_candidates[c].sid == sid){ + k = c + 1; + break; + } + } + return std::format("RngPlan: confirmed tid={} sid={} candidate={} of={}", tid, sid, k, sid_helper_candidates.size()); +} + + +std::vector rng_attempt_lines(const std::vector& attempts){ + std::vector lines; + for (size_t c = 0; c < attempts.size(); c++){ + const RngTarget& target = attempts[c].target; + std::string shiny; + if (attempts[c].sids.empty()){ + shiny = "not shiny for any SID candidate"; + }else{ + shiny = "shiny for SID"; + for (size_t s = 0; s < attempts[c].sids.size(); s++){ + shiny += (s == 0 ? " " : ", ") + std::to_string(attempts[c].sids[s]); + } + shiny += std::format(" ({:.0f}% of the candidates left)", target.shiny_probability * 100); + } + lines.push_back(std::format( + "Attempt {}: Target Seed {:04X}, Advances {}: {}, IVs {}, PID {:08X}, {}.", + c + 1, target.seed.seed, target.advances, + nature_to_string(target.pokemon.nature), ivs_to_string(target.pokemon.ivs), target.pokemon.pid, + shiny + )); + } + return lines; +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h new file mode 100644 index 0000000000..f46954234b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h @@ -0,0 +1,77 @@ +/* RNG Plan Log + * + * From: https://github.com/PokemonAutomation/ + * + * The lines an RNG plan logs and shows: its attempts, and the "RngPlan:" + * lines below. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanLog_H +#define PokemonAutomation_PokemonFRLG_RngPlanLog_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// One line per attempt, for the log and the stop message: the Target Seed +// and Advances to give Starter RNG, the Pokemon, and the SIDs it is shiny for. +std::vector rng_attempt_lines(const std::vector& attempts); + + +// The data to rebuild how likely SID Helper's k-th candidate of N is (the +// 1-2-3-2-1 weights of sid_helper_candidates() are a guess), from the logs +// alone, and to follow AutoStory's Starter RNG loop. Every line starts with +// "RngPlan:"; grep for it. In the order a run logs them: +// RngPlan: tid= source= +// RngPlan: sid_helper tid= target_advances= candidates=,... +// RngPlan: attempt= seed= advances= sids=,... +// seed_wait_ms= ingame_ms= (Starter RNG's waits, before calibration) +// then, with Run Starter RNG in AutoStory, for each try of an attempt +// (rng_log_state() in PokemonFRLG_StarterRngLoop.h): +// RngPlan: state attempt=/ try=/ reset=/ seed= +// advances= sids=,... ruled_out=,... attempt_time=/ +// total_time=/ calibration=// +// (once at the try's start, then after every reset) +// RngPlan: result attempt= try= outcome= +// starter_rng= nature= ivs= +// pid= next= +// RngPlan: confirmed tid= sid= candidate= of= +// Lists that are empty print "-". +// "candidates" are in SID Helper's order; "candidate=k" counts from 1 in +// it, 0 when the SID wasn't among them. Count each TID's "confirmed" once: +// every later run with the SID set logs it again. While the user runs +// Starter RNG by hand, its own "Target Hit!" and "Missed target." lines +// are the attempts' results. +std::string rng_log_tid(uint16_t tid, bool from_card); +std::string rng_log_sid_helper(uint16_t tid, uint32_t target_advances, const std::vector& candidates); +std::string rng_log_attempt(size_t index, const RngAttempt& attempt); + +struct RngResultLog{ + size_t index = 0; + // From 1. + size_t try_number = 1; + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + // How the RNG program put it ("out_of_resets"); empty for none. + std::string detail; + // The Pokemon hit, when known. + std::optional pokemon; + RngPlanNext next = RngPlanNext::STOP; +}; +std::string rng_log_result(const RngResultLog& result); +std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp new file mode 100644 index 0000000000..c69e725da9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp @@ -0,0 +1,109 @@ +/* RNG Plan Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanTestTargets.h" +#include "PokemonFRLG_RngPlanInputs.h" +#include "PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_RngPlanLog_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; +using namespace RngPlanTestTargets; + + +namespace{ + +class Test_RngPlanLog : public UnitTest{ +public: + Test_RngPlanLog(std::string name, std::function body) + : UnitTest("PokemonFRLG::RngPlanLog - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +// The "RngPlan:" lines the candidate odds are rebuilt from. +UnitTestResult test_log_lines(Logger&){ + RngAttempt attempt{make_target(1, 50, {0, 1}), {100, 200}}; + attempt.target.seed.seed = 0x2ef6; + attempt.target.advances = 29364; + struct Case{ + std::string got; + std::string expected; + }; + const Case cases[] = { + {.got = rng_log_tid(43771, true), .expected = "RngPlan: tid=43771 source=card"}, + {.got = rng_log_tid(43771, false), .expected = "RngPlan: tid=43771 source=option"}, + {.got = rng_log_sid_helper(43771, 3001, CANDIDATES), .expected = "RngPlan: sid_helper tid=43771 target_advances=3001 candidates=100,200,300"}, + {.got = rng_log_attempt(0, attempt), .expected = std::format( + "RngPlan: attempt=1 seed=2EF6 advances=29364 sids=100,200 seed_wait_ms=49155 ingame_ms={}", starter_rng_ingame_ms(29364) + )}, + { + .got = rng_log_result(RngResultLog{ + .index = 1, .try_number = 2, .outcome = RngAttemptOutcome::HIT_NOT_SHINY, .detail = "target_hit", + .pokemon = attempt.target.pokemon, .next = RngPlanNext::NEXT_ATTEMPT, + }), + .expected = std::format( + "RngPlan: result attempt=2 try=2 outcome=hit_not_shiny starter_rng=target_hit nature={} ivs={} pid={:08X} next=next_attempt", + nature_to_string(attempt.target.pokemon.nature), ivs_to_string(attempt.target.pokemon.ivs), attempt.target.pokemon.pid + ), + }, + { + .got = rng_log_result(RngResultLog{ + .index = 0, .try_number = 1, .outcome = RngAttemptOutcome::MISSED, .detail = "out_of_resets", + .pokemon = std::nullopt, .next = RngPlanNext::RETRY, + }), + .expected = "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + }, + { + .got = rng_log_result(RngResultLog{ + .index = 2, .try_number = 3, .outcome = RngAttemptOutcome::SHINY_OFF_TARGET, .detail = "shiny_off_target", + .pokemon = std::nullopt, .next = RngPlanNext::STOP, + }), + .expected = "RngPlan: result attempt=3 try=3 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop", + }, + {.got = rng_log_confirmed(43771, 300, CANDIDATES), .expected = "RngPlan: confirmed tid=43771 sid=300 candidate=3 of=3"}, + {.got = rng_log_confirmed(43771, 7, CANDIDATES), .expected = "RngPlan: confirmed tid=43771 sid=7 candidate=0 of=3"}, + }; + for (const Case& item : cases){ + if (item.got != item.expected){ + return "Expected \"" + item.expected + "\", got \"" + item.got + "\"."; + } + } + return true; +} + +} + + +void add_tests_RngPlanLog(UnitTestDatabase& database){ + database.add("RngPlan log lines", test_log_lines); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h new file mode 100644 index 0000000000..9f62eb0b0a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h @@ -0,0 +1,23 @@ +/* RNG Plan Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanLog_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlanLog_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_RngPlanLog(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp new file mode 100644 index 0000000000..5e5bc27838 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp @@ -0,0 +1,61 @@ +/* RNG Plan Test Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_RngPlanTestTargets.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace RngPlanTestTargets{ + + +std::string join(const std::vector& values){ + std::string text; + for (uint16_t value : values){ + text += (text.empty() ? "" : ",") + std::to_string(value); + } + return "{" + text + "}"; +} + + +// SIDs 100, 200 and 300 weigh 3, 2 and 1. +const std::vector CANDIDATES = {{100, 3}, {200, 2}, {300, 1}}; + +// A target reached "seconds" after the reset, shiny for the candidates at +// "shiny" (indices into CANDIDATES). +RngTarget make_target(uint32_t state, uint64_t seconds, std::vector shiny){ + RngTarget target{}; + target.state = state; + target.seed = {uint16_t(state), seconds * 1000, SeedButton::A, BlackoutButton::None}; + target.advances = 0; + target.pokemon = method1_pokemon(state); + for (size_t candidate : shiny){ + target.shiny_for.push_back({candidate, AdvShinyType::Star}); + } + return target; +} + +// By expected wait per shiny over all three (weight 6): 1 = 50 s / (5/6) = 60, +// 2 = 20 s / (1/6) = 120, 3 = 40 s / (3/6) = 80. Then over SID 300 alone, 2 is +// the only one shiny for it. 4 is the quickest and shiny for none. +const std::vector TARGETS = { + make_target(1, 50, {0, 1}), + make_target(2, 20, {2}), + make_target(3, 40, {0}), + make_target(4, 5, {}), +}; + + +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h new file mode 100644 index 0000000000..017d9cd6a8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h @@ -0,0 +1,46 @@ +/* RNG Plan Test Targets + * + * From: https://github.com/PokemonAutomation/ + * + * Made-up SID candidates and targets the RNG plan tests share. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanTestTargets_H +#define PokemonAutomation_PokemonFRLG_RngPlanTestTargets_H + +#include +#include +#include +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace RngPlanTestTargets{ + + +std::string join(const std::vector& values); + +// SIDs 100, 200 and 300 weigh 3, 2 and 1. +extern const std::vector CANDIDATES; + +// A target reached "seconds" after the reset, shiny for the candidates at +// "shiny" (indices into CANDIDATES). +RngTarget make_target(uint32_t state, uint64_t seconds, std::vector shiny); + +// By expected wait per shiny over all three (weight 6): 1 = 50 s / (5/6) = 60, +// 2 = 20 s / (1/6) = 120, 3 = 40 s / (3/6) = 80. Then over SID 300 alone, 2 is +// the only one shiny for it. 4 is the quickest and shiny for none. +extern const std::vector TARGETS; + + +} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp new file mode 100644 index 0000000000..230a25a433 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp @@ -0,0 +1,134 @@ +/* RNG Plan Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_RngPlanTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +RngAttemptOutcome classify_attempt(const RngTarget& target, const RngAttemptResult& result){ + const AdvIVs& want = target.pokemon.ivs; + const AdvIVs& got = result.ivs; + const bool same_ivs = want.hp == got.hp && want.attack == got.attack && want.defense == got.defense + && want.spatk == got.spatk && want.spdef == got.spdef && want.speed == got.speed; + const bool hit = result.nature == target.pokemon.nature && same_ivs; + if (result.shiny){ + return hit ? RngAttemptOutcome::SHINY : RngAttemptOutcome::SHINY_OFF_TARGET; + } + return hit ? RngAttemptOutcome::HIT_NOT_SHINY : RngAttemptOutcome::MISSED; +} + + +RngPlanTracker::RngPlanTracker( + std::vector attempts, + const std::vector& candidates, + bool shiny_required, + size_t max_retries +) + : m_attempts(std::move(attempts)) + , m_shiny_required(shiny_required) + , m_max_retries(max_retries) + , m_step(m_attempts.empty() ? RngPlanStep::OUT_OF_ATTEMPTS : RngPlanStep::RUN_ATTEMPT) +{ + for (const SidCandidate& candidate : candidates){ + m_remaining.push_back(candidate.sid); + } +} + +std::optional RngPlanTracker::confirmed_sid() const{ + if (m_step == RngPlanStep::GOT_SHINY && m_remaining.size() == 1){ + return m_remaining.front(); + } + return std::nullopt; +} + +bool RngPlanTracker::is_ruled_out(uint16_t sid) const{ + return std::find(m_remaining.begin(), m_remaining.end(), sid) == m_remaining.end(); +} + +bool RngPlanTracker::move_to_next_attempt(){ + for (size_t next = m_attempt + 1; next < m_attempts.size(); next++){ + const std::vector& next_sids = m_attempts[next].sids; + if (!m_shiny_required || !std::all_of(next_sids.begin(), next_sids.end(), [&](uint16_t sid){ return is_ruled_out(sid); })){ + m_attempt = next; + m_retries = 0; + return true; + } + } + return false; +} + +RngPlanStep RngPlanTracker::record(RngAttemptOutcome outcome){ + if (m_step != RngPlanStep::RUN_ATTEMPT){ + return m_step; + } + const std::vector& sids = m_attempts[m_attempt].sids; + switch (outcome){ + case RngAttemptOutcome::SHINY: + // The SID is one the target is shiny for. None of them: it wasn't + // among the candidates. + std::erase_if(m_remaining, [&](uint16_t sid){ return std::find(sids.begin(), sids.end(), sid) == sids.end(); }); + m_step = RngPlanStep::GOT_SHINY; + return m_step; + case RngAttemptOutcome::SHINY_OFF_TARGET: + m_step = RngPlanStep::GOT_SHINY_OFF_TARGET; + return m_step; + case RngAttemptOutcome::HIT_NOT_SHINY: + if (!m_shiny_required){ + m_step = RngPlanStep::GOT_TARGET; + return m_step; + } + m_remaining.erase( + std::remove_if(m_remaining.begin(), m_remaining.end(), [&](uint16_t sid){ + return std::find(sids.begin(), sids.end(), sid) != sids.end(); + }), + m_remaining.end() + ); + if (!move_to_next_attempt()){ + m_step = RngPlanStep::OUT_OF_ATTEMPTS; + } + return m_step; + case RngAttemptOutcome::MISSED: + // A miss rules nothing out. Too many: try the next attempt instead. + if (++m_retries <= m_max_retries){ + return m_step; + } + [[fallthrough]]; + case RngAttemptOutcome::UNUSABLE: + if (!move_to_next_attempt()){ + m_step = RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT; + } + return m_step; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngAttemptOutcome."); +} + + +RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return next_index == index ? RngPlanNext::RETRY : RngPlanNext::NEXT_ATTEMPT; + case RngPlanStep::GOT_SHINY: + return RngPlanNext::CONFIRM; + case RngPlanStep::GOT_SHINY_OFF_TARGET: + case RngPlanStep::GOT_TARGET: + case RngPlanStep::OUT_OF_ATTEMPTS: + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: + return RngPlanNext::STOP; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanStep."); +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h new file mode 100644 index 0000000000..3875f3bdbf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h @@ -0,0 +1,119 @@ +/* RNG Plan Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * The step after each attempt of an RNG plan (PokemonFRLG_RngPlan.h), + * from what came out of it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanTracker_H +#define PokemonAutomation_PokemonFRLG_RngPlanTracker_H + +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What came out of one attempt. +enum class RngAttemptOutcome{ + // Shiny, with the target's nature and IVs. + SHINY, + // Shiny, but not the target, or not known to be. + SHINY_OFF_TARGET, + // The target's nature and IVs, not shiny. + HIT_NOT_SHINY, + // Another nature or other IVs: not the target. + MISSED, + // The attempt couldn't run (Starter RNG refused its timings). It rules + // nothing out; the next attempt runs instead. + UNUSABLE, +}; + +struct RngAttemptResult{ + bool shiny; + Pokemon::AdvNature nature; + Pokemon::AdvIVs ivs; +}; +RngAttemptOutcome classify_attempt(const RngTarget& target, const RngAttemptResult& result); + + +enum class RngPlanStep{ + // Run current_attempt(): the first, the next, or the same again after a miss. + RUN_ATTEMPT, + // Shiny, the target hit. remaining_sids() are the SIDs it can be. + GOT_SHINY, + // Shiny, not the target: the SIDs are as they were, none confirmed. + GOT_SHINY_OFF_TARGET, + // Shiny not required, and the target was hit. + GOT_TARGET, + // Every attempt was hit and none was shiny. + OUT_OF_ATTEMPTS, + // The last attempt still shiny for a SID left was missed more often + // than the retries allow, or couldn't run. (Missing an earlier one moves + // on to the next.) + MISSED_EVERY_ATTEMPT_LEFT, +}; + +// Follows the plan through the attempts' outcomes. +class RngPlanTracker{ +public: + RngPlanTracker( + std::vector attempts, + const std::vector& candidates, + bool shiny_required, + size_t max_retries + ); + + RngPlanStep step() const{ return m_step; } + size_t attempt_index() const{ return m_attempt; } + size_t attempt_count() const{ return m_attempts.size(); } + const RngAttempt& current_attempt() const{ return m_attempts[m_attempt]; } + // The SID candidates not ruled out, in the order given. + const std::vector& remaining_sids() const{ return m_remaining; } + // The SID, once a shiny leaves one candidate. + std::optional confirmed_sid() const; + + // The next step after the current attempt came out as "outcome". Once + // the plan has ended, the step stays as it is. + RngPlanStep record(RngAttemptOutcome outcome); + +private: + bool is_ruled_out(uint16_t sid) const; + // Moves to the next attempt still shiny for a SID left (with shiny + // required; else any next one). False if there is none. + bool move_to_next_attempt(); + + std::vector m_attempts; + bool m_shiny_required; + size_t m_max_retries; + std::vector m_remaining; + size_t m_attempt = 0; + size_t m_retries = 0; + RngPlanStep m_step; +}; + + +// What the loop does after an attempt's result. +enum class RngPlanNext{ + RETRY, + NEXT_ATTEMPT, + // Shiny and the target: go on with the story. + CONFIRM, + STOP, +}; +// The step after `index` came out as the tracker's `step` and its attempt +// is now `next_index`. +RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp new file mode 100644 index 0000000000..cd4ed2b5ce --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp @@ -0,0 +1,262 @@ +/* RNG Plan Tracker Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The outcome of an attempt, and the step after each, on made-up targets. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanTestTargets.h" +#include "PokemonFRLG_RngPlanTracker.h" +#include "PokemonFRLG_RngPlanTracker_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; +using namespace RngPlanTestTargets; + + +namespace{ + +class Test_RngPlanTracker : public UnitTest{ +public: + Test_RngPlanTracker(std::string name, std::function body) + : UnitTest("PokemonFRLG::RngPlanTracker - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +UnitTestResult test_classify(Logger&){ + const RngTarget hit = TARGETS[0]; + AdvIVs other_ivs = hit.pokemon.ivs; + other_ivs.speed = uint8_t((other_ivs.speed + 1) % 32); + const AdvNature other_nature = hit.pokemon.nature == AdvNature::Hardy ? AdvNature::Lonely : AdvNature::Hardy; + + struct Case{ + std::string name; + RngAttemptResult result; + RngAttemptOutcome expected; + }; + const Case cases[] = { + {.name = "shiny, the target", .result = {.shiny = true, .nature = hit.pokemon.nature, .ivs = hit.pokemon.ivs}, .expected = RngAttemptOutcome::SHINY}, + {.name = "shiny, not the target", .result = {.shiny = true, .nature = other_nature, .ivs = other_ivs}, .expected = RngAttemptOutcome::SHINY_OFF_TARGET}, + {.name = "same nature and IVs", .result = {.shiny = false, .nature = hit.pokemon.nature, .ivs = hit.pokemon.ivs}, .expected = RngAttemptOutcome::HIT_NOT_SHINY}, + {.name = "other IVs", .result = {.shiny = false, .nature = hit.pokemon.nature, .ivs = other_ivs}, .expected = RngAttemptOutcome::MISSED}, + {.name = "other nature", .result = {.shiny = false, .nature = other_nature, .ivs = hit.pokemon.ivs}, .expected = RngAttemptOutcome::MISSED}, + }; + for (const Case& item : cases){ + if (classify_attempt(hit, item.result) != item.expected){ + return item.name + ": classified wrong."; + } + } + return true; +} + + +const char* step_name(RngPlanStep step){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: return "RUN_ATTEMPT"; + case RngPlanStep::GOT_SHINY: return "GOT_SHINY"; + case RngPlanStep::GOT_SHINY_OFF_TARGET: return "GOT_SHINY_OFF_TARGET"; + case RngPlanStep::GOT_TARGET: return "GOT_TARGET"; + case RngPlanStep::OUT_OF_ATTEMPTS: return "OUT_OF_ATTEMPTS"; + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: return "MISSED_EVERY_ATTEMPT_LEFT"; + } + return "?"; +} + +struct TrackerCase{ + std::string name; + bool shiny_required; + std::vector outcomes; + // The step after each outcome, and the attempt run next. + std::vector steps; + std::vector attempts; + std::vector remaining; + std::optional confirmed; +}; +std::vector tracker_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "shiny at once: one of two SIDs", + .shiny_required = true, .outcomes = {SHINY}, + .steps = {GOT_SHINY}, .attempts = {0}, + .remaining = {100, 200}, .confirmed = std::nullopt, + }, + { + .name = "hit, then shiny: SID confirmed", + .shiny_required = true, .outcomes = {HIT_NOT_SHINY, SHINY}, + .steps = {RUN_ATTEMPT, GOT_SHINY}, .attempts = {1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "a miss retries the same target", + .shiny_required = true, .outcomes = {MISSED, MISSED, HIT_NOT_SHINY, MISSED}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT}, .attempts = {0, 0, 1, 1}, + .remaining = {300}, .confirmed = std::nullopt, + }, + }; +} +// Misses: retried, then the next attempt, mixed with hits and shinies. +std::vector tracker_retry_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "retries used up, then the next attempt", + .shiny_required = true, .outcomes = {MISSED, MISSED, MISSED, SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, GOT_SHINY}, .attempts = {0, 0, 1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "every attempt left missed too often", + .shiny_required = true, .outcomes = {MISSED, MISSED, MISSED, MISSED, MISSED, MISSED}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, MISSED_EVERY_ATTEMPT_LEFT}, + .attempts = {0, 0, 1, 1, 1, 1}, + .remaining = {100, 200, 300}, .confirmed = std::nullopt, + }, + { + .name = "shiny off the target confirms nothing", + .shiny_required = true, .outcomes = {HIT_NOT_SHINY, SHINY_OFF_TARGET, SHINY}, + .steps = {RUN_ATTEMPT, GOT_SHINY_OFF_TARGET, GOT_SHINY_OFF_TARGET}, .attempts = {1, 1, 1}, + .remaining = {300}, .confirmed = std::nullopt, + }, + }; +} +// Attempts that can't run. +std::vector tracker_unusable_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "an attempt that can't run moves on", + .shiny_required = true, .outcomes = {MISSED, UNUSABLE, SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, GOT_SHINY}, .attempts = {0, 1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "the last attempt can't run", + .shiny_required = true, .outcomes = {UNUSABLE, UNUSABLE}, + .steps = {RUN_ATTEMPT, MISSED_EVERY_ATTEMPT_LEFT}, .attempts = {1, 1}, + .remaining = {100, 200, 300}, .confirmed = std::nullopt, + }, + }; +} +std::vector tracker_mixed_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "miss, hit, misses, then shiny", + .shiny_required = true, .outcomes = {MISSED, HIT_NOT_SHINY, MISSED, MISSED, SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, GOT_SHINY}, .attempts = {0, 1, 1, 1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "misses move on, then a hit ends the plan", + .shiny_required = true, .outcomes = {MISSED, MISSED, MISSED, MISSED, HIT_NOT_SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, OUT_OF_ATTEMPTS}, .attempts = {0, 0, 1, 1, 1}, + .remaining = {100, 200}, .confirmed = std::nullopt, + }, + { + .name = "every attempt hit, none shiny", + .shiny_required = true, .outcomes = {HIT_NOT_SHINY, HIT_NOT_SHINY}, + .steps = {RUN_ATTEMPT, OUT_OF_ATTEMPTS}, .attempts = {1, 1}, + .remaining = {}, .confirmed = std::nullopt, + }, + { + .name = "shiny not required: a hit ends it", + .shiny_required = false, .outcomes = {HIT_NOT_SHINY}, + .steps = {GOT_TARGET}, .attempts = {0}, + .remaining = {100, 200, 300}, .confirmed = std::nullopt, + }, + }; +} + +UnitTestResult check_tracker_case(const TrackerCase& item){ + RngPlanTracker tracker(plan_rng_attempts(TARGETS, CANDIDATES, true, 5), CANDIDATES, item.shiny_required, 2); + if (tracker.step() != RngPlanStep::RUN_ATTEMPT){ + return item.name + ": expected to start with RUN_ATTEMPT, got " + step_name(tracker.step()) + "."; + } + for (size_t c = 0; c < item.outcomes.size(); c++){ + const RngPlanStep step = tracker.record(item.outcomes[c]); + if (step != item.steps[c] || tracker.attempt_index() != item.attempts[c]){ + return std::format( + "{}: after outcome {}, expected {} at attempt {}, got {} at attempt {}.", + item.name, c, step_name(item.steps[c]), item.attempts[c], step_name(step), tracker.attempt_index() + ); + } + } + if (tracker.remaining_sids() != item.remaining || tracker.confirmed_sid() != item.confirmed){ + return std::format( + "{}: expected SIDs {} (confirmed {}), got {} (confirmed {}).", + item.name, join(item.remaining), item.confirmed ? std::to_string(*item.confirmed) : "none", + join(tracker.remaining_sids()), tracker.confirmed_sid() ? std::to_string(*tracker.confirmed_sid()) : "none" + ); + } + return true; +} + +UnitTestResult test_tracker(Logger&){ + std::vector cases = tracker_cases(); + for (auto* more : {tracker_retry_cases, tracker_unusable_cases, tracker_mixed_cases}){ + for (TrackerCase& item : more()){ + cases.push_back(std::move(item)); + } + } + for (const TrackerCase& item : cases){ + const UnitTestResult result = check_tracker_case(item); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + RngPlanTracker empty({}, CANDIDATES, true, 2); + if (empty.step() != RngPlanStep::OUT_OF_ATTEMPTS){ + return std::string("An empty plan: expected OUT_OF_ATTEMPTS, got ") + step_name(empty.step()) + "."; + } + // A shiny hit for a SID that is no candidate: none left, none confirmed. + RngPlanTracker outside({RngAttempt{make_target(1, 50, {}), {999}}}, CANDIDATES, true, 2); + outside.record(RngAttemptOutcome::SHINY); + if (outside.step() != RngPlanStep::GOT_SHINY || !outside.remaining_sids().empty() || outside.confirmed_sid()){ + return std::format( + "Shiny for no candidate: expected GOT_SHINY with no SID left, got {} with SIDs {}.", + step_name(outside.step()), join(outside.remaining_sids()) + ); + } + return true; +} + +} + + +void add_tests_RngPlanTracker(UnitTestDatabase& database){ + database.add("attempt outcome", test_classify); + database.add("step after each outcome", test_tracker); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h new file mode 100644 index 0000000000..725491c896 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h @@ -0,0 +1,23 @@ +/* RNG Plan Tracker Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanTracker_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlanTracker_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_RngPlanTracker(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp new file mode 100644 index 0000000000..508ba5fa34 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp @@ -0,0 +1,287 @@ +/* RNG Plan Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The attempt order on made-up targets; SID Helper's candidates and a + * Starter RNG plan from the FireRed seed list. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanTestTargets.h" +#include "PokemonFRLG_RngPlan.h" +#include "PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_RngPlan_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; +using namespace RngPlanTestTargets; + + +namespace{ + +class Test_RngPlan : public UnitTest{ +public: + Test_RngPlan(std::string name, std::function body) + : UnitTest("PokemonFRLG::RngPlan - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +UnitTestResult test_sid_helper_candidates(Logger&){ + const uint16_t tid = 43771; + const uint32_t target_advances = 3001; + const std::vector candidates = sid_helper_candidates(tid, target_advances, 5); + + // The SID is the top half of the state after the TID seed is advanced + // once, then "advances" more times. + auto sid_at = [&](uint32_t advances){ + uint32_t state = tid; + for (uint32_t c = 0; c <= advances; c++){ + state = lcrng_next(state); + } + return uint16_t(state >> 16); + }; + const std::vector advances = {2997, 2999, 3001, 3003, 3005}; + const std::vector weights = {1, 2, 3, 2, 1}; + if (candidates.size() != advances.size()){ + return std::format("Expected {} candidates, got {}.", advances.size(), candidates.size()); + } + for (size_t c = 0; c < candidates.size(); c++){ + if (candidates[c].sid != sid_at(advances[c]) || candidates[c].weight != weights[c]){ + return std::format( + "Candidate {}: expected SID {} weight {}, got SID {} weight {}.", + c, sid_at(advances[c]), weights[c], candidates[c].sid, candidates[c].weight + ); + } + } + + const std::vector even = sid_helper_candidates(tid, target_advances, 4); + const std::vector even_weights = {1, 2, 3, 2}; + for (size_t c = 0; c < even.size() && c < even_weights.size(); c++){ + if (even.size() != even_weights.size() || even[c].sid != candidates[c].sid || even[c].weight != even_weights[c]){ + return std::format("Four candidates: expected the first four of five, weighing 1, 2, 3, 2; candidate {} differs.", c); + } + } + return true; +} + + +struct PlanCase{ + std::string name; + std::vector targets; + bool shiny_required; + size_t max_attempts; + std::vector states; + std::vector> sids; +}; +std::vector plan_cases(){ + const std::vector no_300 = {TARGETS[0], TARGETS[2], TARGETS[3]}; + return { + { + .name = "two candidates in one target first, then the last", + .targets = TARGETS, .shiny_required = true, .max_attempts = 5, + .states = {1, 2}, .sids = {{100, 200}, {300}}, + }, + { + .name = "capped at one attempt", + .targets = TARGETS, .shiny_required = true, .max_attempts = 1, + .states = {1}, .sids = {{100, 200}}, + }, + { + .name = "no target shiny for SID 300", + .targets = no_300, .shiny_required = true, .max_attempts = 5, + .states = {1}, .sids = {{100, 200}}, + }, + { + .name = "shiny not required: the quickest", + .targets = TARGETS, .shiny_required = false, .max_attempts = 5, + .states = {4}, .sids = {{}}, + }, + { + .name = "no targets", + .targets = {}, .shiny_required = true, .max_attempts = 5, + .states = {}, .sids = {}, + }, + }; +} + +UnitTestResult test_plan_order(Logger&){ + for (const PlanCase& item : plan_cases()){ + const std::vector attempts = plan_rng_attempts(item.targets, CANDIDATES, item.shiny_required, item.max_attempts); + std::vector states; + std::vector> sids; + for (const RngAttempt& attempt : attempts){ + states.push_back(attempt.target.state); + sids.push_back(attempt.sids); + } + if (states != item.states || sids != item.sids){ + std::string got; + for (size_t c = 0; c < attempts.size(); c++){ + got += std::format(" target {} {}", states[c], join(sids[c])); + } + return item.name + ": got" + (got.empty() ? " no attempts" : got) + "."; + } + } + return true; +} + + +// A plan from the FireRed (English) list: every attempt starts from a seed +// Starter RNG finds, takes at least its smallest Advances, and is shiny for +// the SIDs it lists, which no earlier attempt listed. +// Console B, 2026-11-02, FireRed English, Mono, Help: Starter RNG refused +// both of these as title screen waits under 30 s. AutoStory's plan for TID +// 55740 started with 11A3 at 945 advances (29,628 ms after Starter RNG's +// offsets); StarterRng by hand with 405C at 990 advances listed 30,488 ms +// from the table, 29,643 ms after them. Neither seed may start an attempt. +UnitTestResult test_starter_plan_seed_delay(Logger&){ + struct Case{ + uint16_t seed; + uint64_t table_ms; + }; + const Case cases[] = { + {.seed = 0x11a3, .table_ms = 30473}, + {.seed = 0x405c, .table_ms = 30488}, + }; + const SeedsDatabase database(seeds_json_path(true, Language::English)); + const std::vector seeds = initial_seed_entries(database, SoundSetting::Mono, "Help", true); + for (const Case& item : cases){ + auto entry = std::find_if(seeds.begin(), seeds.end(), [&](const InitialSeedEntry& seed){ return seed.seed == item.seed; }); + if (entry == seeds.end() || entry->seed_time_ms != item.table_ms){ + return std::format("Expected seed {:04X} at {} ms in the FireRed English list (Mono, Help).", item.seed, item.table_ms); + } + if (starter_rng_can_wait_for(*entry)){ + return std::format("Seed {:04X} ({} ms): expected too early for Starter RNG's title screen.", item.seed, item.table_ms); + } + } + + const uint16_t tid = 55740; + const std::vector attempts = plan_starter_rng(StarterRngPlanInputs{ + .firered = true, + .language = Language::English, + .sound = SoundSetting::Mono, + .tid = tid, + .candidates = sid_helper_candidates(tid, 3001, 5), + .filters = {}, + .max_attempts = 5, + }); + if (attempts.empty()){ + return "Expected attempts for TID 55740, got none."; + } + for (size_t c = 0; c < attempts.size(); c++){ + const InitialSeedEntry& seed = attempts[c].target.seed; + if (seed.seed == 0x11a3 || seed.seed == 0x405c || starter_rng_seed_wait_ms(seed) < 31500){ + return std::format("Attempt {}: seed {:04X} at {} ms is too early for the title screen.", c + 1, seed.seed, seed.seed_time_ms); + } + if (attempts[c].target.advances < 1660){ + return std::format("Attempt {}: {} advances leave no room for the in-game calibration.", c + 1, attempts[c].target.advances); + } + } + return true; +} + +// Starter RNG's in-game wait: 7,500 ms at its 940-advance minimum; console +// B's B579 target at 967 advances was 7,725 ms, which one miss's +// calibration (-720) cut under the minimum. Targets start 720 advances on. +UnitTestResult test_starter_ingame_wait(Logger&){ + struct Case{ + uint64_t advances; + int64_t ms; + }; + const Case cases[] = { + {.advances = 940, .ms = 7500}, + {.advances = 967, .ms = 7725}, + {.advances = 1660, .ms = 13500}, + }; + for (const Case& item : cases){ + if (starter_rng_ingame_ms(item.advances) != item.ms){ + return std::format("{} advances: expected {} ms in game, got {}.", item.advances, item.ms, starter_rng_ingame_ms(item.advances)); + } + } + if (STARTER_RNG_PLAN_MIN_ADVANCES != 1660){ + return std::format("Expected the plan's minimum at 1660 advances, got {}.", STARTER_RNG_PLAN_MIN_ADVANCES); + } + return true; +} + +UnitTestResult test_starter_plan(Logger&){ + const uint16_t tid = 43771; + StarterRngPlanInputs inputs{ + .firered = true, + .language = Language::English, + .sound = SoundSetting::Mono, + .tid = tid, + .candidates = sid_helper_candidates(tid, 3001, 5), + .filters = {}, + .max_attempts = 5, + }; + const std::vector attempts = plan_starter_rng(inputs); + if (attempts.empty()){ + return "Expected attempts for TID 43771 with five SID candidates, got none."; + } + + const SeedsDatabase database(seeds_json_path(true, Language::English)); + std::vector listed; + for (size_t c = 0; c < attempts.size(); c++){ + const RngAttempt& attempt = attempts[c]; + if (!database.find_seed(attempt.target.seed.seed, SoundSetting::Mono, 5).found){ + return std::format("Attempt {}: Starter RNG can't find Target Seed {:04X}.", c + 1, attempt.target.seed.seed); + } + if (attempt.target.advances < STARTER_RNG_PLAN_MIN_ADVANCES){ + return std::format("Attempt {}: Advances {} below the plan's {}.", c + 1, attempt.target.advances, STARTER_RNG_PLAN_MIN_ADVANCES); + } + if (attempt.sids.empty()){ + return std::format("Attempt {}: shiny for no SID candidate.", c + 1); + } + for (uint16_t sid : attempt.sids){ + if (shiny_type(attempt.target.pokemon.pid, tid, sid) == AdvShinyType::Normal){ + return std::format("Attempt {}: PID {:08X} not shiny for SID {}.", c + 1, attempt.target.pokemon.pid, sid); + } + if (std::find(listed.begin(), listed.end(), sid) != listed.end()){ + return std::format("Attempt {}: SID {} already listed by an earlier attempt.", c + 1, sid); + } + listed.push_back(sid); + } + } + if (rng_attempt_lines(attempts).size() != attempts.size()){ + return "Expected one line per attempt."; + } + return true; +} + +} + + +void add_tests_RngPlan(UnitTestDatabase& database){ + database.add("SID Helper's candidates and weights", test_sid_helper_candidates); + database.add("attempt order", test_plan_order); + database.add("Starter RNG plan from the FireRed list", test_starter_plan); + database.add("Starter RNG plan: no seed too early for the title screen", test_starter_plan_seed_delay); + database.add("Starter RNG plan: room for the in-game calibration", test_starter_ingame_wait); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h new file mode 100644 index 0000000000..80d2408130 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h @@ -0,0 +1,23 @@ +/* RNG Plan Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlan_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlan_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_RngPlan(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp new file mode 100644 index 0000000000..32b1d9d90f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp @@ -0,0 +1,283 @@ +/* RNG Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * SID Helper's intro timing per language, and Starter RNG's per-starter + * tables, as SID Helper and Starter RNG computed them before the steps + * moved out of the programs; and whether a shiny was the target. + * + */ + +#include +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "PokemonFRLG_SidSteps.h" +#include "PokemonFRLG_StarterRngAttempts.h" +#include "PokemonFRLG_RngSteps_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +struct SidTimingRow{ + Language language; + uint32_t target_advances; + uint64_t delay_ms; + bool extra_press_at_end; +}; + +// (target_advances - 2 * final text frames + 7) frames of 1000 / 59.999977 ms, +// halved since advances pass 2 by 2. +const std::vector SID_TIMING_ROWS = { + {.language = Language::English, .target_advances = 3001, .delay_ms = 20916, .extra_press_at_end = false}, + {.language = Language::English, .target_advances = 2275, .delay_ms = 14866, .extra_press_at_end = false}, + {.language = Language::Japanese, .target_advances = 3001, .delay_ms = 21833, .extra_press_at_end = true}, + {.language = Language::Italian, .target_advances = 3001, .delay_ms = 21133, .extra_press_at_end = false}, + {.language = Language::French, .target_advances = 3001, .delay_ms = 21650, .extra_press_at_end = true}, + {.language = Language::German, .target_advances = 3001, .delay_ms = 21600, .extra_press_at_end = true}, + {.language = Language::Spanish, .target_advances = 2275, .delay_ms = 15650, .extra_press_at_end = true}, +}; + +class Test_SidTiming : public UnitTest{ +public: + explicit Test_SidTiming(const SidTimingRow& row) + : UnitTest(std::format( + "PokemonFRLG::RngSteps - SID timing {} {}", + language_data(row.language).name, row.target_advances + )) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + SidTiming timing = sid_timing(m_row.language, m_row.target_advances); + if (timing.delay_ms != m_row.delay_ms || timing.extra_press_at_end != m_row.extra_press_at_end){ + return std::format( + "Expected delay {} ms, extra press {}; got {} ms, extra press {}", + m_row.delay_ms, m_row.extra_press_at_end, + timing.delay_ms, timing.extra_press_at_end + ); + } + return true; + } + +private: + SidTimingRow m_row; +}; + + +struct StarterRow{ + StarterSpecies starter; + std::string name; + BaseStats base_stats; + EVs rival_ev_yield; + int steps_left; +}; + +const std::vector STARTER_ROWS = { + { + .starter = StarterSpecies::bulbasaur, + .name = "Bulbasaur", + .base_stats = {45, 49, 49, 65, 65, 45}, + .rival_ev_yield = {0, 0, 0, 0, 0, 1}, + .steps_left = 2, + }, + { + .starter = StarterSpecies::squirtle, + .name = "Squirtle", + .base_stats = {44, 48, 65, 50, 64, 43}, + .rival_ev_yield = {0, 0, 0, 1, 0, 0}, + .steps_left = 3, + }, + { + .starter = StarterSpecies::charmander, + .name = "Charmander", + .base_stats = {39, 52, 43, 60, 50, 65}, + .rival_ev_yield = {0, 0, 1, 0, 0, 0}, + .steps_left = 4, + }, +}; + +std::string to_string(const BaseStats& stats){ + return std::format("{}/{}/{}/{}/{}/{}", stats.hp, stats.attack, stats.defense, stats.spatk, stats.spdef, stats.speed); +} +std::string to_string(const EVs& evs){ + return std::format("{}/{}/{}/{}/{}/{}", evs.hp, evs.attack, evs.defense, evs.spatk, evs.spdef, evs.speed); +} + +class Test_StarterTables : public UnitTest{ +public: + explicit Test_StarterTables(const StarterRow& row) + : UnitTest("PokemonFRLG::RngSteps - Starter tables " + row.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::string expected = std::format( + "base stats {}, rival EVs {}, steps left {}", + to_string(m_row.base_stats), to_string(m_row.rival_ev_yield), m_row.steps_left + ); + std::string got = std::format( + "base stats {}, rival EVs {}, steps left {}", + to_string(starter_base_stats(m_row.starter)), + to_string(rival_ev_yield(m_row.starter)), + steps_left_to_lab_door(m_row.starter) + ); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + return true; + } + +private: + StarterRow m_row; +}; + + + +// Target: seed 0x70FE, advance 1000. +struct ShinyRow{ + std::string name; + // The (seed, advance) of each state the shiny's stats match. + std::vector> hits; + StarterRngOutcome expected; +}; + +const std::vector SHINY_ROWS = { + {.name = "the target alone", .hits = {{0x70fe, 1000}}, .expected = StarterRngOutcome::shiny_on_target}, + {.name = "the target among others", .hits = {{0x70fe, 998}, {0x70fe, 1000}, {0x70ff, 1000}}, .expected = StarterRngOutcome::shiny_on_target}, + {.name = "another advance", .hits = {{0x70fe, 1002}}, .expected = StarterRngOutcome::shiny_off_target}, + {.name = "another seed", .hits = {{0x70fd, 1000}}, .expected = StarterRngOutcome::shiny_off_target}, + {.name = "no match", .hits = {}, .expected = StarterRngOutcome::shiny}, +}; + +const char* outcome_name(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: return "shiny"; + case StarterRngOutcome::shiny_on_target: return "shiny_on_target"; + case StarterRngOutcome::shiny_off_target: return "shiny_off_target"; + case StarterRngOutcome::target_hit: return "target_hit"; + case StarterRngOutcome::wild_shiny: return "wild_shiny"; + case StarterRngOutcome::out_of_resets: return "out_of_resets"; + case StarterRngOutcome::no_matches: return "no_matches"; + } + return "?"; +} + +class Test_IdentifyShiny : public UnitTest{ +public: + explicit Test_IdentifyShiny(const ShinyRow& row) + : UnitTest("PokemonFRLG::RngSteps - Shiny " + row.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::vector hits; + for (const auto& [seed, advance] : m_row.hits){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + hits.push_back(hit); + } + const StarterRngOutcome got = identify_shiny(0x70fe, 1000, hits); + if (got != m_row.expected){ + return std::string("Expected ") + outcome_name(m_row.expected) + ", got " + outcome_name(got); + } + return true; + } + +private: + ShinyRow m_row; +}; + + +AdvRngState state(uint16_t seed, uint64_t advance){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + return hit; +} + +// A state's (seed, advance). +using SeedAdvance = std::pair; + +std::string state_text(const std::optional& state){ + return state ? std::format("{:04x}/{}", state->first, state->second) : "none"; +} + +struct ResetHitRow{ + std::string name; + // The reset's hits, and what update_history() left after it. + std::vector hits; + size_t uncertain = 0; + std::vector calibrated; + // The (seed, advance) taken as hit, if any. + std::optional expected; +}; + +const std::vector RESET_HIT_ROWS = { + {.name = "one hit", .hits = {state(0x70fe, 1001)}, .uncertain = 0, .calibrated = {state(0x70fe, 1001)}, .expected = SeedAdvance{0x70fe, 1001}}, + { + .name = "settled by the history", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 0, + .calibrated = {state(0x70fd, 1004), state(0x70ff, 1003)}, .expected = SeedAdvance{0x70ff, 1003}, + }, + {.name = "a tie", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 2, .calibrated = {state(0x70fd, 1004)}, .expected = std::nullopt}, + {.name = "no hits", .hits = {}, .uncertain = 0, .calibrated = {state(0x70fd, 1004)}, .expected = std::nullopt}, +}; + +class Test_ResetHit : public UnitTest{ +public: + explicit Test_ResetHit(const ResetHitRow& row) + : UnitTest("PokemonFRLG::RngSteps - Reset hit " + row.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + RngUncertainHistory uncertain; + uncertain.results.resize(m_row.uncertain); + RngCalibrationHistory calibration; + calibration.results = m_row.calibrated; + const std::optional hit = reset_hit(uncertain, calibration, m_row.hits); + std::optional got; + if (hit){ + got = SeedAdvance{hit->seed, hit->advance}; + } + if (got != m_row.expected){ + return "Expected " + state_text(m_row.expected) + ", got " + state_text(got); + } + return true; + } + +private: + ResetHitRow m_row; +}; + +} + + +void add_tests_RngSteps(UnitTestDatabase& database){ + for (const SidTimingRow& row : SID_TIMING_ROWS){ + database.add(row); + } + for (const StarterRow& row : STARTER_ROWS){ + database.add(row); + } + for (const ShinyRow& row : SHINY_ROWS){ + database.add(row); + } + for (const ResetHitRow& row : RESET_HIT_ROWS){ + database.add(row); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h new file mode 100644 index 0000000000..a5bca3130c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h @@ -0,0 +1,24 @@ +/* RNG Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngSteps_Tests_H +#define PokemonAutomation_PokemonFRLG_RngSteps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The pure parts of the SID steps and Starter RNG attempts. +void add_tests_RngSteps(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp new file mode 100644 index 0000000000..699e4c051e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp @@ -0,0 +1,417 @@ +/* RNG Target Search + * + * From: https://github.com/PokemonAutomation/ + * + * Ten Lines finds targets in two steps, and this does the same in one: + * 1. Searcher (src/wasm/src/searcher.cpp, search_seeds_static()): PokeFinder's + * StaticSearcher3 lists every RNG state whose Method 1 Pokemon passes the filters. + * 2. Initial Seed (src/wasm/src/initial_seed.cpp, frlg_seeds()): for a target state, + * the initial seeds from the seed table, ordered by the advances from the seed to + * the target. That is the LCRNG distance, since the game starts the RNG at the seed. + * + * The code here is written from that description, not copied from either project. + * + */ + +#include +#include +#include "PokemonFRLG_RngTargetSearch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +const uint32_t LCRNG_MULT = 0x41c64e6d; +const uint32_t LCRNG_ADD = 0x6073; +const uint32_t LCRNG_MULT_INVERSE = 0xeeb9eb65; +const uint32_t LCRNG_ADD_INVERSE = 0x0a3561a1; + +// The GBA frame rate, as Ten Lines uses it (SYSTEM_TIMING_DATA in src/tenLines/index.ts). +const double GBA_FRAMES_PER_SECOND = 16777216.0 / 280896.0; + +} + + +uint32_t lcrng_next(uint32_t state){ + return state * LCRNG_MULT + LCRNG_ADD; +} +uint32_t lcrng_previous(uint32_t state){ + return state * LCRNG_MULT_INVERSE + LCRNG_ADD_INVERSE; +} + +// Bit by bit: once the low k bits of "from" and "to" agree, only a jump of 2^k steps +// keeps them agreeing, and it flips bit k. So bit k of the distance is whether bit k +// still differs. +uint32_t lcrng_distance(uint32_t from, uint32_t to){ + uint32_t mult = LCRNG_MULT; + uint32_t add = LCRNG_ADD; + uint32_t distance = 0; + for (uint32_t bit = 1; from != to; bit <<= 1){ + if ((from ^ to) & bit){ + from = from * mult + add; + distance |= bit; + } + add *= mult + 1; + mult *= mult; + } + return distance; +} + + +AdvPokemonResult method1_pokemon(uint32_t state){ + uint32_t pid_low = lcrng_next(state); + uint32_t pid_high = lcrng_next(pid_low); + uint32_t iv_first = lcrng_next(pid_high); + uint32_t iv_second = lcrng_next(iv_first); + + uint32_t pid = (pid_high & 0xffff0000) | (pid_low >> 16); + iv_first >>= 16; + iv_second >>= 16; + + AdvIVs ivs; + ivs.hp = iv_first & 0x1f; + ivs.attack = (iv_first >> 5) & 0x1f; + ivs.defense = (iv_first >> 10) & 0x1f; + ivs.speed = iv_second & 0x1f; + ivs.spatk = (iv_second >> 5) & 0x1f; + ivs.spdef = (iv_second >> 10) & 0x1f; + + return {pid, uint8_t(pid & 0xff), AdvNature(pid % 25), AdvAbility(pid & 1), ivs}; +} + +AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid){ + uint16_t value = uint16_t(pid >> 16) ^ uint16_t(pid) ^ tid ^ sid; + if (value == 0){ + return AdvShinyType::Square; + } + return value < 8 ? AdvShinyType::Star : AdvShinyType::Normal; +} + +HiddenPower hidden_power(const AdvIVs& ivs){ + static const char* TYPES[] = { + "Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel", + "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark", + }; + // Bit 0 of each IV picks the type, bit 1 the power, in the order HP, Atk, Def, Spe, + // SpA, SpD. + const uint8_t order[] = {ivs.hp, ivs.attack, ivs.defense, ivs.speed, ivs.spatk, ivs.spdef}; + int type_bits = 0; + int power_bits = 0; + for (int c = 0; c < 6; c++){ + type_bits |= (order[c] & 1) << c; + power_bits |= ((order[c] >> 1) & 1) << c; + } + return {TYPES[type_bits * 15 / 63], uint8_t(power_bits * 40 / 63 + 30)}; +} + + +std::vector initial_seed_entries( + const SeedsDatabase& database, + SoundSetting sound, + const std::string& button_mode, + bool allow_blackout +){ + // Like SeedsDatabase::find_seed(), the first entry found wins a tie. + std::map earliest; + auto add = [&](const InitialSeedEntry& entry){ + auto iter = earliest.find(entry.seed); + if (iter == earliest.end() || entry.seed_time_ms < iter->second.seed_time_ms){ + earliest[entry.seed] = entry; + } + }; + + const std::vector& delays = database.delays(); + for (const SeedsDatabase::SeedColumn& column : database.columns()){ + if (column.sound != sound || column.button_mode != button_mode){ + continue; + } + for (size_t c = 0; c < column.seeds.size() && c < delays.size(); c++){ + uint16_t seed = column.seeds[c]; + add({seed, delays[c], column.seed_button, BlackoutButton::None}); + if (allow_blackout){ + add({uint16_t(seed - BLACKOUT_SEED_OFFSET), delays[c], column.seed_button, BlackoutButton::L}); + } + } + } + + std::vector entries; + entries.reserve(earliest.size()); + for (const auto& item : earliest){ + entries.emplace_back(item.second); + } + return entries; +} + + +namespace{ + +// Every 16-bit x times the LCRNG multiplier, sorted. A state with known top 16 bits +// "high" is (high << 16) + x, and its next state is lcrng_next(high << 16) + x * mult, +// so the states whose next state is in a range are a range of this table. +class LowBitsTable{ +public: + LowBitsTable(){ + m_products.reserve(0x10000); + for (uint32_t x = 0; x < 0x10000; x++){ + m_products.emplace_back(x * LCRNG_MULT, uint16_t(x)); + } + std::sort(m_products.begin(), m_products.end()); + } + + // Calls "found" with each state whose top 16 bits are "high" and whose next state + // is in [low, low + width). + template + void find_states(uint16_t high, uint32_t low, uint32_t width, Callback&& found) const{ + uint32_t top = uint32_t(high) << 16; + uint32_t start = low - lcrng_next(top); + uint64_t end = uint64_t(start) + width; + const uint64_t WRAP = uint64_t(1) << 32; + visit(top, start, std::min(end, WRAP), found); + if (end > WRAP){ + visit(top, 0, end - WRAP, found); + } + } + +private: + template + void visit(uint32_t top, uint64_t start, uint64_t end, Callback& found) const{ + auto iter = std::lower_bound( + m_products.begin(), m_products.end(), start, + [](const std::pair& item, uint64_t value){ return item.first < value; } + ); + for (; iter != m_products.end() && iter->first < end; ++iter){ + found(top | iter->second); + } + } + + std::vector> m_products; +}; + + +// Keeps the states whose Pokemon pass the filters, each with its nearest initial seed. +class TargetCollector{ +public: + TargetCollector( + const std::vector& seeds, + uint16_t tid, + const std::vector& candidates, + const RngTargetFilters& filters + ) + : m_tid(tid) + , m_candidates(candidates) + , m_filters(filters) + { + for (const InitialSeedEntry& entry : seeds){ + if (seed_time_allowed(entry.seed_time_ms)){ + m_seeds.push_back({lcrng_distance(0, entry.seed), entry}); + } + } + std::sort(m_seeds.begin(), m_seeds.end(), [](const SeedPosition& x, const SeedPosition& y){ + return x.distance < y.distance; + }); + for (const SidCandidate& candidate : candidates){ + m_total_weight += candidate.weight; + } + } + + void consider(uint32_t state){ + AdvPokemonResult pokemon = method1_pokemon(state); + if (!passes(pokemon)){ + return; + } + RngTarget target{state, {}, 0, pokemon, {}, 0}; + double weight = 0; + for (size_t c = 0; c < m_candidates.size(); c++){ + AdvShinyType type = shiny_type(pokemon.pid, m_tid, m_candidates[c].sid); + if (type != AdvShinyType::Normal){ + target.shiny_for.push_back({c, type}); + weight += m_candidates[c].weight; + } + } + if (m_filters.shiny_required && target.shiny_for.empty()){ + return; + } + if (!nearest_seed(state, target)){ + return; + } + target.shiny_probability = m_total_weight > 0 ? weight / m_total_weight : 0; + m_targets.emplace_back(std::move(target)); + } + + std::vector results(){ + std::sort(m_targets.begin(), m_targets.end(), [](const RngTarget& x, const RngTarget& y){ + return x.advances != y.advances ? x.advances < y.advances : x.state < y.state; + }); + return std::move(m_targets); + } + +private: + struct SeedPosition{ + uint32_t distance; + InitialSeedEntry entry; + }; + + bool seed_time_allowed(uint64_t time) const{ + if (time < m_filters.min_seed_time_ms){ + return false; + } + uint64_t gap = time > m_filters.avoided_seed_time_ms + ? time - m_filters.avoided_seed_time_ms + : m_filters.avoided_seed_time_ms - time; + return m_filters.avoided_seed_time_radius_ms == 0 || gap > m_filters.avoided_seed_time_radius_ms; + } + + bool passes(const AdvPokemonResult& pokemon) const{ + const std::vector& natures = m_filters.natures; + if (!natures.empty() && std::find(natures.begin(), natures.end(), pokemon.nature) == natures.end()){ + return false; + } + if (m_filters.ability != AdvAbility::Any && pokemon.ability != m_filters.ability){ + return false; + } + if (m_filters.gender != AdvGender::Any + && gender_from_gender_value(pokemon.gender, m_filters.gender_threshold) != m_filters.gender + ){ + return false; + } + const AdvIVs& ivs = pokemon.ivs; + const AdvIVs& min = m_filters.min_ivs; + return ivs.hp >= min.hp && ivs.attack >= min.attack && ivs.defense >= min.defense + && ivs.spatk >= min.spatk && ivs.spdef >= min.spdef && ivs.speed >= min.speed; + } + + // The seed with the fewest advances to "state" that are still at least the minimum: + // the one with the largest distance from 0 that is at most "state"'s, less the + // minimum, wrapping around the cycle. + bool nearest_seed(uint32_t state, RngTarget& target) const{ + if (m_seeds.empty()){ + return false; + } + uint32_t distance = lcrng_distance(0, state); + uint32_t latest = distance - uint32_t(m_filters.min_advances); + auto iter = std::upper_bound( + m_seeds.begin(), m_seeds.end(), latest, + [](uint32_t value, const SeedPosition& seed){ return value < seed.distance; } + ); + const SeedPosition& seed = iter == m_seeds.begin() ? m_seeds.back() : *(iter - 1); + uint64_t advances = uint32_t(distance - seed.distance); + if (advances < m_filters.min_advances || advances > m_filters.max_advances){ + return false; + } + target.seed = seed.entry; + target.advances = advances; + return true; + } + + const uint16_t m_tid; + const std::vector& m_candidates; + const RngTargetFilters& m_filters; + double m_total_weight = 0; + std::vector m_seeds; + std::vector m_targets; +}; + + +// Shiny Pokemon only: for each low PID half, the high halves that are shiny for a +// candidate are 8 aligned values, so each takes one lookup. +void search_shiny_states( + const LowBitsTable& table, + uint16_t tid, + const std::vector& candidates, + TargetCollector& collector +){ + std::vector shiny_values; + for (const SidCandidate& candidate : candidates){ + shiny_values.push_back((tid ^ candidate.sid) & 0xfff8); + } + std::sort(shiny_values.begin(), shiny_values.end()); + shiny_values.erase(std::unique(shiny_values.begin(), shiny_values.end()), shiny_values.end()); + + auto found = [&](uint32_t pid_low_state){ + collector.consider(lcrng_previous(pid_low_state)); + }; + for (uint32_t pid_low = 0; pid_low < 0x10000; pid_low++){ + for (uint16_t value : shiny_values){ + uint32_t pid_high = (pid_low & 0xfff8) ^ value; + table.find_states(uint16_t(pid_low), pid_high << 16, 8 << 16, found); + } + } +} + +// Any Pokemon, like PokeFinder's StaticSearcher3: every IV combination at or above the +// minimums gives the top 15 bits of the two IV calls. +void search_iv_states(const LowBitsTable& table, const AdvIVs& min_ivs, TargetCollector& collector){ + auto found = [&](uint32_t iv_first_state){ + collector.consider(lcrng_previous(lcrng_previous(lcrng_previous(iv_first_state)))); + }; + // HP, Atk, Def, Spe, SpA, SpD: the order the IVs sit in the two calls. + const uint8_t mins[6] = {min_ivs.hp, min_ivs.attack, min_ivs.defense, min_ivs.speed, min_ivs.spatk, min_ivs.spdef}; + uint8_t ivs[6]; + std::copy(mins, mins + 6, ivs); + while (true){ + uint16_t first = uint16_t(ivs[0] | (ivs[1] << 5) | (ivs[2] << 10)); + uint16_t second = uint16_t(ivs[3] | (ivs[4] << 5) | (ivs[5] << 10)); + for (uint16_t first_top : {0x0000, 0x8000}){ + for (uint32_t second_top : {0x0000, 0x8000}){ + table.find_states(first | first_top, (second | second_top) << 16, 0x10000, found); + } + } + int c = 0; + while (c < 6 && ivs[c] == 31){ + ivs[c] = mins[c]; + c++; + } + if (c == 6){ + return; + } + ivs[c]++; + } +} + +} + + +std::vector search_rng_targets( + const std::vector& seeds, + uint16_t tid, + const std::vector& candidates, + const RngTargetFilters& filters +){ + TargetCollector collector(seeds, tid, candidates, filters); + LowBitsTable table; + if (filters.shiny_required){ + search_shiny_states(table, tid, candidates, collector); + }else{ + search_iv_states(table, filters.min_ivs, collector); + } + return collector.results(); +} + + +void rank_rng_targets(std::vector& targets){ + auto time_ms = [](const RngTarget& target){ + return double(target.seed.seed_time_ms) + double(target.advances) * 1000.0 / GBA_FRAMES_PER_SECOND; + }; + std::stable_sort(targets.begin(), targets.end(), [&](const RngTarget& x, const RngTarget& y){ + bool x_shiny = x.shiny_probability > 0; + bool y_shiny = y.shiny_probability > 0; + if (x_shiny != y_shiny){ + return x_shiny; + } + if (!x_shiny){ + return time_ms(x) < time_ms(y); + } + return time_ms(x) / x.shiny_probability < time_ms(y) / y.shiny_probability; + }); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h new file mode 100644 index 0000000000..bfe0c90a68 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h @@ -0,0 +1,150 @@ +/* RNG Target Search + * + * From: https://github.com/PokemonAutomation/ + * + * Finds static, gift and starter RNG targets (a Target Seed plus Advances, as + * Static/Gift/Starter RNG take them) for a trainer, the way the "Searcher" and + * "Initial Seed" tabs of Ten Lines do for FRLG on Switch: + * https://lincoln-lm.github.io/ten-lines + * https://github.com/Lincoln-LM/ten-lines + * + * How a program can use it to pick its own target when the SID is not known: + * 1. SID Helper reads the TID and narrows the SID down to a few weighted candidates. + * 2. search_rng_targets() with those candidates, then rank_rng_targets(). + * 3. Run Static/Gift/Starter RNG with the top target's seed and advances. + * 4. Read the result: + * - Shiny: the SID is one of the candidates the target is shiny for. If that is + * one candidate, the SID is confirmed. + * - Nature and IVs match, but not shiny: the target was hit, so every candidate it + * is shiny for is wrong. Drop them and search again. + * - Nature or IVs differ: the target was missed. Retry it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngTargetSearch_H +#define PokemonAutomation_PokemonFRLG_RngTargetSearch_H + +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" +#include "PokemonFRLG_BlindNavigation.h" +#include "PokemonFRLG_SeedsDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The Gen 3 LCRNG: state * 0x41C64E6D + 0x6073. +uint32_t lcrng_next(uint32_t state); +uint32_t lcrng_previous(uint32_t state); +// How many lcrng_next() calls take "from" to "to". The LCRNG has a single cycle of +// 2^32 states, so every pair has exactly one distance. +uint32_t lcrng_distance(uint32_t from, uint32_t to); + +// The static, gift or starter Pokemon (Method 1) generated from "state", the RNG state +// just before the PID is rolled: the next two calls give the low and high PID halves, +// the two after that the IVs (HP/Atk/Def, then Spe/SpA/SpD). +Pokemon::AdvPokemonResult method1_pokemon(uint32_t state); + +Pokemon::AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid); + +struct HiddenPower{ + std::string type; + uint8_t power; +}; +HiddenPower hidden_power(const Pokemon::AdvIVs& ivs); + + +// One way to reach an initial seed from the title screen. +struct InitialSeedEntry{ + // The seed reached, after the blackout offset. + uint16_t seed; + uint64_t seed_time_ms; + SeedButton seed_button; + BlackoutButton blackout_button; +}; + +// The initial seeds reachable with one sound setting and button mode, each by its +// earliest entry in the seed table. That is the entry Static/Gift/Starter RNG use for +// a Target Seed (SeedsDatabase::find_seed()). +// +// Holding a blackout button lowers the seed by BLACKOUT_SEED_OFFSET. Ten Lines lists +// that only for the English Switch tables in Help mode (HELD_BUTTON_OFFSETS["lg_nx"] +// and ["fr_nx"] in src/wasm/src/initial_seed.hpp), so pass "allow_blackout" only then. +std::vector initial_seed_entries( + const SeedsDatabase& database, + SoundSetting sound, + const std::string& button_mode, + bool allow_blackout +); + + +struct SidCandidate{ + uint16_t sid; + // Relative likelihood. The weights need not add up to 1. + double weight; +}; + +struct RngTargetFilters{ + // Empty: any nature. + std::vector natures; + Pokemon::AdvIVs min_ivs; + Pokemon::AdvGender gender = Pokemon::AdvGender::Any; + int16_t gender_threshold = 126; + Pokemon::AdvAbility ability = Pokemon::AdvAbility::Any; + // Shiny for at least one SID candidate. + bool shiny_required = true; + + // Total advances from the initial seed: the "Advances" of Ten Lines and of the RNG + // programs. They include the title and continue screens, so fewer of them are + // spent in game. + uint64_t min_advances = 0; + uint64_t max_advances = 1000000; + + uint64_t min_seed_time_ms = 0; + // Skip seed times within "avoided_seed_time_radius_ms" of this. + uint64_t avoided_seed_time_ms = 0; + uint64_t avoided_seed_time_radius_ms = 0; +}; + +struct ShinyCandidate{ + // Index into the SID candidates. + size_t candidate; + Pokemon::AdvShinyType type; +}; + +struct RngTarget{ + // The RNG state before the PID is rolled: the "Target" column of Ten Lines. + uint32_t state; + InitialSeedEntry seed; + uint64_t advances; + Pokemon::AdvPokemonResult pokemon; + // The candidates this target is shiny for. + std::vector shiny_for; + // Their share of the total candidate weight. + double shiny_probability; +}; + +// Every Method 1 result that passes "filters", each with the initial seed that reaches +// it in the fewest advances, sorted by advances. +std::vector search_rng_targets( + const std::vector& seeds, + uint16_t tid, + const std::vector& candidates, + const RngTargetFilters& filters +); + +// Sorts targets by expected wait per shiny: the time to the target (seed time plus +// advances at the GBA frame rate) divided by shiny_probability. A target shiny for +// every candidate beats one shiny for half of them unless it takes twice as long. +// Targets with no shiny candidate go last, by time. +void rank_rng_targets(std::vector& targets); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp new file mode 100644 index 0000000000..71dec39025 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp @@ -0,0 +1,446 @@ +/* RNG Target Search Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The expected targets were found with Ten Lines (https://lincoln-lm.github.io/ten-lines) + * for LeafGreen (English) on Switch, TID 43771, SID 64694, Mono sound, Help button mode, + * Static 1: the lowest advances per target with total advances of at least 3,000 and + * seed times more than 3 seconds from 30,500 ms. + * + */ + +#include +#include +#include "CommonFramework/Language.h" +#include "PokemonFRLG_RngTargetSearch.h" +#include "PokemonFRLG_RngTargetSearch_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +const uint16_t TID = 43771; +const uint16_t SID = 64694; + +// One Ten Lines result: Target, PID, Shiny, Ability, IVs (HP/Atk/Def/SpA/SpD/Spe), +// Hidden Power, Initial Seed, Advances, Seed Time (ms), Buttons. +struct TenLinesRow{ + uint32_t state; + uint32_t pid; + std::string shiny; + int ability; + std::string ivs; + std::string hidden_power; + uint16_t seed; + uint64_t advances; + uint64_t seed_time_ms; + std::string buttons; +}; + +struct TenLinesGroup{ + std::string name; + std::vector natures; + AdvIVs min_ivs; + std::string rows; +}; + +// Ten Lines results, one per line, sorted by advances. +const char MODEST_ROWS[] = + "9435B76A,68F03EBD,Square,1,31/14/7/29/1/27,Dragon 39,2EF6,29364,52641,A/None\n" + "2E37261A,DB7C8D33,Star,1,28/16/6/30/11/29,Water 63,6E9A,50048,54054,A/Blackout R\n" + "C408B1DF,192D4F60,Square,0,25/8/10/29/0/28,Rock 32,02A8,53397,55259,Start/Blackout R\n" + "814DD9D3,84FBD2B6,Square,0,26/19/17/30/10/30,Flying 67,8EB6,58835,48990,Start/Blackout R\n" + "0D815228,8C45DA08,Square,0,29/5/29/31/22/25,Steel 60,A356,59258,64959,Start/Blackout R\n" + "016CB6DF,9C35CA7C,Star,0,29/11/29/30/20/27,Ground 46,A626,69439,48471,A/None\n" + "5DFAB16B,9FC1C98E,Star,0,26/1/0/30/27/28,Fire 61,2B48,77713,41805,A/None\n" + "0E710A6F,8E60D829,Star,1,26/1/9/31/10/25,Steel 61,47CD,89010,50903,A/None\n" + "74224D48,A59DF3D7,Star,1,26/28/22/31/10/30,Ground 68,2CE5,95029,51237,Start/Blackout R\n" + "18699F2D,4B0B1D46,Square,0,28/23/23/29/17/25,Dragon 33,A4C2,101793,47657,Start/Blackout R\n" + "19D01211,FB76AD3F,Star,1,31/16/12/30/22/30,Fighting 66,7DC6,103697,68622,A/Blackout R\n" + "BCDA4E7A,CF729938,Star,0,30/31/30/31/18/26,Rock 70,99D2,107880,36842,Start/None\n" + "1A5A9954,E80BBE43,Star,1,29/24/22/29/4/29,Bug 32,C1C1,107989,35490,A/None\n" + "5A6B83CC,ABF8FDB7,Star,1,27/30/3/31/17/30,Psychic 49,811D,119809,35822,A/Blackout R\n" + "50F06E45,D01B8656,Square,0,26/8/29/31/4/26,Rock 45,4C09,125356,67439,A/None\n" + "9F536DFD,C6FA90B7,Square,1,28/13/28/29/28/25,Ghost 30,1548,129923,66441,Start/None\n" + "2F82C0CA,21ED77A6,Star,0,25/16/4/29/1/31,Ice 35,4FDC,150758,39071,Start/None\n" + "4C7401EB,5AF00CBC,Star,0,30/12/0/30/21/26,Steel 45,45DC,155101,55440,Start/None\n" + "BE31CFCC,FA05AC4E,Star,0,30/22/21/30/3/29,Grass 62,D17C,158288,38405,Start/Blackout R\n" + "3F487560,7B922DDD,Star,1,30/21/5/31/21/27,Dragon 45,FF1C,171172,58240,A/None\n"; + +const char ADAMANT_ROWS[] = + "537A2752,A823FE6A,Star,0,25/29/15/17/31/27,Dark 57,B897,4437,35972,A/Blackout R\n" + "D9FDB041,B9B4EFFE,Star,0,27/31/19/11/5/31,Dark 49,D356,22897,60771,A/None\n" + "E9F88FDD,EAD6BC98,Star,0,30/29/1/29/23/31,Dragon 56,CE81,26060,33587,Start/None\n" + "C3B70E12,D96E8F26,Star,0,29/31/31/9/4/31,Steel 38,8AA1,30571,57386,Start/None\n" + "37BB3B92,BD83EBCB,Star,1,27/30/19/8/26/25,Ground 54,F054,33142,46390,Start/None\n" + "E8D67E1F,BEF4E8BB,Star,1,26/30/2/25/21/26,Electric 39,A9D1,39694,61024,A/Blackout R\n" + "DE925A82,083B5E70,Star,0,28/30/22/26/3/27,Water 69,4665,42695,49155,Start/Blackout R\n" + "D8713EE8,6E9838D2,Star,0,29/31/14/6/26/27,Poison 69,1233,48679,63991,Start/None\n" + "B50AB28B,EC3FBA76,Star,0,30/31/22/25/27/27,Ice 59,704A,61591,65705,A/None\n" + "0A550D9C,25487304,Star,0,30/29/14/5/27/31,Ice 58,B845,68937,53954,A/None\n" + "119C3777,633C3574,Star,0,26/29/4/26/18/30,Fighting 66,A39D,85194,58722,Start/Blackout R\n" + "315D5C57,AF63F92D,Star,1,30/29/23/13/21/29,Dragon 33,DE4C,95017,36725,A/None\n" + "66A23785,8397D5DA,Square,0,25/30/7/24/27/31,Grass 59,9DAC,95463,59324,A/None\n" + "A31E8DB4,462C1067,Star,1,31/31/17/9/22/28,Bug 52,0D4C,99560,36085,A/None\n" + "6109BF46,A9DAFF92,Star,0,26/31/30/6/2/30,Fighting 70,3136,103312,63359,A/None\n" + "3F5603C4,8C11DA5D,Star,1,25/29/6/6/24/29,Poison 42,D22E,111518,54657,Start/None\n"; + +const char NEUTRAL_ROWS[] = + "130195A8,AD7BFB36,Square,0,31/27/31/31/27/26,Ice 70,4381,17225,61908,Start/None\n" + "BE0D7E8F,6FA739E8,Star,0,31/21/25/29/26/25,Steel 50,C845,21690,41371,Start/None\n" + "1798BCE3,066A5027,Square,1,28/23/25/30/31/28,Water 61,3DDC,26549,44721,A/None\n" + "0602C959,EA14BC5F,Star,1,27/21/27/30/27/25,Electric 63,DA81,31480,46973,Start/None\n" + "5B31FD89,A635F07F,Star,1,31/22/19/31/22/31,Ghost 70,B8BB,48990,35972,A/None\n" + "0BA51887,D464822E,Star,0,25/16/17/31/28/28,Bug 40,3C95,59906,38258,A/Blackout R\n" + "61407261,751D2350,Square,0,30/18/16/31/30/28,Ground 62,B83C,61923,51625,Start/Blackout R\n" + "BBB6D222,9F67C92A,Square,0,30/28/25/30/24/31,Poison 45,1439,76611,62542,A/Blackout R\n" + "2C224D48,1D9D4BD7,Star,1,26/28/28/31/24/30,Ground 45,0210,83512,56705,Start/None\n" + "AC47BD6D,33D86591,Star,1,31/19/19/31/31/27,Dark 70,F483,101418,57476,A/Blackout R\n" + "0937DE0D,AB36FD7F,Star,1,27/18/18/30/19/29,Water 64,E588,103955,53106,A/None\n" + "30339DE2,E8A8BEE1,Star,1,27/17/25/29/19/29,Dark 50,47A0,126746,69310,A/Blackout R\n" + "E78F978E,C86B9E25,Star,1,25/20/31/29/23/29,Dragon 52,5A24,136290,33839,A/None\n" + "4A07D3EB,2CE57AA9,Star,1,25/26/24/30/27/25,Water 61,9754,145893,38338,Start/None\n"; + +std::vector groups(){ + AdvIVs modest; + modest.hp = 25; + modest.spatk = 29; + modest.speed = 25; + AdvIVs adamant; + adamant.hp = 25; + adamant.attack = 29; + adamant.speed = 25; + AdvIVs neutral = modest; + neutral.attack = neutral.defense = neutral.spdef = 16; + + using enum AdvNature; + return { + {"Modest", {Modest}, modest, MODEST_ROWS}, + {"Adamant", {Adamant}, adamant, ADAMANT_ROWS}, + {"Neutral", {Hardy, Docile, Serious, Bashful, Quirky}, neutral, NEUTRAL_ROWS}, + }; +} + +std::vector parse_rows(const std::string& text){ + std::vector rows; + std::istringstream lines(text); + std::string line; + while (std::getline(lines, line)){ + std::vector cells; + std::istringstream fields(line); + std::string cell; + while (std::getline(fields, cell, ',')){ + cells.push_back(cell); + } + rows.push_back({ + uint32_t(std::stoul(cells[0], nullptr, 16)), + uint32_t(std::stoul(cells[1], nullptr, 16)), + cells[2], + std::stoi(cells[3]), + cells[4], + cells[5], + uint16_t(std::stoul(cells[6], nullptr, 16)), + std::stoull(cells[7]), + std::stoull(cells[8]), + cells[9], + }); + } + return rows; +} + +std::string hex(uint32_t value){ + std::ostringstream out; + out << std::hex << std::uppercase << value; + return out.str(); +} + +std::string ivs_text(const AdvIVs& ivs){ + return std::to_string(ivs.hp) + "/" + std::to_string(ivs.attack) + "/" + std::to_string(ivs.defense) + + "/" + std::to_string(ivs.spatk) + "/" + std::to_string(ivs.spdef) + "/" + std::to_string(ivs.speed); +} + +std::string shiny_text(AdvShinyType type){ + switch (type){ + case AdvShinyType::Square: return "Square"; + case AdvShinyType::Star: return "Star"; + default: return "No"; + } +} + +// Ten Lines writes "Blackout R"; its Switch offsets for R and L are the same, and the +// RNG programs hold L. +std::string buttons_text(const InitialSeedEntry& entry){ + std::string seed_button = entry.seed_button == SeedButton::Start ? "Start" + : entry.seed_button == SeedButton::L ? "L" : "A"; + return seed_button + (entry.blackout_button == BlackoutButton::None ? "/None" : "/Blackout R"); +} + +std::string row_name(const TenLinesRow& row){ + return "Target " + hex(row.state) + ": "; +} + +uint32_t advance(uint32_t state, uint64_t advances){ + for (uint64_t c = 0; c < advances; c++){ + state = lcrng_next(state); + } + return state; +} + + +std::string check_pokemon(const TenLinesRow& row, const TenLinesGroup& group){ + AdvPokemonResult pokemon = method1_pokemon(row.state); + HiddenPower power = hidden_power(pokemon.ivs); + std::string actual = hex(pokemon.pid) + " " + shiny_text(shiny_type(pokemon.pid, TID, SID)) + + " " + std::to_string(int(pokemon.ability)) + " " + ivs_text(pokemon.ivs) + + " " + power.type + " " + std::to_string(power.power); + std::string expected = hex(row.pid) + " " + row.shiny + " " + std::to_string(row.ability) + + " " + row.ivs + " " + row.hidden_power; + if (actual != expected){ + return row_name(row) + "expected " + expected + ", got " + actual; + } + const std::vector& natures = group.natures; + if (std::find(natures.begin(), natures.end(), pokemon.nature) == natures.end()){ + return row_name(row) + "nature " + nature_to_string(pokemon.nature) + " is not in the group"; + } + return ""; +} + +std::string check_advances(const TenLinesRow& row){ + if (advance(row.seed, row.advances) != row.state){ + return row_name(row) + "seed " + hex(row.seed) + " + " + std::to_string(row.advances) + + " advances does not reach it"; + } + if (lcrng_distance(row.seed, row.state) != row.advances){ + return row_name(row) + "wrong distance from seed " + hex(row.seed); + } + // The RNG programs count advances the same way. + AdvRngSearcher program(row.seed, row.advances, AdvRngMethod::Method1); + if (program.generate_pokemon().pid != row.pid){ + return row_name(row) + "AdvRngSearcher gives PID " + hex(program.generate_pokemon().pid); + } + return ""; +} + +class Test_RngTargetMethod1 : public UnitTest{ +public: + Test_RngTargetMethod1(TenLinesGroup group) + : UnitTest("PokemonFRLG::RngTargetSearch - Method 1 - " + group.name) + , m_group(std::move(group)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + for (const TenLinesRow& row : parse_rows(m_group.rows)){ + std::string error = check_pokemon(row, m_group); + if (error.empty()){ + error = check_advances(row); + } + if (!error.empty()){ + return error; + } + } + return true; + } + +private: + const TenLinesGroup m_group; +}; + + +RngTargetFilters ten_lines_filters(const TenLinesGroup& group){ + RngTargetFilters filters; + filters.natures = group.natures; + filters.min_ivs = group.min_ivs; + filters.min_advances = 3000; + filters.avoided_seed_time_ms = 30500; + filters.avoided_seed_time_radius_ms = 3000; + return filters; +} + +std::vector leafgreen_mono_help_seeds(){ + SeedsDatabase database(seeds_json_path(false, Language::English)); + return initial_seed_entries(database, SoundSetting::Mono, "Help", true); +} + +std::string compare_seed_entry(const TenLinesRow& row, const InitialSeedEntry& entry){ + std::string expected = std::to_string(row.seed_time_ms) + " " + row.buttons; + std::string actual = std::to_string(entry.seed_time_ms) + " " + buttons_text(entry); + // Ten Lines lists every way to reach a seed, and the RNG programs use the earliest + // (SeedsDatabase::find_seed()): 3136 by Start at 58991 ms, not by A at 63359 ms. + if (buttons_text(entry) != row.buttons){ + return entry.seed_time_ms < row.seed_time_ms ? "" : "Expected " + expected + ", got " + actual; + } + // Ten Lines rounds the seed time down from 1/16 frames; the seed table here is 1 ms + // lower on about 1 row in 17 (61023 instead of 61024 for row 1833). + if (entry.seed_time_ms > row.seed_time_ms || entry.seed_time_ms + 1 < row.seed_time_ms){ + return "Expected " + expected + ", got " + actual; + } + return ""; +} + +std::string compare_target(const TenLinesRow& row, const RngTarget& target){ + std::string expected = hex(row.state) + " " + hex(row.seed) + " " + std::to_string(row.advances); + std::string actual = hex(target.state) + " " + hex(target.seed.seed) + " " + std::to_string(target.advances); + if (actual != expected){ + return "Expected " + expected + ", got " + actual; + } + std::string error = compare_seed_entry(row, target.seed); + if (!error.empty()){ + return row_name(row) + error; + } + if (target.shiny_for.size() != 1 || shiny_text(target.shiny_for[0].type) != row.shiny || target.shiny_probability != 1){ + return row_name(row) + "expected shiny (" + row.shiny + ") for the one SID"; + } + return ""; +} + +class Test_RngTargetSearch : public UnitTest{ +public: + Test_RngTargetSearch(TenLinesGroup group) + : UnitTest("PokemonFRLG::RngTargetSearch - Search - " + group.name) + , m_group(std::move(group)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::vector targets = search_rng_targets( + leafgreen_mono_help_seeds(), TID, {{SID, 1}}, ten_lines_filters(m_group) + ); + std::vector rows = parse_rows(m_group.rows); + if (targets.size() < rows.size()){ + return "Expected at least " + std::to_string(rows.size()) + " targets, got " + std::to_string(targets.size()); + } + for (size_t c = 0; c < rows.size(); c++){ + std::string error = compare_target(rows[c], targets[c]); + if (!error.empty()){ + return "Target #" + std::to_string(c + 1) + ": " + error; + } + } + return true; + } + +private: + const TenLinesGroup m_group; +}; + + +// Searching every IV combination finds the same shiny targets as searching shiny PIDs. +class Test_RngTargetIvSearch : public UnitTest{ +public: + Test_RngTargetIvSearch() + : UnitTest("PokemonFRLG::RngTargetSearch - IV search") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const TenLinesGroup group = groups()[2]; + std::vector seeds = leafgreen_mono_help_seeds(); + RngTargetFilters filters = ten_lines_filters(group); + std::vector shiny = search_rng_targets(seeds, TID, {{SID, 1}}, filters); + + filters.shiny_required = false; + std::vector any = search_rng_targets(seeds, TID, {{SID, 1}}, filters); + std::vector any_shiny; + for (const RngTarget& target : any){ + if (!target.shiny_for.empty()){ + any_shiny.push_back(target); + } + } + if (any.size() <= any_shiny.size()){ + return "Expected targets that are not shiny"; + } + if (any_shiny.size() != shiny.size()){ + return "Expected " + std::to_string(shiny.size()) + " shiny targets, got " + std::to_string(any_shiny.size()); + } + for (size_t c = 0; c < shiny.size(); c++){ + if (any_shiny[c].state != shiny[c].state || any_shiny[c].advances != shiny[c].advances){ + return "Shiny target #" + std::to_string(c + 1) + " differs: " + hex(any_shiny[c].state); + } + } + return true; + } +}; + + +// A second SID candidate: each target is shiny for one of the two, by weight. +class Test_RngTargetCandidates : public UnitTest{ +public: + Test_RngTargetCandidates() + : UnitTest("PokemonFRLG::RngTargetSearch - SID candidates") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const TenLinesGroup group = groups()[0]; + const uint16_t other_sid = SID ^ 0x0100; + std::vector targets = search_rng_targets( + leafgreen_mono_help_seeds(), TID, {{SID, 3}, {other_sid, 1}}, ten_lines_filters(group) + ); + size_t found = 0; + for (const RngTarget& target : targets){ + if (target.shiny_for.size() != 1){ + return "Target " + hex(target.state) + " is shiny for " + std::to_string(target.shiny_for.size()) + " SIDs"; + } + double expected = target.shiny_for[0].candidate == 0 ? 0.75 : 0.25; + if (target.shiny_probability != expected){ + return "Target " + hex(target.state) + " has shiny probability " + std::to_string(target.shiny_probability); + } + found += target.shiny_for[0].candidate == 0 && target.advances <= 171172; + } + if (found != 20){ + return "Expected the 20 Ten Lines targets for SID " + std::to_string(SID) + ", got " + std::to_string(found); + } + return true; + } +}; + + +class Test_RngTargetRanking : public UnitTest{ +public: + Test_RngTargetRanking() + : UnitTest("PokemonFRLG::RngTargetSearch - Ranking") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + auto target = [](uint32_t state, uint64_t advances, double probability){ + RngTarget ret{state, {0, 40000, SeedButton::A, BlackoutButton::None}, advances, {}, {}, probability}; + return ret; + }; + // About 60 advances per second, after a 40 s seed time: A takes 207 s and B 249 s, + // but A is shiny only half the time. D takes 57 s, but is shiny one time in 10. + std::vector targets{ + target(0xA, 10000, 0.5), + target(0xB, 12500, 1), + target(0xC, 100, 0), + target(0xD, 1000, 0.1), + }; + rank_rng_targets(targets); + std::string order; + for (const RngTarget& item : targets){ + order += hex(item.state); + } + if (order != "BADC"){ + return "Expected order BADC, got " + order; + } + return true; + } +}; + +} + + +void add_tests_RngTargetSearch(UnitTestDatabase& database){ + for (const TenLinesGroup& group : groups()){ + database.add(group); + database.add(group); + } + database.add(); + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h new file mode 100644 index 0000000000..0dc22e8b00 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h @@ -0,0 +1,23 @@ +/* RNG Target Search Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngTargetSearch_Tests_H +#define PokemonAutomation_PokemonFRLG_RngTargetSearch_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_RngTargetSearch(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h index 12c1b2a77e..a619054ca0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h @@ -44,10 +44,6 @@ struct SeedMatch{ class SeedsDatabase{ public: - SeedsDatabase(const std::string& json_path); - SeedMatch find_seed(uint16_t target_seed, SoundSetting sound, int radius) const; - -private: struct SeedColumn{ std::string name; SoundSetting sound; @@ -56,6 +52,15 @@ class SeedsDatabase{ std::vector seeds; }; +public: + SeedsDatabase(const std::string& json_path); + SeedMatch find_seed(uint16_t target_seed, SoundSetting sound, int radius) const; + + // The delay in milliseconds before each row of the columns. + const std::vector& delays() const{ return m_delays; } + const std::vector& columns() const{ return m_columns; } + +private: std::vector m_delays; std::vector m_columns; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp index 0c3ac9bd67..c3b2e0f680 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp @@ -9,8 +9,6 @@ #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/ProgramStats/StatsTracking.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "Pokemon/Pokemon_Strings.h" #include "Pokemon/Pokemon_AdvRng.h" @@ -18,7 +16,8 @@ #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" -#include "PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h" +#include "PokemonFRLG_SidSteps.h" #include "PokemonFRLG_SidHelper.h" namespace PokemonAutomation{ @@ -100,133 +99,6 @@ SidHelper::SidHelper() namespace{ -void set_sid_from_name_screen( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const uint64_t& SID_DELAY, - bool extra_press_at_end -){ - // this is performed blind to try to maximize consistency of timing - // ensure the OK button is selected - pbf_press_button(context, BUTTON_PLUS, 200ms, 300ms); - // confirm name (SID delay starts now) - pbf_press_button(context, BUTTON_A, 200ms, 1800ms); - // advance to "...about to unfold!", picking the default rival name - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - pbf_press_button(context, BUTTON_A, 200ms, 1050ms); - pbf_press_button(context, BUTTON_A, 200ms, 1550ms); - pbf_move_left_joystick(context, {0,-1}, 200ms, 300ms); - pbf_press_button(context, BUTTON_A, 200ms, 1050ms); - pbf_press_button(context, BUTTON_A, 200ms, 1550ms); - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - - // 2000 + 2500 + 1250 + 1750 + 500 + 1250 + 1750 + 2500 + 200 ms - Milliseconds delay(SID_DELAY > 13700 - ? SID_DELAY - 13700 - : 0 - ); - - if (extra_press_at_end){ - pbf_press_button(context, BUTTON_A, 200ms, 1300ms); - delay = delay > 1500ms ? delay - 1500ms : 0ms; - } - - pbf_press_button(context, BUTTON_A, 200ms, delay); - - // finish dialogue and lock in SID - pbf_press_button(context, BUTTON_A, 200ms, 0ms); - context.wait_for_all_requests(); -} - -void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - BlackScreenWatcher black_screen; - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, 10s, - { black_screen } - ); - - if (ret < 0){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, "SidHelper(): black screen not detected within 10 seconds of setting SID", env.console - ); - } - - BlackScreenOverWatcher black_screen_over; - context.wait_for_all_requests(); - int ret2 = wait_until( - env.console, context, 10s, - { black_screen_over } - ); - - if (ret2 < 0){ - env.log("finish_intro_animations(): end of black screen not detected within 10 seconds. Continuing anyway..."); - // if there's a problem, an error will be thrown when trying to navigate to the trainer card - } - - pbf_wait(context, 2000ms); - context.wait_for_all_requests(); -} - -void navigate_to_trainer_card(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - int errors = 0; - while (true){ - if (errors >= 5){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, "SidHelper(): failed 5 times to navigate to the Trainer Card", env.console - ); - } - - open_start_menu(env.console, context); - - // the positions are different before recieving a Pokemon and Pokedex - bool cursor = move_cursor_to_position( - env.console, context, SelectionArrowPositionStartMenu(1) - ); - if (!cursor){ - errors++; - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - } - - TrainerCardWatcher trainer_card(COLOR_RED); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - }, - { trainer_card } - ); - - if (ret < 0){ - env.log("SidHelper(): failed to detect Trainer Card"); - errors++; - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - } - - break; - } -} - -uint16_t read_tid(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language lang){ - TrainerIdReader reader; - VideoOverlaySet overlays(env.console.overlay()); - reader.make_overlays(overlays); - - VideoSnapshot screen = env.console.video().snapshot(); - env.log("Trainer Card detected."); - env.log("Reading TID..."); - uint16_t tid = reader.read_tid(env.logger(), lang, screen); - env.log("TID: " + std::to_string(tid)); - - context.wait_for_all_requests(); - - return tid; -} - std::vector> get_sid_messages( SingleSwitchProgramEnvironment& env, ProControllerContext& context, @@ -271,48 +143,15 @@ void SidHelper::program(SingleSwitchProgramEnvironment& env, ProControllerContex // SidHelper_Descriptor::Stats& stats = env.current_stats(); - uint64_t FINAL_TEXT_FRAMES; Language lang = LANGUAGE; - switch (lang){ - case Language::English: - FINAL_TEXT_FRAMES = 249; - break; - case Language::Japanese: - FINAL_TEXT_FRAMES = 194; - break; - case Language::Italian: - FINAL_TEXT_FRAMES = 236; - break; - case Language::French: - FINAL_TEXT_FRAMES = 205; - break; - case Language::German: - FINAL_TEXT_FRAMES = 208; - break; - case Language::Spanish: - FINAL_TEXT_FRAMES = 202; - break; - default: - FINAL_TEXT_FRAMES = 249; - } - - static const int64_t FIXED_ADVANCES_OFFSET = 7; // determined empirically. Probably not console/setup dependent - - bool extra_press_at_end = ( - LANGUAGE == Language::German || - LANGUAGE == Language::Japanese || - LANGUAGE == Language::Spanish || - LANGUAGE == Language::French - ); - - const uint64_t SID_DELAY = uint64_t((TARGET_ADVANCES - 2*FINAL_TEXT_FRAMES + FIXED_ADVANCES_OFFSET) * FRLG_FRAME_DURATION / 2); // advances pass 2 by 2 - env.log("Delay: " + std::to_string(SID_DELAY) + "ms"); + const SidTiming timing = sid_timing(lang, TARGET_ADVANCES); + env.log("Delay: " + std::to_string(timing.delay_ms) + "ms"); - set_sid_from_name_screen(env, context, SID_DELAY, extra_press_at_end); + set_sid_from_name_screen(context, timing); finish_intro_animations(env, context); - navigate_to_trainer_card(env, context); + navigate_to_trainer_card(env.console, context); - uint16_t tid = read_tid(env, context, lang); + uint16_t tid = read_trainer_card_tid(env.console, context, lang); std::vector> sid_messages = get_sid_messages( env, context, tid, TARGET_ADVANCES, NUM_CANDIDATES diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp new file mode 100644 index 0000000000..701411f827 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp @@ -0,0 +1,124 @@ +/* SID Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_SidSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +SidTiming sid_timing(Language language, uint32_t target_advances){ + uint64_t FINAL_TEXT_FRAMES; + switch (language){ + case Language::English: + FINAL_TEXT_FRAMES = 249; + break; + case Language::Japanese: + FINAL_TEXT_FRAMES = 194; + break; + case Language::Italian: + FINAL_TEXT_FRAMES = 236; + break; + case Language::French: + FINAL_TEXT_FRAMES = 205; + break; + case Language::German: + FINAL_TEXT_FRAMES = 208; + break; + case Language::Spanish: + FINAL_TEXT_FRAMES = 202; + break; + default: + FINAL_TEXT_FRAMES = 249; + } + + static const int64_t FIXED_ADVANCES_OFFSET = 7; // determined empirically. Probably not console/setup dependent + + bool extra_press_at_end = ( + language == Language::German || + language == Language::Japanese || + language == Language::Spanish || + language == Language::French + ); + + const uint64_t SID_DELAY = uint64_t((target_advances - 2*FINAL_TEXT_FRAMES + FIXED_ADVANCES_OFFSET) * FRLG_FRAME_DURATION / 2); // advances pass 2 by 2 + return SidTiming{.delay_ms = SID_DELAY, .extra_press_at_end = extra_press_at_end}; +} + +void set_sid_from_name_screen(ProControllerContext& context, const SidTiming& timing){ + // this is performed blind to try to maximize consistency of timing + // ensure the OK button is selected + pbf_press_button(context, BUTTON_PLUS, 200ms, 300ms); + // confirm name (SID delay starts now) + pbf_press_button(context, BUTTON_A, 200ms, 1800ms); + // advance to "...about to unfold!", picking the default rival name + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + pbf_press_button(context, BUTTON_A, 200ms, 1050ms); + pbf_press_button(context, BUTTON_A, 200ms, 1550ms); + pbf_move_left_joystick(context, {0,-1}, 200ms, 300ms); + pbf_press_button(context, BUTTON_A, 200ms, 1050ms); + pbf_press_button(context, BUTTON_A, 200ms, 1550ms); + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + + // 2000 + 2500 + 1250 + 1750 + 500 + 1250 + 1750 + 2500 + 200 ms + Milliseconds delay(timing.delay_ms > 13700 + ? timing.delay_ms - 13700 + : 0 + ); + + if (timing.extra_press_at_end){ + pbf_press_button(context, BUTTON_A, 200ms, 1300ms); + delay = delay > 1500ms ? delay - 1500ms : 0ms; + } + + pbf_press_button(context, BUTTON_A, 200ms, delay); + + // finish dialogue and lock in SID + pbf_press_button(context, BUTTON_A, 200ms, 0ms); + context.wait_for_all_requests(); +} + +void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BlackScreenWatcher black_screen; + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, 10s, + { black_screen } + ); + + if (ret < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "SidHelper(): black screen not detected within 10 seconds of setting SID", env.console + ); + } + + BlackScreenOverWatcher black_screen_over; + context.wait_for_all_requests(); + int ret2 = wait_until( + env.console, context, 10s, + { black_screen_over } + ); + + if (ret2 < 0){ + env.log("finish_intro_animations(): end of black screen not detected within 10 seconds. Continuing anyway..."); + // if there's a problem, an error will be thrown when trying to navigate to the trainer card + } + + pbf_wait(context, 2000ms); + context.wait_for_all_requests(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h new file mode 100644 index 0000000000..f1c358fa20 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h @@ -0,0 +1,50 @@ +/* SID Steps + * + * From: https://github.com/PokemonAutomation/ + * + * SID Helper's steps from the naming screen to the overworld, which set the + * SID by timing the last press of the intro. Shared with AutoStory. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_SidSteps_H +#define PokemonAutomation_PokemonFRLG_SidSteps_H + +#include +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// When to press the last A of the intro to land on an advance. +struct SidTiming{ + // From confirming the player's name to the last press. + uint64_t delay_ms = 0; + // The language's intro has one more text box before the last press. + bool extra_press_at_end = false; +}; + +// The timing that sets the SID at "target_advances" (odd) in a game in +// "language". +SidTiming sid_timing(Language language, uint32_t target_advances); + +// From the player's naming screen, confirms the name, picks the default +// rival name and presses through the intro at "timing", which sets the SID. +// Runs blind; ends on the last press of the intro. +void set_sid_from_name_screen(ProControllerContext& context, const SidTiming& timing); + +// After set_sid_from_name_screen(): waits out the black screen into the +// overworld. Throws OperationFailedException if no black screen comes +// within 10 seconds. +void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp index 5b22bee42f..63da6e6aa8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp @@ -6,22 +6,15 @@ #include "Common/Cpp/Strings/StringTools.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" #include "Pokemon/Pokemon_Strings.h" -#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" -#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" -#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattlePokemonDetector.h" -#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_RngNavigation.h" -#include "PokemonFRLG_HardReset.h" +#include "PokemonFRLG_RngCalibration.h" #include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngAttempts.h" #include "PokemonFRLG_StarterRng.h" namespace PokemonAutomation{ @@ -42,26 +35,6 @@ StarterRng_Descriptor::StarterRng_Descriptor() ) {} -struct StarterRng_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , nonshiny(m_stats["Non-Shiny Hits"]) - , wildshinies(m_stats["Wild Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Non-Shiny Hits", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Wild Shinies", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& nonshiny; - std::atomic& wildshinies; - std::atomic& errors; -}; std::unique_ptr StarterRng_Descriptor::make_stats() const{ return std::unique_ptr(new Stats()); } @@ -115,12 +88,12 @@ StarterRng::StarterRng() , STARTER( "Starter Species:", { - {Starter::bulbasaur, "bulbasaur", "Bulbasaur"}, - {Starter::squirtle, "squirtle", "Squirtle"}, - {Starter::charmander, "charmander", "Charmander"}, + {StarterSpecies::bulbasaur, "bulbasaur", "Bulbasaur"}, + {StarterSpecies::squirtle, "squirtle", "Squirtle"}, + {StarterSpecies::charmander, "charmander", "Charmander"}, }, LockMode::LOCK_WHILE_RUNNING, - Starter::bulbasaur + StarterSpecies::bulbasaur ) , SEED( false, @@ -214,352 +187,12 @@ void StarterRng::on_config_value_changed(void* object){ -bool StarterRng::walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // return to the overworld - pbf_mash_button(context, BUTTON_B, 5000ms); - int num_steps_to_the_left; - switch(STARTER){ - case Starter::bulbasaur: - num_steps_to_the_left = 2; - break; - case Starter::squirtle: - num_steps_to_the_left = 3; - break; - case Starter::charmander: - num_steps_to_the_left = 4; - break; - default: - num_steps_to_the_left = 2; - } - - // dodge rival - pbf_move_left_joystick(context, {0, -1}, 40ms, 460ms); - pbf_move_left_joystick(context, {0, -1}, 100ms, 400ms); - - // line up with the doorway - pbf_move_left_joystick(context, {-1, 0}, 40ms, 460ms); // pivot left - for (int i=0; i( - env.console, context, - [](ProControllerContext& context){ - for (int i=0; i<5; i++){ - ssf_press_left_joystick(context, {0, -1}, 0ms, 20000ms, 0ms); - ssf_mash1_button(context, BUTTON_B, 20000ms); - } - }, - { black_screen } - ); - - bool failed = ret < 0; - if (failed){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "walk_to_rival_battle(): failed to initiate battle." - ); - } - return failed; -} - -bool StarterRng::auto_battle_rival( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS -){ - Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; - switch(STARTER){ - case Starter::bulbasaur: - evyield.speed = 1; // from charmander - break; - case Starter::squirtle: - evyield.spatk = 1; // from bulbasaur - break; - case Starter::charmander: - evyield.defense = 1; // from squirtle - } - - // detect the battle menu - BattleMenuWatcher battle_ready(COLOR_RED); - context.wait_for_all_requests(); - int ret1 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 30s); - }, - { battle_ready } - ); - if (ret1 < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "auto_battle_rival(): failed to detect the battle menu." - ); - return true; - } - env.log("Battle started. Using first move..."); - - // perform the first move and get through Oak's dialogue, - // which messes up most detectors when it dims the screen - pbf_mash_button(context, BUTTON_A, 1000ms); // execute first move - context.wait_for_all_requests(); - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 30s); - }, - { battle_ready } - ); - if (ret2 < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "auto_battle_rival(): failed to detect the battle menu." - ); - return true; - } - env.log("Oak tutorial dialogue finished. Mashing A..."); - - // mash A until somebody faints - BattleOpponentFaintWatcher player_won(COLOR_RED); - BattleFaintWatcher player_lost(COLOR_RED); - context.wait_for_all_requests(); - int ret3 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 300s); - }, - { player_won, player_lost } - ); - - switch(ret3){ - case 0: - env.log("Won battle against rival. Watching for level-up stats..."); - break; - case 1: - env.log("Lost battle against rival."); - pbf_mash_button(context, BUTTON_B, 20s); // exit battle and dialogue - return false; - default: - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "auto_battle_rival(): no fainting detected with 5 minutes." - ); - return true; - } - - // slowly advance dialog until level-up stats are visible - BattleLevelUpWatcher level_up_stats(COLOR_RED, BattleLevelUpDialog::stats, LANGUAGE); - BlackScreenWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret4 = run_until( - env.console, context, - [](ProControllerContext& context){ - for(int i=0; i<60; i++){ - pbf_press_button(context, BUTTON_A, 200ms, 1800ms); - } - }, - { level_up_stats, black_screen } - ); - - switch(ret4){ - case 0: - env.log("Level-up stats detected."); - break; - case 1: - env.log("Battle exited without detecting level-up stats"); - return true; // will cause issues with keeping track of level and EVs - default: - env.log("auto_battle_rival(): no recognized state within 2 minutes of winning battle."); - return true; - } - - // read stats - BattleLevelUpReader reader(COLOR_RED); - VideoOverlaySet overlays(env.console.overlay()); - reader.make_overlays(overlays); - - env.log("Reading stats..."); - VideoSnapshot screen = env.console.video().snapshot(); - StatReads stats = reader.read_stats(env.logger(), screen); - - update_filters(filters, pokemon, stats, evyield, BASE_STATS); - RNG_FILTERS.set(filters); - - // exit battle - pbf_mash_button(context, BUTTON_B, 20s); - context.wait_for_all_requests(); - - return false; -} - - - -bool StarterRng::walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // exit the lab - env.log("Exiting the lab..."); - BlackScreenWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, {0, -1}, 10s, 0ms); - }, - { black_screen } - ); - - if (ret < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "walk_to_route1_from_lab(): failed to exit lab." - ); - return true; - } - - env.log("Lab exited. Walking to Route 1..."); - pbf_wait(context, 5000ms); - pbf_move_left_joystick(context, {-1, 0}, 1280ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 3150ms, 300ms); - pbf_move_left_joystick(context, {+1, 0}, 330ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 720ms, 300ms); - context.wait_for_all_requests(); - return false; -} - -bool StarterRng::walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // exit the house - env.log("Exiting the house..."); - BlackScreenWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); - pbf_move_left_joystick(context, {-1, 0}, 900ms, 300ms); - pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); - }, - { black_screen } - ); - - if (ret < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "walk_to_route1_from_home(): failed to exit the house." - ); - return true; - } - - env.log("House exited. Walking to Route 1..."); - pbf_wait(context, 5s); - pbf_move_left_joystick(context, {+1, 0}, 1370ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 1450ms, 300ms); - pbf_move_left_joystick(context, {+1, 0}, 300ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 1250ms, 300ms); - - return false; -} - -int StarterRng::autolevel_on_route1( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS -){ - Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; - Pokemon::StatReads stats; - - env.log("Arrived at Route 1."); - bool leftright = true; - context.wait_for_all_requests(); - - while (true){ - // trigger encounter - env.log("Triggering wild encounters..."); - int ret = grass_spin(env.console, context, leftright); - if (ret < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "autolevel_on_route1(): failed to trigger encounter." - ); - return -1; - } - - if (ret == 1){ // shiny - return 1; - } - - // auto battle - BattleResult ret2 = spam_first_move(env.console, context); - - BattleLevelUpWatcher level_up(COLOR_RED, BattleLevelUpDialog::stats, LANGUAGE); - BlackScreenWatcher black_screen(COLOR_RED); - VideoSnapshot screen; - int ret3; - bool failed; - BattleLevelUpReader reader; - - switch (ret2){ - case BattleResult::opponentfainted: - env.log("Opponent fainted."); - evyield.speed++; // always rattata or pidgey - leftright = !leftright; - - context.wait_for_all_requests(); - ret3 = run_until( - env.console, context, - [](ProControllerContext& context){ - for (int i=0; i<5; i++){ - pbf_press_button(context, BUTTON_B, 200ms, 1800ms); - } - }, - { level_up, black_screen } - ); - - switch (ret3){ - case 0: - env.log("Level-up stats detected. Reading stats..."); - screen = env.console.video().snapshot(); - stats = reader.read_stats(env.logger(), screen); - update_filters(filters, pokemon, stats, evyield, BASE_STATS); - RNG_FILTERS.set(filters); - exit_wild_battle(env.console, context, false, true); - return 0; - case -1: - exit_wild_battle(env.console, context, false, true); - default: - pbf_wait(context, 1000ms); - context.wait_for_all_requests(); - continue; - } - case BattleResult::playerfainted: - env.log("Pokemon fainted. Mashing B through dialogues..."); - pbf_mash_button(context, BUTTON_B, 30s); // skip through a few transitions and lots of dialogue - failed = walk_to_route1_from_home(env, context); - if (failed){ - return -1; - } - context.wait_for_all_requests(); - leftright = true; - continue; - case BattleResult::outofpp: - case BattleResult::unknown: - default: - return -1; - } - } -} - void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ /* * Settings: Text Speed fast */ - StarterRng_Descriptor::Stats& stats = env.current_stats(); + StarterRngStats& stats = env.current_stats(); home_black_border_check(env.console, context); @@ -572,279 +205,41 @@ void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerConte if (!seed_match.found){ throw UserSetupError(env.console, "The target Seed was not found in the seed database for this game version, language, and sound setting."); } - const std::vector SEED_VALUES = seed_match.seed_values; - const int16_t SEED_POSITION = seed_match.seed_position; - const uint64_t SEED_DELAY = seed_match.seed_delay; - const SeedButton SEED_BUTTON = seed_match.seed_button; - const BlackoutButton EXTRA_BUTTON = seed_match.extra_button; - env.log("Seed delay: " + std::to_string(SEED_DELAY) + "ms, button mode: " + seed_match.button_mode + env.log("Seed delay: " + std::to_string(seed_match.seed_delay) + "ms, button mode: " + seed_match.button_mode + ", column: " + seed_match.column_name); - BaseStats BASE_STATS; - switch (STARTER){ - case Starter::bulbasaur: - BASE_STATS = { 45, 49, 49, 65, 65, 45 }; - break; - case Starter::squirtle: - BASE_STATS = { 44, 48, 65, 50, 64, 43 }; - break; - case Starter::charmander: - BASE_STATS = { 39, 52, 43, 60, 50, 65 }; - break; - default: - break; - } - - static const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate - - static const uint64_t CONTINUE_SCREEN_FRAMES = 200; - - static const uint64_t INITIAL_ADVANCES_RADIUS = 1024; - - static const uint8_t MAX_HISTORY_LENGTH = 10; - - static const int16_t GENDER_THRESHOLD = 30; - - static const std::set SPECIES_LIST = { "bulbasaur", "squirtle", "charmander" }; - - env.log("RNG Target: " + std::to_string(STARTER.current_value())); - env.log("Target Seed: " + to_hex_string(TARGET_SEED)); - env.log("Target Advances: " + std::to_string(ADVANCES)); - - AdvRngSearcher searcher(TARGET_SEED, ADVANCES, AdvRngMethod::Method1); - AdvPokemonResult target_result = searcher.generate_pokemon(); - RNG_TARGET.set_target(target_result, GENDER_THRESHOLD); - log_target_pokemon(env.console, target_result); - - RngCalibrations calibrations = { - RNG_CALIBRATION.seed_calibration / FRLG_FRAME_DURATION, - RNG_CALIBRATION.csf_calibration, - RNG_CALIBRATION.advances_calibration - }; - log_calibrations(env.console, calibrations, true); - - Milliseconds launch_delay = INITIAL_LAUNCH_DELAY; - - RngUncertainHistory uncertain_history; - RngCalibrationHistory calibration_history; - - bool wildshiny_found = false; - - uint16_t failed_searches = 0; - - while (true){ - if (calibration_history.results.size() > 0){ - env.log("Checking for nonshiny target hit..."); - if (have_hit_target(TARGET_SEED, ADVANCES, calibration_history.results.back())){ - env.log("Target Hit!"); - stats.nonshiny++; - break; - } - env.log("Missed target."); - } - - if (failed_searches >= 5){ - env.log("Failed to find any matches 5 times in a row"); - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::NO_ERROR_REPORT, - "Failed to find any matches 5 times in a row. Check your seed and advances settings.", - env.console - ); - break; - } - - if (stats.resets > MAX_RESETS){ - env.log("Max resets reached."); - break; - } - - if (wildshiny_found){ - break; - } - - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Calibrating." - ); - env.update_stats(); - - - uint64_t advances_radius = get_advances_radius(env.console, calibration_history, INITIAL_ADVANCES_RADIUS); - - if (calibration_history.results.size() > 0){ - calibrations = get_calibrations(env.console, calibration_history, SEED_VALUES, SEED_POSITION, ADVANCES); - } - - // if previous resets had uncertain advances, slightly modify the seed delay to try to hit a different target - apply_seed_bump(calibrations, uncertain_history); - - uint64_t ingame_advances = ADVANCES - CONTINUE_SCREEN_FRAMES; - - RngTimings timings = prepare_timings( - env.console, PokemonFRLG_RngTarget::starters, - SEED_DELAY, CONTINUE_SCREEN_FRAMES, ingame_advances, - false, calibrations, - FIXED_SEED_OFFSET - ); - - env.log("Resetting Game..."); - reset_and_perform_blind_sequence( - env.console, context, - LANGUAGE, PokemonFRLG_RngTarget::starters, - SEED_BUTTON, EXTRA_BUTTON, timings, - launch_delay, false, PROFILE - ); - stats.resets++; - - RNG_FILTERS.reset(); - RNG_CALIBRATION.set_calibrations(calibrations); - RNG_CALIBRATION.reset_hits(); - - bool shiny_found = check_for_shiny(env.console, context, PokemonFRLG_RngTarget::starters); - - if (shiny_found){ - env.log("Shiny found!"); - stats.shinies++; - RNG_CALIBRATION.hits.set("Shiny!"); - send_program_notification( - env, - NOTIFICATION_SHINY, - COLOR_YELLOW, - "Shiny found!", - {}, "", - env.console.video().snapshot(), - true - ); - if (TAKE_VIDEO){ - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); - } - break; - } - - // Stage 1: initial search -- starter received - AdvObservedPokemon pokemon = read_summary(env.console, context, LANGUAGE, SPECIES_LIST); - pokemon.level[0] = 5; - AdvRngFilters filters = observation_to_filters(pokemon, BASE_STATS); - RNG_FILTERS.set(filters); - - std::vector search_hits = get_search_results(env.console, searcher, filters, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - RNG_CALIBRATION.set_hits(search_hits); - bool finished = update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1 - ); - if (finished){ - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - continue; - } - - // Stage 2: first search update -- post-rival-battle - bool failed = walk_to_rival_battle(env, context); - if (failed){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - continue; // reset game - } - - failed = auto_battle_rival(env, context, pokemon, filters, BASE_STATS); - if (failed){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - continue; // reset game - } - if (pokemon.level.size() > 1){ - search_hits = get_search_results(env.console, searcher, filters, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - RNG_CALIBRATION.set_hits(search_hits); - env.log("Number of search hits: " + std::to_string(search_hits.size())); - finished = update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 5 - ); - if (finished){ - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - continue; - } - } - - // Stage 3: subsequent search updates -- leveling up from wild encounters - failed = walk_to_route1_from_lab(env, context); - if (failed){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - continue; // reset game - } - - auto num_levels = pokemon.level.size(); - uint16_t MAX_LEVELS = 3; - while(true){ - if (num_levels > MAX_LEVELS){ - env.log("RNG search not complete after 3 level-ups."); - finished = update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 5, 2, true - ); - break; - } - - env.log("Level: " + std::to_string(4 + pokemon.level.size())); - env.log("Speed EVs: " + std::to_string(pokemon.evs.back().speed)); - - int ret2 = autolevel_on_route1(env, context, pokemon, filters, BASE_STATS); - if (ret2 < 0){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - break; - }else if(ret2 == 1){ - env.log("Wild shiny found!"); - stats.wildshinies++; - send_program_notification( - env, - NOTIFICATION_SHINY, - COLOR_YELLOW, - "Wild Shiny found!", - {}, "", - env.console.video().snapshot(), - true - ); - if (TAKE_VIDEO){ - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); - } - if (!IGNORE_WILD_SHINIES){ - wildshiny_found = true; - break; - } - } - - // force the search to finish after enough level-ups - if (pokemon.level.size() > num_levels){ - num_levels = pokemon.level.size(); - search_hits = get_search_results(env.console, searcher, filters, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - RNG_CALIBRATION.set_hits(search_hits); - env.log("Number of search hits: " + std::to_string(search_hits.size())); - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 5, 2, true - ); - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - break; - } - } - + StarterRngAttempts attempts( + StarterRngTarget{ + .starter = STARTER, + .seed = TARGET_SEED, + .advances = ADVANCES, + .seed_match = seed_match, + }, + StarterRngSettings{ + .language = LANGUAGE, + .profile = PROFILE, + .ignore_wild_shinies = IGNORE_WILD_SHINIES, + .take_video = TAKE_VIDEO, + .identify_shiny = false, + .max_resets = [this]{ return uint64_t(MAX_RESETS); }, + .on_reset = nullptr, + .on_read = nullptr, + }, + StarterRngDisplays{.target = RNG_TARGET, .filters = RNG_FILTERS, .calibration = RNG_CALIBRATION}, + StarterRngNotifications{ + .shiny = NOTIFICATION_SHINY, + .status_update = NOTIFICATION_STATUS_UPDATE, + .error_recoverable = NOTIFICATION_ERROR_RECOVERABLE, + }, + stats + ); + StarterRngResult result = attempts.run(env, context); + if (result.outcome == StarterRngOutcome::no_matches){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "Failed to find any matches 5 times in a row. Check your seed and advances settings.", + env.console + ); } if (GO_HOME_WHEN_DONE){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h index 4e99f55bda..c4fec01083 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h @@ -18,6 +18,7 @@ #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_RngDisplays.h" #include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngAttempts.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -26,7 +27,7 @@ namespace PokemonFRLG{ class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ public: StarterRng_Descriptor(); - struct Stats; + using Stats = StarterRngStats; virtual std::unique_ptr make_stats() const override; }; @@ -44,36 +45,11 @@ class StarterRng : public SingleSwitchProgramInstance, private ConfigOption::Lis private: virtual void on_config_value_changed(void* object) override; - enum class Starter{ - bulbasaur, - squirtle, - charmander - }; - enum class GameVersion{ firered, leafgreen }; - bool walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool auto_battle_rival( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS - ); - - bool walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - int autolevel_on_route1( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS - ); - SectionDividerOption m_calibration_displays; RngTargetDisplay RNG_TARGET; RngFilterDisplay RNG_FILTERS; @@ -85,7 +61,7 @@ class StarterRng : public SingleSwitchProgramInstance, private ConfigOption::Lis EnumDropdownOption SOUND; SectionDividerOption m_target_settings; - EnumDropdownOption STARTER; + EnumDropdownOption STARTER; StringOption SEED; SimpleIntegerOptionADVANCES; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp new file mode 100644 index 0000000000..ed67e21b42 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp @@ -0,0 +1,845 @@ +/* Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattlePokemonDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_HardReset.h" +#include "PokemonFRLG_RngNavigation.h" +#include "PokemonFRLG_StarterRngAttempts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate + +const uint64_t CONTINUE_SCREEN_FRAMES = 200; + +const uint64_t INITIAL_ADVANCES_RADIUS = 1024; + +const uint8_t MAX_HISTORY_LENGTH = 10; + +const int16_t GENDER_THRESHOLD = 30; + +const std::set& starter_species(){ + static const std::set SPECIES_LIST = { "bulbasaur", "squirtle", "charmander" }; + return SPECIES_LIST; +} + +} + + +BaseStats starter_base_stats(StarterSpecies starter){ + switch (starter){ + case StarterSpecies::bulbasaur: + return { 45, 49, 49, 65, 65, 45 }; + case StarterSpecies::squirtle: + return { 44, 48, 65, 50, 64, 43 }; + case StarterSpecies::charmander: + return { 39, 52, 43, 60, 50, 65 }; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + +EVs rival_ev_yield(StarterSpecies starter){ + Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; + switch(starter){ + case StarterSpecies::bulbasaur: + evyield.speed = 1; // from charmander + break; + case StarterSpecies::squirtle: + evyield.spatk = 1; // from bulbasaur + break; + case StarterSpecies::charmander: + evyield.defense = 1; // from squirtle + } + return evyield; +} + +int steps_left_to_lab_door(StarterSpecies starter){ + switch(starter){ + case StarterSpecies::bulbasaur: + return 2; + case StarterSpecies::squirtle: + return 3; + case StarterSpecies::charmander: + return 4; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + + +StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits){ + if (hits.empty()){ + return StarterRngOutcome::shiny; + } + const bool on_target = std::any_of(hits.begin(), hits.end(), [&](const AdvRngState& hit){ + return have_hit_target(seed, advances, hit); + }); + return on_target ? StarterRngOutcome::shiny_on_target : StarterRngOutcome::shiny_off_target; +} + +std::optional reset_hit( + const RngUncertainHistory& uncertain, const RngCalibrationHistory& calibration, const std::vector& hits +){ + // update_history() clears `uncertain` only when it takes a hit, and adds + // the reset's last after the earlier ones it settles. + if (hits.empty() || !uncertain.results.empty() || calibration.results.empty()){ + return std::nullopt; + } + return calibration.results.back(); +} + + +StarterRngStats::StarterRngStats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , nonshiny(m_stats["Non-Shiny Hits"]) + , wildshinies(m_stats["Wild Shinies"]) + , errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Non-Shiny Hits", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Wild Shinies", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); +} + + +StarterRngAttempts::StarterRngAttempts( + StarterRngTarget target, + StarterRngSettings settings, + const StarterRngDisplays& displays, + const StarterRngNotifications& notifications, + StarterRngStats& stats +) + : m_target(std::move(target)) + , m_settings(std::move(settings)) + , m_displays(displays) + , m_notifications(notifications) + , m_stats(stats) + , m_base_stats(starter_base_stats(m_target.starter)) + , m_searcher(m_target.seed, m_target.advances, AdvRngMethod::Method1) + , m_launch_delay(INITIAL_LAUNCH_DELAY) +{} + + +StarterRngResult StarterRngAttempts::run(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("RNG Target: " + std::to_string(static_cast(m_target.starter))); + env.log("Target Seed: " + to_hex_string(m_target.seed)); + env.log("Target Advances: " + std::to_string(m_target.advances)); + + AdvPokemonResult target_result = m_searcher.generate_pokemon(); + m_displays.target.set_target(target_result, GENDER_THRESHOLD); + log_target_pokemon(env.console, target_result); + + m_calibrations = { + m_displays.calibration.seed_calibration / FRLG_FRAME_DURATION, + m_displays.calibration.csf_calibration, + m_displays.calibration.advances_calibration + }; + log_calibrations(env.console, m_calibrations, true); + + while (true){ + std::optional outcome = finished(env); + if (outcome){ + StarterRngResult result{.outcome = *outcome, .pokemon = std::nullopt}; + if (*outcome == StarterRngOutcome::target_hit){ + result.pokemon = target_result; + } + return result; + } + + reset_game(env, context); + + if (check_shiny_starter(env, context)){ + const StarterRngOutcome shiny = m_settings.identify_shiny ? identify_shiny_starter(env, context) : StarterRngOutcome::shiny; + const bool on_target = shiny == StarterRngOutcome::shiny_on_target; + report_read(true); + return StarterRngResult{.outcome = shiny, .pokemon = on_target ? std::optional(target_result) : std::nullopt}; + } + + run_attempt(env, context); + report_read(false); + } +} + +void StarterRngAttempts::report_read(bool shiny){ + if (m_settings.on_read){ + m_settings.on_read(RngResetRead{ + .resets = m_stats.resets.load(), + .hits = m_search_hits, + .hit = shiny ? std::nullopt : reset_hit(m_uncertain_history, m_calibration_history, m_search_hits), + .shiny = shiny, + }); + } +} + +std::optional StarterRngAttempts::finished(SingleSwitchProgramEnvironment& env){ + if (m_calibration_history.results.size() > 0){ + env.log("Checking for nonshiny target hit..."); + if (have_hit_target(m_target.seed, m_target.advances, m_calibration_history.results.back())){ + env.log("Target Hit!"); + m_stats.nonshiny++; + return StarterRngOutcome::target_hit; + } + env.log("Missed target."); + } + + if (m_failed_searches >= 5){ + env.log("Failed to find any matches 5 times in a row"); + return StarterRngOutcome::no_matches; + } + + if (m_stats.resets > m_settings.max_resets()){ + env.log("Max resets reached."); + return StarterRngOutcome::out_of_resets; + } + + if (m_wildshiny_found){ + return StarterRngOutcome::wild_shiny; + } + + return std::nullopt; +} + +void StarterRngAttempts::reset_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + send_program_status_notification( + env, m_notifications.status_update, + "Calibrating." + ); + env.update_stats(); + + + m_advances_radius = get_advances_radius(env.console, m_calibration_history, INITIAL_ADVANCES_RADIUS); + + const SeedMatch& seed_match = m_target.seed_match; + if (m_calibration_history.results.size() > 0){ + m_calibrations = get_calibrations(env.console, m_calibration_history, seed_match.seed_values, seed_match.seed_position, m_target.advances); + } + + // if previous resets had uncertain advances, slightly modify the seed delay to try to hit a different target + apply_seed_bump(m_calibrations, m_uncertain_history); + + uint64_t ingame_advances = m_target.advances - CONTINUE_SCREEN_FRAMES; + + RngTimings timings = prepare_timings( + env.console, PokemonFRLG_RngTarget::starters, + seed_match.seed_delay, CONTINUE_SCREEN_FRAMES, ingame_advances, + false, m_calibrations, + FIXED_SEED_OFFSET + ); + + env.log("Resetting Game..."); + reset_and_perform_blind_sequence( + env.console, context, + m_settings.language, PokemonFRLG_RngTarget::starters, + seed_match.seed_button, seed_match.extra_button, timings, + m_launch_delay, false, m_settings.profile + ); + m_stats.resets++; + m_search_hits.clear(); + if (m_settings.on_reset){ + m_settings.on_reset(StarterRngProgress{.resets = m_stats.resets.load(), .calibrations = m_calibrations}); + } + + m_displays.filters.reset(); + m_displays.calibration.set_calibrations(m_calibrations); + m_displays.calibration.reset_hits(); +} + +bool StarterRngAttempts::check_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + bool shiny_found = check_for_shiny(env.console, context, PokemonFRLG_RngTarget::starters); + + if (shiny_found){ + env.log("Shiny found!"); + m_stats.shinies++; + m_displays.calibration.hits.set("Shiny!"); + send_shiny_notification(env, context, "Shiny found!"); + } + return shiny_found; +} + +// On the shiny's summary, as check_for_shiny() leaves it: reads it as +// stage 1 of an attempt does and searches near the target. +StarterRngOutcome StarterRngAttempts::identify_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvObservedPokemon pokemon = read_summary(env.console, context, m_settings.language, starter_species()); + pokemon.level[0] = 5; + AdvRngFilters filters = observation_to_filters(pokemon, m_base_stats); + m_displays.filters.set(filters); + const std::vector hits = search(env, filters); + m_displays.calibration.set_hits(hits); + const StarterRngOutcome outcome = identify_shiny(m_target.seed, m_target.advances, hits); + env.log(std::format( + "Shiny starter: {} states near the target match it; {}.", hits.size(), + outcome == StarterRngOutcome::shiny_on_target ? "the target is one of them" + : outcome == StarterRngOutcome::shiny_off_target ? "the target isn't" : "not known if it is the target" + )); + return outcome; +} + +void StarterRngAttempts::send_shiny_notification( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, const std::string& title +){ + VideoSnapshot screen = env.console.video().snapshot(); + send_program_notification( + env, + m_notifications.shiny, + COLOR_YELLOW, + title, + {}, "", + screen, + true + ); + if (m_settings.take_video){ + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); + } +} + +std::vector StarterRngAttempts::search(SingleSwitchProgramEnvironment& env, AdvRngFilters& filters){ + m_search_hits = get_search_results( + env.console, m_searcher, filters, m_target.seed_match.seed_values, + m_target.advances, m_advances_radius, GENDER_THRESHOLD + ); + return m_search_hits; +} + +void StarterRngAttempts::record_error(SingleSwitchProgramEnvironment& env, const std::vector& search_hits){ + update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 1, 2, true + ); + m_stats.errors++; +} + + +void StarterRngAttempts::run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Stage 1: initial search -- starter received + AdvObservedPokemon pokemon = read_summary(env.console, context, m_settings.language, starter_species()); + pokemon.level[0] = 5; + AdvRngFilters filters = observation_to_filters(pokemon, m_base_stats); + m_displays.filters.set(filters); + + std::vector search_hits = search(env, filters); + m_displays.calibration.set_hits(search_hits); + bool finished = update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 1 + ); + if (finished){ + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); + return; + } + + if (!run_rival_stage(env, context, pokemon, filters, search_hits)){ + return; + } + run_route1_stage(env, context, pokemon, filters, search_hits); +} + +// Returns false when the attempt ends here. +bool StarterRngAttempts::run_rival_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits +){ + // Stage 2: first search update -- post-rival-battle + bool failed = walk_to_rival_battle(env, context); + if (failed){ + record_error(env, search_hits); + return false; // reset game + } + + failed = auto_battle_rival(env, context, pokemon, filters); + if (failed){ + record_error(env, search_hits); + return false; // reset game + } + if (pokemon.level.size() > 1){ + search_hits = search(env, filters); + m_displays.calibration.set_hits(search_hits); + env.log("Number of search hits: " + std::to_string(search_hits.size())); + bool finished = update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 5 + ); + if (finished){ + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); + return false; + } + } + return true; +} + +void StarterRngAttempts::run_route1_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits +){ + // Stage 3: subsequent search updates -- leveling up from wild encounters + bool failed = walk_to_route1_from_lab(env, context); + if (failed){ + record_error(env, search_hits); + return; // reset game + } + + auto num_levels = pokemon.level.size(); + uint16_t MAX_LEVELS = 3; + while(true){ + if (num_levels > MAX_LEVELS){ + env.log("RNG search not complete after 3 level-ups."); + update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 5, 2, true + ); + return; + } + + env.log("Level: " + std::to_string(4 + pokemon.level.size())); + env.log("Speed EVs: " + std::to_string(pokemon.evs.back().speed)); + + int ret2 = autolevel_on_route1(env, context, pokemon, filters); + if (ret2 < 0){ + record_error(env, search_hits); + return; + }else if(ret2 == 1){ + if (stop_on_wild_shiny(env, context)){ + return; + } + } + + // force the search to finish after enough level-ups + if (pokemon.level.size() > num_levels){ + finish_search(env, filters, search_hits); + return; + } + } +} + +// Returns whether the attempts stop for the wild shiny. +bool StarterRngAttempts::stop_on_wild_shiny(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Wild shiny found!"); + m_stats.wildshinies++; + send_shiny_notification(env, context, "Wild Shiny found!"); + if (!m_settings.ignore_wild_shinies){ + m_wildshiny_found = true; + return true; + } + return false; +} + +void StarterRngAttempts::finish_search( + SingleSwitchProgramEnvironment& env, AdvRngFilters& filters, std::vector& search_hits +){ + search_hits = search(env, filters); + m_displays.calibration.set_hits(search_hits); + env.log("Number of search hits: " + std::to_string(search_hits.size())); + update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 5, 2, true + ); + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); +} + + +bool StarterRngAttempts::walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // return to the overworld + pbf_mash_button(context, BUTTON_B, 5000ms); + int num_steps_to_the_left = steps_left_to_lab_door(m_target.starter); + + // dodge rival + pbf_move_left_joystick(context, {0, -1}, 40ms, 460ms); + pbf_move_left_joystick(context, {0, -1}, 100ms, 400ms); + + // line up with the doorway + pbf_move_left_joystick(context, {-1, 0}, 40ms, 460ms); // pivot left + for (int i=0; i( + env.console, context, + [](ProControllerContext& context){ + for (int i=0; i<5; i++){ + ssf_press_left_joystick(context, {0, -1}, 0ms, 20000ms, 0ms); + ssf_mash1_button(context, BUTTON_B, 20000ms); + } + }, + { black_screen } + ); + + bool failed = ret < 0; + if (failed){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "walk_to_rival_battle(): failed to initiate battle." + ); + } + return failed; +} + +// From the start of the rival battle: waits for the battle menu, uses the +// first move and waits out Oak's tutorial. Returns true on failure. +bool StarterRngAttempts::start_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // detect the battle menu + BattleMenuWatcher battle_ready(COLOR_RED); + context.wait_for_all_requests(); + int ret1 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 30s); + }, + { battle_ready } + ); + if (ret1 < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "auto_battle_rival(): failed to detect the battle menu." + ); + return true; + } + env.log("Battle started. Using first move..."); + + // perform the first move and get through Oak's dialogue, + // which messes up most detectors when it dims the screen + pbf_mash_button(context, BUTTON_A, 1000ms); // execute first move + context.wait_for_all_requests(); + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 30s); + }, + { battle_ready } + ); + if (ret2 < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "auto_battle_rival(): failed to detect the battle menu." + ); + return true; + } + env.log("Oak tutorial dialogue finished. Mashing A..."); + return false; +} + +bool StarterRngAttempts::auto_battle_rival( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters +){ + Pokemon::EVs evyield = rival_ev_yield(m_target.starter); + + if (start_rival_battle(env, context)){ + return true; + } + + // mash A until somebody faints + BattleOpponentFaintWatcher player_won(COLOR_RED); + BattleFaintWatcher player_lost(COLOR_RED); + context.wait_for_all_requests(); + int ret3 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 300s); + }, + { player_won, player_lost } + ); + + switch(ret3){ + case 0: + env.log("Won battle against rival. Watching for level-up stats..."); + break; + case 1: + env.log("Lost battle against rival."); + pbf_mash_button(context, BUTTON_B, 20s); // exit battle and dialogue + return false; + default: + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "auto_battle_rival(): no fainting detected with 5 minutes." + ); + return true; + } + + return read_rival_level_up(env, context, pokemon, filters, evyield); +} + +// After winning the rival battle: reads the level-up stats and leaves the +// battle. Returns true on failure. +bool StarterRngAttempts::read_rival_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield +){ + // slowly advance dialog until level-up stats are visible + BattleLevelUpWatcher level_up_stats(COLOR_RED, BattleLevelUpDialog::stats, m_settings.language); + BlackScreenWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret4 = run_until( + env.console, context, + [](ProControllerContext& context){ + for(int i=0; i<60; i++){ + pbf_press_button(context, BUTTON_A, 200ms, 1800ms); + } + }, + { level_up_stats, black_screen } + ); + + switch(ret4){ + case 0: + env.log("Level-up stats detected."); + break; + case 1: + env.log("Battle exited without detecting level-up stats"); + return true; // will cause issues with keeping track of level and EVs + default: + env.log("auto_battle_rival(): no recognized state within 2 minutes of winning battle."); + return true; + } + + read_rival_level_up_stats(env, pokemon, filters, evyield); + + // exit battle + pbf_mash_button(context, BUTTON_B, 20s); + context.wait_for_all_requests(); + + return false; +} + +void StarterRngAttempts::read_rival_level_up_stats( + SingleSwitchProgramEnvironment& env, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield +){ + // read stats + BattleLevelUpReader reader(COLOR_RED); + VideoOverlaySet overlays(env.console.overlay()); + reader.make_overlays(overlays); + + env.log("Reading stats..."); + VideoSnapshot screen = env.console.video().snapshot(); + StatReads stats = reader.read_stats(env.logger(), screen); + + update_filters(filters, pokemon, stats, evyield, m_base_stats); + m_displays.filters.set(filters); +} + + + +bool StarterRngAttempts::walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // exit the lab + env.log("Exiting the lab..."); + BlackScreenWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, {0, -1}, 10s, 0ms); + }, + { black_screen } + ); + + if (ret < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "walk_to_route1_from_lab(): failed to exit lab." + ); + return true; + } + + env.log("Lab exited. Walking to Route 1..."); + pbf_wait(context, 5000ms); + pbf_move_left_joystick(context, {-1, 0}, 1280ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 3150ms, 300ms); + pbf_move_left_joystick(context, {+1, 0}, 330ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 720ms, 300ms); + context.wait_for_all_requests(); + return false; +} + +bool StarterRngAttempts::walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // exit the house + env.log("Exiting the house..."); + BlackScreenWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); + pbf_move_left_joystick(context, {-1, 0}, 900ms, 300ms); + pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); + }, + { black_screen } + ); + + if (ret < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "walk_to_route1_from_home(): failed to exit the house." + ); + return true; + } + + env.log("House exited. Walking to Route 1..."); + pbf_wait(context, 5s); + pbf_move_left_joystick(context, {+1, 0}, 1370ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 1450ms, 300ms); + pbf_move_left_joystick(context, {+1, 0}, 300ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 1250ms, 300ms); + + return false; +} + +int StarterRngAttempts::autolevel_on_route1( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters +){ + Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; + + env.log("Arrived at Route 1."); + bool leftright = true; + context.wait_for_all_requests(); + + while (true){ + int ret = trigger_route1_encounter(env, context, leftright); + if (ret < 0){ + return -1; + } + + if (ret == 1){ // shiny + return 1; + } + + // auto battle + BattleResult ret2 = spam_first_move(env.console, context); + + switch (ret2){ + case BattleResult::opponentfainted: + env.log("Opponent fainted."); + evyield.speed++; // always rattata or pidgey + leftright = !leftright; + if (read_wild_level_up(env, context, pokemon, filters, evyield)){ + return 0; + } + continue; + case BattleResult::playerfainted: + if (return_to_route1_after_faint(env, context)){ + return -1; + } + leftright = true; + continue; + case BattleResult::outofpp: + case BattleResult::unknown: + default: + return -1; + } + } +} + +// Spins in the grass until a wild encounter. Returns grass_spin()'s result. +int StarterRngAttempts::trigger_route1_encounter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool leftright +){ + // trigger encounter + env.log("Triggering wild encounters..."); + int ret = grass_spin(env.console, context, leftright); + if (ret < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "autolevel_on_route1(): failed to trigger encounter." + ); + } + return ret; +} + +// After the player's Pokemon fainted: walks from home back to Route 1. +// Returns true on failure. +bool StarterRngAttempts::return_to_route1_after_faint(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Pokemon fainted. Mashing B through dialogues..."); + pbf_mash_button(context, BUTTON_B, 30s); // skip through a few transitions and lots of dialogue + if (walk_to_route1_from_home(env, context)){ + return true; + } + context.wait_for_all_requests(); + return false; +} + +// After a wild Pokemon fainted: reads the level-up stats if they show and +// leaves the battle. Returns whether the stats were read. +bool StarterRngAttempts::read_wild_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield +){ + BattleLevelUpWatcher level_up(COLOR_RED, BattleLevelUpDialog::stats, m_settings.language); + BlackScreenWatcher black_screen(COLOR_RED); + BattleLevelUpReader reader; + + context.wait_for_all_requests(); + int ret3 = run_until( + env.console, context, + [](ProControllerContext& context){ + for (int i=0; i<5; i++){ + pbf_press_button(context, BUTTON_B, 200ms, 1800ms); + } + }, + { level_up, black_screen } + ); + + switch (ret3){ + case 0:{ + env.log("Level-up stats detected. Reading stats..."); + VideoSnapshot screen = env.console.video().snapshot(); + Pokemon::StatReads stats = reader.read_stats(env.logger(), screen); + update_filters(filters, pokemon, stats, evyield, m_base_stats); + m_displays.filters.set(filters); + exit_wild_battle(env.console, context, false, true); + return true; + } + case -1: + exit_wild_battle(env.console, context, false, true); + [[fallthrough]]; + default: + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + return false; + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h new file mode 100644 index 0000000000..f541f1f9f9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h @@ -0,0 +1,263 @@ +/* Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + * Starter RNG's reset, calibrate and attempt loop, for one target. The + * Starter RNG program runs it with its options, stats and displays; another + * program (AutoStory) can run it with its own. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngAttempts_H +#define PokemonAutomation_PokemonFRLG_StarterRngAttempts_H + +#include +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_AdvRng.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_SeedsDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +enum class StarterSpecies{ + bulbasaur, + squirtle, + charmander +}; + +// The species' base stats. +BaseStats starter_base_stats(StarterSpecies starter); +// The EVs the rival's starter gives when the player's "starter" beats it. +EVs rival_ev_yield(StarterSpecies starter); +// After taking "starter" from its ball and dodging the rival, the steps +// left that line the player up with the lab's door. +int steps_left_to_lab_door(StarterSpecies starter); + + +struct StarterRngStats : public StatsTracker{ + StarterRngStats(); + + std::atomic& resets; + std::atomic& shinies; + std::atomic& nonshiny; + std::atomic& wildshinies; + std::atomic& errors; +}; + + +struct StarterRngTarget{ + StarterSpecies starter = StarterSpecies::bulbasaur; + uint16_t seed = 0; + uint64_t advances = 0; + // The seed's entry in the seeds database (found). + SeedMatch seed_match; +}; + +// Where an attempt is after a reset: the resets so far, and the +// calibration that reset was timed with. +struct StarterRngProgress{ + uint64_t resets = 0; + RngCalibrations calibrations{}; +}; + +// What a reset's reads came to, once its search is done. Gift RNG's +// attempts report theirs this way too. +struct RngResetRead{ + uint64_t resets = 0; + // The states near the target that the Pokemon read matches. + std::vector hits; + // The one the calibration took as hit; none when it couldn't tell. + std::optional hit; + // Shiny right after the reset; `hits` are then its summary's. + bool shiny = false; +}; + +// The state update_history() took as hit for a reset whose last search +// found `hits`: the newest in `calibration`. It takes none for no hits, and +// none for a tie between advances, which it leaves in `uncertain`. +std::optional reset_hit( + const RngUncertainHistory& uncertain, const RngCalibrationHistory& calibration, const std::vector& hits +); + +struct StarterRngSettings{ + Language language = Language::None; + // The Switch profile's position on the user selection screen; 0 for + // the default. + uint8_t profile = 0; + bool ignore_wild_shinies = false; + // Record a video when a shiny is found. + bool take_video = false; + // After a shiny, read its summary and search for the state hit, to + // tell whether it was the target (shiny_on_target or + // shiny_off_target). Off, the attempts end on the shiny at once. + bool identify_shiny = false; + // Read before each reset, since Starter RNG lets the user change it + // while running. + std::function max_resets; + // Called after each reset, if set, for a caller that logs the attempts. + std::function on_reset; + // Called after each reset's reads, if set, as on_reset is. + std::function on_read; +}; + +// Where the attempts show the target, the filters read so far and the +// calibration. The calibration display also holds the starting +// calibration. +struct StarterRngDisplays{ + RngTargetDisplay& target; + RngFilterDisplay& filters; + RngCalibrationDisplay& calibration; +}; + +struct StarterRngNotifications{ + EventNotificationOption& shiny; + EventNotificationOption& status_update; + EventNotificationOption& error_recoverable; +}; + + +enum class StarterRngOutcome{ + shiny, // The starter was shiny after a reset; not known if on the target. + shiny_on_target, // Shiny, and the target is among the states its stats match. + shiny_off_target, // Shiny, and the states its stats match aren't the target. + target_hit, // The calibration shows the target was hit; not shiny. + wild_shiny, // A wild shiny on Route 1, with ignore_wild_shinies off. + out_of_resets, // More resets than max_resets. + no_matches, // 5 searches in a row matched no state near the target. +}; + +// A shiny's outcome from the states its stats match near the target +// ("hits"): on the target if it is among them, off it if not, and just +// shiny if none match. +StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits); + +struct StarterRngResult{ + StarterRngOutcome outcome = StarterRngOutcome::out_of_resets; + // The target's PID, nature and IVs, on target_hit and shiny_on_target. + std::optional pokemon; +}; + + +class StarterRngAttempts{ +public: + StarterRngAttempts( + StarterRngTarget target, + StarterRngSettings settings, + const StarterRngDisplays& displays, + const StarterRngNotifications& notifications, + StarterRngStats& stats + ); + StarterRngAttempts(const StarterRngAttempts&) = delete; + StarterRngAttempts& operator=(const StarterRngAttempts&) = delete; + + // From the HOME menu with the game closed: resets the game and takes + // the starter at the target's timing until the outcome is known. Each + // non-shiny starter is read, battled against the rival and leveled on + // Route 1 to find the state hit and recalibrate. Ends in the game on + // the last screen the attempts reached. Call once per object. + StarterRngResult run(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + std::optional finished(SingleSwitchProgramEnvironment& env); + void reset_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool check_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + StarterRngOutcome identify_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void send_shiny_notification(SingleSwitchProgramEnvironment& env, ProControllerContext& context, const std::string& title); + std::vector search(SingleSwitchProgramEnvironment& env, AdvRngFilters& filters); + void record_error(SingleSwitchProgramEnvironment& env, const std::vector& search_hits); + void report_read(bool shiny); + + void run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool run_rival_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits + ); + void run_route1_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits + ); + bool stop_on_wild_shiny(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void finish_search( + SingleSwitchProgramEnvironment& env, AdvRngFilters& filters, std::vector& search_hits + ); + + bool walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool start_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool auto_battle_rival( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters + ); + bool read_rival_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield + ); + void read_rival_level_up_stats( + SingleSwitchProgramEnvironment& env, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield + ); + + bool walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + int trigger_route1_encounter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool leftright + ); + bool return_to_route1_after_faint(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + int autolevel_on_route1( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters + ); + bool read_wild_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield + ); + + const StarterRngTarget m_target; + const StarterRngSettings m_settings; + StarterRngDisplays m_displays; + StarterRngNotifications m_notifications; + StarterRngStats& m_stats; + const BaseStats m_base_stats; + + AdvRngSearcher m_searcher; + RngCalibrations m_calibrations{}; + Milliseconds m_launch_delay; + RngUncertainHistory m_uncertain_history; + RngCalibrationHistory m_calibration_history; + uint64_t m_advances_radius = 0; + bool m_wildshiny_found = false; + uint16_t m_failed_searches = 0; + // The last search's hits, for on_read. + std::vector m_search_hits; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp new file mode 100644 index 0000000000..40d580b6a8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp @@ -0,0 +1,117 @@ +/* Starter RNG Console Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonFRLG_StarterRngConsoleSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngPlanLogger::RngPlanLogger(ConsoleHandle& console) + : m_console(console) +{} + +void RngPlanLogger::log(const std::string& msg, Color color){ + m_console.log(msg, color); + if (msg.starts_with("RngPlan: result")){ + m_console.overlay().add_log(msg); + } +} + + +std::function reset_line_logger( + ConsoleHandle& console, std::string_view program, const RngAttempt& attempt, const SeedMatch& seed_match, uint64_t max_resets +){ + RngResetLine line{ + .program = program, .max_resets = max_resets, + .target_seed = attempt.target.seed.seed, .target_advances = attempt.target.advances, + .seed_values = seed_match.seed_values, .seed_position = seed_match.seed_position, + .read = {}, + }; + return [&console, line](const RngResetRead& read){ + RngResetLine reset = line; + reset.read = read; + const std::string text = rng_reset_line(reset); + console.log(text); + console.overlay().add_log(text); + }; +} + + +ConsoleStarterRngSteps::ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications +) + : m_env(env) + , m_context(context) + , m_settings(settings) + , m_notifications(notifications) + // TODO: LeafGreen, once AutoStory plays it. + , m_seeds(seeds_json_path(true, settings.language)) +{ + m_calibration_display.set_calibrations(settings.calibration); +} + +WallClock ConsoleStarterRngSteps::now(){ + return current_time(); +} + +StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ + // Starter RNG's default Nearby Seed Radius. + const int SEED_RADIUS = 5; + const SeedMatch seed_match = m_seeds.find_seed(attempt.target.seed.seed, m_settings.sound, SEED_RADIUS); + if (!seed_match.found){ + throw InternalProgramError(&m_env.logger(), PA_CURRENT_FUNCTION, "The plan's seed isn't in the seed list it came from."); + } + + StarterRngStats stats; + StarterRngAttempts attempts( + StarterRngTarget{ + .starter = StarterSpecies::squirtle, + .seed = attempt.target.seed.seed, + .advances = attempt.target.advances, + .seed_match = seed_match, + }, + StarterRngSettings{ + .language = m_settings.language, + .profile = 0, + .ignore_wild_shinies = true, + .take_video = false, + .identify_shiny = true, + .max_resets = [deadline = call.deadline, max_resets = call.max_resets]{ + return current_time() >= deadline ? uint64_t(0) : max_resets; + }, + .on_reset = call.on_reset, + .on_read = reset_line_logger(m_env.console, "Starter RNG", attempt, seed_match, call.max_resets), + }, + StarterRngDisplays{ + .target = m_target_display, + .filters = m_filter_display, + .calibration = m_calibration_display, + }, + m_notifications, + stats + ); + try{ + return attempts.run(m_env, m_context); + }catch (OperationFailedException& e){ + // Starter RNG refuses timings it can't press (check_timings()) this + // way; a failure in the game sends an error report. + if (e.error_report_mode() != ErrorReportMode::NO_ERROR_REPORT){ + throw; + } + throw StarterRngTimingsRefused(e.message()); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h new file mode 100644 index 0000000000..11a7a2adc1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h @@ -0,0 +1,93 @@ +/* Starter RNG Console Steps + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's steps (PokemonFRLG_StarterRngLoop.h) on the + * console, and the log it writes to. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H +#define PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H + +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngDisplays.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The console's log, with the loop's result lines also on the stream's +// overlay log. Its state lines, too long for it, stay in the log. +class RngPlanLogger : public Logger{ +public: + explicit RngPlanLogger(ConsoleHandle& console); + virtual void log(const std::string& msg, Color color = Color()) override; + +private: + ConsoleHandle& m_console; +}; + + +// An on_read for `program`'s tries at `attempt`, which puts each reset's +// line (rng_reset_line()) on the console's log and its stream's overlay +// log. `program` is a literal, as "Starter RNG". +std::function reset_line_logger( + ConsoleHandle& console, std::string_view program, const RngAttempt& attempt, const SeedMatch& seed_match, uint64_t max_resets +); + + +struct StarterRngConsoleSettings{ + Language language = Language::English; + SoundSetting sound = SoundSetting::Mono; + // The calibration the first try starts from. + RngCalibrations calibration = {}; +}; + +// The loop's steps on the console, with Starter RNG's displays, stats and +// calibration kept here (AutoStory doesn't show them). Each try after the +// first starts from the calibration the last one ended with, and each +// reset puts one line (rng_reset_line()) on the log and the stream's +// overlay log. Squirtle, FireRed, the Switch's default profile. +class ConsoleStarterRngSteps : public StarterRngLoopSteps{ +public: + ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications + ); + + virtual WallClock now() override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; + +private: + SingleSwitchProgramEnvironment& m_env; + ProControllerContext& m_context; + StarterRngConsoleSettings m_settings; + StarterRngNotifications m_notifications; + SeedsDatabase m_seeds; + RngTargetDisplay m_target_display; + RngFilterDisplay m_filter_display; + RngCalibrationDisplay m_calibration_display; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp new file mode 100644 index 0000000000..a8a1d94f8c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp @@ -0,0 +1,337 @@ +/* Starter RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_StarterRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny_on_target: + return RngAttemptOutcome::SHINY; + case StarterRngOutcome::shiny: + case StarterRngOutcome::shiny_off_target: + return RngAttemptOutcome::SHINY_OFF_TARGET; + case StarterRngOutcome::target_hit: + return RngAttemptOutcome::HIT_NOT_SHINY; + case StarterRngOutcome::wild_shiny: + case StarterRngOutcome::out_of_resets: + case StarterRngOutcome::no_matches: + return RngAttemptOutcome::MISSED; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + +std::string starter_rng_outcome_name(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: + return "shiny"; + case StarterRngOutcome::shiny_on_target: + return "shiny_on_target"; + case StarterRngOutcome::shiny_off_target: + return "shiny_off_target"; + case StarterRngOutcome::target_hit: + return "target_hit"; + case StarterRngOutcome::wild_shiny: + return "wild_shiny"; + case StarterRngOutcome::out_of_resets: + return "out_of_resets"; + case StarterRngOutcome::no_matches: + return "no_matches"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + + +namespace{ + +// "-" for none. +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text.empty() ? "-" : text; +} + +std::string clock_text(Milliseconds time){ + const int64_t seconds = std::chrono::duration_cast(time).count(); + return std::format("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60); +} + +std::string calibration_text(const std::optional& calibration){ + if (!calibration){ + return "-"; + } + return std::format("{:.2f}/{:.2f}/{:.2f}", calibration->seed_offset, calibration->csf_offset, calibration->ingame_offset); +} + +} + +std::string rng_log_state(const RngLoopState& state){ + return std::format( + "RngPlan: state attempt={}/{} try={}/{} reset={}/{} seed={:04X} advances={} sids={} ruled_out={} " + "attempt_time={}/{} total_time={}/{} calibration={}", + state.attempt, state.attempts, state.try_number, state.tries, state.resets, state.max_resets, + state.seed, state.advances, join_sids(state.sids), join_sids(state.ruled_out), + clock_text(state.attempt_time), clock_text(state.attempt_cap), + clock_text(state.total_time), clock_text(state.total_cap), + calibration_text(state.calibration) + ); +} + + +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed){ + const auto found = std::find(seed_values.begin(), seed_values.end(), seed); + if (target_position < 0 || found == seed_values.end()){ + return std::nullopt; + } + return int(found - seed_values.begin()) - target_position; +} + +namespace{ + +std::string seed_text(const RngResetLine& line, uint16_t seed){ + if (seed == line.target_seed){ + return std::format("seed {:04x} = target", seed); + } + const std::optional frames = seed_frame_offset(line.seed_values, line.seed_position, seed); + if (!frames){ + return std::format("seed {:04x} (not near the target)", seed); + } + return std::format( + "seed {:04x} ({:+} frame{} {})", seed, *frames, std::abs(*frames) == 1 ? "" : "s", *frames > 0 ? "late" : "early" + ); +} + +std::string advance_text(uint64_t target, uint64_t advance){ + if (advance == target){ + return std::format("advance {}", advance); + } + return std::format("advance {} (target {}, {:+})", advance, target, int64_t(advance) - int64_t(target)); +} + +size_t distinct_states(const std::vector& hits){ + std::set> states; + for (const AdvRngState& hit : hits){ + states.emplace(hit.seed, hit.advance); + } + return states.size(); +} + +std::string shiny_text(const RngResetLine& line){ + const std::vector& hits = line.read.hits; + const bool on_target = std::any_of(hits.begin(), hits.end(), [&](const AdvRngState& hit){ + return have_hit_target(line.target_seed, line.target_advances, hit); + }); + if (on_target){ + return seed_text(line, line.target_seed) + ", " + advance_text(line.target_advances, line.target_advances) + ". HIT, shiny!"; + } + return hits.empty() ? "shiny, not known if on the target." : "shiny, not on the target."; +} + +} + +std::string rng_reset_line(const RngResetLine& line){ + const RngResetRead& read = line.read; + const std::string head = std::format("{} try {}/{}: ", line.program, read.resets, line.max_resets); + if (read.shiny){ + return head + shiny_text(line); + } + const size_t states = distinct_states(read.hits); + std::optional hit = read.hit; + if (!hit && states == 1){ + hit = read.hits.front(); + } + if (!hit){ + return head + (states == 0 + ? std::string("no match read (stats fit no seed/advance).") + : std::format("{} possible matches, can't tell which.", states)); + } + const bool on_target = have_hit_target(line.target_seed, line.target_advances, *hit); + return head + seed_text(line, hit->seed) + ", " + advance_text(line.target_advances, hit->advance) + + (on_target ? ". HIT, not shiny." : ". Missed."); +} + + +namespace{ + +std::optional loop_end(RngPlanStep step){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return std::nullopt; + case RngPlanStep::GOT_SHINY: + return StarterRngLoopEnd::SHINY; + case RngPlanStep::GOT_SHINY_OFF_TARGET: + return StarterRngLoopEnd::SHINY_OFF_TARGET; + case RngPlanStep::GOT_TARGET: + return StarterRngLoopEnd::TARGET; + case RngPlanStep::OUT_OF_ATTEMPTS: + return StarterRngLoopEnd::OUT_OF_ATTEMPTS; + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: + return StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); +} + +// The loop's state lines and tries, across the attempts. +class LoopLog{ +public: + LoopLog(Logger& logger, const RngPlanTracker& tracker, const StarterRngLoopLimits& limits, WallClock start) + : m_logger(logger) + , m_tracker(tracker) + , m_limits(limits) + , m_start(start) + , m_start_sids(tracker.remaining_sids()) + {} + + // A new try of the tracker's current attempt, starting at `now`. + void begin_try(WallClock now){ + const size_t index = m_tracker.attempt_index(); + m_try = (m_tries_of && *m_tries_of == index) ? m_try + 1 : 1; + m_tries_of = index; + m_try_start = now; + } + size_t try_number() const{ + return m_try; + } + + void log_state(WallClock now, uint64_t resets, const std::optional& calibration){ + const RngAttempt& attempt = m_tracker.current_attempt(); + std::vector ruled_out; + for (uint16_t sid : m_start_sids){ + const std::vector& left = m_tracker.remaining_sids(); + if (std::find(left.begin(), left.end(), sid) == left.end()){ + ruled_out.push_back(sid); + } + } + m_logger.log(rng_log_state(RngLoopState{ + .attempt = m_tracker.attempt_index() + 1, .attempts = m_tracker.attempt_count(), + .try_number = m_try, .tries = m_limits.max_retries + 1, + .resets = resets, .max_resets = m_limits.max_resets, + .seed = attempt.target.seed.seed, .advances = attempt.target.advances, + .sids = attempt.sids, .ruled_out = std::move(ruled_out), + .attempt_time = std::chrono::duration_cast(now - m_try_start), .attempt_cap = m_limits.attempt_time, + .total_time = std::chrono::duration_cast(now - m_start), .total_cap = m_limits.total_time, + .calibration = calibration, + })); + } + +private: + Logger& m_logger; + const RngPlanTracker& m_tracker; + const StarterRngLoopLimits& m_limits; + const WallClock m_start; + const std::vector m_start_sids; + std::optional m_tries_of; + size_t m_try = 0; + WallClock m_try_start; +}; + +// What one try came to, for the tracker and the result line. +struct TryOutcome{ + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + std::string detail; + std::optional pokemon; +}; + +// Runs one try of the tracker's current attempt, logging its state lines. +StarterRngResult run_try( + LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + log.begin_try(start); + log.log_state(start, 0, std::nullopt); + StarterRngAttemptCall call{ + .index = tracker.attempt_index(), + .deadline = deadline, + .max_resets = limits.max_resets, + .on_reset = [&](const StarterRngProgress& progress){ + log.log_state(steps.now(), progress.resets, progress.calibrations); + }, + }; + return steps.run_attempt(tracker.current_attempt(), call); +} + +// run_try(), with Starter RNG refusing the attempt's timings as an attempt +// that can't run. Other errors, a setup error such as no sound included, +// would fail every attempt the same way, so they end the loop. +TryOutcome run_try_outcome( + Logger& logger, LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + try{ + const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); + // The deadline ends a try as out of resets. + const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; + return TryOutcome{ + .outcome = plan_outcome(attempt.outcome), + .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), + .pokemon = attempt.pokemon, + }; + }catch (StarterRngTimingsRefused& e){ + logger.log(std::format("RngPlan: attempt {} can't run: {}", tracker.attempt_index() + 1, e.message()), COLOR_RED); + return TryOutcome{.outcome = RngAttemptOutcome::UNUSABLE, .detail = "setup_error", .pokemon = std::nullopt}; + } +} + +} + + +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +){ + StarterRngLoopResult result; + const WallClock loop_start = steps.now(); + const WallClock total_deadline = loop_start + limits.total_time; + LoopLog log(logger, tracker, limits, loop_start); + while (true){ + std::optional end = loop_end(tracker.step()); + if (end){ + result.end = *end; + break; + } + const WallClock start = steps.now(); + if (start >= total_deadline){ + logger.log("RngPlan: out of time before attempt " + std::to_string(tracker.attempt_index() + 1)); + result.end = StarterRngLoopEnd::OUT_OF_TIME; + break; + } + const size_t index = tracker.attempt_index(); + const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); + const TryOutcome attempt = run_try_outcome(logger, log, tracker, steps, limits, start, deadline); + result.attempts_run++; + const RngPlanStep step = tracker.record(attempt.outcome); + logger.log(rng_log_result(RngResultLog{ + .index = index, .try_number = log.try_number(), .outcome = attempt.outcome, + .detail = attempt.detail, .pokemon = attempt.pokemon, + .next = rng_plan_next(step, index, tracker.attempt_index()), + })); + } + result.remaining_sids = tracker.remaining_sids(); + result.sid = tracker.confirmed_sid(); + if (result.end == StarterRngLoopEnd::SHINY && result.sid){ + logger.log(rng_log_confirmed(tid, *result.sid, sid_helper_candidates)); + } + return result; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h new file mode 100644 index 0000000000..bae408320b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h @@ -0,0 +1,182 @@ +/* Starter RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + * An RNG plan's attempts (PokemonFRLG_RngPlan.h), each run with Starter + * RNG's attempt loop (StarterRngAttempts), until one comes out shiny or + * the plan, its retries or the time run out. Its "RngPlan: state" and + * "RngPlan: result" lines are listed with the plan's in + * PokemonFRLG_RngPlanLog.h. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoop_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoop_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the +// target is SHINY; one off it, or not known to be on it, is +// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, +// which the plan runs again. +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); +// As the result line names it: "shiny_on_target", "target_hit", +// "out_of_resets"... (The loop says "attempt_deadline" instead of +// "out_of_resets" once the try's deadline has passed.) +std::string starter_rng_outcome_name(StarterRngOutcome outcome); + + +// Where the loop is, for an "RngPlan: state" line. +struct RngLoopState{ + // From 1, of `attempts`. + size_t attempt = 1; + size_t attempts = 0; + // From 1, of `tries`. + size_t try_number = 1; + size_t tries = 0; + uint64_t resets = 0; + uint64_t max_resets = 0; + uint16_t seed = 0; + uint64_t advances = 0; + // The SIDs the attempt is shiny for, and those ruled out so far. + std::vector sids; + std::vector ruled_out; + Milliseconds attempt_time = Milliseconds(0); + Milliseconds attempt_cap = Milliseconds(0); + Milliseconds total_time = Milliseconds(0); + Milliseconds total_cap = Milliseconds(0); + // The calibration of the last reset, in frames; none before the first. + std::optional calibration; +}; +std::string rng_log_state(const RngLoopState& state); + + +// A reset's reads, for its one line on the stream's log. +struct RngResetLine{ + // "Starter RNG" or "Gift RNG". + std::string_view program; + uint64_t max_resets = 0; + uint16_t target_seed = 0; + uint64_t target_advances = 0; + // The seeds near the target, in the order of their delays, and the + // target's place among them (SeedMatch). + std::vector seed_values; + int16_t seed_position = -1; + RngResetRead read; +}; +// The frames from the target seed to `seed` among `seed_values`: +1 for +// the seed a frame later. None when either isn't among them. +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed); +// As "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed." +std::string rng_reset_line(const RngResetLine& line); + + +struct StarterRngLoopLimits{ + // An attempt makes no more resets after this long, and counts as missed. + Milliseconds attempt_time = Milliseconds(0); + // No attempt starts after this long. + Milliseconds total_time = Milliseconds(0); + // Resets per try of an attempt. + uint64_t max_resets = 0; + // The tracker's retries of a missed attempt, for the state lines. + size_t max_retries = 0; +}; + +// Starter RNG refused an attempt's timings (check_timings()). The loop +// records the attempt as unusable and moves on; any other error, a +// UserSetupError included, stops the loop. +class StarterRngTimingsRefused : public Exception{ +public: + explicit StarterRngTimingsRefused(std::string message) : m_message(std::move(message)) {} + virtual const char* name() const override{ return "StarterRngTimingsRefused"; } + virtual std::string message() const override{ return m_message; } + +private: + std::string m_message; +}; + +// One try of an attempt, as the loop asks the steps for it. +struct StarterRngAttemptCall{ + // From 0. + size_t index = 0; + // No reset after this. + WallClock deadline; + uint64_t max_resets = 0; + // To call after each reset. + std::function on_reset; +}; + +// The game steps of the loop, injected so that its decisions run in tests +// without a Switch. +class StarterRngLoopSteps{ +public: + virtual ~StarterRngLoopSteps() = default; + virtual WallClock now() = 0; + // Runs Starter RNG's attempts at `attempt`'s target from the save under + // the ball, as `call` says. Throws StarterRngTimingsRefused when + // Starter RNG refuses the attempt's timings; the loop logs it and moves on. + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; +}; + +enum class StarterRngLoopEnd{ + // The starter is shiny and the target; the game is on its summary, not saved. + SHINY, + // The starter is shiny but not the target (or not known to be), so it + // doesn't tell the SID; the game is on its summary, not saved. + SHINY_OFF_TARGET, + // Shiny not required, and the target was hit. The game is where + // Starter RNG's calibration left it, not saved. + TARGET, + // Every attempt was hit and none was shiny. + OUT_OF_ATTEMPTS, + // The last attempt still shiny for a SID left missed more often than + // the retries allow, or couldn't run. + MISSED_EVERY_ATTEMPT_LEFT, + // The total time ran out with attempts left. + OUT_OF_TIME, +}; + +struct StarterRngLoopResult{ + StarterRngLoopEnd end = StarterRngLoopEnd::OUT_OF_TIME; + // Attempts run, retries included. + size_t attempts_run = 0; + // The SID candidates not ruled out. + std::vector remaining_sids; + // The SID, once a shiny leaves one candidate. + std::optional sid; +}; + +// Runs `tracker`'s attempts through `steps` until the plan ends or +// `limits.total_time` has passed. Logs an "RngPlan: state" line at the +// start of each try and after each reset, an "RngPlan: result" line after +// it and, when a shiny leaves one SID, an "RngPlan: confirmed" line placing +// it among SID Helper's candidates for `tid`. +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp new file mode 100644 index 0000000000..4b24859aa0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp @@ -0,0 +1,516 @@ +/* Starter RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's decisions and log lines on scripted attempt + * outcomes and a fake clock. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_StarterRngLoop.h" +#include "PokemonFRLG_StarterRngLoop_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class Test_StarterRngLoop : public UnitTest{ +public: + Test_StarterRngLoop(std::string name, std::function body) + : UnitTest("PokemonFRLG::StarterRngLoop - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +class LineLogger : public Logger{ +public: + virtual void log(const std::string& msg, Color) override{ + lines.push_back(msg); + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + + std::vector lines; +}; + +// Each try takes `minutes_per_attempt` on the clock, makes one reset at +// its end with calibration 1.5/-2/0.25 frames, and comes out as the next +// of `outcomes`. An empty one is Starter RNG refusing the timings: a +// StarterRngTimingsRefused at once. +class ScriptedSteps : public StarterRngLoopSteps{ +public: + ScriptedSteps(std::vector> outcomes, int minutes_per_attempt) + : m_outcomes(std::move(outcomes)) + , m_minutes(minutes_per_attempt) + {} + + virtual WallClock now() override{ + return m_now; + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ + if (m_next >= m_outcomes.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "More attempts than scripted."); + } + indices.push_back(call.index); + deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); + const std::optional outcome = m_outcomes[m_next++]; + if (!outcome){ + throw StarterRngTimingsRefused("Refused timings."); + } + m_now += std::chrono::minutes(m_minutes); + call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); + return StarterRngResult{.outcome = *outcome, .pokemon = std::nullopt}; + } + + std::vector indices; + // Each attempt's deadline, in minutes from the start. + std::vector deadlines_min; + +private: + static inline const WallClock START = WallClock{} + std::chrono::hours(1000); + std::vector> m_outcomes; + int m_minutes; + LineLogger m_logger; + WallClock m_now = START; + size_t m_next = 0; +}; + +// A setup problem Starter RNG hits on every attempt alike, such as no +// audio input. +class SetupErrorSteps : public StarterRngLoopSteps{ +public: + virtual WallClock now() override{ + return WallClock{} + std::chrono::hours(1000); + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall&) override{ + calls++; + throw UserSetupError(m_logger, "No sound detected."); + } + + size_t calls = 0; + +private: + LineLogger m_logger; +}; + +// SID Helper's candidates 100, 200, 300; attempt 1 is shiny for 100 and +// 200, attempt 2 for 300. +const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; + +std::vector attempts(){ + RngAttempt first{}; + first.target.seed.seed = 0xceff; + first.target.advances = 983; + first.sids = {100, 200}; + RngAttempt second{}; + second.target.seed.seed = 0x2ef6; + second.target.advances = 29364; + second.sids = {300}; + return {first, second}; +} + +// 60-minute tries, 12 hours in all, 50 resets a try, 2 retries. +const StarterRngLoopLimits LIMITS{ + .attempt_time = std::chrono::minutes(60), + .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, +}; + +std::string end_name(StarterRngLoopEnd end){ + switch (end){ + case StarterRngLoopEnd::SHINY: + return "SHINY"; + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return "SHINY_OFF_TARGET"; + case StarterRngLoopEnd::TARGET: + return "TARGET"; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return "OUT_OF_ATTEMPTS"; + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "MISSED_EVERY_ATTEMPT_LEFT"; + case StarterRngLoopEnd::OUT_OF_TIME: + return "OUT_OF_TIME"; + } + return "?"; +} + +std::string join(const std::vector& values){ + std::string text; + for (size_t value : values){ + text += (text.empty() ? "" : ",") + std::to_string(value + 1); + } + return text; +} + + +struct LoopRow{ + std::string name; + // Empty: Starter RNG refuses the attempt's timings. + std::vector> outcomes; + int minutes_per_attempt; + bool shiny_required; + StarterRngLoopEnd end; + // The attempts run, from 1, as "1,1,2". + std::string attempts_run; + // The SID confirmed, or 0 for none; with it, an "RngPlan: confirmed" line. + uint16_t sid; + // Log lines the loop must write. + std::vector lines; +}; + +using enum StarterRngOutcome; +const std::optional REFUSED = std::nullopt; + +const std::vector LOOP_ROWS = { + { + .name = "hit, then shiny confirms the SID", + .outcomes = {target_hit, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: state attempt=1/2 try=1/3 reset=0/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:00:00/01:00:00 total_time=00:00:00/12:00:00 calibration=-", + "RngPlan: state attempt=1/2 try=1/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:30:00/01:00:00 total_time=00:30:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: result attempt=1 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: state attempt=2/2 try=1/3 reset=0/50 seed=2EF6 advances=29364 sids=300 ruled_out=100,200 " + "attempt_time=00:00:00/01:00:00 total_time=00:30:00/12:00:00 calibration=-", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "shiny on the target for two SIDs confirms none", + .outcomes = {shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm"}, + }, + { + .name = "shiny off the target confirms nothing", + .outcomes = {target_hit, shiny_off_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a shiny not known to be the target confirms nothing", + .outcomes = {shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny_off_target starter_rng=shiny nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "misses retry the same attempt", + .outcomes = {out_of_resets, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, + .lines = { + "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=2 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, + }, + { + .name = "an attempt past its deadline", + .outcomes = {out_of_resets, shiny_on_target}, + .minutes_per_attempt = 90, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=missed starter_rng=attempt_deadline nature=- ivs=- pid=- next=retry"}, + }, + { + .name = "retries used up, then the next attempt", + .outcomes = {out_of_resets, no_matches, wild_shiny, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "every attempt left missed too often", + .outcomes = {out_of_resets, out_of_resets, out_of_resets, no_matches, no_matches, no_matches}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,1,1,2,2,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=3 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "miss, hit, miss, then shiny", + .outcomes = {out_of_resets, target_hit, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,2,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=2 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=2 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, + }, + { + .name = "an attempt whose timings Starter RNG refuses is skipped", + .outcomes = {REFUSED, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: attempt 1 can't run: Refused timings.", + "RngPlan: result attempt=1 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=next_attempt", + }, + }, + { + .name = "no attempt Starter RNG will run", + .outcomes = {REFUSED, REFUSED}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "every attempt hit, none shiny", + .outcomes = {target_hit, target_hit}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a hit ends the plan with shiny not required", + .outcomes = {target_hit}, + .minutes_per_attempt = 30, .shiny_required = false, + .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, + .lines = {}, + }, + { + .name = "no attempt starts after the total time", + .outcomes = {out_of_resets, out_of_resets}, + .minutes_per_attempt = 400, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, + .lines = { + "RngPlan: state attempt=1/2 try=2/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=06:40:00/01:00:00 total_time=13:20:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: out of time before attempt 1", + }, + }, +}; + +UnitTestResult run_loop_row(const LoopRow& row){ + RngPlanTracker tracker(attempts(), CANDIDATES, row.shiny_required, 2); + ScriptedSteps steps(row.outcomes, row.minutes_per_attempt); + LineLogger logger; + StarterRngLoopResult result = run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + + const std::string expected = std::format("end {}, attempts {}, sid {}", end_name(row.end), row.attempts_run, row.sid); + const std::string got = std::format( + "end {}, attempts {}, sid {}", end_name(result.end), join(steps.indices), result.sid.value_or(0) + ); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + for (const std::string& line : row.lines){ + if (!logger.has(line)){ + return "Expected the log line \"" + line + "\""; + } + } + const bool confirmed = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: confirmed"); + }); + if (confirmed != (row.sid != 0)){ + return std::format("Expected {} \"RngPlan: confirmed\" line", row.sid != 0 ? "a" : "no"); + } + if (result.attempts_run != steps.indices.size()){ + return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); + } + return true; +} + + +// An attempt's deadline is an hour after it starts, or the end of the +// total time if sooner: attempts of 400 minutes start at 0 and 400, and +// none at 800, past the total of 430. +UnitTestResult test_deadlines(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 5); + ScriptedSteps steps({StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, 400); + LineLogger logger; + const StarterRngLoopLimits limits{ + .attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430), .max_resets = 50, .max_retries = 5, + }; + run_starter_rng_plan(logger, tracker, steps, limits, 12345, CANDIDATES); + std::string got; + for (int deadline : steps.deadlines_min){ + got += (got.empty() ? "" : ",") + std::to_string(deadline); + } + if (got != "60,430"){ + return "Expected deadlines 60,430 minutes; got " + got; + } + return true; +} + + +// A setup error other than refused timings stops the loop at once: it +// reaches the program, and the attempt is neither recorded nor skipped. +UnitTestResult test_setup_error_stops(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 2); + SetupErrorSteps steps; + LineLogger logger; + const size_t sids = tracker.remaining_sids().size(); + bool thrown = false; + try{ + run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + }catch (UserSetupError&){ + thrown = true; + } + const bool result_line = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: result") || line.starts_with("RngPlan: attempt"); + }); + const std::string expected = std::format("thrown 1, calls 1, attempt 1, sids {}, result line 0", sids); + const std::string got = std::format( + "thrown {}, calls {}, attempt {}, sids {}, result line {}", + int(thrown), steps.calls, tracker.attempt_index() + 1, tracker.remaining_sids().size(), int(result_line) + ); + if (got != expected){ + return "Expected " + expected + "; got " + got; + } + return true; +} + + +// The state line on its own: hours, empty lists and a negative offset. +UnitTestResult test_state_line(){ + const std::string got = rng_log_state(RngLoopState{ + .attempt = 3, .attempts = 5, .try_number = 2, .tries = 3, .resets = 41, .max_resets = 50, + .seed = 0x70fe, .advances = 1200, .sids = {}, .ruled_out = {7, 8}, + .attempt_time = std::chrono::seconds(3 * 3600 + 61), .attempt_cap = std::chrono::hours(3), + .total_time = std::chrono::minutes(605), .total_cap = std::chrono::hours(12), + .calibration = RngCalibrations{-0.5, 12, -3.125}, + }); + const std::string expected = + "RngPlan: state attempt=3/5 try=2/3 reset=41/50 seed=70FE advances=1200 sids=- ruled_out=7,8 " + "attempt_time=03:01:01/03:00:00 total_time=10:05:00/12:00:00 calibration=-0.50/12.00/-3.12"; + if (got != expected){ + return "Expected \"" + expected + "\", got \"" + got + "\"."; + } + return true; +} + + + +AdvRngState state(uint16_t seed, uint64_t advance){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + return hit; +} + +// Target: seed 9cf3 at advance 1670, between 7425 a frame earlier and +// e66e a frame later. +struct ResetLineRow{ + std::string name; + std::string program; + RngResetRead read; + std::string expected; +}; + +const std::vector RESET_LINE_ROWS = { + { + .name = "seed on the target", .program = "Gift RNG", + .read = {.resets = 28, .hits = {state(0x9cf3, 1669)}, .hit = state(0x9cf3, 1669), .shiny = false}, + .expected = "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed.", + }, + { + .name = "seed a frame late", .program = "Starter RNG", + .read = {.resets = 27, .hits = {state(0xe66e, 1677), state(0x7425, 1690)}, .hit = state(0xe66e, 1677), .shiny = false}, + .expected = "Starter RNG try 27/50: seed e66e (+1 frame late), advance 1677 (target 1670, +7). Missed.", + }, + { + .name = "seed a frame early", .program = "Gift RNG", + .read = {.resets = 4, .hits = {state(0x7425, 1670)}, .hit = std::nullopt, .shiny = false}, + .expected = "Gift RNG try 4/50: seed 7425 (-1 frame early), advance 1670. Missed.", + }, + { + .name = "seed not near the target", .program = "Gift RNG", + .read = {.resets = 5, .hits = {state(0x1234, 1670)}, .hit = state(0x1234, 1670), .shiny = false}, + .expected = "Gift RNG try 5/50: seed 1234 (not near the target), advance 1670. Missed.", + }, + { + .name = "no match", .program = "Gift RNG", + .read = {.resets = 19, .hits = {}, .hit = std::nullopt, .shiny = false}, + .expected = "Gift RNG try 19/50: no match read (stats fit no seed/advance).", + }, + { + .name = "several matches", .program = "Gift RNG", + .read = { + .resets = 3, .hits = {state(0x9cf3, 1668), state(0x9cf3, 1668), state(0xe66e, 1671), state(0x7425, 1675)}, + .hit = std::nullopt, .shiny = false, + }, + .expected = "Gift RNG try 3/50: 3 possible matches, can't tell which.", + }, + { + .name = "target hit", .program = "Starter RNG", + .read = {.resets = 12, .hits = {state(0x9cf3, 1670)}, .hit = state(0x9cf3, 1670), .shiny = false}, + .expected = "Starter RNG try 12/50: seed 9cf3 = target, advance 1670. HIT, not shiny.", + }, + { + .name = "shiny on the target", .program = "Gift RNG", + .read = {.resets = 31, .hits = {state(0xe66e, 1671), state(0x9cf3, 1670)}, .hit = std::nullopt, .shiny = true}, + .expected = "Gift RNG try 31/50: seed 9cf3 = target, advance 1670. HIT, shiny!", + }, + { + .name = "shiny off the target", .program = "Gift RNG", + .read = {.resets = 9, .hits = {state(0xe66e, 1671)}, .hit = std::nullopt, .shiny = true}, + .expected = "Gift RNG try 9/50: shiny, not on the target.", + }, +}; + +UnitTestResult test_reset_line(const ResetLineRow& row){ + const std::string got = rng_reset_line(RngResetLine{ + .program = row.program, .max_resets = 50, .target_seed = 0x9cf3, .target_advances = 1670, + .seed_values = {0x1111, 0x7425, 0x9cf3, 0xe66e, 0x2222}, .seed_position = 2, + .read = row.read, + }); + if (got != row.expected){ + return "Expected \"" + row.expected + "\", got \"" + got + "\"."; + } + return true; +} + +} + + +void add_tests_StarterRngLoop(UnitTestDatabase& database){ + for (const LoopRow& row : LOOP_ROWS){ + database.add(row.name, [row]{ return run_loop_row(row); }); + } + database.add("attempt deadlines", test_deadlines); + database.add("a setup error stops the loop", test_setup_error_stops); + database.add("state line", test_state_line); + for (const ResetLineRow& row : RESET_LINE_ROWS){ + database.add("reset line " + row.name, [row]{ return test_reset_line(row); }); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h new file mode 100644 index 0000000000..8c98b0a8cb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h @@ -0,0 +1,23 @@ +/* Starter RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoop_Tests_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoop_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_StarterRngLoop(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index c99a56150f..e1dee1738e 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1859,13 +1859,18 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.h @@ -1881,10 +1886,16 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_BlindNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_BlindNavigation.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -1907,16 +1918,50 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngLoopRoutines.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngStatsDatabase.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngStatsDatabase.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp From fb423d72be4499cb7cd58305e8e896c344e4c6fc Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 5 Nov 2026 18:41:52 -0800 Subject: [PATCH 02/13] FRLG AutoStory stage 2: align with PR #231 lint conventions --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 626 ++++++++++++------ .../AutoStory/PokemonFRLG_AutoStory.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 2 +- .../PokemonFRLG_AutoStoryRngLoop.cpp | 8 +- .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 7 +- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 58 +- .../PokemonFRLG_AutoStoryRngOptions.cpp | 6 +- .../PokemonFRLG_AutoStoryRngOptions.h | 7 +- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 111 ++-- .../Programs/PokemonFRLG_NamingScreen.cpp | 8 +- .../Programs/PokemonFRLG_NamingScreen.h | 6 +- .../PokemonFRLG_NamingScreenKeyboard.cpp | 8 +- .../PokemonFRLG_NamingScreenKeyboard.h | 18 +- .../Programs/PokemonFRLG_TrainerCard.cpp | 8 +- .../Programs/PokemonFRLG_TrainerCard.h | 6 +- .../RngManipulation/PokemonFRLG_RngPlan.cpp | 8 +- .../RngManipulation/PokemonFRLG_RngPlan.h | 8 +- .../PokemonFRLG_RngPlanInputs.cpp | 8 +- .../PokemonFRLG_RngPlanInputs.h | 7 +- .../PokemonFRLG_RngPlanInputs_Tests.cpp | 53 +- .../PokemonFRLG_RngPlanInputs_Tests.h | 7 +- .../PokemonFRLG_RngPlanLog.cpp | 10 +- .../RngManipulation/PokemonFRLG_RngPlanLog.h | 11 +- .../PokemonFRLG_RngPlanLog_Tests.cpp | 43 +- .../PokemonFRLG_RngPlanLog_Tests.h | 7 +- .../PokemonFRLG_RngPlanTestTargets.cpp | 8 +- .../PokemonFRLG_RngPlanTestTargets.h | 9 +- .../PokemonFRLG_RngPlanTracker.cpp | 6 +- .../PokemonFRLG_RngPlanTracker.h | 10 +- .../PokemonFRLG_RngPlanTracker_Tests.cpp | 48 +- .../PokemonFRLG_RngPlanTracker_Tests.h | 7 +- .../PokemonFRLG_RngPlan_Tests.cpp | 63 +- .../PokemonFRLG_RngPlan_Tests.h | 7 +- .../PokemonFRLG_RngSteps_Tests.cpp | 170 +++-- .../PokemonFRLG_RngSteps_Tests.h | 6 +- .../PokemonFRLG_RngTargetSearch.cpp | 10 +- .../PokemonFRLG_RngTargetSearch.h | 14 +- .../PokemonFRLG_RngTargetSearch_Tests.cpp | 312 +++++---- .../PokemonFRLG_RngTargetSearch_Tests.h | 7 +- .../RngManipulation/PokemonFRLG_SidSteps.cpp | 6 +- .../RngManipulation/PokemonFRLG_SidSteps.h | 6 +- .../PokemonFRLG_StarterRngAttempts.cpp | 8 +- .../PokemonFRLG_StarterRngAttempts.h | 14 +- .../PokemonFRLG_StarterRngConsoleSteps.cpp | 6 +- .../PokemonFRLG_StarterRngConsoleSteps.h | 7 +- .../PokemonFRLG_StarterRngLoop.cpp | 12 +- .../PokemonFRLG_StarterRngLoop.h | 10 +- .../PokemonFRLG_StarterRngLoop_Tests.cpp | 83 ++- .../PokemonFRLG_StarterRngLoop_Tests.h | 7 +- 49 files changed, 1207 insertions(+), 672 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 4ccaa6a0d7..02af6ba183 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -286,27 +286,35 @@ void add_tests_ExitWildBattle(UnitTestDatabase& database){ // Naming screen keyboard: cursor moves, plans and text checks, against pokefirered's // src/naming_screen.c. -struct NamingCursorScenario{ +struct NamingCursorInput{ std::string name = ""; NamingCursor start = {}; std::vector actions = {}; +}; + +struct NamingCursorExpectation{ NamingCursor expected = {}; }; +struct NamingCursorScenario{ + NamingCursorInput input; + NamingCursorExpectation expectation; +}; + class Test_NamingCursor : public UnitTest{ public: - Test_NamingCursor(NamingCursorScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen cursor - " + scenario.name) + explicit Test_NamingCursor(NamingCursorScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen cursor - " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - NamingCursor cursor = m_scenario.start; - for (NamingAction action : m_scenario.actions){ + NamingCursor cursor = m_scenario.input.start; + for (NamingAction action : m_scenario.input.actions){ cursor = apply_naming_action(cursor, action); } - if (cursor != m_scenario.expected){ - return "After " + to_string(m_scenario.actions) + ": expected " + to_string(m_scenario.expected) + if (cursor != m_scenario.expectation.expected){ + return "After " + to_string(m_scenario.input.actions) + ": expected " + to_string(m_scenario.expectation.expected) + ", got " + to_string(cursor); } return true; @@ -316,148 +324,200 @@ class Test_NamingCursor : public UnitTest{ const NamingCursorScenario m_scenario; }; -// Crossing and moving on the button column. -std::vector naming_cursor_button_column_scenarios(){ - using enum NamingAction; - using enum NamingScreenPage; - return { - { +const NamingCursorScenario NAMING_CURSOR_CASES[] = { + // Crossing and moving on the button column. + { + .input = { .name = "left from A goes to the page button", - .actions = {LEFT}, - .expected = {.page = UPPER, .row = 0, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::LEFT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, + }, + }, + { + .input = { .name = "left and right return to A", - .actions = {LEFT, RIGHT}, - .expected = {.page = UPPER, .row = 0, .column = 0, .remembered_row = 1}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, }, - { - // Rows 1 and 2 share the back button; the game remembers which one it came from. + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { .name = "row 1 crosses the button column", - .start = {.page = UPPER, .row = 1, .column = 0}, - .actions = {LEFT, RIGHT}, - .expected = {.page = UPPER, .row = 1, .column = 0, .remembered_row = 1}, + .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { .name = "row 2 crosses the button column", - .start = {.page = UPPER, .row = 2, .column = 0}, - .actions = {LEFT, RIGHT}, - .expected = {.page = UPPER, .row = 2, .column = 0, .remembered_row = 2}, + .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0, .remembered_row = 2}, + }, + }, + { + .input = { .name = "row 3 crosses the OK button", - .start = {.page = UPPER, .row = 3, .column = 0}, - .actions = {LEFT, RIGHT}, - .expected = {.page = UPPER, .row = 3, .column = 0, .remembered_row = 2}, + .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0, .remembered_row = 2}, + }, + }, + { + .input = { .name = "right from the last column wraps through the buttons", - .start = {.page = UPPER, .row = 0, .column = 7}, - .actions = {RIGHT, RIGHT}, - .expected = {.page = UPPER, .row = 0, .column = 0, .remembered_row = 1}, + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, + .actions = {NamingAction::RIGHT, NamingAction::RIGHT}, }, - { - // Moving on the button column overwrites the remembered row with BACK. + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { .name = "moving on the button column forgets row 2", - .start = {.page = UPPER, .row = 2, .column = 0}, - .actions = {LEFT, UP, DOWN, RIGHT}, - .expected = {.page = UPPER, .row = 1, .column = 0, .remembered_row = 1}, + .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::UP, NamingAction::DOWN, NamingAction::RIGHT}, }, - }; -} -// Wrap-around on the keys and the button column. -std::vector naming_cursor_wrap_scenarios(){ - using enum NamingAction; - using enum NamingScreenPage; - return { - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }, + // Wrap-around on the keys and the button column. + { + .input = { .name = "button column wraps over three buttons", - .start = {.page = UPPER, .row = 0, .column = 8, .remembered_row = 1}, - .actions = {UP}, - .expected = {.page = UPPER, .row = 2, .column = 8, .remembered_row = 2}, + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::UP}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 8, .remembered_row = 2}, + }, + }, + { + .input = { .name = "rows wrap up", - .actions = {UP}, - .expected = {.page = UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::UP}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + }, + }, + { + .input = { .name = "rows wrap down", - .start = {.page = UPPER, .row = 3, .column = 0}, - .actions = {DOWN}, - .expected = {.page = UPPER, .row = 0, .column = 0}, + .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::DOWN}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, + }, + }, + { + .input = { .name = "symbols page has six key columns", - .start = {.page = SYMBOLS, .row = 0, .column = 0}, - .actions = {LEFT, LEFT}, - .expected = {.page = SYMBOLS, .row = 0, .column = 5, .remembered_row = 1}, + .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::LEFT}, }, - }; -} -// SELECT and START. -std::vector naming_cursor_page_scenarios(){ - using enum NamingAction; - using enum NamingScreenPage; - return { - { + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 5, .remembered_row = 1}, + }, + }, + // SELECT and START. + { + .input = { .name = "SELECT goes to lower case", - .actions = {SELECT}, - .expected = {.page = LOWER, .row = 0, .column = 0}, + .actions = {NamingAction::SELECT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::LOWER, .row = 0, .column = 0}, + }, + }, + { + .input = { .name = "SELECT twice goes to symbols", - .actions = {SELECT, SELECT}, - .expected = {.page = SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::SELECT, NamingAction::SELECT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + }, + }, + { + .input = { .name = "SELECT three times returns to upper case", - .actions = {SELECT, SELECT, SELECT}, - .expected = {.page = UPPER, .row = 0, .column = 0}, + .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, + }, + }, + { + .input = { .name = "SELECT moves the cursor into the symbols columns", - .start = {.page = UPPER, .row = 0, .column = 7}, - .actions = {SELECT, SELECT, SELECT}, - .expected = {.page = UPPER, .row = 0, .column = 5}, + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, + .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 5}, + }, + }, + { + .input = { .name = "SELECT keeps the cursor on the button column", - .start = {.page = UPPER, .row = 1, .column = 8, .remembered_row = 1}, - .actions = {SELECT, SELECT}, - .expected = {.page = SYMBOLS, .row = 1, .column = 6, .remembered_row = 1}, + .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::SELECT, NamingAction::SELECT}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 1, .column = 6, .remembered_row = 1}, + }, + }, + { + .input = { .name = "START goes to OK", - .start = {.page = LOWER, .row = 1, .column = 3}, - .actions = {START}, - .expected = {.page = LOWER, .row = 2, .column = 8}, + .start = {.page = NamingScreenPage::LOWER, .row = 1, .column = 3}, + .actions = {NamingAction::START}, }, - { + .expectation = { + .expected = {.page = NamingScreenPage::LOWER, .row = 2, .column = 8}, + }, + }, + { + .input = { .name = "START goes to OK on symbols", - .start = {.page = SYMBOLS, .row = 0, .column = 0}, - .actions = {START}, - .expected = {.page = SYMBOLS, .row = 2, .column = 6}, + .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::START}, }, - }; -} + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 2, .column = 6}, + }, + }, +}; + void add_tests_NamingCursor(UnitTestDatabase& database){ - for (auto scenarios : { - naming_cursor_button_column_scenarios(), - naming_cursor_wrap_scenarios(), - naming_cursor_page_scenarios(), - }){ - for (const NamingCursorScenario& scenario : scenarios){ - database.add(scenario); - } + for (const NamingCursorScenario& scenario : NAMING_CURSOR_CASES){ + database.add(scenario); } } -struct NamingPlanScenario{ +struct NamingPlanInput{ std::string name = ""; std::string text = ""; NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingPlanExpectation{ // What the game shows when it differs from `text` (another spelling of a key). std::string typed = ""; // The exact plan, when the shortest one is unique; "" to skip. @@ -466,48 +526,62 @@ struct NamingPlanScenario{ size_t expected_presses = 0; }; +struct NamingPlanScenario{ + NamingPlanInput input; + NamingPlanExpectation expectation; +}; + +std::string replay_naming_plan( + const std::vector& actions, + const std::string& plan, + const NamingPlanScenario& scenario +){ + std::string typed; + NamingCursor cursor; + for (size_t i = 0; i < actions.size(); i++){ + cursor = apply_naming_action(cursor, actions[i]); + if (actions[i] != NamingAction::A){ + continue; + } + const uint8_t columns = NAMING_SCREEN_KEY_COLUMNS[(size_t)cursor.page]; + if (i + 1 == actions.size()){ + if (cursor.column != columns || cursor.row != NAMING_SCREEN_BUTTON_OK){ + return "The last A is not on OK but on " + to_string(cursor) + ": " + plan; + } + break; + } + if (cursor.column >= columns){ + return "A pressed on the button column at " + to_string(cursor) + ": " + plan; + } + typed += NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; + } + const std::string& expected = scenario.expectation.typed.empty() ? scenario.input.text : scenario.expectation.typed; + if (typed != expected){ + return "Expected the plan to type \"" + expected + "\", it types \"" + typed + "\": " + plan; + } + return ""; +} + class Test_NamingPlan : public UnitTest{ public: - Test_NamingPlan(NamingPlanScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen plan - " + scenario.name) + explicit Test_NamingPlan(NamingPlanScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen plan - " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::vector actions = plan_naming_input(m_scenario.text, m_scenario.kind); + const std::vector actions = plan_naming_input(m_scenario.input.text, m_scenario.input.kind); const std::string plan = to_string(actions); - if (!m_scenario.expected_actions.empty() && plan != m_scenario.expected_actions){ - return "Expected plan: " + m_scenario.expected_actions + "\nActual plan: " + plan; + if (!m_scenario.expectation.expected_actions.empty() && plan != m_scenario.expectation.expected_actions){ + return "Expected plan: " + m_scenario.expectation.expected_actions + "\nActual plan: " + plan; } - if (m_scenario.expected_presses != 0 && actions.size() != m_scenario.expected_presses){ - return "Expected " + std::to_string(m_scenario.expected_presses) + " presses, got " + if (m_scenario.expectation.expected_presses != 0 && actions.size() != m_scenario.expectation.expected_presses){ + return "Expected " + std::to_string(m_scenario.expectation.expected_presses) + " presses, got " + std::to_string(actions.size()) + ": " + plan; } - - // Replay the plan: every A but the last types the key under the cursor, and the last - // presses OK. - std::string typed; - NamingCursor cursor; - for (size_t i = 0; i < actions.size(); i++){ - cursor = apply_naming_action(cursor, actions[i]); - if (actions[i] != NamingAction::A){ - continue; - } - const uint8_t columns = NAMING_SCREEN_KEY_COLUMNS[(size_t)cursor.page]; - if (i + 1 == actions.size()){ - if (cursor.column != columns || cursor.row != NAMING_SCREEN_BUTTON_OK){ - return "The last A is not on OK but on " + to_string(cursor) + ": " + plan; - } - break; - } - if (cursor.column >= columns){ - return "A pressed on the button column at " + to_string(cursor) + ": " + plan; - } - typed += NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; - } - const std::string& expected = m_scenario.typed.empty() ? m_scenario.text : m_scenario.typed; - if (typed != expected){ - return "Expected the plan to type \"" + expected + "\", it types \"" + typed + "\": " + plan; + std::string replay_error = replay_naming_plan(actions, plan, m_scenario); + if (!replay_error.empty()){ + return replay_error; } return true; } @@ -516,70 +590,132 @@ class Test_NamingPlan : public UnitTest{ const NamingPlanScenario m_scenario; }; -void add_tests_NamingPlan(UnitTestDatabase& database){ - using enum NamingScreenKind; - const NamingPlanScenario scenarios[] = { - {.name = "starts on A", .text = "A", .expected_actions = "A START A"}, - {.name = "next key", .text = "AB", .expected_actions = "A RIGHT A START A"}, - {.name = "next row", .text = "AG", .expected_actions = "A DOWN A START A"}, - {.name = "rows wrap", .text = "T", .expected_actions = "UP A START A"}, - { +const NamingPlanScenario NAMING_PLAN_CASES[] = { + { + .input = {.name = "starts on A", .text = "A"}, + .expectation = {.expected_actions = "A START A"}, + }, + { + .input = {.name = "next key", .text = "AB"}, + .expectation = {.expected_actions = "A RIGHT A START A"}, + }, + { + .input = {.name = "next row", .text = "AG"}, + .expectation = {.expected_actions = "A DOWN A START A"}, + }, + { + .input = {.name = "rows wrap", .text = "T"}, + .expectation = {.expected_actions = "UP A START A"}, + }, + { + .input = { .name = "columns wrap through the button column", .text = ".", - .expected_actions = "LEFT LEFT A START A", }, - {.name = "lower case page", .text = "a", .expected_actions = "SELECT A START A"}, - {.name = "symbols page", .text = "0", .expected_actions = "SELECT SELECT A START A"}, - { - // The cursor moves from column 7 to the symbols page's last column, 5. + .expectation = {.expected_actions = "LEFT LEFT A START A"}, + }, + { + .input = {.name = "lower case page", .text = "a"}, + .expectation = {.expected_actions = "SELECT A START A"}, + }, + { + .input = {.name = "symbols page", .text = "0"}, + .expectation = {.expected_actions = "SELECT SELECT A START A"}, + }, + { + .input = { .name = "page change moves the cursor into the symbols columns", .text = ".4", - .expected_actions = "LEFT LEFT A SELECT SELECT LEFT A START A", - }, - {.name = "both ways round", .text = "Z", .expected_presses = 7}, - {.name = "male sign", .text = "\xE2\x99\x82", .expected_presses = 9}, - {.name = "full player name", .text = "ABCDEFG", .expected_presses = 19}, - {.name = "mixed case", .text = "Gary", .expected_presses = 16}, - {.name = "space", .text = "A B", .expected_presses = 12}, - {.name = "full nickname", .text = "BULBASAURS", .kind = POKEMON}, - {.name = "female sign", .text = "NIDORAN\xE2\x99\x80", .kind = POKEMON}, - {.name = "box name", .text = "BOX 1-2!", .kind = BOX}, - {.name = "rival", .text = "Blue?", .kind = RIVAL}, - { + }, + .expectation = {.expected_actions = "LEFT LEFT A SELECT SELECT LEFT A START A"}, + }, + { + .input = {.name = "both ways round", .text = "Z"}, + .expectation = {.expected_presses = 7}, + }, + { + .input = {.name = "male sign", .text = "\xE2\x99\x82"}, + .expectation = {.expected_presses = 9}, + }, + { + .input = {.name = "full player name", .text = "ABCDEFG"}, + .expectation = {.expected_presses = 19}, + }, + { + .input = {.name = "mixed case", .text = "Gary"}, + .expectation = {.expected_presses = 16}, + }, + { + .input = {.name = "space", .text = "A B"}, + .expectation = {.expected_presses = 12}, + }, + { + .input = {.name = "full nickname", .text = "BULBASAURS", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "female sign", .text = "NIDORAN\xE2\x99\x80", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "box name", .text = "BOX 1-2!", .kind = NamingScreenKind::BOX}, + .expectation = {}, + }, + { + .input = {.name = "rival", .text = "Blue?", .kind = NamingScreenKind::RIVAL}, + .expectation = {}, + }, + { + .input = { .name = "symbols row 4", .text = "\xE2\x80\xA6\xE2\x80\x9C\xE2\x80\x9D\xE2\x80\x98'", - .kind = POKEMON, + .kind = NamingScreenKind::POKEMON, }, - {.name = "curly apostrophe", .text = "IT\xE2\x80\x99S", .typed = "IT'S"}, - }; - for (const NamingPlanScenario& scenario : scenarios){ + .expectation = {}, + }, + { + .input = {.name = "curly apostrophe", .text = "IT\xE2\x80\x99S"}, + .expectation = {.typed = "IT'S"}, + }, +}; + +void add_tests_NamingPlan(UnitTestDatabase& database){ + for (const NamingPlanScenario& scenario : NAMING_PLAN_CASES){ database.add(scenario); } } -struct NamingKeysScenario{ +struct NamingKeysInput{ std::string name = ""; std::string text = ""; NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingKeysExpectation{ // The exact plan, when the shortest one is unique; "" to skip. std::string expected_actions = ""; }; +struct NamingKeysScenario{ + NamingKeysInput input; + NamingKeysExpectation expectation; +}; + // plan_naming_keys() stops before OK: it is plan_naming_input() without the final START A. class Test_NamingKeys : public UnitTest{ public: - Test_NamingKeys(NamingKeysScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen keys only - " + scenario.name) + explicit Test_NamingKeys(NamingKeysScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen keys only - " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::string keys = to_string(plan_naming_keys(m_scenario.text, m_scenario.kind)); - if (!m_scenario.expected_actions.empty() && keys != m_scenario.expected_actions){ - return "Expected keys: " + m_scenario.expected_actions + "\nActual keys: " + keys; + const std::string keys = to_string(plan_naming_keys(m_scenario.input.text, m_scenario.input.kind)); + if (!m_scenario.expectation.expected_actions.empty() && keys != m_scenario.expectation.expected_actions){ + return "Expected keys: " + m_scenario.expectation.expected_actions + "\nActual keys: " + keys; } - const std::string input = to_string(plan_naming_input(m_scenario.text, m_scenario.kind)); + const std::string input = to_string(plan_naming_input(m_scenario.input.text, m_scenario.input.kind)); if (input != keys + " START A"){ return "Expected the confirmed plan to be \"" + keys + " START A\", got \"" + input + "\""; } @@ -590,91 +726,149 @@ class Test_NamingKeys : public UnitTest{ const NamingKeysScenario m_scenario; }; +const NamingKeysScenario NAMING_KEYS_CASES[] = { + { + .input = {.name = "one key", .text = "A"}, + .expectation = {.expected_actions = "A"}, + }, + { + .input = {.name = "next key", .text = "AB"}, + .expectation = {.expected_actions = "A RIGHT A"}, + }, + { + .input = {.name = "lower case page", .text = "a"}, + .expectation = {.expected_actions = "SELECT A"}, + }, + { + .input = {.name = "full player name", .text = "ABCDEFG"}, + .expectation = {}, + }, + { + .input = {.name = "mixed case", .text = "Kosmos"}, + .expectation = {}, + }, +}; + void add_tests_NamingKeys(UnitTestDatabase& database){ - using enum NamingScreenKind; - const NamingKeysScenario scenarios[] = { - {.name = "one key", .text = "A", .expected_actions = "A"}, - {.name = "next key", .text = "AB", .expected_actions = "A RIGHT A"}, - {.name = "lower case page", .text = "a", .expected_actions = "SELECT A"}, - // A full name: the game moves the cursor to OK by itself, but nothing presses it. - {.name = "full player name", .text = "ABCDEFG"}, - {.name = "mixed case", .text = "Kosmos"}, - }; - for (const NamingKeysScenario& scenario : scenarios){ + for (const NamingKeysScenario& scenario : NAMING_KEYS_CASES){ database.add(scenario); } } -struct NamingTextScenario{ +struct NamingTextInput{ std::string name = ""; std::string text = ""; NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingTextExpectation{ // A part of the expected error; "" if the text is fine. std::string expected_error = ""; }; +struct NamingTextScenario{ + NamingTextInput input; + NamingTextExpectation expectation; +}; + class Test_NamingText : public UnitTest{ public: - Test_NamingText(NamingTextScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen text - " + scenario.name) + explicit Test_NamingText(NamingTextScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen text - " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::string error = naming_text_error(m_scenario.text, m_scenario.kind); - if (m_scenario.expected_error.empty()){ + const std::string error = naming_text_error(m_scenario.input.text, m_scenario.input.kind); + if (m_scenario.expectation.expected_error.empty()){ if (!error.empty()){ - return "Expected \"" + m_scenario.text + "\" to be accepted, got: " + error; + return "Expected \"" + m_scenario.input.text + "\" to be accepted, got: " + error; } return true; } - if (error.find(m_scenario.expected_error) == std::string::npos){ - return "Expected an error containing \"" + m_scenario.expected_error + "\", got: \"" + error + "\""; + if (error.find(m_scenario.expectation.expected_error) == std::string::npos){ + return "Expected an error containing \"" + m_scenario.expectation.expected_error + "\", got: \"" + error + "\""; } try{ - plan_naming_input(m_scenario.text, m_scenario.kind); + plan_naming_input(m_scenario.input.text, m_scenario.input.kind); }catch (InternalProgramError&){ return true; } - return "Expected plan_naming_input() to throw for \"" + m_scenario.text + "\""; + return "Expected plan_naming_input() to throw for \"" + m_scenario.input.text + "\""; } private: const NamingTextScenario m_scenario; }; -void add_tests_NamingText(UnitTestDatabase& database){ - using enum NamingScreenKind; - const NamingTextScenario scenarios[] = { - {.name = "player name of 7", .text = "ABCDEFG", .kind = PLAYER}, - {.name = "player name of 8", .text = "ABCDEFGH", .kind = PLAYER, .expected_error = "at most 7"}, - {.name = "rival name of 7", .text = "ABCDEFG", .kind = RIVAL}, - {.name = "rival name of 8", .text = "ABCDEFGH", .kind = RIVAL, .expected_error = "at most 7"}, - {.name = "box name of 8", .text = "ABCDEFGH", .kind = BOX}, - {.name = "box name of 9", .text = "ABCDEFGHI", .kind = BOX, .expected_error = "at most 8"}, - {.name = "nickname of 10", .text = "ABCDEFGHIJ", .kind = POKEMON}, - {.name = "nickname of 11", .text = "ABCDEFGHIJK", .kind = POKEMON, .expected_error = "at most 10"}, - { - // Seven characters, 21 bytes. +const NamingTextScenario NAMING_TEXT_CASES[] = { + { + .input = {.name = "player name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::PLAYER}, + .expectation = {}, + }, + { + .input = {.name = "player name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "at most 7"}, + }, + { + .input = {.name = "rival name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::RIVAL}, + .expectation = {}, + }, + { + .input = {.name = "rival name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::RIVAL}, + .expectation = {.expected_error = "at most 7"}, + }, + { + .input = {.name = "box name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::BOX}, + .expectation = {}, + }, + { + .input = {.name = "box name of 9", .text = "ABCDEFGHI", .kind = NamingScreenKind::BOX}, + .expectation = {.expected_error = "at most 8"}, + }, + { + .input = {.name = "nickname of 10", .text = "ABCDEFGHIJ", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "nickname of 11", .text = "ABCDEFGHIJK", .kind = NamingScreenKind::POKEMON}, + .expectation = {.expected_error = "at most 10"}, + }, + { + .input = { .name = "symbols count as one character", .text = "\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82", + .kind = NamingScreenKind::PLAYER, }, - {.name = "unknown character", .text = "Ash@", .expected_error = "type: \"@\""}, - {.name = "unknown accented character", .text = "Jos\xC3\xA9", .expected_error = "type: \"\xC3\xA9\""}, - {.name = "empty", .text = "", .expected_error = "empty"}, - {.name = "only spaces", .text = " ", .expected_error = "only spaces"}, - }; - for (const NamingTextScenario& scenario : scenarios){ + .expectation = {}, + }, + { + .input = {.name = "unknown character", .text = "Ash@", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "type: \"@\""}, + }, + { + .input = {.name = "unknown accented character", .text = "Jos\xC3\xA9", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "type: \"\xC3\xA9\""}, + }, + { + .input = {.name = "empty", .text = "", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "empty"}, + }, + { + .input = {.name = "only spaces", .text = " ", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "only spaces"}, + }, +}; + +void add_tests_NamingText(UnitTestDatabase& database){ + for (const NamingTextScenario& scenario : NAMING_TEXT_CASES){ database.add(scenario); } } -} - +} // namespace -// The menu readers AutoStory brought: the bag's and Marts' lists, the -// options, the save card and the summary's moves. static void add_tests_AutoStoryReaders(UnitTestDatabase& database){ add_tests_ItemListReader(database); add_tests_OptionMenuReader(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index acfd4e062f..7c30b1dbf0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -460,7 +460,7 @@ const StarterRngLoopLimits STARTER_RNG_LIMITS{ .max_retries = 2, }; -} +} // namespace // Starter RNG's attempts in the program, from the save south of the table. // Returns true for a shiny Squirtle, on the target or not, the game on its diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 365d3398cd..f812ead269 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -467,7 +467,7 @@ StoryCheckpoint joined_rows(const StoryCheckpoint& first, const StoryCheckpoint& return row; } -} +} // namespace StoryRunPlan plan_story_run( const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index f6c1f5d3c9..add7a07d36 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -25,7 +25,7 @@ std::string join_sids(const std::vector& sids){ return text.empty() ? "-" : text; } -} +} // namespace std::string starter_rng_loop_message(const StarterRngLoopResult& result){ const std::string sids = join_sids(result.remaining_sids); @@ -114,6 +114,6 @@ std::vector rows_after_starter_rng( -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index a6c0f248af..6161bf4305 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -63,11 +63,12 @@ std::vector rows_after_starter_rng( ); +// Registers AutoStory RNG loop unit tests. void add_tests_AutoStoryRngLoop(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index f042a5349c..0e506e7465 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -24,22 +24,36 @@ namespace PokemonFRLG{ namespace{ +struct AutoStoryRngLoopInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct AutoStoryRngLoopExpectation{ + const char* description; +}; + +struct AutoStoryRngLoopTestCase{ + AutoStoryRngLoopInput input; + AutoStoryRngLoopExpectation expectation; +}; + class Test_AutoStoryRngLoop : public UnitTest{ public: - Test_AutoStoryRngLoop(std::string name, std::function body) - : UnitTest("PokemonFRLG::AutoStoryRngLoop - " + std::move(name)) - , m_body(std::move(body)) + explicit Test_AutoStoryRngLoop(AutoStoryRngLoopTestCase scenario) + : UnitTest("PokemonFRLG::AutoStoryRngLoop - " + scenario.input.name) + , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ try{ - return m_body(); + return m_scenario.input.body(); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + AutoStoryRngLoopTestCase m_scenario; }; @@ -190,18 +204,36 @@ UnitTestResult test_starter_calibration_saved(){ return true; } -} +const AutoStoryRngLoopTestCase AUTO_STORY_RNG_LOOP_CASES[] = { + { + .input = {.name = "shiny messages", .body = test_shiny_messages}, + .expectation = {.description = "formats notifications for shiny starter encounters"}, + }, + { + .input = {.name = "rows after a shiny", .body = test_rows_after_shiny}, + .expectation = {.description = "plans continuation rows following shiny discovery"}, + }, + { + .input = {.name = "Starter RNG starts from the RNG plan's calibration", .body = test_starter_calibration_from_options}, + .expectation = {.description = "initializes starter calibrations from program options"}, + }, + { + .input = {.name = "Starter RNG saves its calibration after each reset", .body = test_starter_calibration_saved}, + .expectation = {.description = "persists calibration adjustments across reset cycles"}, + }, +}; + +} // namespace void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ - database.add("shiny messages", test_shiny_messages); - database.add("rows after a shiny", test_rows_after_shiny); - database.add("Starter RNG starts from the RNG plan's calibration", test_starter_calibration_from_options); - database.add("Starter RNG saves its calibration after each reset", test_starter_calibration_saved); + for (const auto& scenario : AUTO_STORY_RNG_LOOP_CASES){ + database.add(scenario); + } } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp index 57943c2dcd..a92f1bf0f9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp @@ -194,6 +194,6 @@ std::vector StarterRngPlanOptions::plan(Logger& logger, Language lan -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h index dc0a8e1343..44d73a275c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h @@ -54,6 +54,7 @@ class RngStopCalibrationOptions : public GroupOption{ }; +// User options for Starter RNG plan execution. class StarterRngPlanOptions : public GroupOption{ public: StarterRngPlanOptions(); @@ -94,7 +95,7 @@ class StarterRngPlanOptions : public GroupOption{ -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index fd5689010a..23a48261d8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -573,30 +573,38 @@ const char* handoff_name(StoryHandoff handoff){ return "?"; } -struct RunPlanScenario{ +struct RunPlanInput{ std::string name = ""; std::string first = ""; // The table's last row if empty. std::string last = ""; StoryHandoffs handoffs = {}; +}; + +struct RunPlanExpectation{ std::string expected_ids = ""; StoryHandoff expected_stop = StoryHandoff::NONE; }; +struct RunPlanTestCase{ + RunPlanInput input; + RunPlanExpectation expectation; +}; + class Test_RunPlan : public UnitTest{ public: - Test_RunPlan(RunPlanScenario scenario) - : UnitTest("PokemonFRLG::AutoStory - run plan: " + scenario.name) + explicit Test_RunPlan(RunPlanTestCase scenario) + : UnitTest("PokemonFRLG::AutoStory - run plan: " + scenario.input.name) , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ try{ - const size_t last = m_scenario.last.empty() ? story_checkpoints().size() - 1 : row_index(m_scenario.last); - const StoryRunPlan plan = plan_story_run(story_checkpoints(), row_index(m_scenario.first), last, m_scenario.handoffs); + const size_t last = m_scenario.input.last.empty() ? story_checkpoints().size() - 1 : row_index(m_scenario.input.last); + const StoryRunPlan plan = plan_story_run(story_checkpoints(), row_index(m_scenario.input.first), last, m_scenario.input.handoffs); const std::string ids = joined_ids(plan.rows); - if (ids != m_scenario.expected_ids || plan.stop != m_scenario.expected_stop){ - return "Expected rows \"" + m_scenario.expected_ids + "\", stop " + handoff_name(m_scenario.expected_stop) + if (ids != m_scenario.expectation.expected_ids || plan.stop != m_scenario.expectation.expected_stop){ + return "Expected rows \"" + m_scenario.expectation.expected_ids + "\", stop " + handoff_name(m_scenario.expectation.expected_stop) + "; got \"" + ids + "\", stop " + handoff_name(plan.stop) + "."; } return true; @@ -606,49 +614,58 @@ class Test_RunPlan : public UnitTest{ } private: - const RunPlanScenario m_scenario; + const RunPlanTestCase m_scenario; +}; + +const RunPlanTestCase RUN_PLAN_CASES[] = { + { + .input = {.name = "handoffs off: the story as before", .first = "00.01"}, + .expectation = {.expected_ids = "00.01 00.02 00.03 00.04 00.05 00.06 00.07 00.08 00.09 00.10"}, + }, + { + .input = {.name = "handoffs off: a range", .first = "00.02", .last = "00.04"}, + .expectation = {.expected_ids = "00.02 00.03 00.04"}, + }, + { + .input = {.name = "SID Helper: 00.01 stops on the keyboard", .first = "00.01", .handoffs = {.sid_helper = true}}, + .expectation = {.expected_ids = "", .expected_stop = StoryHandoff::SID_HELPER}, + }, + { + .input = {.name = "SID Helper: back in at 00.01b", .first = "00.01b", .last = "00.03", .handoffs = {.sid_helper = true}}, + .expectation = {.expected_ids = "00.01b 00.02 00.03"}, + }, + { + .input = {.name = "00.01b runs when started at, option off", .first = "00.01b", .last = "00.02"}, + .expectation = {.expected_ids = "00.01b 00.02"}, + }, + { + .input = {.name = "SID Helper: a later start passes over it", .first = "00.02", .last = "00.03", .handoffs = {.sid_helper = true}}, + .expectation = {.expected_ids = "00.02 00.03"}, + }, + { + .input = {.name = "handoffs off: an end at 00.04 still takes the rival's battle", .first = "00.03", .last = "00.04"}, + .expectation = {.expected_ids = "00.03 00.04"}, + }, + { + .input = {.name = "Starter RNG: stops after 00.04's save", .first = "00.02", .handoffs = {.starter_rng = true}}, + .expectation = {.expected_ids = "00.02 00.03 00.04", .expected_stop = StoryHandoff::STARTER_RNG}, + }, + { + .input = {.name = "00.04b runs from its own save", .first = "00.04b", .last = "00.05"}, + .expectation = {.expected_ids = "00.04b 00.05"}, + }, + { + .input = {.name = "Starter RNG: a later start doesn't stop", .first = "00.05", .last = "00.06", .handoffs = {.starter_rng = true}}, + .expectation = {.expected_ids = "00.05 00.06"}, + }, + { + .input = {.name = "both handoffs, back in after SID Helper", .first = "00.01b", .handoffs = {.sid_helper = true, .starter_rng = true}}, + .expectation = {.expected_ids = "00.01b 00.02 00.03 00.04", .expected_stop = StoryHandoff::STARTER_RNG}, + }, }; void add_tests_RunPlan(UnitTestDatabase& database){ - const std::string TODAY = "00.01 00.02 00.03 00.04 00.05 00.06 00.07 00.08 00.09 00.10"; - const RunPlanScenario scenarios[] = { - {.name = "handoffs off: the story as before", .first = "00.01", .expected_ids = TODAY}, - {.name = "handoffs off: a range", .first = "00.02", .last = "00.04", .expected_ids = "00.02 00.03 00.04"}, - { - .name = "SID Helper: 00.01 stops on the keyboard", - .first = "00.01", - .handoffs = {.sid_helper = true}, - .expected_ids = "", - .expected_stop = StoryHandoff::SID_HELPER, - }, - { - .name = "SID Helper: back in at 00.01b", - .first = "00.01b", - .last = "00.03", - .handoffs = {.sid_helper = true}, - .expected_ids = "00.01b 00.02 00.03", - }, - {.name = "00.01b runs when started at, option off", .first = "00.01b", .last = "00.02", .expected_ids = "00.01b 00.02"}, - {.name = "SID Helper: a later start passes over it", .first = "00.02", .last = "00.03", .handoffs = {.sid_helper = true}, .expected_ids = "00.02 00.03"}, - {.name = "handoffs off: an end at 00.04 still takes the rival's battle", .first = "00.03", .last = "00.04", .expected_ids = "00.03 00.04"}, - { - .name = "Starter RNG: stops after 00.04's save", - .first = "00.02", - .handoffs = {.starter_rng = true}, - .expected_ids = "00.02 00.03 00.04", - .expected_stop = StoryHandoff::STARTER_RNG, - }, - {.name = "00.04b runs from its own save", .first = "00.04b", .last = "00.05", .expected_ids = "00.04b 00.05"}, - {.name = "Starter RNG: a later start doesn't stop", .first = "00.05", .last = "00.06", .handoffs = {.starter_rng = true}, .expected_ids = "00.05 00.06"}, - { - .name = "both handoffs, back in after SID Helper", - .first = "00.01b", - .handoffs = {.sid_helper = true, .starter_rng = true}, - .expected_ids = "00.01b 00.02 00.03 00.04", - .expected_stop = StoryHandoff::STARTER_RNG, - }, - }; - for (const RunPlanScenario& scenario : scenarios){ + for (const auto& scenario : RUN_PLAN_CASES){ database.add(scenario); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp index 974acd42c9..ece34d24c1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp @@ -81,7 +81,7 @@ bool press_on_naming_screen( return true; } -} +} // namespace bool type_name( @@ -101,6 +101,6 @@ bool type_name_without_confirming( } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h index 65acefc8f4..3db414aedc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h @@ -37,7 +37,7 @@ bool type_name_without_confirming( ); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp index c148871808..1ab0e9aa39 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp @@ -267,7 +267,7 @@ NamingCursor append_moves_to_key(const NamingCursor& start, const char* key, std throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string("No path to naming screen key: ") + key); } -} +} // namespace NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action){ @@ -343,6 +343,6 @@ std::vector plan_naming_input( -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h index 496c46df63..4d9b7c1337 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h @@ -30,8 +30,11 @@ enum class NamingScreenPage : uint8_t{ LOWER, SYMBOLS, }; +// Total page count on naming screen. constexpr size_t NAMING_SCREEN_PAGES = 3; +// Number of key rows per page. constexpr size_t NAMING_SCREEN_KEY_ROWS = 4; +// Maximum key columns across pages. constexpr size_t NAMING_SCREEN_MAX_KEY_COLUMNS = 8; // Key columns on each page (sPageColumnCounts). The button column (page / back / OK) comes @@ -66,8 +69,12 @@ constexpr const char* NAMING_SCREEN_KEYS }; // The three buttons in the button column, top to bottom. +// The three buttons in the button column, top to bottom. +// Button index for switching character pages. constexpr uint8_t NAMING_SCREEN_BUTTON_PAGE = 0; +// Button index for backspacing a character. constexpr uint8_t NAMING_SCREEN_BUTTON_BACK = 1; +// Button index for confirming naming input. constexpr uint8_t NAMING_SCREEN_BUTTON_OK = 2; @@ -78,7 +85,9 @@ enum class NamingScreenKind : uint8_t{ BOX, // BOX_NAME_LENGTH POKEMON, // POKEMON_NAME_LENGTH, for caught Pokemon and the nickname rater }; +// Maximum character length for the given naming screen type. size_t naming_screen_max_chars(NamingScreenKind kind); +// Display name for naming screen kind. const char* naming_screen_kind_name(NamingScreenKind kind); @@ -94,9 +103,11 @@ struct NamingCursor{ bool operator==(const NamingCursor& other) const = default; }; +// String representation of cursor coordinates. std::string to_string(const NamingCursor& cursor); +// Input action on the naming screen keyboard. enum class NamingAction : uint8_t{ UP, DOWN, @@ -106,6 +117,7 @@ enum class NamingAction : uint8_t{ SELECT, // next page START, // move the cursor to OK }; +// String representation of naming action. const char* naming_action_name(NamingAction action); // Space-separated action names, e.g. "LEFT LEFT A START A". std::string to_string(const std::vector& actions); @@ -134,7 +146,7 @@ std::vector plan_naming_input( -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp index 54af553f9b..623f97c947 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp @@ -80,7 +80,7 @@ auto read_on_card(ConsoleHandle& console, ProControllerContext& context, Read re return tid; } -} +} // namespace uint16_t read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language){ uint16_t tid = read_on_card(console, context, [&](TrainerIdReader& reader, const VideoSnapshot& screen){ @@ -100,6 +100,6 @@ std::optional try_read_trainer_card_tid(ConsoleHandle& console, ProCon -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h index c52c212cba..16307cfce4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h @@ -35,7 +35,7 @@ std::optional try_read_trainer_card_tid(ConsoleHandle& console, ProCon -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp index b462362ec9..eae30812ce 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp @@ -75,7 +75,7 @@ RngAttempt make_attempt(const RngTarget& target, const std::vector return attempt; } -} +} // namespace std::vector plan_rng_attempts( @@ -154,6 +154,6 @@ std::vector plan_starter_rng(const StarterRngPlanInputs& inputs){ } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h index 3cc5276748..4408e4f8cf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h @@ -40,6 +40,7 @@ namespace PokemonFRLG{ std::vector sid_helper_candidates(uint16_t tid, uint32_t target_advances, uint8_t count); +// An individual RNG calibration attempt. struct RngAttempt{ RngTarget target; // The SIDs the target is shiny for, of those the attempts before it @@ -108,6 +109,7 @@ int64_t starter_rng_ingame_ms(uint64_t advances); // plan's targets are at least this many advances past Starter RNG's // minimum. To tune from the logs' calibrations. inline constexpr uint64_t STARTER_RNG_INGAME_MARGIN_ADVANCES = 720; +// Minimum advance threshold for planning starter attempts. inline constexpr uint64_t STARTER_RNG_PLAN_MIN_ADVANCES = STARTER_RNG_MIN_ADVANCES + STARTER_RNG_INGAME_MARGIN_ADVANCES; // The attempts for Starter RNG, from the seed list of the version and @@ -115,7 +117,7 @@ inline constexpr uint64_t STARTER_RNG_PLAN_MIN_ADVANCES = STARTER_RNG_MIN_ADVANC std::vector plan_starter_rng(const StarterRngPlanInputs& inputs); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp index 9e0d1a087f..67163884ef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp @@ -39,7 +39,7 @@ std::vector split(const std::string& text, char separator){ } } -} +} // namespace std::optional parse_trainer_id(const std::string& text){ @@ -101,6 +101,6 @@ std::optional> parse_natures(const std::string& text){ } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h index da7fe44525..ee606b7b07 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h @@ -26,6 +26,7 @@ std::optional parse_trainer_id(const std::string& text); // "HP/Atk/Def/SpA/SpD/Spe", as Ten Lines and the RNG programs list IVs. // Nothing for text that isn't six numbers from 0 to 31. std::optional parse_ivs(const std::string& text); +// Formats IV values as a comma-separated string. std::string ivs_to_string(const Pokemon::AdvIVs& ivs); // Natures separated by commas ("Modest, Timid"). Empty text is any nature @@ -33,7 +34,7 @@ std::string ivs_to_string(const Pokemon::AdvIVs& ivs); std::optional> parse_natures(const std::string& text); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp index 6cf8e40bde..fb9a978b41 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp @@ -22,22 +22,36 @@ using namespace Pokemon; namespace{ +struct RngPlanInputsInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanInputsExpectation{ + const char* description; +}; + +struct RngPlanInputsTestCase{ + RngPlanInputsInput input; + RngPlanInputsExpectation expectation; +}; + class Test_RngPlanInputs : public UnitTest{ public: - Test_RngPlanInputs(std::string name, std::function body) - : UnitTest("PokemonFRLG::RngPlanInputs - " + std::move(name)) - , m_body(std::move(body)) + explicit Test_RngPlanInputs(RngPlanInputsTestCase scenario) + : UnitTest("PokemonFRLG::RngPlanInputs - " + scenario.input.name) + , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_body(logger); + return m_scenario.input.body(logger); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + RngPlanInputsTestCase m_scenario; }; @@ -121,17 +135,32 @@ UnitTestResult test_parse_natures(Logger&){ return true; } -} +const RngPlanInputsTestCase RNG_PLAN_INPUTS_CASES[] = { + { + .input = {.name = "TID and SID text", .body = test_parse_trainer_id}, + .expectation = {.description = "parses TID and SID text formats"}, + }, + { + .input = {.name = "IVs text", .body = test_parse_ivs}, + .expectation = {.description = "parses six individual IV integer values"}, + }, + { + .input = {.name = "natures text", .body = test_parse_natures}, + .expectation = {.description = "parses comma-separated nature names"}, + }, +}; + +} // namespace void add_tests_RngPlanInputs(UnitTestDatabase& database){ - database.add("TID and SID text", test_parse_trainer_id); - database.add("IVs text", test_parse_ivs); - database.add("natures text", test_parse_natures); + for (const auto& scenario : RNG_PLAN_INPUTS_CASES){ + database.add(scenario); + } } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h index 5da86a73d4..836fcfee94 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Registers RNG plan input parsing unit tests. void add_tests_RngPlanInputs(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp index a10f229e73..a81eec85cf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp @@ -26,7 +26,7 @@ std::string join_sids(const std::vector& sids){ return text; } -} +} // namespace std::string rng_log_tid(uint16_t tid, bool from_card){ return std::format("RngPlan: tid={} source={}", tid, from_card ? "card" : "option"); @@ -80,7 +80,7 @@ const char* next_name(RngPlanNext next){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanNext."); } -} +} // namespace std::string rng_log_result(const RngResultLog& result){ const std::optional& pokemon = result.pokemon; @@ -132,6 +132,6 @@ std::vector rng_attempt_lines(const std::vector& attemp } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h index f46954234b..4d3b3f6e4f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h @@ -53,9 +53,12 @@ std::vector rng_attempt_lines(const std::vector& attemp // Starter RNG by hand, its own "Target Hit!" and "Missed target." lines // are the attempts' results. std::string rng_log_tid(uint16_t tid, bool from_card); +// Formats SID Helper summary line for log output. std::string rng_log_sid_helper(uint16_t tid, uint32_t target_advances, const std::vector& candidates); +// Formats attempt parameters for log output. std::string rng_log_attempt(size_t index, const RngAttempt& attempt); +// Structured log summary of an RNG outcome. struct RngResultLog{ size_t index = 0; // From 1. @@ -67,11 +70,13 @@ struct RngResultLog{ std::optional pokemon; RngPlanNext next = RngPlanNext::STOP; }; +// Formats RNG attempt result for logging. std::string rng_log_result(const RngResultLog& result); +// Formats confirmed SID and candidate weights for logging. std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp index c69e725da9..167bf0f628 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp @@ -25,22 +25,36 @@ using namespace RngPlanTestTargets; namespace{ +struct RngPlanLogInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanLogExpectation{ + const char* description; +}; + +struct RngPlanLogTestCase{ + RngPlanLogInput input; + RngPlanLogExpectation expectation; +}; + class Test_RngPlanLog : public UnitTest{ public: - Test_RngPlanLog(std::string name, std::function body) - : UnitTest("PokemonFRLG::RngPlanLog - " + std::move(name)) - , m_body(std::move(body)) + explicit Test_RngPlanLog(RngPlanLogTestCase scenario) + : UnitTest("PokemonFRLG::RngPlanLog - " + scenario.input.name) + , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_body(logger); + return m_scenario.input.body(logger); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + RngPlanLogTestCase m_scenario; }; @@ -95,15 +109,24 @@ UnitTestResult test_log_lines(Logger&){ return true; } -} +const RngPlanLogTestCase RNG_PLAN_LOG_CASES[] = { + { + .input = {.name = "RngPlan log lines", .body = test_log_lines}, + .expectation = {.description = "verifies structured RNG plan log lines formatting"}, + }, +}; + +} // namespace void add_tests_RngPlanLog(UnitTestDatabase& database){ - database.add("RngPlan log lines", test_log_lines); + for (const auto& scenario : RNG_PLAN_LOG_CASES){ + database.add(scenario); + } } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h index 9f62eb0b0a..b06f432443 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Registers RNG plan logging unit tests. void add_tests_RngPlanLog(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp index 5e5bc27838..5fc1b663e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp @@ -53,9 +53,9 @@ const std::vector TARGETS = { }; -} +} // namespace RngPlanTestTargets -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h index 017d9cd6a8..e76decb033 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h @@ -22,6 +22,7 @@ namespace PokemonFRLG{ namespace RngPlanTestTargets{ +// Formats vector of integer values as space-delimited string. std::string join(const std::vector& values); // SIDs 100, 200 and 300 weigh 3, 2 and 1. @@ -37,10 +38,10 @@ RngTarget make_target(uint32_t state, uint64_t seconds, std::vector shin extern const std::vector TARGETS; -} +} // namespace RngPlanTestTargets -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp index 230a25a433..c857f65b93 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp @@ -129,6 +129,6 @@ RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index){ } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h index 3875f3bdbf..6064306511 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h @@ -36,14 +36,16 @@ enum class RngAttemptOutcome{ UNUSABLE, }; +// Outcome details from an attempted RNG frame hit. struct RngAttemptResult{ bool shiny; Pokemon::AdvNature nature; Pokemon::AdvIVs ivs; }; +// Classifies attempt result relative to target specifications. RngAttemptOutcome classify_attempt(const RngTarget& target, const RngAttemptResult& result); - +// Current execution phase within the RNG plan state machine. enum class RngPlanStep{ // Run current_attempt(): the first, the next, or the same again after a miss. RUN_ATTEMPT, @@ -113,7 +115,7 @@ enum class RngPlanNext{ RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp index cd4ed2b5ce..987daa3140 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp @@ -26,22 +26,36 @@ using namespace RngPlanTestTargets; namespace{ +struct RngPlanTrackerInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanTrackerExpectation{ + const char* description; +}; + +struct RngPlanTrackerTestCase{ + RngPlanTrackerInput input; + RngPlanTrackerExpectation expectation; +}; + class Test_RngPlanTracker : public UnitTest{ public: - Test_RngPlanTracker(std::string name, std::function body) - : UnitTest("PokemonFRLG::RngPlanTracker - " + std::move(name)) - , m_body(std::move(body)) + explicit Test_RngPlanTracker(RngPlanTrackerTestCase scenario) + : UnitTest("PokemonFRLG::RngPlanTracker - " + scenario.input.name) + , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_body(logger); + return m_scenario.input.body(logger); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + RngPlanTrackerTestCase m_scenario; }; @@ -247,16 +261,28 @@ UnitTestResult test_tracker(Logger&){ return true; } -} +const RngPlanTrackerTestCase RNG_PLAN_TRACKER_CASES[] = { + { + .input = {.name = "attempt outcome", .body = test_classify}, + .expectation = {.description = "classifies outcome of target attempt"}, + }, + { + .input = {.name = "step after each outcome", .body = test_tracker}, + .expectation = {.description = "evaluates state transitions after attempt outcomes"}, + }, +}; + +} // namespace void add_tests_RngPlanTracker(UnitTestDatabase& database){ - database.add("attempt outcome", test_classify); - database.add("step after each outcome", test_tracker); + for (const auto& scenario : RNG_PLAN_TRACKER_CASES){ + database.add(scenario); + } } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h index 725491c896..a0406bf2f3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Registers RNG plan tracker unit tests. void add_tests_RngPlanTracker(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp index 508ba5fa34..a6cea3e727 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp @@ -28,22 +28,36 @@ using namespace RngPlanTestTargets; namespace{ +struct RngPlanInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanExpectation{ + const char* description; +}; + +struct RngPlanTestCase{ + RngPlanInput input; + RngPlanExpectation expectation; +}; + class Test_RngPlan : public UnitTest{ public: - Test_RngPlan(std::string name, std::function body) - : UnitTest("PokemonFRLG::RngPlan - " + std::move(name)) - , m_body(std::move(body)) + explicit Test_RngPlan(RngPlanTestCase scenario) + : UnitTest("PokemonFRLG::RngPlan - " + scenario.input.name) + , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_body(logger); + return m_scenario.input.body(logger); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + RngPlanTestCase m_scenario; }; @@ -269,19 +283,40 @@ UnitTestResult test_starter_plan(Logger&){ return true; } -} +const RngPlanTestCase RNG_PLAN_CASES[] = { + { + .input = {.name = "SID Helper's candidates and weights", .body = test_sid_helper_candidates}, + .expectation = {.description = "evaluates SID Helper candidates and candidate weighting"}, + }, + { + .input = {.name = "attempt order", .body = test_plan_order}, + .expectation = {.description = "validates chronological ordering of plan attempts"}, + }, + { + .input = {.name = "Starter RNG plan from the FireRed list", .body = test_starter_plan}, + .expectation = {.description = "builds Starter RNG plan from FireRed seed list"}, + }, + { + .input = {.name = "Starter RNG plan: no seed too early for the title screen", .body = test_starter_plan_seed_delay}, + .expectation = {.description = "filters out seeds too early for title screen timing"}, + }, + { + .input = {.name = "Starter RNG plan: room for the in-game calibration", .body = test_starter_ingame_wait}, + .expectation = {.description = "allows sufficient margin for in-game calibration advances"}, + }, +}; + +} // namespace void add_tests_RngPlan(UnitTestDatabase& database){ - database.add("SID Helper's candidates and weights", test_sid_helper_candidates); - database.add("attempt order", test_plan_order); - database.add("Starter RNG plan from the FireRed list", test_starter_plan); - database.add("Starter RNG plan: no seed too early for the title screen", test_starter_plan_seed_delay); - database.add("Starter RNG plan: room for the in-game calibration", test_starter_ingame_wait); + for (const auto& scenario : RNG_PLAN_CASES){ + database.add(scenario); + } } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h index 80d2408130..66c39522e7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Registers RNG plan unit tests. void add_tests_RngPlan(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp index 32b1d9d90f..8b054d7ab1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp @@ -27,23 +27,31 @@ using namespace Pokemon; namespace{ -struct SidTimingRow{ +struct SidTimingInput{ Language language; uint32_t target_advances; +}; + +struct SidTimingExpectation{ uint64_t delay_ms; bool extra_press_at_end; }; +struct SidTimingRow{ + SidTimingInput input; + SidTimingExpectation expectation; +}; + // (target_advances - 2 * final text frames + 7) frames of 1000 / 59.999977 ms, // halved since advances pass 2 by 2. const std::vector SID_TIMING_ROWS = { - {.language = Language::English, .target_advances = 3001, .delay_ms = 20916, .extra_press_at_end = false}, - {.language = Language::English, .target_advances = 2275, .delay_ms = 14866, .extra_press_at_end = false}, - {.language = Language::Japanese, .target_advances = 3001, .delay_ms = 21833, .extra_press_at_end = true}, - {.language = Language::Italian, .target_advances = 3001, .delay_ms = 21133, .extra_press_at_end = false}, - {.language = Language::French, .target_advances = 3001, .delay_ms = 21650, .extra_press_at_end = true}, - {.language = Language::German, .target_advances = 3001, .delay_ms = 21600, .extra_press_at_end = true}, - {.language = Language::Spanish, .target_advances = 2275, .delay_ms = 15650, .extra_press_at_end = true}, + {.input = {.language = Language::English, .target_advances = 3001}, .expectation = {.delay_ms = 20916, .extra_press_at_end = false}}, + {.input = {.language = Language::English, .target_advances = 2275}, .expectation = {.delay_ms = 14866, .extra_press_at_end = false}}, + {.input = {.language = Language::Japanese, .target_advances = 3001}, .expectation = {.delay_ms = 21833, .extra_press_at_end = true}}, + {.input = {.language = Language::Italian, .target_advances = 3001}, .expectation = {.delay_ms = 21133, .extra_press_at_end = false}}, + {.input = {.language = Language::French, .target_advances = 3001}, .expectation = {.delay_ms = 21650, .extra_press_at_end = true}}, + {.input = {.language = Language::German, .target_advances = 3001}, .expectation = {.delay_ms = 21600, .extra_press_at_end = true}}, + {.input = {.language = Language::Spanish, .target_advances = 2275}, .expectation = {.delay_ms = 15650, .extra_press_at_end = true}}, }; class Test_SidTiming : public UnitTest{ @@ -51,17 +59,17 @@ class Test_SidTiming : public UnitTest{ explicit Test_SidTiming(const SidTimingRow& row) : UnitTest(std::format( "PokemonFRLG::RngSteps - SID timing {} {}", - language_data(row.language).name, row.target_advances + language_data(row.input.language).name, row.input.target_advances )) , m_row(row) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - SidTiming timing = sid_timing(m_row.language, m_row.target_advances); - if (timing.delay_ms != m_row.delay_ms || timing.extra_press_at_end != m_row.extra_press_at_end){ + SidTiming timing = sid_timing(m_row.input.language, m_row.input.target_advances); + if (timing.delay_ms != m_row.expectation.delay_ms || timing.extra_press_at_end != m_row.expectation.extra_press_at_end){ return std::format( "Expected delay {} ms, extra press {}; got {} ms, extra press {}", - m_row.delay_ms, m_row.extra_press_at_end, + m_row.expectation.delay_ms, m_row.expectation.extra_press_at_end, timing.delay_ms, timing.extra_press_at_end ); } @@ -73,35 +81,46 @@ class Test_SidTiming : public UnitTest{ }; -struct StarterRow{ +struct StarterInput{ StarterSpecies starter; std::string name; +}; + +struct StarterExpectation{ BaseStats base_stats; EVs rival_ev_yield; int steps_left; }; +struct StarterRow{ + StarterInput input; + StarterExpectation expectation; +}; + const std::vector STARTER_ROWS = { { - .starter = StarterSpecies::bulbasaur, - .name = "Bulbasaur", - .base_stats = {45, 49, 49, 65, 65, 45}, - .rival_ev_yield = {0, 0, 0, 0, 0, 1}, - .steps_left = 2, + .input = {.starter = StarterSpecies::bulbasaur, .name = "Bulbasaur"}, + .expectation = { + .base_stats = {45, 49, 49, 65, 65, 45}, + .rival_ev_yield = {0, 0, 0, 0, 0, 1}, + .steps_left = 2, + }, }, { - .starter = StarterSpecies::squirtle, - .name = "Squirtle", - .base_stats = {44, 48, 65, 50, 64, 43}, - .rival_ev_yield = {0, 0, 0, 1, 0, 0}, - .steps_left = 3, + .input = {.starter = StarterSpecies::squirtle, .name = "Squirtle"}, + .expectation = { + .base_stats = {44, 48, 65, 50, 64, 43}, + .rival_ev_yield = {0, 0, 0, 1, 0, 0}, + .steps_left = 3, + }, }, { - .starter = StarterSpecies::charmander, - .name = "Charmander", - .base_stats = {39, 52, 43, 60, 50, 65}, - .rival_ev_yield = {0, 0, 1, 0, 0, 0}, - .steps_left = 4, + .input = {.starter = StarterSpecies::charmander, .name = "Charmander"}, + .expectation = { + .base_stats = {39, 52, 43, 60, 50, 65}, + .rival_ev_yield = {0, 0, 1, 0, 0, 0}, + .steps_left = 4, + }, }, }; @@ -115,20 +134,20 @@ std::string to_string(const EVs& evs){ class Test_StarterTables : public UnitTest{ public: explicit Test_StarterTables(const StarterRow& row) - : UnitTest("PokemonFRLG::RngSteps - Starter tables " + row.name) + : UnitTest("PokemonFRLG::RngSteps - Starter tables " + row.input.name) , m_row(row) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ std::string expected = std::format( "base stats {}, rival EVs {}, steps left {}", - to_string(m_row.base_stats), to_string(m_row.rival_ev_yield), m_row.steps_left + to_string(m_row.expectation.base_stats), to_string(m_row.expectation.rival_ev_yield), m_row.expectation.steps_left ); std::string got = std::format( "base stats {}, rival EVs {}, steps left {}", - to_string(starter_base_stats(m_row.starter)), - to_string(rival_ev_yield(m_row.starter)), - steps_left_to_lab_door(m_row.starter) + to_string(starter_base_stats(m_row.input.starter)), + to_string(rival_ev_yield(m_row.input.starter)), + steps_left_to_lab_door(m_row.input.starter) ); if (expected != got){ return "Expected " + expected + "; got " + got; @@ -142,20 +161,30 @@ class Test_StarterTables : public UnitTest{ +// A state's (seed, advance). +using SeedAdvance = std::pair; + // Target: seed 0x70FE, advance 1000. -struct ShinyRow{ +struct ShinyInput{ std::string name; - // The (seed, advance) of each state the shiny's stats match. - std::vector> hits; + std::vector hits; +}; + +struct ShinyExpectation{ StarterRngOutcome expected; }; +struct ShinyRow{ + ShinyInput input; + ShinyExpectation expectation; +}; + const std::vector SHINY_ROWS = { - {.name = "the target alone", .hits = {{0x70fe, 1000}}, .expected = StarterRngOutcome::shiny_on_target}, - {.name = "the target among others", .hits = {{0x70fe, 998}, {0x70fe, 1000}, {0x70ff, 1000}}, .expected = StarterRngOutcome::shiny_on_target}, - {.name = "another advance", .hits = {{0x70fe, 1002}}, .expected = StarterRngOutcome::shiny_off_target}, - {.name = "another seed", .hits = {{0x70fd, 1000}}, .expected = StarterRngOutcome::shiny_off_target}, - {.name = "no match", .hits = {}, .expected = StarterRngOutcome::shiny}, + {.input = {.name = "the target alone", .hits = {{0x70fe, 1000}}}, .expectation = {.expected = StarterRngOutcome::shiny_on_target}}, + {.input = {.name = "the target among others", .hits = {{0x70fe, 998}, {0x70fe, 1000}, {0x70ff, 1000}}}, .expectation = {.expected = StarterRngOutcome::shiny_on_target}}, + {.input = {.name = "another advance", .hits = {{0x70fe, 1002}}}, .expectation = {.expected = StarterRngOutcome::shiny_off_target}}, + {.input = {.name = "another seed", .hits = {{0x70fd, 1000}}}, .expectation = {.expected = StarterRngOutcome::shiny_off_target}}, + {.input = {.name = "no match", .hits = {}}, .expectation = {.expected = StarterRngOutcome::shiny}}, }; const char* outcome_name(StarterRngOutcome outcome){ @@ -174,21 +203,21 @@ const char* outcome_name(StarterRngOutcome outcome){ class Test_IdentifyShiny : public UnitTest{ public: explicit Test_IdentifyShiny(const ShinyRow& row) - : UnitTest("PokemonFRLG::RngSteps - Shiny " + row.name) + : UnitTest("PokemonFRLG::RngSteps - Shiny " + row.input.name) , m_row(row) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ std::vector hits; - for (const auto& [seed, advance] : m_row.hits){ + for (const auto& [seed, advance] : m_row.input.hits){ AdvRngState hit{}; hit.seed = seed; hit.advance = advance; hits.push_back(hit); } const StarterRngOutcome got = identify_shiny(0x70fe, 1000, hits); - if (got != m_row.expected){ - return std::string("Expected ") + outcome_name(m_row.expected) + ", got " + outcome_name(got); + if (got != m_row.expectation.expected){ + return std::string("Expected ") + outcome_name(m_row.expectation.expected) + ", got " + outcome_name(got); } return true; } @@ -205,52 +234,67 @@ AdvRngState state(uint16_t seed, uint64_t advance){ return hit; } -// A state's (seed, advance). -using SeedAdvance = std::pair; std::string state_text(const std::optional& state){ return state ? std::format("{:04x}/{}", state->first, state->second) : "none"; } -struct ResetHitRow{ +struct ResetHitInput{ std::string name; // The reset's hits, and what update_history() left after it. std::vector hits; size_t uncertain = 0; std::vector calibrated; +}; + +struct ResetHitExpectation{ // The (seed, advance) taken as hit, if any. std::optional expected; }; +struct ResetHitRow{ + ResetHitInput input; + ResetHitExpectation expectation; +}; + const std::vector RESET_HIT_ROWS = { - {.name = "one hit", .hits = {state(0x70fe, 1001)}, .uncertain = 0, .calibrated = {state(0x70fe, 1001)}, .expected = SeedAdvance{0x70fe, 1001}}, { - .name = "settled by the history", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 0, - .calibrated = {state(0x70fd, 1004), state(0x70ff, 1003)}, .expected = SeedAdvance{0x70ff, 1003}, + .input = {.name = "one hit", .hits = {state(0x70fe, 1001)}, .uncertain = 0, .calibrated = {state(0x70fe, 1001)}}, + .expectation = {.expected = SeedAdvance{0x70fe, 1001}}, + }, + { + .input = {.name = "settled by the history", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 0, .calibrated = {state(0x70fd, 1004), state(0x70ff, 1003)}}, + .expectation = {.expected = SeedAdvance{0x70ff, 1003}}, + }, + { + .input = {.name = "a tie", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 2, .calibrated = {state(0x70fd, 1004)}}, + .expectation = {.expected = std::nullopt}, + }, + { + .input = {.name = "no hits", .hits = {}, .uncertain = 0, .calibrated = {state(0x70fd, 1004)}}, + .expectation = {.expected = std::nullopt}, }, - {.name = "a tie", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 2, .calibrated = {state(0x70fd, 1004)}, .expected = std::nullopt}, - {.name = "no hits", .hits = {}, .uncertain = 0, .calibrated = {state(0x70fd, 1004)}, .expected = std::nullopt}, }; class Test_ResetHit : public UnitTest{ public: explicit Test_ResetHit(const ResetHitRow& row) - : UnitTest("PokemonFRLG::RngSteps - Reset hit " + row.name) + : UnitTest("PokemonFRLG::RngSteps - Reset hit " + row.input.name) , m_row(row) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ RngUncertainHistory uncertain; - uncertain.results.resize(m_row.uncertain); + uncertain.results.resize(m_row.input.uncertain); RngCalibrationHistory calibration; - calibration.results = m_row.calibrated; - const std::optional hit = reset_hit(uncertain, calibration, m_row.hits); + calibration.results = m_row.input.calibrated; + const std::optional hit = reset_hit(uncertain, calibration, m_row.input.hits); std::optional got; if (hit){ got = SeedAdvance{hit->seed, hit->advance}; } - if (got != m_row.expected){ - return "Expected " + state_text(m_row.expected) + ", got " + state_text(got); + if (got != m_row.expectation.expected){ + return "Expected " + state_text(m_row.expectation.expected) + ", got " + state_text(got); } return true; } @@ -259,7 +303,7 @@ class Test_ResetHit : public UnitTest{ ResetHitRow m_row; }; -} +} // namespace void add_tests_RngSteps(UnitTestDatabase& database){ @@ -278,6 +322,6 @@ void add_tests_RngSteps(UnitTestDatabase& database){ } -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h index a5bca3130c..4d771cd519 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h @@ -18,7 +18,7 @@ namespace PokemonFRLG{ void add_tests_RngSteps(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp index 699e4c051e..af2a8de742 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp @@ -34,7 +34,7 @@ const uint32_t LCRNG_ADD_INVERSE = 0x0a3561a1; // The GBA frame rate, as Ten Lines uses it (SYSTEM_TIMING_DATA in src/tenLines/index.ts). const double GBA_FRAMES_PER_SECOND = 16777216.0 / 280896.0; -} +} // namespace uint32_t lcrng_next(uint32_t state){ @@ -373,7 +373,7 @@ void search_iv_states(const LowBitsTable& table, const AdvIVs& min_ivs, TargetCo } } -} +} // namespace std::vector search_rng_targets( @@ -412,6 +412,6 @@ void rank_rng_targets(std::vector& targets){ -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h index bfe0c90a68..83620b0bcf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h @@ -38,6 +38,7 @@ namespace PokemonFRLG{ // The Gen 3 LCRNG: state * 0x41C64E6D + 0x6073. uint32_t lcrng_next(uint32_t state); +// Steps the Gen 3 LCRNG backward by one advance. uint32_t lcrng_previous(uint32_t state); // How many lcrng_next() calls take "from" to "to". The LCRNG has a single cycle of // 2^32 states, so every pair has exactly one distance. @@ -48,12 +49,15 @@ uint32_t lcrng_distance(uint32_t from, uint32_t to); // the two after that the IVs (HP/Atk/Def, then Spe/SpA/SpD). Pokemon::AdvPokemonResult method1_pokemon(uint32_t state); +// Determines shiny type (none, star, square) from PID and trainer IDs. Pokemon::AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid); +// Calculated Hidden Power typing and base power. struct HiddenPower{ std::string type; uint8_t power; }; +// Calculates Hidden Power attributes from individual values. HiddenPower hidden_power(const Pokemon::AdvIVs& ivs); @@ -81,12 +85,14 @@ std::vector initial_seed_entries( ); +// Candidate SID with associated relative weight. struct SidCandidate{ uint16_t sid; // Relative likelihood. The weights need not add up to 1. double weight; }; +// Criteria for filtering acceptable RNG targets. struct RngTargetFilters{ // Empty: any nature. std::vector natures; @@ -109,12 +115,14 @@ struct RngTargetFilters{ uint64_t avoided_seed_time_radius_ms = 0; }; +// A candidate target evaluated for shininess against an SID candidate. struct ShinyCandidate{ // Index into the SID candidates. size_t candidate; Pokemon::AdvShinyType type; }; +// A target RNG state and its rolled attributes. struct RngTarget{ // The RNG state before the PID is rolled: the "Target" column of Ten Lines. uint32_t state; @@ -144,7 +152,7 @@ void rank_rng_targets(std::vector& targets); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp index 71dec39025..df407eb24b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp @@ -226,30 +226,18 @@ std::string check_advances(const TenLinesRow& row){ return ""; } -class Test_RngTargetMethod1 : public UnitTest{ -public: - Test_RngTargetMethod1(TenLinesGroup group) - : UnitTest("PokemonFRLG::RngTargetSearch - Method 1 - " + group.name) - , m_group(std::move(group)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - for (const TenLinesRow& row : parse_rows(m_group.rows)){ - std::string error = check_pokemon(row, m_group); - if (error.empty()){ - error = check_advances(row); - } - if (!error.empty()){ - return error; - } +UnitTestResult run_method1(const TenLinesGroup& group){ + for (const TenLinesRow& row : parse_rows(group.rows)){ + std::string error = check_pokemon(row, group); + if (error.empty()){ + error = check_advances(row); + } + if (!error.empty()){ + return error; } - return true; } - -private: - const TenLinesGroup m_group; -}; - + return true; +} RngTargetFilters ten_lines_filters(const TenLinesGroup& group){ RngTargetFilters filters; @@ -298,149 +286,193 @@ std::string compare_target(const TenLinesRow& row, const RngTarget& target){ return ""; } -class Test_RngTargetSearch : public UnitTest{ -public: - Test_RngTargetSearch(TenLinesGroup group) - : UnitTest("PokemonFRLG::RngTargetSearch - Search - " + group.name) - , m_group(std::move(group)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - std::vector targets = search_rng_targets( - leafgreen_mono_help_seeds(), TID, {{SID, 1}}, ten_lines_filters(m_group) - ); - std::vector rows = parse_rows(m_group.rows); - if (targets.size() < rows.size()){ - return "Expected at least " + std::to_string(rows.size()) + " targets, got " + std::to_string(targets.size()); - } - for (size_t c = 0; c < rows.size(); c++){ - std::string error = compare_target(rows[c], targets[c]); - if (!error.empty()){ - return "Target #" + std::to_string(c + 1) + ": " + error; - } +UnitTestResult run_search(const TenLinesGroup& group){ + std::vector targets = search_rng_targets( + leafgreen_mono_help_seeds(), TID, {{SID, 1}}, ten_lines_filters(group) + ); + std::vector rows = parse_rows(group.rows); + if (targets.size() < rows.size()){ + return "Expected at least " + std::to_string(rows.size()) + " targets, got " + std::to_string(targets.size()); + } + for (size_t c = 0; c < rows.size(); c++){ + std::string error = compare_target(rows[c], targets[c]); + if (!error.empty()){ + return "Target #" + std::to_string(c + 1) + ": " + error; } - return true; } + return true; +} -private: - const TenLinesGroup m_group; -}; - - -// Searching every IV combination finds the same shiny targets as searching shiny PIDs. -class Test_RngTargetIvSearch : public UnitTest{ -public: - Test_RngTargetIvSearch() - : UnitTest("PokemonFRLG::RngTargetSearch - IV search") - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const TenLinesGroup group = groups()[2]; - std::vector seeds = leafgreen_mono_help_seeds(); - RngTargetFilters filters = ten_lines_filters(group); - std::vector shiny = search_rng_targets(seeds, TID, {{SID, 1}}, filters); - - filters.shiny_required = false; - std::vector any = search_rng_targets(seeds, TID, {{SID, 1}}, filters); - std::vector any_shiny; - for (const RngTarget& target : any){ - if (!target.shiny_for.empty()){ - any_shiny.push_back(target); - } +UnitTestResult run_iv_search(){ + const TenLinesGroup group = groups()[2]; + std::vector seeds = leafgreen_mono_help_seeds(); + RngTargetFilters filters = ten_lines_filters(group); + std::vector shiny = search_rng_targets(seeds, TID, {{SID, 1}}, filters); + + filters.shiny_required = false; + std::vector any = search_rng_targets(seeds, TID, {{SID, 1}}, filters); + std::vector any_shiny; + for (const RngTarget& target : any){ + if (!target.shiny_for.empty()){ + any_shiny.push_back(target); } - if (any.size() <= any_shiny.size()){ - return "Expected targets that are not shiny"; + } + if (any.size() <= any_shiny.size()){ + return "Expected targets that are not shiny"; + } + if (any_shiny.size() != shiny.size()){ + return "Expected " + std::to_string(shiny.size()) + " shiny targets, got " + std::to_string(any_shiny.size()); + } + for (size_t c = 0; c < shiny.size(); c++){ + if (any_shiny[c].state != shiny[c].state || any_shiny[c].advances != shiny[c].advances){ + return "Shiny target #" + std::to_string(c + 1) + " differs: " + hex(any_shiny[c].state); } - if (any_shiny.size() != shiny.size()){ - return "Expected " + std::to_string(shiny.size()) + " shiny targets, got " + std::to_string(any_shiny.size()); + } + return true; +} + +UnitTestResult run_candidates(){ + const TenLinesGroup group = groups()[0]; + const uint16_t other_sid = SID ^ 0x0100; + std::vector targets = search_rng_targets( + leafgreen_mono_help_seeds(), TID, {{SID, 3}, {other_sid, 1}}, ten_lines_filters(group) + ); + size_t found = 0; + for (const RngTarget& target : targets){ + if (target.shiny_for.size() != 1){ + return "Target " + hex(target.state) + " is shiny for " + std::to_string(target.shiny_for.size()) + " SIDs"; } - for (size_t c = 0; c < shiny.size(); c++){ - if (any_shiny[c].state != shiny[c].state || any_shiny[c].advances != shiny[c].advances){ - return "Shiny target #" + std::to_string(c + 1) + " differs: " + hex(any_shiny[c].state); - } + double expected = target.shiny_for[0].candidate == 0 ? 0.75 : 0.25; + if (target.shiny_probability != expected){ + return "Target " + hex(target.state) + " has shiny probability " + std::to_string(target.shiny_probability); } - return true; + found += target.shiny_for[0].candidate == 0 && target.advances <= 171172; + } + if (found != 20){ + return "Expected the 20 Ten Lines targets for SID " + std::to_string(SID) + ", got " + std::to_string(found); + } + return true; +} + +UnitTestResult run_ranking(){ + auto target = [](uint32_t state, uint64_t advances, double probability){ + RngTarget ret{state, {0, 40000, SeedButton::A, BlackoutButton::None}, advances, {}, {}, probability}; + return ret; + }; + std::vector targets{ + target(0xA, 10000, 0.5), + target(0xB, 12500, 1), + target(0xC, 100, 0), + target(0xD, 1000, 0.1), + }; + rank_rng_targets(targets); + std::string order; + for (const RngTarget& item : targets){ + order += hex(item.state); + } + if (order != "BADC"){ + return "Expected order BADC, got " + order; } + return true; +} + +enum class RngTargetSearchKind{ + Method1, + Search, + IvSearch, + Candidates, + Ranking, }; +struct RngTargetSearchInput{ + std::string name; + RngTargetSearchKind kind = RngTargetSearchKind::Method1; + size_t group_index = 0; +}; -// A second SID candidate: each target is shiny for one of the two, by weight. -class Test_RngTargetCandidates : public UnitTest{ -public: - Test_RngTargetCandidates() - : UnitTest("PokemonFRLG::RngTargetSearch - SID candidates") - {} +struct RngTargetSearchExpectation{ + std::string description = ""; +}; - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const TenLinesGroup group = groups()[0]; - const uint16_t other_sid = SID ^ 0x0100; - std::vector targets = search_rng_targets( - leafgreen_mono_help_seeds(), TID, {{SID, 3}, {other_sid, 1}}, ten_lines_filters(group) - ); - size_t found = 0; - for (const RngTarget& target : targets){ - if (target.shiny_for.size() != 1){ - return "Target " + hex(target.state) + " is shiny for " + std::to_string(target.shiny_for.size()) + " SIDs"; - } - double expected = target.shiny_for[0].candidate == 0 ? 0.75 : 0.25; - if (target.shiny_probability != expected){ - return "Target " + hex(target.state) + " has shiny probability " + std::to_string(target.shiny_probability); - } - found += target.shiny_for[0].candidate == 0 && target.advances <= 171172; - } - if (found != 20){ - return "Expected the 20 Ten Lines targets for SID " + std::to_string(SID) + ", got " + std::to_string(found); - } - return true; - } +struct RngTargetSearchCase{ + RngTargetSearchInput input; + RngTargetSearchExpectation expectation; }; +const RngTargetSearchCase RNG_TARGET_SEARCH_CASES[] = { + { + .input = {.name = "Method 1 - Modest", .kind = RngTargetSearchKind::Method1, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "Method 1 - Adamant", .kind = RngTargetSearchKind::Method1, .group_index = 1}, + .expectation = {}, + }, + { + .input = {.name = "Method 1 - Neutral", .kind = RngTargetSearchKind::Method1, .group_index = 2}, + .expectation = {}, + }, + { + .input = {.name = "Search - Modest", .kind = RngTargetSearchKind::Search, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "Search - Adamant", .kind = RngTargetSearchKind::Search, .group_index = 1}, + .expectation = {}, + }, + { + .input = {.name = "Search - Neutral", .kind = RngTargetSearchKind::Search, .group_index = 2}, + .expectation = {}, + }, + { + .input = {.name = "IV search", .kind = RngTargetSearchKind::IvSearch, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "SID candidates", .kind = RngTargetSearchKind::Candidates, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "Ranking", .kind = RngTargetSearchKind::Ranking, .group_index = 0}, + .expectation = {}, + }, +}; -class Test_RngTargetRanking : public UnitTest{ +class Test_RngTargetSearch : public UnitTest{ public: - Test_RngTargetRanking() - : UnitTest("PokemonFRLG::RngTargetSearch - Ranking") + explicit Test_RngTargetSearch(const RngTargetSearchCase& test_case) + : UnitTest("PokemonFRLG::RngTargetSearch - " + test_case.input.name) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - auto target = [](uint32_t state, uint64_t advances, double probability){ - RngTarget ret{state, {0, 40000, SeedButton::A, BlackoutButton::None}, advances, {}, {}, probability}; - return ret; - }; - // About 60 advances per second, after a 40 s seed time: A takes 207 s and B 249 s, - // but A is shiny only half the time. D takes 57 s, but is shiny one time in 10. - std::vector targets{ - target(0xA, 10000, 0.5), - target(0xB, 12500, 1), - target(0xC, 100, 0), - target(0xD, 1000, 0.1), - }; - rank_rng_targets(targets); - std::string order; - for (const RngTarget& item : targets){ - order += hex(item.state); + switch (m_case.input.kind){ + case RngTargetSearchKind::Method1: + return run_method1(groups()[m_case.input.group_index]); + case RngTargetSearchKind::Search: + return run_search(groups()[m_case.input.group_index]); + case RngTargetSearchKind::IvSearch: + return run_iv_search(); + case RngTargetSearchKind::Candidates: + return run_candidates(); + case RngTargetSearchKind::Ranking: + return run_ranking(); } - if (order != "BADC"){ - return "Expected order BADC, got " + order; - } - return true; + return "Unknown test kind"; } -}; -} +private: + const RngTargetSearchCase m_case; +}; +} // namespace void add_tests_RngTargetSearch(UnitTestDatabase& database){ - for (const TenLinesGroup& group : groups()){ - database.add(group); - database.add(group); + for (const RngTargetSearchCase& test_case : RNG_TARGET_SEARCH_CASES){ + database.add(test_case); } - database.add(); - database.add(); - database.add(); } - -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h index 0dc22e8b00..1e79216cc4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Registers RNG target search unit tests. void add_tests_RngTargetSearch(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp index 701411f827..63438dbdb9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp @@ -119,6 +119,6 @@ void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerC -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h index f1c358fa20..033a4a8d7f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h @@ -44,7 +44,7 @@ void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerC -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp index ed67e21b42..a42d25e781 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp @@ -46,7 +46,7 @@ const std::set& starter_species(){ return SPECIES_LIST; } -} +} // namespace BaseStats starter_base_stats(StarterSpecies starter){ @@ -840,6 +840,6 @@ bool StarterRngAttempts::read_wild_level_up( -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h index f541f1f9f9..702c94f492 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h @@ -32,6 +32,7 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Selectable Kanto starter species. enum class StarterSpecies{ bulbasaur, squirtle, @@ -47,6 +48,7 @@ EVs rival_ev_yield(StarterSpecies starter); int steps_left_to_lab_door(StarterSpecies starter); +// Statistical counters for Starter RNG attempts. struct StarterRngStats : public StatsTracker{ StarterRngStats(); @@ -58,6 +60,7 @@ struct StarterRngStats : public StatsTracker{ }; +// Target criteria for starter manipulation. struct StarterRngTarget{ StarterSpecies starter = StarterSpecies::bulbasaur; uint16_t seed = 0; @@ -92,6 +95,7 @@ std::optional reset_hit( const RngUncertainHistory& uncertain, const RngCalibrationHistory& calibration, const std::vector& hits ); +// Console and game environment settings for starter RNG. struct StarterRngSettings{ Language language = Language::None; // The Switch profile's position on the user selection screen; 0 for @@ -122,6 +126,7 @@ struct StarterRngDisplays{ RngCalibrationDisplay& calibration; }; +// Notification event options for starter RNG outcomes. struct StarterRngNotifications{ EventNotificationOption& shiny; EventNotificationOption& status_update; @@ -129,6 +134,7 @@ struct StarterRngNotifications{ }; +// Result outcome of an individual starter attempt. enum class StarterRngOutcome{ shiny, // The starter was shiny after a reset; not known if on the target. shiny_on_target, // Shiny, and the target is among the states its stats match. @@ -144,6 +150,7 @@ enum class StarterRngOutcome{ // shiny if none match. StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits); +// Complete result report from starter RNG execution. struct StarterRngResult{ StarterRngOutcome outcome = StarterRngOutcome::out_of_resets; // The target's PID, nature and IVs, on target_hit and shiny_on_target. @@ -151,6 +158,7 @@ struct StarterRngResult{ }; +// Manages execution loop and tracking for starter resets. class StarterRngAttempts{ public: StarterRngAttempts( @@ -257,7 +265,7 @@ class StarterRngAttempts{ -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp index 40d580b6a8..3a914823e7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp @@ -112,6 +112,6 @@ StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h index 11a7a2adc1..5baafa8774 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h @@ -52,6 +52,7 @@ std::function reset_line_logger( ); +// Console hardware and audio setup for starter manipulation. struct StarterRngConsoleSettings{ Language language = Language::English; SoundSetting sound = SoundSetting::Mono; @@ -87,7 +88,7 @@ class ConsoleStarterRngSteps : public StarterRngLoopSteps{ -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp index a8a1d94f8c..63e17835ab 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp @@ -79,7 +79,7 @@ std::string calibration_text(const std::optional& calibration){ return std::format("{:.2f}/{:.2f}/{:.2f}", calibration->seed_offset, calibration->csf_offset, calibration->ingame_offset); } -} +} // namespace std::string rng_log_state(const RngLoopState& state){ return std::format( @@ -143,7 +143,7 @@ std::string shiny_text(const RngResetLine& line){ return hits.empty() ? "shiny, not known if on the target." : "shiny, not on the target."; } -} +} // namespace std::string rng_reset_line(const RngResetLine& line){ const RngResetRead& read = line.read; @@ -288,7 +288,7 @@ TryOutcome run_try_outcome( } } -} +} // namespace StarterRngLoopResult run_starter_rng_plan( @@ -332,6 +332,6 @@ StarterRngLoopResult run_starter_rng_plan( -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h index bae408320b..4223f6f233 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h @@ -66,6 +66,7 @@ struct RngLoopState{ // The calibration of the last reset, in frames; none before the first. std::optional calibration; }; +// Formats loop state summary line for logging. std::string rng_log_state(const RngLoopState& state); @@ -89,6 +90,7 @@ std::optional seed_frame_offset(const std::vector& seed_values, i std::string rng_reset_line(const RngResetLine& line); +// Timeout and iteration constraints on starter RNG loop. struct StarterRngLoopLimits{ // An attempt makes no more resets after this long, and counts as missed. Milliseconds attempt_time = Milliseconds(0); @@ -136,6 +138,7 @@ class StarterRngLoopSteps{ virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; }; +// Termination condition of the starter RNG loop. enum class StarterRngLoopEnd{ // The starter is shiny and the target; the game is on its summary, not saved. SHINY, @@ -154,6 +157,7 @@ enum class StarterRngLoopEnd{ OUT_OF_TIME, }; +// Aggregated outcome of the starter RNG loop. struct StarterRngLoopResult{ StarterRngLoopEnd end = StarterRngLoopEnd::OUT_OF_TIME; // Attempts run, retries included. @@ -176,7 +180,7 @@ StarterRngLoopResult run_starter_rng_plan( -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp index 4b24859aa0..694bb86460 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp @@ -25,22 +25,36 @@ namespace PokemonFRLG{ namespace{ +struct StarterRngLoopInput{ + std::string name; + std::function body; +}; + +struct StarterRngLoopExpectation{ + const char* description; +}; + +struct StarterRngLoopTestCase{ + StarterRngLoopInput input; + StarterRngLoopExpectation expectation; +}; + class Test_StarterRngLoop : public UnitTest{ public: - Test_StarterRngLoop(std::string name, std::function body) - : UnitTest("PokemonFRLG::StarterRngLoop - " + std::move(name)) - , m_body(std::move(body)) + explicit Test_StarterRngLoop(StarterRngLoopTestCase scenario) + : UnitTest("PokemonFRLG::StarterRngLoop - " + scenario.input.name) + , m_scenario(std::move(scenario)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ try{ - return m_body(); + return m_scenario.input.body(); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + StarterRngLoopTestCase m_scenario; }; @@ -494,23 +508,60 @@ UnitTestResult test_reset_line(const ResetLineRow& row){ return true; } -} - - -void add_tests_StarterRngLoop(UnitTestDatabase& database){ +UnitTestResult test_loop_rows(){ for (const LoopRow& row : LOOP_ROWS){ - database.add(row.name, [row]{ return run_loop_row(row); }); + UnitTestResult res = run_loop_row(row); + if (res.result != UnitTestResult::PASSED){ + return row.name + ": " + res.message; + } } - database.add("attempt deadlines", test_deadlines); - database.add("a setup error stops the loop", test_setup_error_stops); - database.add("state line", test_state_line); + return true; +} + +UnitTestResult test_reset_line_rows(){ for (const ResetLineRow& row : RESET_LINE_ROWS){ - database.add("reset line " + row.name, [row]{ return test_reset_line(row); }); + UnitTestResult res = test_reset_line(row); + if (res.result != UnitTestResult::PASSED){ + return row.name + ": " + res.message; + } } + return true; } +const StarterRngLoopTestCase STARTER_RNG_LOOP_CASES[] = { + { + .input = {.name = "attempt deadlines", .body = test_deadlines}, + .expectation = {.description = "verifies attempt timeout and deadline handling"}, + }, + { + .input = {.name = "a setup error stops the loop", .body = test_setup_error_stops}, + .expectation = {.description = "aborts loop when setup verification fails"}, + }, + { + .input = {.name = "state line", .body = test_state_line}, + .expectation = {.description = "formats loop state line output correctly"}, + }, + { + .input = {.name = "loop row scenarios", .body = test_loop_rows}, + .expectation = {.description = "evaluates simulated starter RNG loop rows"}, + }, + { + .input = {.name = "reset line scenarios", .body = test_reset_line_rows}, + .expectation = {.description = "evaluates RNG reset summary lines"}, + }, +}; + +} // namespace +void add_tests_StarterRngLoop(UnitTestDatabase& database){ + for (const auto& scenario : STARTER_RNG_LOOP_CASES){ + database.add(scenario); + } } -} -} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h index 8c98b0a8cb..378eee8684 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// Registers starter RNG loop unit tests. void add_tests_StarterRngLoop(UnitTestDatabase& database); -} -} -} +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif From d633063b1a7c8b2cd481fef093fe8b2dbed64b38 Mon Sep 17 00:00:00 2001 From: dayfine Date: Fri, 6 Nov 2026 20:45:40 -0800 Subject: [PATCH 03/13] Type RNG search top-bit literals explicitly for MSVC --- .../Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp index af2a8de742..e03b4c2ab4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp @@ -356,7 +356,7 @@ void search_iv_states(const LowBitsTable& table, const AdvIVs& min_ivs, TargetCo while (true){ uint16_t first = uint16_t(ivs[0] | (ivs[1] << 5) | (ivs[2] << 10)); uint16_t second = uint16_t(ivs[3] | (ivs[4] << 5) | (ivs[5] << 10)); - for (uint16_t first_top : {0x0000, 0x8000}){ + for (uint16_t first_top : {uint16_t(0x0000), uint16_t(0x8000)}){ for (uint32_t second_top : {0x0000, 0x8000}){ table.find_states(first | first_top, (second | second_top) << 16, 0x10000, found); } From 9d6d1a8d448675b28216c5e2fdcef04c57259a48 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 19:36:40 -0800 Subject: [PATCH 04/13] [FRLG RNG] Check free party slots in applicable RNG programs The RNG programs' documentation lists how many free party slots each one needs. Check that at program startup through a new pre-startup hook, start_program_game_checks(), instead of failing after a catch or gift goes to the box. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../NintendoSwitch_SingleSwitchProgram.cpp | 1 + .../NintendoSwitch_SingleSwitchProgram.h | 9 + .../PokemonFRLG/PokemonFRLG_Navigation.cpp | 15 +- .../PokemonFRLG/PokemonFRLG_Navigation.h | 3 + .../PokemonFRLG/PokemonFRLG_Tests.cpp | 291 ++++++++++++++++++ .../RngManipulation/PokemonFRLG_EggRng.h | 7 +- .../RngManipulation/PokemonFRLG_GiftRng.h | 6 +- .../RngManipulation/PokemonFRLG_RngHelper.h | 7 +- .../PokemonFRLG_RngProgram.cpp | 95 ++++++ .../RngManipulation/PokemonFRLG_RngProgram.h | 79 +++++ .../PokemonFRLG_RoamingLegendaryRng.h | 6 +- .../RngManipulation/PokemonFRLG_StarterRng.h | 7 +- .../RngManipulation/PokemonFRLG_StaticRng.h | 6 +- .../RngManipulation/PokemonFRLG_WildRng.h | 9 +- SerialPrograms/cmake/SourceFiles.cmake | 2 + 15 files changed, 520 insertions(+), 23 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp index 8f4e94ab65..cbb210b0b7 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp @@ -86,6 +86,7 @@ void SingleSwitchProgramInstance::program(SingleSwitchProgramEnvironment& env, C }; try{ + start_program_game_checks(env, context); program(env, context); }catch (FatalProgramException&){ record_debug_video(); diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h index 9c464ca3a7..b44bb655a1 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h @@ -86,6 +86,15 @@ class SingleSwitchProgramInstance : public GameConsole::ConsoleProgramInstance{ FeedbackType feedback_type ); + // Called with the controller ready, just before program(env, context). + // Override to check that the game is set up the way the program needs + // (e.g. a free party slot) and throw UserSetupError if not, so a setup + // mistake stops the program before it starts its work. + virtual void start_program_game_checks( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context + ){} + private: virtual void program(GameConsole::ConsoleProgramEnvironment& env, CancellableScope& scope) override; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp index 970080ca26..8de1341438 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp @@ -839,18 +839,15 @@ void open_party_menu_from_overworld(ConsoleHandle& console, ProControllerContext } PartySlot detect_last_occupied_party_slot(ConsoleHandle& console){ - const auto snapshot = console.video().snapshot(); - constexpr std::array slots{ - PartySlot::SIX, - PartySlot::FIVE, - PartySlot::FOUR, - PartySlot::THREE, - PartySlot::TWO, - }; + return detect_last_occupied_party_slot(console.video().snapshot()); +} + +PartySlot detect_last_occupied_party_slot(const ImageViewRGB32& screen){ + constexpr std::array slots{PartySlot::SIX, PartySlot::FIVE, PartySlot::FOUR, PartySlot::THREE, PartySlot::TWO}; for (PartySlot slot : slots){ PartyEmptySlotDetector empty_slot_detector(COLOR_RED, slot); - if (!empty_slot_detector.detect(snapshot)){ + if (!empty_slot_detector.detect(screen)){ return slot; } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h index e802a4be6d..b19ead8d00 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h @@ -10,6 +10,7 @@ #define PokemonAutomation_PokemonFRLG_Navigation_H #include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Language.h" #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" @@ -136,6 +137,8 @@ void open_party_menu_from_overworld(ConsoleHandle& console, ProControllerContext // Starting from the party menu, detect the last occupied party slot PartySlot detect_last_occupied_party_slot(ConsoleHandle& console); +// Detect the last occupied party slot on a screenshot of the party menu +PartySlot detect_last_occupied_party_slot(const ImageViewRGB32& screen); // Starting from the start menu, a sub-screen of the start menu, or the overworld, navigate to the bag void open_bag_from_overworld(ConsoleHandle& console, ProControllerContext& context, StartMenuContext menu_context = StartMenuContext::STANDARD); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 49d9b56265..f8bcb64246 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -4,8 +4,16 @@ * */ +#include #include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" #include "Inference/Box/PokemonFRLG_BoxCellOccupiedDetector.h" @@ -28,7 +36,16 @@ #include "Inference/PokemonFRLG_TrainerIdReader.h" #include "Inference/PokemonFRLG_WildEncounterReader.h" #include "Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_EggRng.h" +#include "Programs/RngManipulation/PokemonFRLG_GiftRng.h" +#include "Programs/RngManipulation/PokemonFRLG_RngHelper.h" +#include "Programs/RngManipulation/PokemonFRLG_RngProgram.h" +#include "Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h" +#include "Programs/RngManipulation/PokemonFRLG_StarterRng.h" +#include "Programs/RngManipulation/PokemonFRLG_StaticRng.h" +#include "Programs/RngManipulation/PokemonFRLG_WildRng.h" #include "PokemonFRLG_Navigation.h" +#include "Tests/ImageUnitTest.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -261,6 +278,277 @@ void add_tests_ExitWildBattle(UnitTestDatabase& database){ } } + +std::string slot_name(PartySlot slot){ + return std::to_string(static_cast(slot) + 1); +} + +// Reads the last occupied slot from a party menu screenshot, as the RNG programs' party check does. +class Test_LastOccupiedPartySlot : public ImageUnitTest{ +public: + Test_LastOccupiedPartySlot(std::string_view image, PartySlot expected) + : ImageUnitTest("PokemonFRLG::LastOccupiedPartySlot - " + std::string(image), {std::string(image)}) + , m_expected(expected) + {} + + virtual UnitTestResult run_on_images( + Logger&, CancellableScope&, + const std::vector& images + ) const override{ + const PartySlot slot = detect_last_occupied_party_slot(images[0]); + if (slot != m_expected){ + return std::format("Expected last occupied slot {}, got {}", slot_name(m_expected), slot_name(slot)); + } + return true; + } + +private: + const PartySlot m_expected; +}; + +void add_tests_LastOccupiedPartySlot(UnitTestDatabase& database){ + for (unsigned occupied = 1; occupied <= 6; occupied++){ + database.add( + "PokemonFRLG/Party/Party_" + std::to_string(occupied) + ".png", + static_cast(occupied - 1) + ); + } + database.add("PokemonFRLG/Party/Party_6_With_Held_Items.png", PartySlot::SIX); + database.add("PokemonFRLG/Party/JPN_HeldItem.png", PartySlot::SIX); + database.add("PokemonFRLG/Party/JPN_Party.png", PartySlot::FOUR); + database.add("PokemonFRLG/Party/SPA_HeldItem.png", PartySlot::SIX); +} + +// Steps that return scripted reads, and record what check_party_free_slots() asked for. +class ScriptedPartyCheck : public PartyCheckActions{ +public: + bool menu_opens = true; + PartySlot last_occupied = PartySlot::ONE; + std::string steps; + + virtual bool open_party_menu() override{ + steps += steps.empty() ? "open" : " open"; + return menu_opens; + } + virtual PartySlot read_last_occupied_slot() override{ + steps += steps.empty() ? "read" : " read"; + return last_occupied; + } +}; + +struct PartyCheckInput{ + std::string name; + size_t free_slots_needed = 1; + bool menu_opens = true; + PartySlot last_occupied = PartySlot::ONE; +}; + +struct PartyCheckExpectation{ + std::string steps = ""; + // Start of the UserSetupError message; empty if the check passes. + std::string error = ""; +}; + +struct PartyCheckCase{ + PartyCheckInput input; + PartyCheckExpectation expectation; +}; + +class Test_PartyCheck : public UnitTest{ +public: + Test_PartyCheck(PartyCheckCase test_case) + : UnitTest("PokemonFRLG::RngPartyCheck - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const PartyCheckInput& input = m_case.input; + const PartyCheckExpectation& expected = m_case.expectation; + ScriptedPartyCheck actions; + actions.menu_opens = input.menu_opens; + actions.last_occupied = input.last_occupied; + + NullLogger logger; + std::string error; + try{ + check_party_free_slots(logger, input.free_slots_needed, actions); + }catch (UserSetupError& e){ + error = e.message(); + } + const bool error_matches = expected.error.empty() + ? error.empty() + : error.rfind(expected.error, 0) == 0; + if (!error_matches){ + return std::format("Expected error: \"{}\"\nActual error: \"{}\"", expected.error, error); + } + if (actions.steps != expected.steps){ + return std::format("Expected steps: {}\nActual steps: {}", expected.steps, actions.steps); + } + return true; + } + +private: + const PartyCheckCase m_case; +}; + +void add_tests_PartyCheck(UnitTestDatabase& database){ + const PartyCheckCase cases[] = { + { + // Programs that don't add a Pokemon to the party don't open the menu. + .input = {.name = "no free slot needed, full party", .free_slots_needed = 0, .last_occupied = PartySlot::SIX}, + .expectation = {}, + }, + { + .input = {.name = "one free slot needed, one Pokemon"}, + .expectation = {.steps = "open read"}, + }, + { + .input = {.name = "one free slot needed, five Pokemon", .last_occupied = PartySlot::FIVE}, + .expectation = {.steps = "open read"}, + }, + { + .input = {.name = "one free slot needed, full party", .last_occupied = PartySlot::SIX}, + .expectation = {.steps = "open read", .error = "Your party is full. Leave a party slot free"}, + }, + { + .input = {.name = "three free slots needed, three Pokemon", .free_slots_needed = 3, .last_occupied = PartySlot::THREE}, + .expectation = {.steps = "open read"}, + }, + { + .input = {.name = "three free slots needed, four Pokemon", .free_slots_needed = 3, .last_occupied = PartySlot::FOUR}, + .expectation = {.steps = "open read", .error = "Your party has 4 "}, + }, + { + // A menu that can't be opened skips the check rather than stopping the program. + .input = {.name = "party menu not opened", .menu_opens = false, .last_occupied = PartySlot::SIX}, + .expectation = {.steps = "open"}, + }, + }; + for (const PartyCheckCase& test_case : cases){ + database.add(test_case); + } +} + + +std::string menu_context_name(StartMenuContext context){ + switch (context){ + case StartMenuContext::STANDARD: return "STANDARD"; + case StartMenuContext::SAFARI_ZONE: return "SAFARI_ZONE"; + case StartMenuContext::NO_DEX: return "NO_DEX"; + } + return "?"; +} + +template +std::unique_ptr make_rng_program(){ + return std::make_unique(); +} + +struct RngProgramPartyInput{ + std::string name; + std::function()> make_program; + // Program settings by option name, as in the saved settings JSON. + std::map settings = {}; +}; + +struct RngProgramPartyExpectation{ + size_t free_slots; + StartMenuContext menu_context = StartMenuContext::STANDARD; +}; + +struct RngProgramPartyCase{ + RngProgramPartyInput input; + RngProgramPartyExpectation expectation; +}; + +// Builds the program with the given settings and checks what its start check asks for. The +// check itself runs for every RNG program: RngProgramInstance's start hook is final. +class Test_RngProgramPartyRequirement : public UnitTest{ +public: + Test_RngProgramPartyRequirement(RngProgramPartyCase test_case) + : UnitTest("PokemonFRLG::RngProgramPartyRequirement - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const RngProgramPartyInput& input = m_case.input; + const RngProgramPartyExpectation& expected = m_case.expectation; + std::unique_ptr program = input.make_program(); + JsonObject settings; + for (const auto& [option, value] : input.settings){ + settings[option] = value; + } + program->load_json(JsonValue(std::move(settings))); + + const size_t free_slots = program->free_party_slots_needed(); + if (free_slots != expected.free_slots){ + return std::format("Expected {} free party slots needed, got {}", expected.free_slots, free_slots); + } + const StartMenuContext menu_context = program->start_menu_context(); + if (menu_context != expected.menu_context){ + return std::format( + "Expected start menu {}, got {}", menu_context_name(expected.menu_context), menu_context_name(menu_context) + ); + } + return true; + } + +private: + const RngProgramPartyCase m_case; +}; + +const RngProgramPartyCase RNG_PROGRAM_PARTY_CASES[] = { + { + .input = {.name = "StarterRng", .make_program = make_rng_program}, + .expectation = {.free_slots = 0}, + }, + { + // The egg and the two wild Pokemon caught to confirm the seed. + .input = {.name = "EggRng", .make_program = make_rng_program}, + .expectation = {.free_slots = 3}, + }, + { + .input = {.name = "GiftRng", .make_program = make_rng_program}, + .expectation = {.free_slots = 1}, + }, + { + .input = {.name = "StaticRng", .make_program = make_rng_program}, + .expectation = {.free_slots = 1}, + }, + { + .input = {.name = "RoamingLegendaryRng", .make_program = make_rng_program}, + .expectation = {.free_slots = 1}, + }, + { + .input = { + .name = "WildRng on Route 1", + .make_program = make_rng_program, + .settings = {{"GAME_LOCATION", "route_1"}}, + }, + .expectation = {.free_slots = 1}, + }, + { + // The Safari Zone start menu has no POKEMON entry in the usual place. + .input = { + .name = "WildRng in the Safari Zone", + .make_program = make_rng_program, + .settings = {{"GAME_LOCATION", "safari_zone_entrance"}}, + }, + .expectation = {.free_slots = 1, .menu_context = StartMenuContext::SAFARI_ZONE}, + }, + // RngHelper is the manual tool: whatever the target, it trusts the user's party. + { + .input = {.name = "RngHelper lapras", .make_program = make_rng_program, .settings = {{"TARGET", "lapras"}}}, + .expectation = {.free_slots = 0}, + }, +}; + +void add_tests_RngProgramPartyRequirement(UnitTestDatabase& database){ + for (const RngProgramPartyCase& test_case : RNG_PROGRAM_PARTY_CASES){ + database.add(test_case); + } +} + } @@ -279,12 +567,15 @@ void add_tests(UnitTestDatabase& database){ add_tests_EliteFourRoomDetector(database); add_tests_ExitWildBattle(database); add_tests_HallOfFameSavingDetector(database); + add_tests_LastOccupiedPartySlot(database); + add_tests_PartyCheck(database); add_tests_PartyEmptySlotDetector(database); add_tests_PartyHeldItemDetector(database); add_tests_PartyLevelUpReader(database); add_tests_PartyMenuDetector(database); add_tests_PrizeSelectDetector(database); add_tests_PartySlotDetector(database); + add_tests_RngProgramPartyRequirement(database); add_tests_StatsReader(database); add_tests_SelectionDialogDetector(database); add_tests_ShinySymbolDetector(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h index 5462ee2eac..6adb83effc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h @@ -14,12 +14,12 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonFramework/Options/LabelCellOption.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Options/Pokemon_NameSelectOption.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_RngStatsDatabase.h" #include "PokemonFRLG_RngDisplays.h" #include "PokemonFRLG_RngLoopRoutines.h" @@ -56,9 +56,12 @@ class EggRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class EggRng : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a daycare egg. +class EggRng : public RngProgramInstance, public ConfigOption::Listener{ public: using Descriptor = EggRng_Descriptor; + // The egg and the two wild Pokemon caught to confirm the seed. + virtual size_t free_party_slots_needed() const override{ return 3; } ~EggRng(); EggRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h index 3df8e600ac..fc18d1b111 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h @@ -12,10 +12,10 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -29,9 +29,11 @@ class GiftRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class GiftRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a gift Pokemon. +class GiftRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = GiftRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~GiftRng(); GiftRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h index 3f4e694065..cbecd81a9e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h @@ -13,9 +13,9 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" +#include "PokemonFRLG_RngProgram.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -28,9 +28,12 @@ class RngHelper_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class RngHelper : public SingleSwitchProgramInstance{ +// Soft resets with given timings to hit a target seed and frame. +class RngHelper : public RngProgramInstance{ public: using Descriptor = RngHelper_Descriptor; + // The manual tool: the user sets the target and the party, so no check. + virtual size_t free_party_slots_needed() const override{ return 0; } RngHelper(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; virtual void start_program_border_check( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp new file mode 100644 index 0000000000..573e991687 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp @@ -0,0 +1,95 @@ +/* RNG Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon/Pokemon_Strings.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartySlot.h" +#include "PokemonFRLG_RngProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class ConsolePartyCheckActions : public PartyCheckActions{ +public: + ConsolePartyCheckActions(ConsoleHandle& console, ProControllerContext& context, StartMenuContext menu_context) + : m_console(console), m_context(context), m_menu_context(menu_context) + {} + + virtual bool open_party_menu() override{ + try{ + open_party_menu_from_overworld(m_console, m_context, m_menu_context); + }catch (OperationFailedException&){ + return false; + } + m_context.wait_for_all_requests(); + return true; + } + virtual PartySlot read_last_occupied_slot() override{ + return detect_last_occupied_party_slot(m_console); + } + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; + StartMenuContext m_menu_context; +}; + +std::string not_enough_free_slots_message(size_t party_size, size_t free_slots_needed){ + if (free_slots_needed == 1){ + return std::format( + "Your party is full. Leave a party slot free so the program can check the {} it catches or receives.", + Pokemon::STRING_POKEMON + ); + } + return std::format( + "Your party has {} {}. Leave at least {} party slots free for the {} the program catches or receives.", + party_size, Pokemon::STRING_POKEMON, free_slots_needed, Pokemon::STRING_POKEMON + ); +} + +} // namespace + + +void check_party_free_slots( + Logger& logger, + size_t free_slots_needed, + PartyCheckActions& actions +){ + if (free_slots_needed == 0){ + return; + } + logger.log("Checking for " + std::to_string(free_slots_needed) + " free party slot(s)..."); + if (!actions.open_party_menu()){ + logger.log("Unable to open the party menu. Skipping the free party slot check.", COLOR_RED); + return; + } + constexpr size_t MAX_PARTY_SIZE = 6; + const size_t party_size = static_cast(actions.read_last_occupied_slot()) + 1; + if (MAX_PARTY_SIZE - party_size < free_slots_needed){ + throw UserSetupError(logger, not_enough_free_slots_message(party_size, free_slots_needed)); + } + logger.log("Party has enough free slots."); +} + + +void RngProgramInstance::start_program_game_checks( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context +){ + ConsolePartyCheckActions actions(env.console, context, start_menu_context()); + check_party_free_slots(env.console.logger(), free_party_slots_needed(), actions); +} + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h new file mode 100644 index 0000000000..8ec4935ef9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h @@ -0,0 +1,79 @@ +/* RNG Program + * + * From: https://github.com/PokemonAutomation/ + * + * Base class for the FRLG RNG programs. Each program states what the game + * must look like when it starts, and the base class checks it before the + * program runs, so a setup mistake stops the run at once instead of failing + * in a misleading way many resets later. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngProgram_H +#define PokemonAutomation_PokemonFRLG_RngProgram_H + +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartySlot.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The game steps that check_party_free_slots() takes. They are injected so +// that its decisions run in tests without a Switch. +class PartyCheckActions{ +public: + virtual ~PartyCheckActions() = default; + + // Open the party menu from the overworld. Returns false if it can't. + virtual bool open_party_menu() = 0; + + // Read the last occupied slot on the open party menu. + virtual PartySlot read_last_occupied_slot() = 0; +}; + +// Checks that the party has at least `free_slots_needed` free slots, +// starting from the overworld. Throws UserSetupError if it doesn't. If the +// party menu can't be opened, logs that and returns. May leave the party +// menu open. +void check_party_free_slots( + Logger& logger, + size_t free_slots_needed, + PartyCheckActions& actions +); + + +// Base class of the RNG programs. Before program() runs, it checks that the +// party has the free slots the program needs. +class RngProgramInstance : public SingleSwitchProgramInstance{ +public: + using SingleSwitchProgramInstance::SingleSwitchProgramInstance; + + // How many free party slots the program needs: one for each Pokemon it + // catches or receives and then reads from the end of the party. In a full + // party that Pokemon would go to the PC instead. + virtual size_t free_party_slots_needed() const = 0; + + // The start menu the player sees where the program starts. + virtual StartMenuContext start_menu_context() const{ + return StartMenuContext::STANDARD; + } + + // Runs with the game on the overworld where the player saved. May leave a + // menu open: the program's first reset closes the game. Final so that + // every RNG program runs the check free_party_slots_needed() asks for. + virtual void start_program_game_checks( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context + ) override final; +}; + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h index f53f60a6ce..2b331ac54d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h @@ -12,10 +12,10 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -29,9 +29,11 @@ class RoamingLegendaryRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class RoamingLegendaryRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a roaming legendary. +class RoamingLegendaryRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = RoamingLegendaryRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~RoamingLegendaryRng(); RoamingLegendaryRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h index 4e99f55bda..ea5fa11c06 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h @@ -12,11 +12,11 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Pokemon_StatsCalculation.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -30,9 +30,12 @@ class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class StarterRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a starter. +class StarterRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = StarterRng_Descriptor; + // The party is empty before the starter, so there is nothing to check. + virtual size_t free_party_slots_needed() const override{ return 0; } ~StarterRng(); StarterRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h index 29e117f7fa..3a274e79e8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h @@ -14,13 +14,13 @@ #include "Common/Cpp/Options/TextEditOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Pokemon_StatsCalculation.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngCalibration.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -34,9 +34,11 @@ class StaticRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class StaticRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a static encounter. +class StaticRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = StaticRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~StaticRng(); StaticRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h index 1fa342063a..968f68119a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h @@ -13,11 +13,11 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" #include "CommonTools/Options/StringSelectOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -31,9 +31,14 @@ class WildRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class WildRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a random wild encounter. +class WildRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = WildRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } + virtual StartMenuContext start_menu_context() const override{ + return in_safari_zone() ? StartMenuContext::SAFARI_ZONE : StartMenuContext::STANDARD; + } ~WildRng(); WildRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 8ce94da419..cd41727485 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1818,6 +1818,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngLoopRoutines.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngStatsDatabase.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngStatsDatabase.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp From 9d54f1bd4d91f279edaad19b6d8cc48bbe4df1b5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 10:03:35 -0800 Subject: [PATCH 05/13] FRLG AutoStory: delete stage 2's C++ story rows, parity proven The merge's parity test passed: every StoryData file, 00.01b and the 00.04/00.04b split included, loads to its C++ row. The rows and the test go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 1 - .../AutoStory/PokemonFRLG_AutoStoryTable.h | 2 - ...PokemonFRLG_AutoStoryTableParity_Tests.cpp | 379 ------------------ SerialPrograms/cmake/SourceFiles.cmake | 1 - 4 files changed, 383 deletions(-) delete mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 5c65e8ee28..bc405956b3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -911,7 +911,6 @@ void add_tests(UnitTestDatabase& database){ add_tests_OverworldRecovery(database); add_tests_PlayerFacingReader(database); add_tests_AutoStory(database); - add_tests_AutoStoryTableParity(database); add_tests_AutoStoryExport(database); add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index 50bfe92342..0201a8e65f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -61,8 +61,6 @@ const std::vector& story_checkpoints(); // Registers AutoStory table validation unit tests. void add_tests_AutoStory(UnitTestDatabase& database); -// The story files against the C++ rows they replace. -void add_tests_AutoStoryTableParity(UnitTestDatabase& database); // The table run end to end against a fake game (PokemonFRLG_AutoStorySimulation_Tests.cpp). void add_tests_AutoStorySimulation(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp deleted file mode 100644 index d4853c8a49..0000000000 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp +++ /dev/null @@ -1,379 +0,0 @@ -/* AutoStory Table Parity Tests - * - * From: https://github.com/PokemonAutomation/ - * - * The C++ rows the story table had before StoryData/, built with the - * shared step API, against the checkpoints read from the files: each - * loads to the same steps, args (with the fallbacks the reader fills in), - * poses, supplies and START menu. Removed with the C++ rows. - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTest.h" -#include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h" -#include "PokemonFRLG_AutoStoryParty.h" -#include "PokemonFRLG_AutoStoryTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonFRLG{ - - -namespace{ - -constexpr Direction NORTH = Direction::NORTH; -constexpr Direction SOUTH = Direction::SOUTH; -constexpr Direction EAST = Direction::EAST; -constexpr Direction WEST = Direction::WEST; - -constexpr std::string_view BEDROOM = "PalletTown_PlayersHouse_2F"; -constexpr std::string_view PALLET = "PalletTown"; -constexpr std::string_view LAB = "PalletTown_ProfessorOaksLab"; -constexpr std::string_view VIRIDIAN = "ViridianCity"; -constexpr std::string_view VIRIDIAN_MART = "ViridianCity_Mart"; -constexpr std::string_view VIRIDIAN_CENTER = "ViridianCity_PokemonCenter_1F"; -constexpr std::string_view FOREST = "ViridianForest"; -constexpr std::string_view FOREST_GATE = "Route2_ViridianForest_NorthEntrance"; -constexpr std::string_view PEWTER = "PewterCity"; -constexpr std::string_view PEWTER_CENTER = "PewterCity_PokemonCenter_1F"; -constexpr std::string_view GYM = "PewterCity_Gym"; - -Pokemon::GridPose at(std::string_view map, int x, int y, std::optional facing = std::nullopt){ - return Pokemon::GridPose{std::string(map), {{x, y}}, facing}; -} - -StoryCheckpoint row( - std::string id, std::string title, std::optional start, - Supplies supplies, StartMenu menu, std::vector steps -){ - StoryCheckpoint checkpoint; - checkpoint.id = std::move(id); - checkpoint.title = std::move(title); - checkpoint.start = std::move(start); - checkpoint.steps = std::move(steps); - checkpoint.supplies = supplies; - checkpoint.menu = menu; - return checkpoint; -} - -Supplies after_brock(){ - Supplies supplies; - supplies.lead = story_lead_after_brock(); - return supplies; -} - -// What a walk does about wild Pokemon: runs, or fights them for EXP. -enum class WildBattles{ - RUN, - FIGHT, -}; - -StoryStep make(StoryStepKind kind, std::string name, std::string why, Pokemon::StoryActionArgs args = {}){ - StoryStep step; - step.kind = kind; - step.name = std::move(name); - step.why = std::move(why); - step.args = std::move(args); - return step; -} - -StoryStep route(std::string name, Pokemon::GridPose target, std::string why, WildBattles wild = WildBattles::RUN){ - return make(StoryStepKind::ROUTE, std::move(name), std::move(why), { - {"target", std::move(target)}, {"fight_wild", wild == WildBattles::FIGHT}, - }); -} - -StoryStep step_into(std::string name, Direction direction, std::string why){ - return make(StoryStepKind::STEP, std::move(name), std::move(why), {{"direction", direction}}); -} - -StoryStep answer(std::string name, bool yes, std::string why){ - return make(StoryStepKind::ANSWER, std::move(name), std::move(why), {{"yes", yes}}); -} - -StoryStep scene(std::string name, std::optional pose_after, std::string why){ - StoryStep step = make(StoryStepKind::MASH, std::move(name), std::move(why)); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep battle(std::string name, Pokemon::GridPose pose_after, bool may_lose, std::string why){ - StoryStep step = make(StoryStepKind::BATTLE, std::move(name), std::move(why), {{"may_lose", may_lose}}); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep legs(std::string name, std::vector legs, std::string why, WildBattles wild = WildBattles::RUN){ - return make(StoryStepKind::LEGS, std::move(name), std::move(why), { - {"legs", std::move(legs)}, {"fight_wild", wild == WildBattles::FIGHT}, - }); -} - -StoryStep new_game_intro(Pokemon::GridPose pose_after, std::string why){ - StoryStep step = make(StoryStepKind::NEW_GAME, "intro", std::move(why)); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep talk(std::string name, std::string why){ - return make(StoryStepKind::TALK, std::move(name), std::move(why)); -} - -StoryStep ready(std::string name, Pokemon::GridPose nurse, std::string why){ - return make(StoryStepKind::READY, std::move(name), std::move(why), {{"target", std::move(nurse)}}); -} - -StoryStep heal(std::string name){ - return make(StoryStepKind::HEAL, std::move(name), "full HP"); -} - -StoryStep shop(std::string name, std::vector items, std::string why){ - return make(StoryStepKind::SHOP, std::move(name), std::move(why), {{"items", std::move(items)}}); -} - -StoryStep game_step(std::string action, Pokemon::GridPose pose_after, std::string why){ - StoryStep step = make(StoryStepKind::GAME, action, std::move(why)); - step.action = std::move(action); - step.pose_after = std::move(pose_after); - return step; -} - -StoryStep options_step(){ - return make(StoryStepKind::OPTIONS, "options", "fast text; no switch prompt between a trainer's Pokemon"); -} - - -StoryCheckpoint new_game(){ - StoryCheckpoint checkpoint = row("00.01", "new game to the bedroom", std::nullopt, {}, StartMenu::BEFORE_POKEMON, { - // new_game.c: the bedroom at (6, 6), facing the TV. - new_game_intro(at(BEDROOM, 6, 6, NORTH), "Oak's speech, BOY, the player's name (default if none is set), rival GREEN"), - options_step(), - }); - checkpoint.handoff = StoryHandoff::SID_HELPER; - return checkpoint; -} - -// SID Helper confirms the name, finishes the intro and reads the Trainer -// Card from the START menu, without moving the player or saving. -StoryCheckpoint after_sid_helper(){ - StoryCheckpoint checkpoint = row("00.01b", "after SID Helper: close the Trainer Card, save in the bedroom", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { - game_step(CLOSE_TRAINER_CARD, at(BEDROOM, 6, 6, NORTH), "the Trainer Card SID Helper left open, or HOME"), - options_step(), - }); - checkpoint.live_start = true; - return checkpoint; -} - -StoryCheckpoint leave_house(){ - return row("00.02", "bedroom to Pallet Town", at(BEDROOM, 6, 6, NORTH), {}, StartMenu::BEFORE_POKEMON, { - route("front_door", at(PALLET, 6, 8), "down the stairs and out of the house"), - }); -} - -StoryCheckpoint oaks_trigger(){ - return row("00.03", "Oak stops the player and walks them to the lab", at(PALLET, 6, 8, SOUTH), {}, StartMenu::BEFORE_POKEMON, { - route("below_oaks_trigger", at(PALLET, 12, 2, NORTH), "below the north exit, short of Oak's trigger at (12, 1)"), - step_into("oaks_trigger", NORTH, "the trigger: \"Don't go out!\""), - // PlayerEnter walks the player up 8 tiles from the lab's door. - scene("to_the_lab", at(LAB, 6, 4, NORTH), "Oak walks the player into the lab; the scene ends at the table"), - }); -} - -// Starter RNG starts from a save south of the table, facing the ball. -StoryCheckpoint to_starter_ball(){ - StoryCheckpoint checkpoint = row("00.04", "to Squirtle's ball, south of the table", at(LAB, 6, 4, NORTH), {}, StartMenu::BEFORE_POKEMON, { - route("below_squirtle", at(LAB, 9, 5, NORTH), "under Squirtle's ball (9, 4)"), - }); - checkpoint.handoff = StoryHandoff::STARTER_RNG; - return checkpoint; -} - -StoryCheckpoint starter(){ - return row("00.04b", "Squirtle, then the rival's battle", at(LAB, 9, 5, NORTH), {}, StartMenu::BEFORE_POKEDEX, { - talk("squirtle_ball", "\"So, you want the WATER POKEMON SQUIRTLE?\""), - answer("choose_squirtle", true, "take Squirtle"), - answer("no_nickname", false, "\"give a nickname?\" NO"), - scene("rival_takes_bulbasaur", at(LAB, 9, 5, NORTH), "the rival picks his ball; the player still faces the table (console B, 2026-11-01)"), - route("above_rival_trigger", at(LAB, 7, 7, SOUTH), "short of the rival's trigger row 8"), - step_into("rival_trigger", SOUTH, "\"Wait, let's check out our POKEMON!\""), - // The rival leaves; PlayerWatchRivalExitAfterBattleRight ends facing down. - battle("rival_battle", at(LAB, 7, 8, SOUTH), true, "the tutorial battle; losing goes on too"), - }); -} - -StoryCheckpoint parcel(){ - return row("00.05", "Route 1 to Viridian Mart: Oak's Parcel", at(LAB, 7, 8, SOUTH), {}, StartMenu::BEFORE_POKEDEX, { - route("below_mart_door", at(VIRIDIAN, 36, 20, NORTH), "Route 1, running from wild battles"), - step_into("mart_door", NORTH, "the clerk's scene starts on entering"), - // ApproachCounter: up 4 from the mat, then faces the clerk. - scene("parcel_from_clerk", at(VIRIDIAN_MART, 4, 3, WEST), "the clerk gives OAK'S PARCEL"), - }); -} - -StoryCheckpoint pokedex(){ - return row("00.06", "Oak's Parcel to the Pokedex", at(VIRIDIAN_MART, 4, 3, WEST), {}, StartMenu::FULL, { - route("below_oak", at(LAB, 6, 4, NORTH), "back down Route 1 to Oak"), - talk("give_parcel", "Oak takes the parcel"), - scene("pokedex_scene", at(LAB, 6, 4, SOUTH), "the rival comes in, Pokedexes from the desk; the player ends facing south (console B, 2026-11-01)"), - }); -} - -StoryCheckpoint shopping(){ - return row("00.07", "Viridian shopping, then into Viridian Forest", at(LAB, 6, 4, SOUTH), {}, StartMenu::FULL, { - route("mart_clerk", at(VIRIDIAN_MART, 4, 3, WEST), "Route 1 again"), - // 2000 of the 3000 a new game starts with, plus the rival's prize. - shop("potions_and_antidotes", {{"potion", 5}, {"antidote", 3}, {"parlyz_heal", 1}}, "5 Potions, 3 Antidotes, 1 Parlyz Heal"), - route("viridian_nurse", at(VIRIDIAN_CENTER, 7, 4, NORTH), "heal before the forest"), - heal("heal_viridian"), - route("below_old_man_trigger", at(VIRIDIAN, 20, 9, NORTH), "short of the tutorial trigger (20, 8)"), - step_into("old_man_trigger", NORTH, "the old man's catching tutorial can't be walked around"), - // TutorialTriggerLeft turns the player right, to the old man. - scene("old_man_tutorial", at(VIRIDIAN, 20, 8, EAST), "about 60 lines and his demo battle; TEACHY TV"), - // After his demo the old man stands east of the player, beside (20, 8), where - // the map doesn't have him: "east 2" from there didn't move, and the walk north - // ended under Route 2's ledge in column 8 (console B, 2026-11-01). Go north first. - route("past_old_man", at(VIRIDIAN, 20, 5, NORTH), "north along column 20, clear of the old man"), - // The gate's north warp lands on the forest's exit mat (29, 62), facing - // north. The save there keeps a forest failure from going back to Pallet. - route("forest_entrance", at(FOREST, 29, 62, NORTH), "Route 2 and the south gate, running from wild battles"), - }); -} - -StoryCheckpoint forest(){ - // The supplies bought in 00.07. - return row("00.08", "Viridian Forest to Pewter Center", at(FOREST, 29, 62, NORTH), {5, 3, 1}, StartMenu::FULL, { - // Wild battles are fought for EXP. Straight up the east side from the - // entrance, each leg ending on a wall (the Boy at (45, 58) stops the - // east one). Rick (47, 45) sees (42..46, 45), so the last leg meets - // his battle and is held on to its wall after it. The by-hand run's - // detour west to (13, 46) and back is dropped. - legs("forest_east", {{EAST, 1}, {NORTH, 4}, {EAST, 14}, {NORTH, 15}}, "up the east side to (44, 43)", WildBattles::FIGHT), - route("forest_north", at(FOREST, 39, 25), "north part", WildBattles::FIGHT), - // To the gate by legs that end on walls, which the walker holds again - // after a battle instead of estimating where it stopped: planned - // routes with open legs lost the player in the north of the forest - // (console B, 2026-11-01). The two 1-tile legs are single steps. - legs("forest_exit", { - {NORTH, 10}, {WEST, 12}, {SOUTH, 10}, {WEST, 6}, {NORTH, 20}, - {SOUTH, 1}, {WEST, 10}, {SOUTH, 27}, {WEST, 8}, {NORTH, 20}, {EAST, 1}, - }, "walls all the way to the gate's column", WildBattles::FIGHT), - route("forest_gate", at(FOREST_GATE, 7, 10, NORTH), "north onto the exit, arriving on the gate's mat", WildBattles::FIGHT), - // Out of the forest, wild battles are run from; trainers are still fought. - route("pewter_nurse", at(PEWTER_CENTER, 7, 4, NORTH), "Route 2 north to Pewter's Center"), - heal("heal_pewter"), - }); -} - -StoryCheckpoint brock(){ - // The by-hand save: 2 Potions and 1 Antidote left after the forest. - return row("00.09", "Pewter Gym: Camper Liam, then Brock", at(PEWTER_CENTER, 7, 4, NORTH), {2, 1}, StartMenu::FULL, { - // Camper Liam (3, 8) always faces east (MOVEMENT_TYPE_FACE_RIGHT, sight - // 4) and sees (4..7, 8): walking north up column 6 from the door, - // the step onto (6, 8) starts his battle. He walks up to the player, - // who stays put and keeps facing north (FRLG doesn't turn the player - // to a trainer). That step is taken on its own, so no leg is cut. - route("below_liam_line", at(GYM, 6, 9, NORTH), "in by the door, up column 6 to below Liam's row"), - step_into("liam_line", NORTH, "onto (6, 8), in Liam's line"), - battle("camper_liam", at(GYM, 6, 8, NORTH), false, "Geodude and Sandshrew; EXP before Brock"), - // On to Brock unless red HP or a status is left that no item cures. - ready("ready_for_brock", at(PEWTER_CENTER, 7, 4, NORTH), "items for a status or low HP; the nurse only if they can't"), - route("before_brock", at(GYM, 6, 6, NORTH), "below Brock (6, 5); Liam, beaten, stands at (5, 8)"), - talk("challenge_brock", "Brock's speech"), - battle("brock", at(GYM, 6, 6, NORTH), false, "Geodude and Onix, with Bubble; Boulder Badge and TM39"), - }); -} - -StoryCheckpoint running_shoes(){ - return row("00.10", "Pewter: the Running Shoes from Oak's aide", at(GYM, 6, 6, NORTH), after_brock(), StartMenu::FULL, { - // Brock's win sets VAR_MAP_SCENE_PEWTER_CITY to 1 and shows the aide at - // (46, 20); his triggers are (46, 21..23) (PewterCity map.json). The - // Gym guide's triggers at (42..43, 21..23) need the scene at 0. - route("before_aide_trigger", at(PEWTER, 45, 21, EAST), "out of the Gym, east along row 21, short of the top trigger"), - step_into("aide_trigger", EAST, "onto (46, 21), below the aide"), - // RunningShoesAideTriggerTop: the aide talks from (46, 20), no YES/NO; - // the player only turns up. He walks off and is removed; FLAG_SYS_B_DASH - // is set (console B, 2026-11-02: about 20 B presses to the overworld). - scene("shoes_from_aide", at(PEWTER, 46, 21, NORTH), "\"Oh, PLAYER!\" ... the Running Shoes; ends facing north"), - }); -} - - -std::vector cpp_rows(){ - return { - new_game(), after_sid_helper(), leave_house(), oaks_trigger(), to_starter_ball(), starter(), parcel(), pokedex(), shopping(), forest(), brock(), - running_shoes(), - }; -} - -// Why `loaded` differs from `row`, or empty. Steps compare as their -// shared JSON, which writes every field. -std::string checkpoint_difference(const StoryCheckpoint& row, const StoryCheckpoint& loaded){ - const std::string row_json = Pokemon::story_checkpoint_json(row).dump(); - const std::string loaded_json = Pokemon::story_checkpoint_json(loaded).dump(); - if (row_json != loaded_json){ - return std::format("{}: the file loads to\n{}\nbut the C++ row is\n{}", row.id, loaded_json, row_json); - } - if (row.handoff != loaded.handoff || row.live_start != loaded.live_start){ - return row.id + ": a different handoff or live start."; - } - if (row.menu != loaded.menu){ - return row.id + ": a different START menu."; - } - const Supplies& a = row.supplies; - const Supplies& b = loaded.supplies; - if (a.potions != b.potions || a.antidotes != b.antidotes || a.parlyz_heals != b.parlyz_heals){ - return row.id + ": different supplies."; - } - if (a.lead.species != b.lead.species || a.lead.level != b.lead.level || a.lead.moves.size() != b.lead.moves.size()){ - return row.id + ": a different lead."; - } - for (size_t c = 0; c < a.lead.moves.size(); c++){ - if (a.lead.moves[c].move != b.lead.moves[c].move || a.lead.moves[c].pp != b.lead.moves[c].pp){ - return row.id + ": a different lead move " + std::to_string(c + 1) + "."; - } - } - return ""; -} - -class Test_AutoStoryTableParity : public UnitTest{ -public: - Test_AutoStoryTableParity() - : UnitTest("PokemonFRLG::AutoStory - the story files load to the C++ rows") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - try{ - const std::vector rows = cpp_rows(); - const std::vector& loaded = story_checkpoints(); - if (rows.size() != loaded.size()){ - return std::format("{} C++ rows, {} files.", rows.size(), loaded.size()); - } - for (size_t c = 0; c < rows.size(); c++){ - const std::string difference = checkpoint_difference(rows[c], loaded[c]); - if (!difference.empty()){ - return difference; - } - } - return true; - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } -}; - -} // namespace - - -void add_tests_AutoStoryTableParity(UnitTestDatabase& database){ - database.add(); -} - - - -} // namespace PokemonFRLG -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 3b11728b46..37529b52c5 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1953,7 +1953,6 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableParity_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp From eb565cba4012b575d63cb60b1eb1a6ef230342f7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 14:35:54 -0800 Subject: [PATCH 06/13] FRLG RNG stage: string_view for char*, split the large RNG and naming headers Code health on the stage's own code: names and key text as std::string_view, the naming keyboard header split into keys, cursor and planner, the RNG headers split by concern (Method 1, Starter RNG timings, target, outcome, loop log), and the naming screen tests moved into their own file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 611 +---------------- .../AutoStory/PokemonFRLG_AutoStory.cpp | 2 +- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStory_Tests.cpp | 2 +- .../Programs/PokemonFRLG_NamingScreenCursor.h | 65 ++ .../PokemonFRLG_NamingScreenKeyboard.cpp | 98 +-- .../PokemonFRLG_NamingScreenKeyboard.h | 96 +-- ...PokemonFRLG_NamingScreenKeyboard_Tests.cpp | 620 ++++++++++++++++++ .../PokemonFRLG_NamingScreenKeyboard_Tests.h | 25 + .../Programs/PokemonFRLG_NamingScreenKeys.h | 80 +++ .../RngManipulation/PokemonFRLG_RngMethod1.h | 51 ++ .../RngManipulation/PokemonFRLG_RngPlan.h | 34 +- .../PokemonFRLG_RngPlanInputs_Tests.cpp | 2 +- .../PokemonFRLG_RngPlanLog.cpp | 4 +- .../PokemonFRLG_RngPlanLog_Tests.cpp | 2 +- .../PokemonFRLG_RngPlanTracker_Tests.cpp | 4 +- .../PokemonFRLG_RngPlan_Tests.cpp | 2 +- .../PokemonFRLG_RngSteps_Tests.cpp | 2 +- .../PokemonFRLG_RngTargetSearch.cpp | 4 +- .../PokemonFRLG_RngTargetSearch.h | 26 +- .../PokemonFRLG_RngTargetSearch_Tests.cpp | 6 +- .../PokemonFRLG_StarterRngAttempts.h | 62 +- .../PokemonFRLG_StarterRngLoop.h | 59 +- .../PokemonFRLG_StarterRngLoopLog.h | 86 +++ .../PokemonFRLG_StarterRngLoop_Tests.cpp | 2 +- .../PokemonFRLG_StarterRngOutcome.h | 43 ++ .../PokemonFRLG_StarterRngTarget.h | 72 ++ .../PokemonFRLG_StarterRngTimings.h | 61 ++ SerialPrograms/cmake/SourceFiles.cmake | 9 + 29 files changed, 1207 insertions(+), 925 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index d261fb3cbd..5b6a47e2c1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -42,7 +42,7 @@ #include "Overworld/PokemonFRLG_OverworldRoute.h" #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" -#include "Programs/PokemonFRLG_NamingScreenKeyboard.h" +#include "Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h" #include "PokemonFRLG_Navigation.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" @@ -287,591 +287,6 @@ void add_tests_ExitWildBattle(UnitTestDatabase& database){ } } - -// Naming screen keyboard: cursor moves, plans and text checks, against pokefirered's -// src/naming_screen.c. - -struct NamingCursorInput{ - std::string name = ""; - NamingCursor start = {}; - std::vector actions = {}; -}; - -struct NamingCursorExpectation{ - NamingCursor expected = {}; -}; - -struct NamingCursorScenario{ - NamingCursorInput input; - NamingCursorExpectation expectation; -}; - -class Test_NamingCursor : public UnitTest{ -public: - explicit Test_NamingCursor(NamingCursorScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen cursor - " + scenario.input.name) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - NamingCursor cursor = m_scenario.input.start; - for (NamingAction action : m_scenario.input.actions){ - cursor = apply_naming_action(cursor, action); - } - if (cursor != m_scenario.expectation.expected){ - return "After " + to_string(m_scenario.input.actions) + ": expected " + to_string(m_scenario.expectation.expected) - + ", got " + to_string(cursor); - } - return true; - } - -private: - const NamingCursorScenario m_scenario; -}; - -const NamingCursorScenario NAMING_CURSOR_CASES[] = { - // Crossing and moving on the button column. - { - .input = { - .name = "left from A goes to the page button", - .actions = {NamingAction::LEFT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, - }, - }, - { - .input = { - .name = "left and right return to A", - .actions = {NamingAction::LEFT, NamingAction::RIGHT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, - }, - }, - { - .input = { - .name = "row 1 crosses the button column", - .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0}, - .actions = {NamingAction::LEFT, NamingAction::RIGHT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, - }, - }, - { - .input = { - .name = "row 2 crosses the button column", - .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, - .actions = {NamingAction::LEFT, NamingAction::RIGHT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0, .remembered_row = 2}, - }, - }, - { - .input = { - .name = "row 3 crosses the OK button", - .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, - .actions = {NamingAction::LEFT, NamingAction::RIGHT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0, .remembered_row = 2}, - }, - }, - { - .input = { - .name = "right from the last column wraps through the buttons", - .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, - .actions = {NamingAction::RIGHT, NamingAction::RIGHT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, - }, - }, - { - .input = { - .name = "moving on the button column forgets row 2", - .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, - .actions = {NamingAction::LEFT, NamingAction::UP, NamingAction::DOWN, NamingAction::RIGHT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, - }, - }, - // Wrap-around on the keys and the button column. - { - .input = { - .name = "button column wraps over three buttons", - .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, - .actions = {NamingAction::UP}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 8, .remembered_row = 2}, - }, - }, - { - .input = { - .name = "rows wrap up", - .actions = {NamingAction::UP}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, - }, - }, - { - .input = { - .name = "rows wrap down", - .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, - .actions = {NamingAction::DOWN}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, - }, - }, - { - .input = { - .name = "symbols page has six key columns", - .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, - .actions = {NamingAction::LEFT, NamingAction::LEFT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 5, .remembered_row = 1}, - }, - }, - // SELECT and START. - { - .input = { - .name = "SELECT goes to lower case", - .actions = {NamingAction::SELECT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::LOWER, .row = 0, .column = 0}, - }, - }, - { - .input = { - .name = "SELECT twice goes to symbols", - .actions = {NamingAction::SELECT, NamingAction::SELECT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, - }, - }, - { - .input = { - .name = "SELECT three times returns to upper case", - .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, - }, - }, - { - .input = { - .name = "SELECT moves the cursor into the symbols columns", - .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, - .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 5}, - }, - }, - { - .input = { - .name = "SELECT keeps the cursor on the button column", - .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 8, .remembered_row = 1}, - .actions = {NamingAction::SELECT, NamingAction::SELECT}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::SYMBOLS, .row = 1, .column = 6, .remembered_row = 1}, - }, - }, - { - .input = { - .name = "START goes to OK", - .start = {.page = NamingScreenPage::LOWER, .row = 1, .column = 3}, - .actions = {NamingAction::START}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::LOWER, .row = 2, .column = 8}, - }, - }, - { - .input = { - .name = "START goes to OK on symbols", - .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, - .actions = {NamingAction::START}, - }, - .expectation = { - .expected = {.page = NamingScreenPage::SYMBOLS, .row = 2, .column = 6}, - }, - }, -}; - -void add_tests_NamingCursor(UnitTestDatabase& database){ - for (const NamingCursorScenario& scenario : NAMING_CURSOR_CASES){ - database.add(scenario); - } -} - - -struct NamingPlanInput{ - std::string name = ""; - std::string text = ""; - NamingScreenKind kind = NamingScreenKind::PLAYER; -}; - -struct NamingPlanExpectation{ - // What the game shows when it differs from `text` (another spelling of a key). - std::string typed = ""; - // The exact plan, when the shortest one is unique; "" to skip. - std::string expected_actions = ""; - // The number of presses, including A and the final START A; 0 to skip. - size_t expected_presses = 0; -}; - -struct NamingPlanScenario{ - NamingPlanInput input; - NamingPlanExpectation expectation; -}; - -std::string replay_naming_plan( - const std::vector& actions, - const std::string& plan, - const NamingPlanScenario& scenario -){ - std::string typed; - NamingCursor cursor; - for (size_t i = 0; i < actions.size(); i++){ - cursor = apply_naming_action(cursor, actions[i]); - if (actions[i] != NamingAction::A){ - continue; - } - const uint8_t columns = NAMING_SCREEN_KEY_COLUMNS[(size_t)cursor.page]; - if (i + 1 == actions.size()){ - if (cursor.column != columns || cursor.row != NAMING_SCREEN_BUTTON_OK){ - return "The last A is not on OK but on " + to_string(cursor) + ": " + plan; - } - break; - } - if (cursor.column >= columns){ - return "A pressed on the button column at " + to_string(cursor) + ": " + plan; - } - typed += NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; - } - const std::string& expected = scenario.expectation.typed.empty() ? scenario.input.text : scenario.expectation.typed; - if (typed != expected){ - return "Expected the plan to type \"" + expected + "\", it types \"" + typed + "\": " + plan; - } - return ""; -} - -class Test_NamingPlan : public UnitTest{ -public: - explicit Test_NamingPlan(NamingPlanScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen plan - " + scenario.input.name) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::vector actions = plan_naming_input(m_scenario.input.text, m_scenario.input.kind); - const std::string plan = to_string(actions); - if (!m_scenario.expectation.expected_actions.empty() && plan != m_scenario.expectation.expected_actions){ - return "Expected plan: " + m_scenario.expectation.expected_actions + "\nActual plan: " + plan; - } - if (m_scenario.expectation.expected_presses != 0 && actions.size() != m_scenario.expectation.expected_presses){ - return "Expected " + std::to_string(m_scenario.expectation.expected_presses) + " presses, got " - + std::to_string(actions.size()) + ": " + plan; - } - std::string replay_error = replay_naming_plan(actions, plan, m_scenario); - if (!replay_error.empty()){ - return replay_error; - } - return true; - } - -private: - const NamingPlanScenario m_scenario; -}; - -const NamingPlanScenario NAMING_PLAN_CASES[] = { - { - .input = {.name = "starts on A", .text = "A"}, - .expectation = {.expected_actions = "A START A"}, - }, - { - .input = {.name = "next key", .text = "AB"}, - .expectation = {.expected_actions = "A RIGHT A START A"}, - }, - { - .input = {.name = "next row", .text = "AG"}, - .expectation = {.expected_actions = "A DOWN A START A"}, - }, - { - .input = {.name = "rows wrap", .text = "T"}, - .expectation = {.expected_actions = "UP A START A"}, - }, - { - .input = { - .name = "columns wrap through the button column", - .text = ".", - }, - .expectation = {.expected_actions = "LEFT LEFT A START A"}, - }, - { - .input = {.name = "lower case page", .text = "a"}, - .expectation = {.expected_actions = "SELECT A START A"}, - }, - { - .input = {.name = "symbols page", .text = "0"}, - .expectation = {.expected_actions = "SELECT SELECT A START A"}, - }, - { - .input = { - .name = "page change moves the cursor into the symbols columns", - .text = ".4", - }, - .expectation = {.expected_actions = "LEFT LEFT A SELECT SELECT LEFT A START A"}, - }, - { - .input = {.name = "both ways round", .text = "Z"}, - .expectation = {.expected_presses = 7}, - }, - { - .input = {.name = "male sign", .text = "\xE2\x99\x82"}, - .expectation = {.expected_presses = 9}, - }, - { - .input = {.name = "full player name", .text = "ABCDEFG"}, - .expectation = {.expected_presses = 19}, - }, - { - .input = {.name = "mixed case", .text = "Gary"}, - .expectation = {.expected_presses = 16}, - }, - { - .input = {.name = "space", .text = "A B"}, - .expectation = {.expected_presses = 12}, - }, - { - .input = {.name = "full nickname", .text = "BULBASAURS", .kind = NamingScreenKind::POKEMON}, - .expectation = {}, - }, - { - .input = {.name = "female sign", .text = "NIDORAN\xE2\x99\x80", .kind = NamingScreenKind::POKEMON}, - .expectation = {}, - }, - { - .input = {.name = "box name", .text = "BOX 1-2!", .kind = NamingScreenKind::BOX}, - .expectation = {}, - }, - { - .input = {.name = "rival", .text = "Blue?", .kind = NamingScreenKind::RIVAL}, - .expectation = {}, - }, - { - .input = { - .name = "symbols row 4", - .text = "\xE2\x80\xA6\xE2\x80\x9C\xE2\x80\x9D\xE2\x80\x98'", - .kind = NamingScreenKind::POKEMON, - }, - .expectation = {}, - }, - { - .input = {.name = "curly apostrophe", .text = "IT\xE2\x80\x99S"}, - .expectation = {.typed = "IT'S"}, - }, -}; - -void add_tests_NamingPlan(UnitTestDatabase& database){ - for (const NamingPlanScenario& scenario : NAMING_PLAN_CASES){ - database.add(scenario); - } -} - - -struct NamingKeysInput{ - std::string name = ""; - std::string text = ""; - NamingScreenKind kind = NamingScreenKind::PLAYER; -}; - -struct NamingKeysExpectation{ - // The exact plan, when the shortest one is unique; "" to skip. - std::string expected_actions = ""; -}; - -struct NamingKeysScenario{ - NamingKeysInput input; - NamingKeysExpectation expectation; -}; - -// plan_naming_keys() stops before OK: it is plan_naming_input() without the final START A. -class Test_NamingKeys : public UnitTest{ -public: - explicit Test_NamingKeys(NamingKeysScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen keys only - " + scenario.input.name) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::string keys = to_string(plan_naming_keys(m_scenario.input.text, m_scenario.input.kind)); - if (!m_scenario.expectation.expected_actions.empty() && keys != m_scenario.expectation.expected_actions){ - return "Expected keys: " + m_scenario.expectation.expected_actions + "\nActual keys: " + keys; - } - const std::string input = to_string(plan_naming_input(m_scenario.input.text, m_scenario.input.kind)); - if (input != keys + " START A"){ - return "Expected the confirmed plan to be \"" + keys + " START A\", got \"" + input + "\""; - } - return true; - } - -private: - const NamingKeysScenario m_scenario; -}; - -const NamingKeysScenario NAMING_KEYS_CASES[] = { - { - .input = {.name = "one key", .text = "A"}, - .expectation = {.expected_actions = "A"}, - }, - { - .input = {.name = "next key", .text = "AB"}, - .expectation = {.expected_actions = "A RIGHT A"}, - }, - { - .input = {.name = "lower case page", .text = "a"}, - .expectation = {.expected_actions = "SELECT A"}, - }, - { - .input = {.name = "full player name", .text = "ABCDEFG"}, - .expectation = {}, - }, - { - .input = {.name = "mixed case", .text = "Kosmos"}, - .expectation = {}, - }, -}; - -void add_tests_NamingKeys(UnitTestDatabase& database){ - for (const NamingKeysScenario& scenario : NAMING_KEYS_CASES){ - database.add(scenario); - } -} - - -struct NamingTextInput{ - std::string name = ""; - std::string text = ""; - NamingScreenKind kind = NamingScreenKind::PLAYER; -}; - -struct NamingTextExpectation{ - // A part of the expected error; "" if the text is fine. - std::string expected_error = ""; -}; - -struct NamingTextScenario{ - NamingTextInput input; - NamingTextExpectation expectation; -}; - -class Test_NamingText : public UnitTest{ -public: - explicit Test_NamingText(NamingTextScenario scenario) - : UnitTest("PokemonFRLG::NamingScreen text - " + scenario.input.name) - , m_scenario(std::move(scenario)) - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::string error = naming_text_error(m_scenario.input.text, m_scenario.input.kind); - if (m_scenario.expectation.expected_error.empty()){ - if (!error.empty()){ - return "Expected \"" + m_scenario.input.text + "\" to be accepted, got: " + error; - } - return true; - } - if (error.find(m_scenario.expectation.expected_error) == std::string::npos){ - return "Expected an error containing \"" + m_scenario.expectation.expected_error + "\", got: \"" + error + "\""; - } - try{ - plan_naming_input(m_scenario.input.text, m_scenario.input.kind); - }catch (InternalProgramError&){ - return true; - } - return "Expected plan_naming_input() to throw for \"" + m_scenario.input.text + "\""; - } - -private: - const NamingTextScenario m_scenario; -}; - -const NamingTextScenario NAMING_TEXT_CASES[] = { - { - .input = {.name = "player name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::PLAYER}, - .expectation = {}, - }, - { - .input = {.name = "player name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::PLAYER}, - .expectation = {.expected_error = "at most 7"}, - }, - { - .input = {.name = "rival name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::RIVAL}, - .expectation = {}, - }, - { - .input = {.name = "rival name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::RIVAL}, - .expectation = {.expected_error = "at most 7"}, - }, - { - .input = {.name = "box name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::BOX}, - .expectation = {}, - }, - { - .input = {.name = "box name of 9", .text = "ABCDEFGHI", .kind = NamingScreenKind::BOX}, - .expectation = {.expected_error = "at most 8"}, - }, - { - .input = {.name = "nickname of 10", .text = "ABCDEFGHIJ", .kind = NamingScreenKind::POKEMON}, - .expectation = {}, - }, - { - .input = {.name = "nickname of 11", .text = "ABCDEFGHIJK", .kind = NamingScreenKind::POKEMON}, - .expectation = {.expected_error = "at most 10"}, - }, - { - .input = { - .name = "symbols count as one character", - .text = "\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82", - .kind = NamingScreenKind::PLAYER, - }, - .expectation = {}, - }, - { - .input = {.name = "unknown character", .text = "Ash@", .kind = NamingScreenKind::PLAYER}, - .expectation = {.expected_error = "type: \"@\""}, - }, - { - .input = {.name = "unknown accented character", .text = "Jos\xC3\xA9", .kind = NamingScreenKind::PLAYER}, - .expectation = {.expected_error = "type: \"\xC3\xA9\""}, - }, - { - .input = {.name = "empty", .text = "", .kind = NamingScreenKind::PLAYER}, - .expectation = {.expected_error = "empty"}, - }, - { - .input = {.name = "only spaces", .text = " ", .kind = NamingScreenKind::PLAYER}, - .expectation = {.expected_error = "only spaces"}, - }, -}; - -void add_tests_NamingText(UnitTestDatabase& database){ - for (const NamingTextScenario& scenario : NAMING_TEXT_CASES){ - database.add(scenario); - } -} - } // namespace // The menu readers AutoStory brought: the bag's and Marts' lists, the @@ -886,6 +301,17 @@ static void add_tests_AutoStoryReaders(UnitTestDatabase& database){ add_tests_AutoStoryScreenEvents(database); } +// The RNG plan: its targets, attempts and the Starter RNG loop. +static void add_tests_RngPlanning(UnitTestDatabase& database){ + add_tests_RngTargetSearch(database); + add_tests_RngPlanInputs(database); + add_tests_RngPlan(database); + add_tests_RngPlanTracker(database); + add_tests_RngPlanLog(database); + add_tests_RngSteps(database); + add_tests_StarterRngLoop(database); +} + void add_tests(UnitTestDatabase& database){ add_tests_AdvanceWhiteDialogDetector(database); add_tests_BoxCellOccupiedDetector(database); @@ -925,17 +351,8 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); add_tests_AutoStoryRngLoop(database); - add_tests_NamingCursor(database); - add_tests_NamingPlan(database); - add_tests_NamingKeys(database); - add_tests_NamingText(database); - add_tests_RngTargetSearch(database); - add_tests_RngPlanInputs(database); - add_tests_RngPlan(database); - add_tests_RngPlanTracker(database); - add_tests_RngPlanLog(database); - add_tests_RngSteps(database); - add_tests_StarterRngLoop(database); + add_tests_NamingScreen(database); + add_tests_RngPlanning(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index eff9b08f50..5acfad4051 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -78,7 +78,7 @@ const std::string KEEP_START_FRAME_TEXT = } // namespace -const char* const RUN_STARTER_RNG_TEXT = +const std::string RUN_STARTER_RNG_TEXT = "Run Starter RNG in AutoStory:
Off by default. Instead of stopping for them, run SID Helper's steps on the " "new game's keyboard when the RNG plan has no SID, and Starter RNG's attempts from a save south of the table at the " "end of 00.04, as the RNG plan lists them. A shiny Squirtle goes on to the rival's battle, saves after it and the run " diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 0e506e7465..c164ec0bef 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -30,7 +30,7 @@ struct AutoStoryRngLoopInput{ }; struct AutoStoryRngLoopExpectation{ - const char* description; + std::string_view description; }; struct AutoStoryRngLoopTestCase{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index b9a48fa2b5..2b9756cf86 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -560,7 +560,7 @@ std::string joined_ids(const std::vector& rows){ return text; } -const char* handoff_name(StoryHandoff handoff){ +std::string handoff_name(StoryHandoff handoff){ switch (handoff){ case StoryHandoff::NONE: return "none"; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h new file mode 100644 index 0000000000..abd8760670 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h @@ -0,0 +1,65 @@ +/* Naming Screen Cursor + * + * From: https://github.com/PokemonAutomation/ + * + * The naming screen's cursor and the presses that move it, as + * pret/pokefirered src/naming_screen.c moves them (see PokemonFRLG_NamingScreenKeys.h). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenCursor_H +#define PokemonAutomation_PokemonFRLG_NamingScreenCursor_H + +#include +#include +#include +#include +#include "PokemonFRLG_NamingScreenKeys.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The cursor, as the game tracks it. +struct NamingCursor{ + NamingScreenPage page = NamingScreenPage::UPPER; + // Key row (0-3), or button (0-2) when on the button column. + uint8_t row = 0; + // Key column, or NAMING_SCREEN_KEY_COLUMNS[page] for the button column. + uint8_t column = 0; + // The game's tButtonId: the key row to return to when leaving the middle button. + uint8_t remembered_row = 0; + + bool operator==(const NamingCursor& other) const = default; +}; +// String representation of cursor coordinates. +std::string to_string(const NamingCursor& cursor); + + +// Input action on the naming screen keyboard. +enum class NamingAction : uint8_t{ + UP, + DOWN, + LEFT, + RIGHT, + A, + SELECT, // next page + START, // move the cursor to OK +}; +// String representation of naming action. +std::string_view naming_action_name(NamingAction action); +// Space-separated action names, e.g. "LEFT LEFT A START A". +std::string to_string(const std::vector& actions); + + +// Where the cursor ends up after one press (HandleDpadMovement, MainState_WaitPageSwap, +// MoveCursorToOKButton). A leaves the cursor in place. +NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp index 1ab0e9aa39..68a3234e06 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp @@ -4,7 +4,8 @@ * */ -#include +#include +#include #include "Common/Compiler.h" #include "Common/Cpp/Exceptions.h" #include "PokemonFRLG_NamingScreenKeyboard.h" @@ -23,7 +24,7 @@ size_t naming_screen_max_chars(NamingScreenKind kind){ } return 0; } -const char* naming_screen_kind_name(NamingScreenKind kind){ +std::string_view naming_screen_kind_name(NamingScreenKind kind){ switch (kind){ case NamingScreenKind::PLAYER: return "player"; case NamingScreenKind::RIVAL: return "rival"; @@ -34,14 +35,14 @@ const char* naming_screen_kind_name(NamingScreenKind kind){ } std::string to_string(const NamingCursor& cursor){ - static const char* const PAGE_NAMES[] = {"UPPER", "LOWER", "SYMBOLS"}; - return std::string(PAGE_NAMES[(size_t)cursor.page]) - + " row " + std::to_string(cursor.row) - + " column " + std::to_string(cursor.column) - + " (remembered row " + std::to_string(cursor.remembered_row) + ")"; + static constexpr std::string_view PAGE_NAMES[] = {"UPPER", "LOWER", "SYMBOLS"}; + return std::format( + "{} row {} column {} (remembered row {})", + PAGE_NAMES[(size_t)cursor.page], cursor.row, cursor.column, cursor.remembered_row + ); } -const char* naming_action_name(NamingAction action){ +std::string_view naming_action_name(NamingAction action){ switch (action){ case NamingAction::UP: return "UP"; case NamingAction::DOWN: return "DOWN"; @@ -141,45 +142,54 @@ NamingCursor next_page(NamingCursor cursor){ return cursor; } -const char* key_at(const NamingCursor& cursor){ +std::string_view key_at(const NamingCursor& cursor){ if (cursor.column >= key_columns(cursor.page)){ - return nullptr; + return {}; } return NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; } struct KeyAlias{ - const char* typed; - const char* key; + std::string_view typed; + std::string_view key; }; // Other spellings of a key's character. constexpr KeyAlias KEY_ALIASES[] = { {"\xE2\x80\x99", "'"}, // right single quote: the apostrophe key types it }; -bool text_has_at(const std::string& text, size_t position, const char* str){ - return text.compare(position, strlen(str), str) == 0; +bool text_has_at(const std::string& text, size_t position, std::string_view str){ + return text.compare(position, str.size(), str) == 0; } -// The key text at `position` in `text`, or nullptr if no key types it. -const char* key_text_at(const std::string& text, size_t position, size_t& length){ - const char* best = nullptr; - length = 0; +// A key typing the text at a position, and how many bytes of the text it covers. +struct KeyMatch{ + std::string_view key; + size_t length = 0; +}; + +// `best`, or the longest key of `row` that types the text at `position` if it is longer. +KeyMatch longer_match(KeyMatch best, std::span row, const std::string& text, size_t position){ + for (std::string_view key : row){ + if (key.size() > best.length && text_has_at(text, position, key)){ + best = {key, key.size()}; + } + } + return best; +} + +// The key text at `position` in `text`; an empty key if no key types it. +KeyMatch key_text_at(const std::string& text, size_t position){ + KeyMatch best; for (const auto& page : NAMING_SCREEN_KEYS){ for (const auto& row : page){ - for (const char* key : row){ - if (key != nullptr && strlen(key) > length && text_has_at(text, position, key)){ - best = key; - length = strlen(key); - } - } + best = longer_match(best, row, text, position); } } for (const KeyAlias& alias : KEY_ALIASES){ - if (strlen(alias.typed) > length && text_has_at(text, position, alias.typed)){ - best = alias.key; - length = strlen(alias.typed); + if (alias.typed.size() > best.length && text_has_at(text, position, alias.typed)){ + best = {alias.key, alias.typed.size()}; } } return best; @@ -200,19 +210,18 @@ std::string utf8_char_at(const std::string& text, size_t position){ } // Splits `text` into the keys that type it. Returns the error, or "" on success. -std::string split_into_keys(const std::string& text, std::vector& keys){ +std::string split_into_keys(const std::string& text, std::vector& keys){ keys.clear(); for (size_t position = 0; position < text.size();){ - size_t length; - const char* key = key_text_at(text, position, length); - if (key == nullptr){ + const KeyMatch match = key_text_at(text, position); + if (match.key.empty()){ return "\"" + text + "\" has a character the naming screen can't type: \"" + utf8_char_at(text, position) + "\" (byte " + std::to_string(position) + "). " "It types A-Z, a-z, 0-9, space and . , ! ? / - ' and the game's " "male/female signs, ellipsis and curly quotes."; } - keys.emplace_back(key); - position += length; + keys.emplace_back(match.key); + position += match.length; } return ""; } @@ -227,7 +236,7 @@ constexpr size_t STATE_COUNT = // Breadth-first search over cursor states for the fewest presses that reach a key typing `key`. // Appends the moves and returns the cursor on that key. -NamingCursor append_moves_to_key(const NamingCursor& start, const char* key, std::vector& actions){ +NamingCursor append_moves_to_key(const NamingCursor& start, std::string_view key, std::vector& actions){ // START is left out: it only jumps to OK, which the plan uses once at the end. static const NamingAction MOVES[] = { NamingAction::UP, NamingAction::DOWN, NamingAction::LEFT, NamingAction::RIGHT, NamingAction::SELECT, @@ -243,8 +252,7 @@ NamingCursor append_moves_to_key(const NamingCursor& start, const char* key, std for (size_t head = 0; head < queue.size(); head++){ const NamingCursor cursor = queue[head]; - const char* here = key_at(cursor); - if (here != nullptr && strcmp(here, key) == 0){ + if (key_at(cursor) == key){ std::vector path; for (size_t index = state_index(cursor); index != state_index(start); index = visits[index].parent){ path.emplace_back(visits[index].action); @@ -264,7 +272,7 @@ NamingCursor append_moves_to_key(const NamingCursor& start, const char* key, std } } // Every key is reachable, so this is a bug. - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string("No path to naming screen key: ") + key); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No path to naming screen key: {}", key)); } } // namespace @@ -291,22 +299,24 @@ NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action std::string naming_text_error(const std::string& text, NamingScreenKind kind){ - std::vector keys; + std::vector keys; std::string error = split_into_keys(text, keys); if (!error.empty()){ return error; } bool only_spaces = true; - for (const char* key : keys){ - only_spaces &= strcmp(key, " ") == 0; + for (std::string_view key : keys){ + only_spaces &= key == " "; } if (only_spaces){ return "The name \"" + text + "\" is empty or only spaces, so the game would not keep it."; } const size_t max_chars = naming_screen_max_chars(kind); if (keys.size() > max_chars){ - return "\"" + text + "\" is " + std::to_string(keys.size()) + " characters, but a " - + naming_screen_kind_name(kind) + " name holds at most " + std::to_string(max_chars) + "."; + return std::format( + "\"{}\" is {} characters, but a {} name holds at most {}.", + text, keys.size(), naming_screen_kind_name(kind), max_chars + ); } return ""; } @@ -318,12 +328,12 @@ std::vector plan_naming_keys( if (!error.empty()){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, error); } - std::vector keys; + std::vector keys; split_into_keys(text, keys); std::vector actions; NamingCursor cursor = start; - for (const char* key : keys){ + for (std::string_view key : keys){ cursor = append_moves_to_key(cursor, key, actions); actions.emplace_back(NamingAction::A); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h index 4d9b7c1337..132dbeb3bd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h @@ -17,67 +17,15 @@ #include #include #include +#include #include +#include "PokemonFRLG_NamingScreenCursor.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// The keyboard pages, in the order SELECT cycles through them. The screen opens on UPPER. -enum class NamingScreenPage : uint8_t{ - UPPER, - LOWER, - SYMBOLS, -}; -// Total page count on naming screen. -constexpr size_t NAMING_SCREEN_PAGES = 3; -// Number of key rows per page. -constexpr size_t NAMING_SCREEN_KEY_ROWS = 4; -// Maximum key columns across pages. -constexpr size_t NAMING_SCREEN_MAX_KEY_COLUMNS = 8; - -// Key columns on each page (sPageColumnCounts). The button column (page / back / OK) comes -// right after the last key column, so on a page with N key columns it is column N. -constexpr uint8_t NAMING_SCREEN_KEY_COLUMNS[NAMING_SCREEN_PAGES] = {8, 8, 6}; - -// The text each key types, in UTF-8 (sKeyboardChars), indexed [page][row][column]. -// nullptr: no key (past the page's last column). -// The decomp pads each row with byte 0x00, which is a space in the game's charmap, and the -// keyboard labels draw a blank there: those cells type a space just like the spaces in rows 0-1. -// The apostrophe key types the game's right single quote (charmap 0xB4). -constexpr const char* NAMING_SCREEN_KEYS - [NAMING_SCREEN_PAGES][NAMING_SCREEN_KEY_ROWS][NAMING_SCREEN_MAX_KEY_COLUMNS] = { - { // UPPER - {"A", "B", "C", "D", "E", "F", " ", "."}, - {"G", "H", "I", "J", "K", "L", " ", ","}, - {"M", "N", "O", "P", "Q", "R", "S", " "}, - {"T", "U", "V", "W", "X", "Y", "Z", " "}, - }, - { // LOWER - {"a", "b", "c", "d", "e", "f", " ", "."}, - {"g", "h", "i", "j", "k", "l", " ", ","}, - {"m", "n", "o", "p", "q", "r", "s", " "}, - {"t", "u", "v", "w", "x", "y", "z", " "}, - }, - { // SYMBOLS - {"0", "1", "2", "3", "4", " ", nullptr, nullptr}, - {"5", "6", "7", "8", "9", " ", nullptr, nullptr}, - {"!", "?", "\xE2\x99\x82", "\xE2\x99\x80", "/", "-", nullptr, nullptr}, // ! ? male female / - - {"\xE2\x80\xA6", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x98", "'", " ", nullptr, nullptr}, // ellipsis, double quotes, left single quote, ' - }, -}; - -// The three buttons in the button column, top to bottom. -// The three buttons in the button column, top to bottom. -// Button index for switching character pages. -constexpr uint8_t NAMING_SCREEN_BUTTON_PAGE = 0; -// Button index for backspacing a character. -constexpr uint8_t NAMING_SCREEN_BUTTON_BACK = 1; -// Button index for confirming naming input. -constexpr uint8_t NAMING_SCREEN_BUTTON_OK = 2; - - // Which naming screen is open; it sets how many characters fit (NamingScreenTemplate.maxChars). enum class NamingScreenKind : uint8_t{ PLAYER, // PLAYER_NAME_LENGTH @@ -88,44 +36,7 @@ enum class NamingScreenKind : uint8_t{ // Maximum character length for the given naming screen type. size_t naming_screen_max_chars(NamingScreenKind kind); // Display name for naming screen kind. -const char* naming_screen_kind_name(NamingScreenKind kind); - - -// The cursor, as the game tracks it. -struct NamingCursor{ - NamingScreenPage page = NamingScreenPage::UPPER; - // Key row (0-3), or button (0-2) when on the button column. - uint8_t row = 0; - // Key column, or NAMING_SCREEN_KEY_COLUMNS[page] for the button column. - uint8_t column = 0; - // The game's tButtonId: the key row to return to when leaving the middle button. - uint8_t remembered_row = 0; - - bool operator==(const NamingCursor& other) const = default; -}; -// String representation of cursor coordinates. -std::string to_string(const NamingCursor& cursor); - - -// Input action on the naming screen keyboard. -enum class NamingAction : uint8_t{ - UP, - DOWN, - LEFT, - RIGHT, - A, - SELECT, // next page - START, // move the cursor to OK -}; -// String representation of naming action. -const char* naming_action_name(NamingAction action); -// Space-separated action names, e.g. "LEFT LEFT A START A". -std::string to_string(const std::vector& actions); - - -// Where the cursor ends up after one press (HandleDpadMovement, MainState_WaitPageSwap, -// MoveCursorToOKButton). A leaves the cursor in place. -NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action); +std::string_view naming_screen_kind_name(NamingScreenKind kind); // Why the game can't take `text` as a name of this kind, or "" if it can: a character with // no key, more characters than fit, or nothing but spaces (the game then keeps no name). @@ -146,6 +57,7 @@ std::vector plan_naming_input( + } // namespace PokemonFRLG } // namespace NintendoSwitch } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp new file mode 100644 index 0000000000..17806b6788 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp @@ -0,0 +1,620 @@ +/* Naming Screen Keyboard Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_NamingScreenKeyboard.h" +#include "PokemonFRLG_NamingScreenKeyboard_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + + +// Naming screen keyboard: cursor moves, plans and text checks, against pokefirered's +// src/naming_screen.c. + +struct NamingCursorInput{ + std::string name = ""; + NamingCursor start = {}; + std::vector actions = {}; +}; + +struct NamingCursorExpectation{ + NamingCursor expected = {}; +}; + +struct NamingCursorScenario{ + NamingCursorInput input; + NamingCursorExpectation expectation; +}; + +class Test_NamingCursor : public UnitTest{ +public: + explicit Test_NamingCursor(NamingCursorScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen cursor - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + NamingCursor cursor = m_scenario.input.start; + for (NamingAction action : m_scenario.input.actions){ + cursor = apply_naming_action(cursor, action); + } + if (cursor != m_scenario.expectation.expected){ + return "After " + to_string(m_scenario.input.actions) + ": expected " + to_string(m_scenario.expectation.expected) + + ", got " + to_string(cursor); + } + return true; + } + +private: + const NamingCursorScenario m_scenario; +}; + +const NamingCursorScenario NAMING_CURSOR_CASES[] = { + // Crossing and moving on the button column. + { + .input = { + .name = "left from A goes to the page button", + .actions = {NamingAction::LEFT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "left and right return to A", + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "row 1 crosses the button column", + .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "row 2 crosses the button column", + .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0, .remembered_row = 2}, + }, + }, + { + .input = { + .name = "row 3 crosses the OK button", + .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0, .remembered_row = 2}, + }, + }, + { + .input = { + .name = "right from the last column wraps through the buttons", + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, + .actions = {NamingAction::RIGHT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "moving on the button column forgets row 2", + .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::UP, NamingAction::DOWN, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }, + // Wrap-around on the keys and the button column. + { + .input = { + .name = "button column wraps over three buttons", + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::UP}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 8, .remembered_row = 2}, + }, + }, + { + .input = { + .name = "rows wrap up", + .actions = {NamingAction::UP}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + }, + }, + { + .input = { + .name = "rows wrap down", + .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::DOWN}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "symbols page has six key columns", + .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::LEFT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 5, .remembered_row = 1}, + }, + }, + // SELECT and START. + { + .input = { + .name = "SELECT goes to lower case", + .actions = {NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::LOWER, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "SELECT twice goes to symbols", + .actions = {NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "SELECT three times returns to upper case", + .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "SELECT moves the cursor into the symbols columns", + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, + .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 5}, + }, + }, + { + .input = { + .name = "SELECT keeps the cursor on the button column", + .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 1, .column = 6, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "START goes to OK", + .start = {.page = NamingScreenPage::LOWER, .row = 1, .column = 3}, + .actions = {NamingAction::START}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::LOWER, .row = 2, .column = 8}, + }, + }, + { + .input = { + .name = "START goes to OK on symbols", + .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::START}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 2, .column = 6}, + }, + }, +}; + +void add_tests_NamingCursor(UnitTestDatabase& database){ + for (const NamingCursorScenario& scenario : NAMING_CURSOR_CASES){ + database.add(scenario); + } +} + + +struct NamingPlanInput{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingPlanExpectation{ + // What the game shows when it differs from `text` (another spelling of a key). + std::string typed = ""; + // The exact plan, when the shortest one is unique; "" to skip. + std::string expected_actions = ""; + // The number of presses, including A and the final START A; 0 to skip. + size_t expected_presses = 0; +}; + +struct NamingPlanScenario{ + NamingPlanInput input; + NamingPlanExpectation expectation; +}; + +std::string replay_naming_plan( + const std::vector& actions, + const std::string& plan, + const NamingPlanScenario& scenario +){ + std::string typed; + NamingCursor cursor; + for (size_t i = 0; i < actions.size(); i++){ + cursor = apply_naming_action(cursor, actions[i]); + if (actions[i] != NamingAction::A){ + continue; + } + const uint8_t columns = NAMING_SCREEN_KEY_COLUMNS[(size_t)cursor.page]; + if (i + 1 == actions.size()){ + if (cursor.column != columns || cursor.row != NAMING_SCREEN_BUTTON_OK){ + return "The last A is not on OK but on " + to_string(cursor) + ": " + plan; + } + break; + } + if (cursor.column >= columns){ + return "A pressed on the button column at " + to_string(cursor) + ": " + plan; + } + typed += NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; + } + const std::string& expected = scenario.expectation.typed.empty() ? scenario.input.text : scenario.expectation.typed; + if (typed != expected){ + return "Expected the plan to type \"" + expected + "\", it types \"" + typed + "\": " + plan; + } + return ""; +} + +class Test_NamingPlan : public UnitTest{ +public: + explicit Test_NamingPlan(NamingPlanScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen plan - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector actions = plan_naming_input(m_scenario.input.text, m_scenario.input.kind); + const std::string plan = to_string(actions); + if (!m_scenario.expectation.expected_actions.empty() && plan != m_scenario.expectation.expected_actions){ + return "Expected plan: " + m_scenario.expectation.expected_actions + "\nActual plan: " + plan; + } + if (m_scenario.expectation.expected_presses != 0 && actions.size() != m_scenario.expectation.expected_presses){ + return "Expected " + std::to_string(m_scenario.expectation.expected_presses) + " presses, got " + + std::to_string(actions.size()) + ": " + plan; + } + std::string replay_error = replay_naming_plan(actions, plan, m_scenario); + if (!replay_error.empty()){ + return replay_error; + } + return true; + } + +private: + const NamingPlanScenario m_scenario; +}; + +const NamingPlanScenario NAMING_PLAN_CASES[] = { + { + .input = {.name = "starts on A", .text = "A"}, + .expectation = {.expected_actions = "A START A"}, + }, + { + .input = {.name = "next key", .text = "AB"}, + .expectation = {.expected_actions = "A RIGHT A START A"}, + }, + { + .input = {.name = "next row", .text = "AG"}, + .expectation = {.expected_actions = "A DOWN A START A"}, + }, + { + .input = {.name = "rows wrap", .text = "T"}, + .expectation = {.expected_actions = "UP A START A"}, + }, + { + .input = { + .name = "columns wrap through the button column", + .text = ".", + }, + .expectation = {.expected_actions = "LEFT LEFT A START A"}, + }, + { + .input = {.name = "lower case page", .text = "a"}, + .expectation = {.expected_actions = "SELECT A START A"}, + }, + { + .input = {.name = "symbols page", .text = "0"}, + .expectation = {.expected_actions = "SELECT SELECT A START A"}, + }, + { + .input = { + .name = "page change moves the cursor into the symbols columns", + .text = ".4", + }, + .expectation = {.expected_actions = "LEFT LEFT A SELECT SELECT LEFT A START A"}, + }, + { + .input = {.name = "both ways round", .text = "Z"}, + .expectation = {.expected_presses = 7}, + }, + { + .input = {.name = "male sign", .text = "\xE2\x99\x82"}, + .expectation = {.expected_presses = 9}, + }, + { + .input = {.name = "full player name", .text = "ABCDEFG"}, + .expectation = {.expected_presses = 19}, + }, + { + .input = {.name = "mixed case", .text = "Gary"}, + .expectation = {.expected_presses = 16}, + }, + { + .input = {.name = "space", .text = "A B"}, + .expectation = {.expected_presses = 12}, + }, + { + .input = {.name = "full nickname", .text = "BULBASAURS", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "female sign", .text = "NIDORAN\xE2\x99\x80", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "box name", .text = "BOX 1-2!", .kind = NamingScreenKind::BOX}, + .expectation = {}, + }, + { + .input = {.name = "rival", .text = "Blue?", .kind = NamingScreenKind::RIVAL}, + .expectation = {}, + }, + { + .input = { + .name = "symbols row 4", + .text = "\xE2\x80\xA6\xE2\x80\x9C\xE2\x80\x9D\xE2\x80\x98'", + .kind = NamingScreenKind::POKEMON, + }, + .expectation = {}, + }, + { + .input = {.name = "curly apostrophe", .text = "IT\xE2\x80\x99S"}, + .expectation = {.typed = "IT'S"}, + }, +}; + +void add_tests_NamingPlan(UnitTestDatabase& database){ + for (const NamingPlanScenario& scenario : NAMING_PLAN_CASES){ + database.add(scenario); + } +} + + +struct NamingKeysInput{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingKeysExpectation{ + // The exact plan, when the shortest one is unique; "" to skip. + std::string expected_actions = ""; +}; + +struct NamingKeysScenario{ + NamingKeysInput input; + NamingKeysExpectation expectation; +}; + +// plan_naming_keys() stops before OK: it is plan_naming_input() without the final START A. +class Test_NamingKeys : public UnitTest{ +public: + explicit Test_NamingKeys(NamingKeysScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen keys only - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string keys = to_string(plan_naming_keys(m_scenario.input.text, m_scenario.input.kind)); + if (!m_scenario.expectation.expected_actions.empty() && keys != m_scenario.expectation.expected_actions){ + return "Expected keys: " + m_scenario.expectation.expected_actions + "\nActual keys: " + keys; + } + const std::string input = to_string(plan_naming_input(m_scenario.input.text, m_scenario.input.kind)); + if (input != keys + " START A"){ + return "Expected the confirmed plan to be \"" + keys + " START A\", got \"" + input + "\""; + } + return true; + } + +private: + const NamingKeysScenario m_scenario; +}; + +const NamingKeysScenario NAMING_KEYS_CASES[] = { + { + .input = {.name = "one key", .text = "A"}, + .expectation = {.expected_actions = "A"}, + }, + { + .input = {.name = "next key", .text = "AB"}, + .expectation = {.expected_actions = "A RIGHT A"}, + }, + { + .input = {.name = "lower case page", .text = "a"}, + .expectation = {.expected_actions = "SELECT A"}, + }, + { + .input = {.name = "full player name", .text = "ABCDEFG"}, + .expectation = {}, + }, + { + .input = {.name = "mixed case", .text = "Kosmos"}, + .expectation = {}, + }, +}; + +void add_tests_NamingKeys(UnitTestDatabase& database){ + for (const NamingKeysScenario& scenario : NAMING_KEYS_CASES){ + database.add(scenario); + } +} + + +struct NamingTextInput{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingTextExpectation{ + // A part of the expected error; "" if the text is fine. + std::string expected_error = ""; +}; + +struct NamingTextScenario{ + NamingTextInput input; + NamingTextExpectation expectation; +}; + +class Test_NamingText : public UnitTest{ +public: + explicit Test_NamingText(NamingTextScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen text - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = naming_text_error(m_scenario.input.text, m_scenario.input.kind); + if (m_scenario.expectation.expected_error.empty()){ + if (!error.empty()){ + return "Expected \"" + m_scenario.input.text + "\" to be accepted, got: " + error; + } + return true; + } + if (error.find(m_scenario.expectation.expected_error) == std::string::npos){ + return "Expected an error containing \"" + m_scenario.expectation.expected_error + "\", got: \"" + error + "\""; + } + try{ + plan_naming_input(m_scenario.input.text, m_scenario.input.kind); + }catch (InternalProgramError&){ + return true; + } + return "Expected plan_naming_input() to throw for \"" + m_scenario.input.text + "\""; + } + +private: + const NamingTextScenario m_scenario; +}; + +const NamingTextScenario NAMING_TEXT_CASES[] = { + { + .input = {.name = "player name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::PLAYER}, + .expectation = {}, + }, + { + .input = {.name = "player name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "at most 7"}, + }, + { + .input = {.name = "rival name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::RIVAL}, + .expectation = {}, + }, + { + .input = {.name = "rival name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::RIVAL}, + .expectation = {.expected_error = "at most 7"}, + }, + { + .input = {.name = "box name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::BOX}, + .expectation = {}, + }, + { + .input = {.name = "box name of 9", .text = "ABCDEFGHI", .kind = NamingScreenKind::BOX}, + .expectation = {.expected_error = "at most 8"}, + }, + { + .input = {.name = "nickname of 10", .text = "ABCDEFGHIJ", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "nickname of 11", .text = "ABCDEFGHIJK", .kind = NamingScreenKind::POKEMON}, + .expectation = {.expected_error = "at most 10"}, + }, + { + .input = { + .name = "symbols count as one character", + .text = "\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82", + .kind = NamingScreenKind::PLAYER, + }, + .expectation = {}, + }, + { + .input = {.name = "unknown character", .text = "Ash@", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "type: \"@\""}, + }, + { + .input = {.name = "unknown accented character", .text = "Jos\xC3\xA9", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "type: \"\xC3\xA9\""}, + }, + { + .input = {.name = "empty", .text = "", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "empty"}, + }, + { + .input = {.name = "only spaces", .text = " ", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "only spaces"}, + }, +}; + +void add_tests_NamingText(UnitTestDatabase& database){ + for (const NamingTextScenario& scenario : NAMING_TEXT_CASES){ + database.add(scenario); + } +} + +} // namespace + + +void add_tests_NamingScreen(UnitTestDatabase& database){ + add_tests_NamingCursor(database); + add_tests_NamingPlan(database); + add_tests_NamingKeys(database); + add_tests_NamingText(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h new file mode 100644 index 0000000000..7eb7c2b2b8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h @@ -0,0 +1,25 @@ +/* Naming Screen Keyboard Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_Tests_H +#define PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers the naming screen keyboard's tests: cursor moves, plans and +// text checks, against pokefirered's src/naming_screen.c. +void add_tests_NamingScreen(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h new file mode 100644 index 0000000000..fc0c6622bd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h @@ -0,0 +1,80 @@ +/* Naming Screen Keys + * + * From: https://github.com/PokemonAutomation/ + * + * The in-game keyboard's layout, as pret/pokefirered src/naming_screen.c at commit + * ce6406d8c2eaf46d543c8a2606de0c3cb1951982 (English game) has it. The decomp includes the + * Switch revision (REVISION >= 0xA), so the layout is the one on the Switch release. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenKeys_H +#define PokemonAutomation_PokemonFRLG_NamingScreenKeys_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The keyboard pages, in the order SELECT cycles through them. The screen opens on UPPER. +enum class NamingScreenPage : uint8_t{ + UPPER, + LOWER, + SYMBOLS, +}; +// Total page count on naming screen. +constexpr size_t NAMING_SCREEN_PAGES = 3; +// Number of key rows per page. +constexpr size_t NAMING_SCREEN_KEY_ROWS = 4; +// Maximum key columns across pages. +constexpr size_t NAMING_SCREEN_MAX_KEY_COLUMNS = 8; + +// Key columns on each page (sPageColumnCounts). The button column (page / back / OK) comes +// right after the last key column, so on a page with N key columns it is column N. +constexpr uint8_t NAMING_SCREEN_KEY_COLUMNS[NAMING_SCREEN_PAGES] = {8, 8, 6}; + +// The text each key types, in UTF-8 (sKeyboardChars), indexed [page][row][column]. +// Empty: no key (past the page's last column). +// The decomp pads each row with byte 0x00, which is a space in the game's charmap, and the +// keyboard labels draw a blank there: those cells type a space just like the spaces in rows 0-1. +// The apostrophe key types the game's right single quote (charmap 0xB4). +constexpr std::string_view NAMING_SCREEN_KEYS + [NAMING_SCREEN_PAGES][NAMING_SCREEN_KEY_ROWS][NAMING_SCREEN_MAX_KEY_COLUMNS] = { + { // UPPER + {"A", "B", "C", "D", "E", "F", " ", "."}, + {"G", "H", "I", "J", "K", "L", " ", ","}, + {"M", "N", "O", "P", "Q", "R", "S", " "}, + {"T", "U", "V", "W", "X", "Y", "Z", " "}, + }, + { // LOWER + {"a", "b", "c", "d", "e", "f", " ", "."}, + {"g", "h", "i", "j", "k", "l", " ", ","}, + {"m", "n", "o", "p", "q", "r", "s", " "}, + {"t", "u", "v", "w", "x", "y", "z", " "}, + }, + { // SYMBOLS + {"0", "1", "2", "3", "4", " ", "", ""}, + {"5", "6", "7", "8", "9", " ", "", ""}, + {"!", "?", "\xE2\x99\x82", "\xE2\x99\x80", "/", "-", "", ""}, // ! ? male female / - + {"\xE2\x80\xA6", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x98", "'", " ", "", ""}, // ellipsis, double quotes, left single quote, ' + }, +}; + +// The three buttons in the button column, top to bottom. +// Button index for switching character pages. +constexpr uint8_t NAMING_SCREEN_BUTTON_PAGE = 0; +// Button index for backspacing a character. +constexpr uint8_t NAMING_SCREEN_BUTTON_BACK = 1; +// Button index for confirming naming input. +constexpr uint8_t NAMING_SCREEN_BUTTON_OK = 2; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h new file mode 100644 index 0000000000..b329e8214c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h @@ -0,0 +1,51 @@ +/* RNG Method 1 + * + * From: https://github.com/PokemonAutomation/ + * + * The Gen 3 LCRNG and the Method 1 Pokemon it generates: PID, IVs, shininess + * and Hidden Power. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngMethod1_H +#define PokemonAutomation_PokemonFRLG_RngMethod1_H + +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The Gen 3 LCRNG: state * 0x41C64E6D + 0x6073. +uint32_t lcrng_next(uint32_t state); +// Steps the Gen 3 LCRNG backward by one advance. +uint32_t lcrng_previous(uint32_t state); +// How many lcrng_next() calls take "from" to "to". The LCRNG has a single cycle of +// 2^32 states, so every pair has exactly one distance. +uint32_t lcrng_distance(uint32_t from, uint32_t to); + +// The static, gift or starter Pokemon (Method 1) generated from "state", the RNG state +// just before the PID is rolled: the next two calls give the low and high PID halves, +// the two after that the IVs (HP/Atk/Def, then Spe/SpA/SpD). +Pokemon::AdvPokemonResult method1_pokemon(uint32_t state); + +// Determines shiny type (none, star, square) from PID and trainer IDs. +Pokemon::AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid); + +// Calculated Hidden Power typing and base power. +struct HiddenPower{ + std::string type; + uint8_t power; +}; +// Calculates Hidden Power attributes from individual values. +HiddenPower hidden_power(const Pokemon::AdvIVs& ivs); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h index 4408e4f8cf..cfb2fb4edf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h @@ -27,6 +27,7 @@ #include "CommonFramework/Language.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngTimings.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -76,39 +77,6 @@ struct StarterRngPlanInputs{ size_t max_attempts; }; -// Starter RNG's smallest Advances setting. -inline constexpr uint64_t STARTER_RNG_MIN_ADVANCES = 940; - -// Starter RNG's title screen wait, before calibration: the seed list's -// delay plus this (FIXED_SEED_OFFSET in StarterRng's attempts). -inline constexpr int64_t STARTER_RNG_FIXED_SEED_OFFSET_MS = -845; -// The shortest title screen wait the plan uses. Starter RNG refuses waits -// under 29,650 ms, and its docs (pokemonautomation.github.io, -// docs/Programs/PokemonFRLG/StarterRng.md, "Avoid low seed delays when -// possible") warn that waits near 30,500 ms can miss the title screen -// press. 31,500 ms keeps a second clear of that for the seed calibration. -inline constexpr int64_t STARTER_RNG_MIN_SEED_WAIT_MS = 31500; -// Starter RNG's title screen wait for `seed`, as prepare_timings() makes it -// before calibration. -int64_t starter_rng_seed_wait_ms(const InitialSeedEntry& seed); -// Whether the wait is at least STARTER_RNG_MIN_SEED_WAIT_MS. (Console B, -// 2026-11-02, FireRed English: seeds 11A3 and 405C, at 30,473 and -// 30,488 ms in the table, are 29,628 and 29,643 ms waits, which Starter -// RNG refuses.) -bool starter_rng_can_wait_for(const InitialSeedEntry& seed); - -// Starter RNG's Continue Screen frames, taken off the advances before the -// in-game wait (CONTINUE_SCREEN_FRAMES in StarterRng's attempts). -inline constexpr uint64_t STARTER_RNG_CONTINUE_SCREEN_FRAMES = 200; -// Starter RNG's in-game wait for `advances`, before calibration. It -// refuses one under 7,500 ms, which STARTER_RNG_MIN_ADVANCES just makes. -int64_t starter_rng_ingame_ms(uint64_t advances); -// Room for the in-game calibration, in advances (2 per frame of wait): the -// calibration moves the wait, and it went to -720 after one miss on console -// B (2026-11-02, seed B579 at 967 advances: an 8 s wait cut to 1.7 s). The -// plan's targets are at least this many advances past Starter RNG's -// minimum. To tune from the logs' calibrations. -inline constexpr uint64_t STARTER_RNG_INGAME_MARGIN_ADVANCES = 720; // Minimum advance threshold for planning starter attempts. inline constexpr uint64_t STARTER_RNG_PLAN_MIN_ADVANCES = STARTER_RNG_MIN_ADVANCES + STARTER_RNG_INGAME_MARGIN_ADVANCES; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp index fb9a978b41..b20c68e28a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp @@ -28,7 +28,7 @@ struct RngPlanInputsInput{ }; struct RngPlanInputsExpectation{ - const char* description; + std::string_view description; }; struct RngPlanInputsTestCase{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp index a81eec85cf..41228fb92c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp @@ -50,7 +50,7 @@ std::string rng_log_attempt(size_t index, const RngAttempt& attempt){ namespace{ -const char* outcome_name(RngAttemptOutcome outcome){ +std::string_view outcome_name(RngAttemptOutcome outcome){ switch (outcome){ case RngAttemptOutcome::SHINY: return "shiny"; @@ -66,7 +66,7 @@ const char* outcome_name(RngAttemptOutcome outcome){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngAttemptOutcome."); } -const char* next_name(RngPlanNext next){ +std::string_view next_name(RngPlanNext next){ switch (next){ case RngPlanNext::RETRY: return "retry"; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp index 167bf0f628..f3d7894df5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp @@ -31,7 +31,7 @@ struct RngPlanLogInput{ }; struct RngPlanLogExpectation{ - const char* description; + std::string_view description; }; struct RngPlanLogTestCase{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp index 987daa3140..5aa505c7af 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp @@ -32,7 +32,7 @@ struct RngPlanTrackerInput{ }; struct RngPlanTrackerExpectation{ - const char* description; + std::string_view description; }; struct RngPlanTrackerTestCase{ @@ -86,7 +86,7 @@ UnitTestResult test_classify(Logger&){ } -const char* step_name(RngPlanStep step){ +std::string step_name(RngPlanStep step){ switch (step){ case RngPlanStep::RUN_ATTEMPT: return "RUN_ATTEMPT"; case RngPlanStep::GOT_SHINY: return "GOT_SHINY"; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp index a6cea3e727..be4b758989 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp @@ -34,7 +34,7 @@ struct RngPlanInput{ }; struct RngPlanExpectation{ - const char* description; + std::string_view description; }; struct RngPlanTestCase{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp index 8b054d7ab1..ceb2bfa571 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp @@ -187,7 +187,7 @@ const std::vector SHINY_ROWS = { {.input = {.name = "no match", .hits = {}}, .expectation = {.expected = StarterRngOutcome::shiny}}, }; -const char* outcome_name(StarterRngOutcome outcome){ +std::string outcome_name(StarterRngOutcome outcome){ switch (outcome){ case StarterRngOutcome::shiny: return "shiny"; case StarterRngOutcome::shiny_on_target: return "shiny_on_target"; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp index e03b4c2ab4..81556f0146 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp @@ -93,7 +93,7 @@ AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid){ } HiddenPower hidden_power(const AdvIVs& ivs){ - static const char* TYPES[] = { + static constexpr std::string_view TYPES[] = { "Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel", "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark", }; @@ -106,7 +106,7 @@ HiddenPower hidden_power(const AdvIVs& ivs){ type_bits |= (order[c] & 1) << c; power_bits |= ((order[c] >> 1) & 1) << c; } - return {TYPES[type_bits * 15 / 63], uint8_t(power_bits * 40 / 63 + 30)}; + return {std::string(TYPES[type_bits * 15 / 63]), uint8_t(power_bits * 40 / 63 + 30)}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h index 83620b0bcf..521a881cda 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h @@ -30,37 +30,13 @@ #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_RngMethod1.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// The Gen 3 LCRNG: state * 0x41C64E6D + 0x6073. -uint32_t lcrng_next(uint32_t state); -// Steps the Gen 3 LCRNG backward by one advance. -uint32_t lcrng_previous(uint32_t state); -// How many lcrng_next() calls take "from" to "to". The LCRNG has a single cycle of -// 2^32 states, so every pair has exactly one distance. -uint32_t lcrng_distance(uint32_t from, uint32_t to); - -// The static, gift or starter Pokemon (Method 1) generated from "state", the RNG state -// just before the PID is rolled: the next two calls give the low and high PID halves, -// the two after that the IVs (HP/Atk/Def, then Spe/SpA/SpD). -Pokemon::AdvPokemonResult method1_pokemon(uint32_t state); - -// Determines shiny type (none, star, square) from PID and trainer IDs. -Pokemon::AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid); - -// Calculated Hidden Power typing and base power. -struct HiddenPower{ - std::string type; - uint8_t power; -}; -// Calculates Hidden Power attributes from individual values. -HiddenPower hidden_power(const Pokemon::AdvIVs& ivs); - - // One way to reach an initial seed from the title screen. struct InitialSeedEntry{ // The seed reached, after the blackout offset. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp index df407eb24b..05fb861fb0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp @@ -50,7 +50,7 @@ struct TenLinesGroup{ }; // Ten Lines results, one per line, sorted by advances. -const char MODEST_ROWS[] = +const std::string MODEST_ROWS = "9435B76A,68F03EBD,Square,1,31/14/7/29/1/27,Dragon 39,2EF6,29364,52641,A/None\n" "2E37261A,DB7C8D33,Star,1,28/16/6/30/11/29,Water 63,6E9A,50048,54054,A/Blackout R\n" "C408B1DF,192D4F60,Square,0,25/8/10/29/0/28,Rock 32,02A8,53397,55259,Start/Blackout R\n" @@ -72,7 +72,7 @@ const char MODEST_ROWS[] = "BE31CFCC,FA05AC4E,Star,0,30/22/21/30/3/29,Grass 62,D17C,158288,38405,Start/Blackout R\n" "3F487560,7B922DDD,Star,1,30/21/5/31/21/27,Dragon 45,FF1C,171172,58240,A/None\n"; -const char ADAMANT_ROWS[] = +const std::string ADAMANT_ROWS = "537A2752,A823FE6A,Star,0,25/29/15/17/31/27,Dark 57,B897,4437,35972,A/Blackout R\n" "D9FDB041,B9B4EFFE,Star,0,27/31/19/11/5/31,Dark 49,D356,22897,60771,A/None\n" "E9F88FDD,EAD6BC98,Star,0,30/29/1/29/23/31,Dragon 56,CE81,26060,33587,Start/None\n" @@ -90,7 +90,7 @@ const char ADAMANT_ROWS[] = "6109BF46,A9DAFF92,Star,0,26/31/30/6/2/30,Fighting 70,3136,103312,63359,A/None\n" "3F5603C4,8C11DA5D,Star,1,25/29/6/6/24/29,Poison 42,D22E,111518,54657,Start/None\n"; -const char NEUTRAL_ROWS[] = +const std::string NEUTRAL_ROWS = "130195A8,AD7BFB36,Square,0,31/27/31/31/27/26,Ice 70,4381,17225,61908,Start/None\n" "BE0D7E8F,6FA739E8,Star,0,31/21/25/29/26/25,Steel 50,C845,21690,41371,Start/None\n" "1798BCE3,066A5027,Square,1,28/23/25/30/31/28,Water 61,3DDC,26549,44721,A/None\n" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h index 702c94f492..c9a2d47116 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h @@ -26,56 +26,14 @@ #include "PokemonFRLG_RngCalibration.h" #include "PokemonFRLG_RngDisplays.h" #include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngOutcome.h" +#include "PokemonFRLG_StarterRngTarget.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Selectable Kanto starter species. -enum class StarterSpecies{ - bulbasaur, - squirtle, - charmander -}; - -// The species' base stats. -BaseStats starter_base_stats(StarterSpecies starter); -// The EVs the rival's starter gives when the player's "starter" beats it. -EVs rival_ev_yield(StarterSpecies starter); -// After taking "starter" from its ball and dodging the rival, the steps -// left that line the player up with the lab's door. -int steps_left_to_lab_door(StarterSpecies starter); - - -// Statistical counters for Starter RNG attempts. -struct StarterRngStats : public StatsTracker{ - StarterRngStats(); - - std::atomic& resets; - std::atomic& shinies; - std::atomic& nonshiny; - std::atomic& wildshinies; - std::atomic& errors; -}; - - -// Target criteria for starter manipulation. -struct StarterRngTarget{ - StarterSpecies starter = StarterSpecies::bulbasaur; - uint16_t seed = 0; - uint64_t advances = 0; - // The seed's entry in the seeds database (found). - SeedMatch seed_match; -}; - -// Where an attempt is after a reset: the resets so far, and the -// calibration that reset was timed with. -struct StarterRngProgress{ - uint64_t resets = 0; - RngCalibrations calibrations{}; -}; - // What a reset's reads came to, once its search is done. Gift RNG's // attempts report theirs this way too. struct RngResetRead{ @@ -134,22 +92,6 @@ struct StarterRngNotifications{ }; -// Result outcome of an individual starter attempt. -enum class StarterRngOutcome{ - shiny, // The starter was shiny after a reset; not known if on the target. - shiny_on_target, // Shiny, and the target is among the states its stats match. - shiny_off_target, // Shiny, and the states its stats match aren't the target. - target_hit, // The calibration shows the target was hit; not shiny. - wild_shiny, // A wild shiny on Route 1, with ignore_wild_shinies off. - out_of_resets, // More resets than max_resets. - no_matches, // 5 searches in a row matched no state near the target. -}; - -// A shiny's outcome from the states its stats match near the target -// ("hits"): on the target if it is among them, off it if not, and just -// shiny if none match. -StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits); - // Complete result report from starter RNG execution. struct StarterRngResult{ StarterRngOutcome outcome = StarterRngOutcome::out_of_resets; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h index 4223f6f233..3960b6fff0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h @@ -27,69 +27,13 @@ #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "PokemonFRLG_StarterRngLoopLog.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the -// target is SHINY; one off it, or not known to be on it, is -// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, -// which the plan runs again. -RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); -// As the result line names it: "shiny_on_target", "target_hit", -// "out_of_resets"... (The loop says "attempt_deadline" instead of -// "out_of_resets" once the try's deadline has passed.) -std::string starter_rng_outcome_name(StarterRngOutcome outcome); - - -// Where the loop is, for an "RngPlan: state" line. -struct RngLoopState{ - // From 1, of `attempts`. - size_t attempt = 1; - size_t attempts = 0; - // From 1, of `tries`. - size_t try_number = 1; - size_t tries = 0; - uint64_t resets = 0; - uint64_t max_resets = 0; - uint16_t seed = 0; - uint64_t advances = 0; - // The SIDs the attempt is shiny for, and those ruled out so far. - std::vector sids; - std::vector ruled_out; - Milliseconds attempt_time = Milliseconds(0); - Milliseconds attempt_cap = Milliseconds(0); - Milliseconds total_time = Milliseconds(0); - Milliseconds total_cap = Milliseconds(0); - // The calibration of the last reset, in frames; none before the first. - std::optional calibration; -}; -// Formats loop state summary line for logging. -std::string rng_log_state(const RngLoopState& state); - - -// A reset's reads, for its one line on the stream's log. -struct RngResetLine{ - // "Starter RNG" or "Gift RNG". - std::string_view program; - uint64_t max_resets = 0; - uint16_t target_seed = 0; - uint64_t target_advances = 0; - // The seeds near the target, in the order of their delays, and the - // target's place among them (SeedMatch). - std::vector seed_values; - int16_t seed_position = -1; - RngResetRead read; -}; -// The frames from the target seed to `seed` among `seed_values`: +1 for -// the seed a frame later. None when either isn't among them. -std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed); -// As "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed." -std::string rng_reset_line(const RngResetLine& line); - - // Timeout and iteration constraints on starter RNG loop. struct StarterRngLoopLimits{ // An attempt makes no more resets after this long, and counts as missed. @@ -108,6 +52,7 @@ struct StarterRngLoopLimits{ class StarterRngTimingsRefused : public Exception{ public: explicit StarterRngTimingsRefused(std::string message) : m_message(std::move(message)) {} + // code-health: allow char_pointer -- Exception::name() is the fixed base-class interface it overrides virtual const char* name() const override{ return "StarterRngTimingsRefused"; } virtual std::string message() const override{ return m_message; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h new file mode 100644 index 0000000000..31ab38ef8f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h @@ -0,0 +1,86 @@ +/* Starter RNG Loop Log + * + * From: https://github.com/PokemonAutomation/ + * + * How the Starter RNG loop reports: an attempt's outcome as the plan counts + * it, the loop's state line and each reset's line. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoopLog_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoopLog_H + +#include +#include +#include +#include +#include "PokemonFRLG_RngPlan.h" +#include "PokemonFRLG_StarterRngOutcome.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the +// target is SHINY; one off it, or not known to be on it, is +// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, +// which the plan runs again. +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); +// As the result line names it: "shiny_on_target", "target_hit", +// "out_of_resets"... (The loop says "attempt_deadline" instead of +// "out_of_resets" once the try's deadline has passed.) +std::string starter_rng_outcome_name(StarterRngOutcome outcome); + + +// Where the loop is, for an "RngPlan: state" line. +struct RngLoopState{ + // From 1, of `attempts`. + size_t attempt = 1; + size_t attempts = 0; + // From 1, of `tries`. + size_t try_number = 1; + size_t tries = 0; + uint64_t resets = 0; + uint64_t max_resets = 0; + uint16_t seed = 0; + uint64_t advances = 0; + // The SIDs the attempt is shiny for, and those ruled out so far. + std::vector sids; + std::vector ruled_out; + Milliseconds attempt_time = Milliseconds(0); + Milliseconds attempt_cap = Milliseconds(0); + Milliseconds total_time = Milliseconds(0); + Milliseconds total_cap = Milliseconds(0); + // The calibration of the last reset, in frames; none before the first. + std::optional calibration; +}; +// Formats loop state summary line for logging. +std::string rng_log_state(const RngLoopState& state); + + +// A reset's reads, for its one line on the stream's log. +struct RngResetLine{ + // "Starter RNG" or "Gift RNG". + std::string_view program; + uint64_t max_resets = 0; + uint16_t target_seed = 0; + uint64_t target_advances = 0; + // The seeds near the target, in the order of their delays, and the + // target's place among them (SeedMatch). + std::vector seed_values; + int16_t seed_position = -1; + RngResetRead read; +}; +// The frames from the target seed to `seed` among `seed_values`: +1 for +// the seed a frame later. None when either isn't among them. +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed); +// As "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed." +std::string rng_reset_line(const RngResetLine& line); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp index 694bb86460..03765216f1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp @@ -31,7 +31,7 @@ struct StarterRngLoopInput{ }; struct StarterRngLoopExpectation{ - const char* description; + std::string_view description; }; struct StarterRngLoopTestCase{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h new file mode 100644 index 0000000000..44a93b0977 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h @@ -0,0 +1,43 @@ +/* Starter RNG Outcome + * + * From: https://github.com/PokemonAutomation/ + * + * What one Starter RNG attempt ended with, and how a shiny is identified + * from the seed and advances it hit. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngOutcome_H +#define PokemonAutomation_PokemonFRLG_StarterRngOutcome_H + +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Result outcome of an individual starter attempt. +enum class StarterRngOutcome{ + shiny, // The starter was shiny after a reset; not known if on the target. + shiny_on_target, // Shiny, and the target is among the states its stats match. + shiny_off_target, // Shiny, and the states its stats match aren't the target. + target_hit, // The calibration shows the target was hit; not shiny. + wild_shiny, // A wild shiny on Route 1, with ignore_wild_shinies off. + out_of_resets, // More resets than max_resets. + no_matches, // 5 searches in a row matched no state near the target. +}; + +// A shiny's outcome from the states its stats match near the target +// ("hits"): on the target if it is among them, off it if not, and just +// shiny if none match. +StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h new file mode 100644 index 0000000000..035afc19e6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h @@ -0,0 +1,72 @@ +/* Starter RNG Target + * + * From: https://github.com/PokemonAutomation/ + * + * The starter Starter RNG aims for: its species and their stats, the target + * advances and the program's stats. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngTarget_H +#define PokemonAutomation_PokemonFRLG_StarterRngTarget_H + +#include +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "Pokemon/Pokemon_AdvRng.h" +#include "Pokemon/Pokemon_StatsCalculation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Selectable Kanto starter species. +enum class StarterSpecies{ + bulbasaur, + squirtle, + charmander +}; + +// The species' base stats. +BaseStats starter_base_stats(StarterSpecies starter); +// The EVs the rival's starter gives when the player's "starter" beats it. +EVs rival_ev_yield(StarterSpecies starter); +// After taking "starter" from its ball and dodging the rival, the steps +// left that line the player up with the lab's door. +int steps_left_to_lab_door(StarterSpecies starter); + + +// Statistical counters for Starter RNG attempts. +struct StarterRngStats : public StatsTracker{ + StarterRngStats(); + + std::atomic& resets; + std::atomic& shinies; + std::atomic& nonshiny; + std::atomic& wildshinies; + std::atomic& errors; +}; + + +// Target criteria for starter manipulation. +struct StarterRngTarget{ + StarterSpecies starter = StarterSpecies::bulbasaur; + uint16_t seed = 0; + uint64_t advances = 0; + // The seed's entry in the seeds database (found). + SeedMatch seed_match; +}; + +// Where an attempt is after a reset: the resets so far, and the +// calibration that reset was timed with. +struct StarterRngProgress{ + uint64_t resets = 0; + RngCalibrations calibrations{}; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h new file mode 100644 index 0000000000..9d6f5c4716 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h @@ -0,0 +1,61 @@ +/* Starter RNG Timings + * + * From: https://github.com/PokemonAutomation/ + * + * Starter RNG's waits as the RNG plan computes them: its smallest Advances + * setting, its title screen and in-game waits before calibration, and the + * margins the plan keeps from Starter RNG's limits. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngTimings_H +#define PokemonAutomation_PokemonFRLG_StarterRngTimings_H + +#include +#include "PokemonFRLG_RngTargetSearch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Starter RNG's smallest Advances setting. +inline constexpr uint64_t STARTER_RNG_MIN_ADVANCES = 940; + +// Starter RNG's title screen wait, before calibration: the seed list's +// delay plus this (FIXED_SEED_OFFSET in StarterRng's attempts). +inline constexpr int64_t STARTER_RNG_FIXED_SEED_OFFSET_MS = -845; +// The shortest title screen wait the plan uses. Starter RNG refuses waits +// under 29,650 ms, and its docs (pokemonautomation.github.io, +// docs/Programs/PokemonFRLG/StarterRng.md, "Avoid low seed delays when +// possible") warn that waits near 30,500 ms can miss the title screen +// press. 31,500 ms keeps a second clear of that for the seed calibration. +inline constexpr int64_t STARTER_RNG_MIN_SEED_WAIT_MS = 31500; +// Starter RNG's title screen wait for `seed`, as prepare_timings() makes it +// before calibration. +int64_t starter_rng_seed_wait_ms(const InitialSeedEntry& seed); +// Whether the wait is at least STARTER_RNG_MIN_SEED_WAIT_MS. (Console B, +// 2026-11-02, FireRed English: seeds 11A3 and 405C, at 30,473 and +// 30,488 ms in the table, are 29,628 and 29,643 ms waits, which Starter +// RNG refuses.) +bool starter_rng_can_wait_for(const InitialSeedEntry& seed); + +// Starter RNG's Continue Screen frames, taken off the advances before the +// in-game wait (CONTINUE_SCREEN_FRAMES in StarterRng's attempts). +inline constexpr uint64_t STARTER_RNG_CONTINUE_SCREEN_FRAMES = 200; +// Starter RNG's in-game wait for `advances`, before calibration. It +// refuses one under 7,500 ms, which STARTER_RNG_MIN_ADVANCES just makes. +int64_t starter_rng_ingame_ms(uint64_t advances); +// Room for the in-game calibration, in advances (2 per frame of wait): the +// calibration moves the wait, and it went to -720 after one miss on console +// B (2026-11-02, seed B579 at 967 advances: an 8 s wait cut to 1.7 s). The +// plan's targets are at least this many advances past Starter RNG's +// minimum. To tune from the logs' calibrations. +inline constexpr uint64_t STARTER_RNG_INGAME_MARGIN_ADVANCES = 720; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5a89c5f767..809f60f31e 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2013,7 +2013,11 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.cpp @@ -2040,6 +2044,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngLoopRoutines.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngLoopRoutines.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp @@ -2084,8 +2089,12 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp From 34a59ded4c9879061d3fb7634dd2b0282d35bd65 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 17:28:52 -0800 Subject: [PATCH 07/13] FRLG party check: image-backed tests; keep the original slots formatting Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/PokemonFRLG_Navigation.cpp | 8 +- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 74 +++++++++++++++++-- 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp index 8de1341438..49d239d45f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp @@ -843,7 +843,13 @@ PartySlot detect_last_occupied_party_slot(ConsoleHandle& console){ } PartySlot detect_last_occupied_party_slot(const ImageViewRGB32& screen){ - constexpr std::array slots{PartySlot::SIX, PartySlot::FIVE, PartySlot::FOUR, PartySlot::THREE, PartySlot::TWO}; + constexpr std::array slots{ + PartySlot::SIX, + PartySlot::FIVE, + PartySlot::FOUR, + PartySlot::THREE, + PartySlot::TWO, + }; for (PartySlot slot : slots){ PartyEmptySlotDetector empty_slot_detector(COLOR_RED, slot); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index f8bcb64246..9cd1d0d2fd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -406,18 +406,10 @@ void add_tests_PartyCheck(UnitTestDatabase& database){ .input = {.name = "one free slot needed, five Pokemon", .last_occupied = PartySlot::FIVE}, .expectation = {.steps = "open read"}, }, - { - .input = {.name = "one free slot needed, full party", .last_occupied = PartySlot::SIX}, - .expectation = {.steps = "open read", .error = "Your party is full. Leave a party slot free"}, - }, { .input = {.name = "three free slots needed, three Pokemon", .free_slots_needed = 3, .last_occupied = PartySlot::THREE}, .expectation = {.steps = "open read"}, }, - { - .input = {.name = "three free slots needed, four Pokemon", .free_slots_needed = 3, .last_occupied = PartySlot::FOUR}, - .expectation = {.steps = "open read", .error = "Your party has 4 "}, - }, { // A menu that can't be opened skips the check rather than stopping the program. .input = {.name = "party menu not opened", .menu_opens = false, .last_occupied = PartySlot::SIX}, @@ -429,6 +421,71 @@ void add_tests_PartyCheck(UnitTestDatabase& database){ } } +// Party menu steps for a menu that is already open on the given screenshot. +class ImagePartyCheck : public PartyCheckActions{ +public: + explicit ImagePartyCheck(const ImageViewRGB32& screen) + : m_screen(screen) + {} + + virtual bool open_party_menu() override{ + return true; + } + virtual PartySlot read_last_occupied_slot() override{ + return detect_last_occupied_party_slot(m_screen); + } + +private: + const ImageViewRGB32& m_screen; +}; + +// Runs check_party_free_slots() on a party menu screenshot. +class Test_PartyCheckOnImage : public ImageUnitTest{ +public: + // expected_error: start of the UserSetupError message; empty if the check passes. + Test_PartyCheckOnImage(std::string_view image, size_t free_slots_needed, std::string_view expected_error) + : ImageUnitTest( + std::format("PokemonFRLG::RngPartyCheck - {} free slots needed, {}", free_slots_needed, image), + {std::string(image)} + ) + , m_free_slots_needed(free_slots_needed) + , m_expected_error(expected_error) + {} + + virtual UnitTestResult run_on_images( + Logger&, CancellableScope&, + const std::vector& images + ) const override{ + ImagePartyCheck actions(images[0]); + NullLogger logger; + std::string error; + try{ + check_party_free_slots(logger, m_free_slots_needed, actions); + }catch (UserSetupError& e){ + error = e.message(); + } + const bool error_matches = m_expected_error.empty() + ? error.empty() + : error.rfind(m_expected_error, 0) == 0; + if (!error_matches){ + return std::format("Expected error: \"{}\"\nActual error: \"{}\"", m_expected_error, error); + } + return true; + } + +private: + const size_t m_free_slots_needed; + const std::string m_expected_error; +}; + +void add_tests_PartyCheckOnImage(UnitTestDatabase& database){ + database.add( + "PokemonFRLG/Party/Party_6_With_Held_Items.png", 1, "Your party is full. Leave a party slot free" + ); + database.add("PokemonFRLG/Party/JPN_Party.png", 3, "Your party has 4 "); + database.add("PokemonFRLG/Party/JPN_Party.png", 1, ""); +} + std::string menu_context_name(StartMenuContext context){ switch (context){ @@ -569,6 +626,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_HallOfFameSavingDetector(database); add_tests_LastOccupiedPartySlot(database); add_tests_PartyCheck(database); + add_tests_PartyCheckOnImage(database); add_tests_PartyEmptySlotDetector(database); add_tests_PartyHeldItemDetector(database); add_tests_PartyLevelUpReader(database); From 827430978c252126138982dbbf8d307fa0afa631 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 17:39:57 -0800 Subject: [PATCH 08/13] FRLG party check: one image-backed test for the slot reader and the check Each case runs check_party_free_slots() with the real slot detector on a party menu screenshot, replacing the scripted PartyCheck cases and the separate LastOccupiedPartySlot test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 216 +++++------------- 1 file changed, 54 insertions(+), 162 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 9cd1d0d2fd..c2229c22ee 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -279,110 +279,76 @@ void add_tests_ExitWildBattle(UnitTestDatabase& database){ } -std::string slot_name(PartySlot slot){ - return std::to_string(static_cast(slot) + 1); -} - -// Reads the last occupied slot from a party menu screenshot, as the RNG programs' party check does. -class Test_LastOccupiedPartySlot : public ImageUnitTest{ +// Party menu steps on a screenshot of the open menu: the real slot detector reads it, +// and the steps check_party_free_slots() asked for are recorded. +class ImagePartyCheck : public PartyCheckActions{ public: - Test_LastOccupiedPartySlot(std::string_view image, PartySlot expected) - : ImageUnitTest("PokemonFRLG::LastOccupiedPartySlot - " + std::string(image), {std::string(image)}) - , m_expected(expected) + ImagePartyCheck(const ImageViewRGB32& screen, bool menu_opens) + : m_screen(screen) + , m_menu_opens(menu_opens) {} - virtual UnitTestResult run_on_images( - Logger&, CancellableScope&, - const std::vector& images - ) const override{ - const PartySlot slot = detect_last_occupied_party_slot(images[0]); - if (slot != m_expected){ - return std::format("Expected last occupied slot {}, got {}", slot_name(m_expected), slot_name(slot)); - } - return true; - } - -private: - const PartySlot m_expected; -}; - -void add_tests_LastOccupiedPartySlot(UnitTestDatabase& database){ - for (unsigned occupied = 1; occupied <= 6; occupied++){ - database.add( - "PokemonFRLG/Party/Party_" + std::to_string(occupied) + ".png", - static_cast(occupied - 1) - ); - } - database.add("PokemonFRLG/Party/Party_6_With_Held_Items.png", PartySlot::SIX); - database.add("PokemonFRLG/Party/JPN_HeldItem.png", PartySlot::SIX); - database.add("PokemonFRLG/Party/JPN_Party.png", PartySlot::FOUR); - database.add("PokemonFRLG/Party/SPA_HeldItem.png", PartySlot::SIX); -} - -// Steps that return scripted reads, and record what check_party_free_slots() asked for. -class ScriptedPartyCheck : public PartyCheckActions{ -public: - bool menu_opens = true; - PartySlot last_occupied = PartySlot::ONE; - std::string steps; - virtual bool open_party_menu() override{ steps += steps.empty() ? "open" : " open"; - return menu_opens; + return m_menu_opens; } virtual PartySlot read_last_occupied_slot() override{ steps += steps.empty() ? "read" : " read"; - return last_occupied; + return detect_last_occupied_party_slot(m_screen); } + + std::string steps; + +private: + const ImageViewRGB32& m_screen; + const bool m_menu_opens; }; -struct PartyCheckInput{ - std::string name; +struct PartyCheckCase{ + std::string image; size_t free_slots_needed = 1; bool menu_opens = true; - PartySlot last_occupied = PartySlot::ONE; -}; - -struct PartyCheckExpectation{ - std::string steps = ""; + std::string steps = "open read"; // Start of the UserSetupError message; empty if the check passes. std::string error = ""; }; -struct PartyCheckCase{ - PartyCheckInput input; - PartyCheckExpectation expectation; -}; - -class Test_PartyCheck : public UnitTest{ +// Runs check_party_free_slots() on a party menu screenshot. +class Test_PartyCheck : public ImageUnitTest{ public: Test_PartyCheck(PartyCheckCase test_case) - : UnitTest("PokemonFRLG::RngPartyCheck - " + test_case.input.name) + : ImageUnitTest( + std::format( + "PokemonFRLG::RngPartyCheck - {} free slots needed{}, {}", + test_case.free_slots_needed, + test_case.menu_opens ? "" : ", menu not opened", + test_case.image + ), + {test_case.image} + ) , m_case(std::move(test_case)) {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const PartyCheckInput& input = m_case.input; - const PartyCheckExpectation& expected = m_case.expectation; - ScriptedPartyCheck actions; - actions.menu_opens = input.menu_opens; - actions.last_occupied = input.last_occupied; - + virtual UnitTestResult run_on_images( + Logger&, CancellableScope&, + const std::vector& images + ) const override{ + ImagePartyCheck actions(images[0], m_case.menu_opens); NullLogger logger; std::string error; try{ - check_party_free_slots(logger, input.free_slots_needed, actions); + check_party_free_slots(logger, m_case.free_slots_needed, actions); }catch (UserSetupError& e){ error = e.message(); } - const bool error_matches = expected.error.empty() + const bool error_matches = m_case.error.empty() ? error.empty() - : error.rfind(expected.error, 0) == 0; + : error.rfind(m_case.error, 0) == 0; if (!error_matches){ - return std::format("Expected error: \"{}\"\nActual error: \"{}\"", expected.error, error); + return std::format("Expected error: \"{}\"\nActual error: \"{}\"", m_case.error, error); } - if (actions.steps != expected.steps){ - return std::format("Expected steps: {}\nActual steps: {}", expected.steps, actions.steps); + if (actions.steps != m_case.steps){ + return std::format("Expected steps: {}\nActual steps: {}", m_case.steps, actions.steps); } return true; } @@ -392,100 +358,28 @@ class Test_PartyCheck : public UnitTest{ }; void add_tests_PartyCheck(UnitTestDatabase& database){ + const std::string FULL = "Your party is full. Leave a party slot free"; + for (unsigned occupied = 1; occupied <= 5; occupied++){ + database.add(PartyCheckCase{.image = "PokemonFRLG/Party/Party_" + std::to_string(occupied) + ".png"}); + } const PartyCheckCase cases[] = { - { - // Programs that don't add a Pokemon to the party don't open the menu. - .input = {.name = "no free slot needed, full party", .free_slots_needed = 0, .last_occupied = PartySlot::SIX}, - .expectation = {}, - }, - { - .input = {.name = "one free slot needed, one Pokemon"}, - .expectation = {.steps = "open read"}, - }, - { - .input = {.name = "one free slot needed, five Pokemon", .last_occupied = PartySlot::FIVE}, - .expectation = {.steps = "open read"}, - }, - { - .input = {.name = "three free slots needed, three Pokemon", .free_slots_needed = 3, .last_occupied = PartySlot::THREE}, - .expectation = {.steps = "open read"}, - }, - { - // A menu that can't be opened skips the check rather than stopping the program. - .input = {.name = "party menu not opened", .menu_opens = false, .last_occupied = PartySlot::SIX}, - .expectation = {.steps = "open"}, - }, + {.image = "PokemonFRLG/Party/Party_6.png", .error = FULL}, + {.image = "PokemonFRLG/Party/Party_6_With_Held_Items.png", .error = FULL}, + {.image = "PokemonFRLG/Party/JPN_HeldItem.png", .error = FULL}, + {.image = "PokemonFRLG/Party/SPA_HeldItem.png", .error = FULL}, + {.image = "PokemonFRLG/Party/JPN_Party.png"}, + {.image = "PokemonFRLG/Party/Party_3.png", .free_slots_needed = 3}, + {.image = "PokemonFRLG/Party/JPN_Party.png", .free_slots_needed = 3, .error = "Your party has 4 "}, + // Programs that don't add a Pokemon to the party don't open the menu. + {.image = "PokemonFRLG/Party/Party_6.png", .free_slots_needed = 0, .steps = ""}, + // A menu that can't be opened skips the check rather than stopping the program. + {.image = "PokemonFRLG/Party/Party_6.png", .menu_opens = false, .steps = "open"}, }; for (const PartyCheckCase& test_case : cases){ database.add(test_case); } } -// Party menu steps for a menu that is already open on the given screenshot. -class ImagePartyCheck : public PartyCheckActions{ -public: - explicit ImagePartyCheck(const ImageViewRGB32& screen) - : m_screen(screen) - {} - - virtual bool open_party_menu() override{ - return true; - } - virtual PartySlot read_last_occupied_slot() override{ - return detect_last_occupied_party_slot(m_screen); - } - -private: - const ImageViewRGB32& m_screen; -}; - -// Runs check_party_free_slots() on a party menu screenshot. -class Test_PartyCheckOnImage : public ImageUnitTest{ -public: - // expected_error: start of the UserSetupError message; empty if the check passes. - Test_PartyCheckOnImage(std::string_view image, size_t free_slots_needed, std::string_view expected_error) - : ImageUnitTest( - std::format("PokemonFRLG::RngPartyCheck - {} free slots needed, {}", free_slots_needed, image), - {std::string(image)} - ) - , m_free_slots_needed(free_slots_needed) - , m_expected_error(expected_error) - {} - - virtual UnitTestResult run_on_images( - Logger&, CancellableScope&, - const std::vector& images - ) const override{ - ImagePartyCheck actions(images[0]); - NullLogger logger; - std::string error; - try{ - check_party_free_slots(logger, m_free_slots_needed, actions); - }catch (UserSetupError& e){ - error = e.message(); - } - const bool error_matches = m_expected_error.empty() - ? error.empty() - : error.rfind(m_expected_error, 0) == 0; - if (!error_matches){ - return std::format("Expected error: \"{}\"\nActual error: \"{}\"", m_expected_error, error); - } - return true; - } - -private: - const size_t m_free_slots_needed; - const std::string m_expected_error; -}; - -void add_tests_PartyCheckOnImage(UnitTestDatabase& database){ - database.add( - "PokemonFRLG/Party/Party_6_With_Held_Items.png", 1, "Your party is full. Leave a party slot free" - ); - database.add("PokemonFRLG/Party/JPN_Party.png", 3, "Your party has 4 "); - database.add("PokemonFRLG/Party/JPN_Party.png", 1, ""); -} - std::string menu_context_name(StartMenuContext context){ switch (context){ @@ -624,9 +518,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_EliteFourRoomDetector(database); add_tests_ExitWildBattle(database); add_tests_HallOfFameSavingDetector(database); - add_tests_LastOccupiedPartySlot(database); add_tests_PartyCheck(database); - add_tests_PartyCheckOnImage(database); add_tests_PartyEmptySlotDetector(database); add_tests_PartyHeldItemDetector(database); add_tests_PartyLevelUpReader(database); From 055c5a40f70f001b7c51cb09284c4889ffbe5a4a Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 18:29:41 -0800 Subject: [PATCH 09/13] FRLG RNG: run the party check from RngProgramInstance, not a SingleSwitchProgram hook Drop the start_program_game_checks() hook from SingleSwitchProgramInstance. Each RNG program calls check_free_party_slots() first in program(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../NintendoSwitch_SingleSwitchProgram.cpp | 1 - .../NintendoSwitch_SingleSwitchProgram.h | 9 -------- .../RngManipulation/PokemonFRLG_EggRng.cpp | 1 + .../RngManipulation/PokemonFRLG_GiftRng.cpp | 1 + .../RngManipulation/PokemonFRLG_RngHelper.cpp | 1 + .../PokemonFRLG_RngProgram.cpp | 2 +- .../RngManipulation/PokemonFRLG_RngProgram.h | 21 ++++++++++--------- .../PokemonFRLG_RoamingLegendaryRng.cpp | 1 + .../PokemonFRLG_StarterRng.cpp | 1 + .../RngManipulation/PokemonFRLG_StaticRng.cpp | 1 + .../RngManipulation/PokemonFRLG_WildRng.cpp | 1 + 11 files changed, 19 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp index cbb210b0b7..8f4e94ab65 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp @@ -86,7 +86,6 @@ void SingleSwitchProgramInstance::program(SingleSwitchProgramEnvironment& env, C }; try{ - start_program_game_checks(env, context); program(env, context); }catch (FatalProgramException&){ record_debug_video(); diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h index b44bb655a1..9c464ca3a7 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h @@ -86,15 +86,6 @@ class SingleSwitchProgramInstance : public GameConsole::ConsoleProgramInstance{ FeedbackType feedback_type ); - // Called with the controller ready, just before program(env, context). - // Override to check that the game is set up the way the program needs - // (e.g. a free party slot) and throw UserSetupError if not, so a setup - // mistake stops the program before it starts its work. - virtual void start_program_game_checks( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context - ){} - private: virtual void program(GameConsole::ConsoleProgramEnvironment& env, CancellableScope& scope) override; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp index a05d693683..c5ade3c53e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -722,6 +722,7 @@ void EggRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); EggRng_Descriptor::Stats& stats = env.current_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp index 3341d8cef2..c1dd785904 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp @@ -231,6 +231,7 @@ void GiftRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); GiftRng_Descriptor::Stats& stats = env.current_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp index 16065cbda0..240d872593 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp @@ -242,6 +242,7 @@ void RngHelper::program(SingleSwitchProgramEnvironment& env, ProControllerContex /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); RngHelper_Descriptor::Stats& stats = env.current_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp index 7e80dc64f0..034d713973 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp @@ -35,7 +35,7 @@ std::string not_enough_free_slots_message(size_t party_size, size_t free_slots_n } // namespace -void RngProgramInstance::start_program_game_checks( +void RngProgramInstance::check_free_party_slots( SingleSwitchProgramEnvironment& env, ProControllerContext& context ){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h index 69a0dd8e03..78dc1ebbf1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h @@ -3,9 +3,9 @@ * From: https://github.com/PokemonAutomation/ * * Base class for the FRLG RNG programs. Each program states what the game - * must look like when it starts, and the base class checks it before the - * program runs, so a setup mistake stops the run at once instead of failing - * in a misleading way many resets later. + * must look like when it starts, and checks it first thing, so a setup + * mistake stops the run at once instead of failing in a misleading way many + * resets later. * */ @@ -21,8 +21,7 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// Base class of the RNG programs. Before program() runs, it checks that the -// party has the free slots the program needs. +// Base class of the RNG programs. class RngProgramInstance : public SingleSwitchProgramInstance{ public: using SingleSwitchProgramInstance::SingleSwitchProgramInstance; @@ -37,13 +36,15 @@ class RngProgramInstance : public SingleSwitchProgramInstance{ return StartMenuContext::STANDARD; } - // Runs with the game on the overworld where the player saved. May leave a - // menu open: the program's first reset closes the game. Final so that - // every RNG program runs the check free_party_slots_needed() asks for. - virtual void start_program_game_checks( +protected: + // Checks that the party has the free slots free_party_slots_needed() + // asks for; throws UserSetupError if not. Call it first in program(), + // with the game on the overworld where the player saved. May leave the + // party menu open: the program's first reset closes the game. + void check_free_party_slots( SingleSwitchProgramEnvironment& env, ProControllerContext& context - ) override final; + ); }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp index fe284e8a2c..abdc185711 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp @@ -226,6 +226,7 @@ void RoamingLegendaryRng::program(SingleSwitchProgramEnvironment& env, ProContro /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); RoamingLegendaryRng_Descriptor::Stats& stats = env.current_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp index 5b22bee42f..3de06022f8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp @@ -558,6 +558,7 @@ void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerConte /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); StarterRng_Descriptor::Stats& stats = env.current_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp index 30bdaaea7a..e865610de4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp @@ -232,6 +232,7 @@ void StaticRng::program(SingleSwitchProgramEnvironment& env, ProControllerContex /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); StaticRng_Descriptor::Stats& stats = env.current_stats(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp index 9aeb97fb45..370e1cb260 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp @@ -277,6 +277,7 @@ void WildRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ + check_free_party_slots(env, context); WildRng_Descriptor::Stats& stats = env.current_stats(); From f33000c9fe3cb3ec535062042747e1a8439c7944 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 18:32:56 -0800 Subject: [PATCH 10/13] FRLG RNG: run_precheck() runs the party check and the black border check Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../RngManipulation/PokemonFRLG_EggRng.cpp | 4 +--- .../RngManipulation/PokemonFRLG_GiftRng.cpp | 4 +--- .../RngManipulation/PokemonFRLG_RngHelper.cpp | 4 +--- .../RngManipulation/PokemonFRLG_RngProgram.cpp | 8 ++++++++ .../RngManipulation/PokemonFRLG_RngProgram.h | 14 ++++++++++---- .../PokemonFRLG_RoamingLegendaryRng.cpp | 4 +--- .../RngManipulation/PokemonFRLG_StarterRng.cpp | 4 +--- .../RngManipulation/PokemonFRLG_StaticRng.cpp | 4 +--- .../RngManipulation/PokemonFRLG_WildRng.cpp | 4 +--- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp index c5ade3c53e..3144110055 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -722,12 +722,10 @@ void EggRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); EggRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - // prepare database of base stats and gender thresholds RngStatsDatabase STATS_DATA("PokemonFRLG/BaseStats.json"); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp index c1dd785904..c81241ddbe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp @@ -231,12 +231,10 @@ void GiftRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); GiftRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp index 240d872593..961217cacd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp @@ -242,12 +242,10 @@ void RngHelper::program(SingleSwitchProgramEnvironment& env, ProControllerContex /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); RngHelper_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - bool shiny_found = false; static const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp index 034d713973..12a9a4f151 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp @@ -60,6 +60,14 @@ void RngProgramInstance::check_free_party_slots( logger.log("Party has enough free slots."); } +void RngProgramInstance::run_precheck( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context +){ + check_free_party_slots(env, context); + home_black_border_check(env.console, context); +} + } // namespace PokemonFRLG } // namespace NintendoSwitch } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h index 78dc1ebbf1..b35ef4c14f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h @@ -37,10 +37,16 @@ class RngProgramInstance : public SingleSwitchProgramInstance{ } protected: - // Checks that the party has the free slots free_party_slots_needed() - // asks for; throws UserSetupError if not. Call it first in program(), - // with the game on the overworld where the player saved. May leave the - // party menu open: the program's first reset closes the game. + // Call first in program(), with the game on the overworld where the + // player saved: checks the party has the free slots + // free_party_slots_needed() asks for, then goes Home for the black + // border check. Throws UserSetupError if a check fails. + void run_precheck( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context + ); + +private: void check_free_party_slots( SingleSwitchProgramEnvironment& env, ProControllerContext& context diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp index abdc185711..ca6ea548e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp @@ -226,12 +226,10 @@ void RoamingLegendaryRng::program(SingleSwitchProgramEnvironment& env, ProContro /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); RoamingLegendaryRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp index 3de06022f8..7e8413e136 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp @@ -558,12 +558,10 @@ void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerConte /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); StarterRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp index e865610de4..d4cde6017c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp @@ -232,12 +232,10 @@ void StaticRng::program(SingleSwitchProgramEnvironment& env, ProControllerContex /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); StaticRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp index 370e1cb260..96a98f5084 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp @@ -277,12 +277,10 @@ void WildRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ - check_free_party_slots(env, context); + run_precheck(env, context); WildRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); From 986e7fd0bf882374071c4f2d5e78d4111167f5e3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 20:25:25 -0800 Subject: [PATCH 11/13] FRLG RNG: run the black border check before the free party slots check --- .../Programs/RngManipulation/PokemonFRLG_RngProgram.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp index 12a9a4f151..3bc49ecb46 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp @@ -64,8 +64,8 @@ void RngProgramInstance::run_precheck( SingleSwitchProgramEnvironment& env, ProControllerContext& context ){ - check_free_party_slots(env, context); home_black_border_check(env.console, context); + check_free_party_slots(env, context); } } // namespace PokemonFRLG From 5d1fc804c9e5e6fd724204af20e40a671dfe9fd8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 21:10:57 -0800 Subject: [PATCH 12/13] FRLG EggRng: free party slots check depends on STARTING_POINT --- .../Programs/RngManipulation/PokemonFRLG_EggRng.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h index 6adb83effc..921d9b862a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h @@ -60,8 +60,12 @@ class EggRng_Descriptor : public SingleSwitchProgramDescriptor{ class EggRng : public RngProgramInstance, public ConfigOption::Listener{ public: using Descriptor = EggRng_Descriptor; - // The egg and the two wild Pokemon caught to confirm the seed. - virtual size_t free_party_slots_needed() const override{ return 3; } + virtual size_t free_party_slots_needed() const override{ + if (STARTING_POINT == EggProgramState::pickup_calibration){ + return 2; + } + return 3; + } ~EggRng(); EggRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; From c09beca6d7747bbfe12efbd8da85abe24cac1ba6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Wed, 11 Nov 2026 21:32:05 -0800 Subject: [PATCH 13/13] FRLG RNG: remove start_menu_context; all save locations use standard menu --- .../Programs/RngManipulation/PokemonFRLG_RngProgram.cpp | 3 ++- .../Programs/RngManipulation/PokemonFRLG_RngProgram.h | 6 ------ .../Programs/RngManipulation/PokemonFRLG_WildRng.h | 3 --- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp index 3bc49ecb46..a1014876d1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp @@ -10,6 +10,7 @@ #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon/Pokemon_Strings.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartySlot.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_RngProgram.h" namespace PokemonAutomation{ @@ -46,7 +47,7 @@ void RngProgramInstance::check_free_party_slots( Logger& logger = env.console.logger(); logger.log("Checking for " + std::to_string(free_slots_needed) + " free party slot(s)..."); try{ - open_party_menu_from_overworld(env.console, context, start_menu_context()); + open_party_menu_from_overworld(env.console, context); }catch (OperationFailedException&){ logger.log("Unable to open the party menu. Skipping the free party slot check.", COLOR_RED); return; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h index b35ef4c14f..727ba9b099 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h @@ -14,7 +14,6 @@ #include #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -31,11 +30,6 @@ class RngProgramInstance : public SingleSwitchProgramInstance{ // party that Pokemon would go to the PC instead. virtual size_t free_party_slots_needed() const = 0; - // The start menu the player sees where the program starts. - virtual StartMenuContext start_menu_context() const{ - return StartMenuContext::STANDARD; - } - protected: // Call first in program(), with the game on the overworld where the // player saved: checks the party has the free slots diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h index 968f68119a..25daee4b08 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h @@ -36,9 +36,6 @@ class WildRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = WildRng_Descriptor; virtual size_t free_party_slots_needed() const override{ return 1; } - virtual StartMenuContext start_menu_context() const override{ - return in_safari_zone() ? StartMenuContext::SAFARI_ZONE : StartMenuContext::STANDARD; - } ~WildRng(); WildRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override;