diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 673b391abb..df008e51c0 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -257,9 +257,9 @@ jobs: uses: actions/checkout@v7 if: inputs.run-tests with: - # The fork's fixtures: upstream's plus the SystemKeyboardDetector and HomeTileReader screenshots. + # The fork's fixtures: upstream's plus the SystemKeyboardDetector, HomeTileReader and BDSP MenuDetector screenshots. repository: 'dayfine/CommandLineTests' - ref: 'eae4697738d5fe18975e77c05a4e01216bed68e7' + ref: '248d24fc7d1803c5187aae680d37ad1c5c0f13e7' path: 'CommandLineTests' # The unit tests assume the downloadable resources they need are already downloaded diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp index 6d23f8fb83..d4af9f47d1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp @@ -28,10 +28,14 @@ constexpr double STRIPE_BOTTOM = 0.598; // Each column sits in the gap right of an icon, clear of the "NEW" tag on // its top right corner. The tag on TOWN MAP extends into a column at 0.160. constexpr double STRIPE_LEFT = 0.166; +// The selected icon glows about 0.008 past its left edge, into the gap left +// of it. A column of 0.015 reached the glow from 0.177 (cursor on the first +// icon of a row); 0.010 ends just short of it. +constexpr double STRIPE_WIDTH = 0.010; ImageFloatBox menu_stripe(size_t index, bool skip_new_banner){ double top = skip_new_banner ? STRIPE_TOP_BELOW_BANNER : STRIPE_TOP; - return ImageFloatBox(STRIPE_LEFT + 0.166 * (double)index, top, 0.015, STRIPE_BOTTOM - top); + return ImageFloatBox(STRIPE_LEFT + 0.166 * (double)index, top, STRIPE_WIDTH, STRIPE_BOTTOM - top); } } // namespace @@ -149,52 +153,58 @@ class Test_MenuDetector : public ImageUnitTest{ MenuExpectation m_expectation; }; +// Every image runs with both column modes. +constexpr std::array MENU_CASES{{ + {.input = {.image = "PokemonBDSP/MenuDetector/FrenchCursorOnMap_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FrenchCursorOnMap_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::FromTop}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = true}}, + {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::FromTop}, + .expectation = {.detected = false}}, + {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::BelowNewTags}, + .expectation = {.detected = false}}, +}}; + } // namespace void add_tests_MenuDetector(UnitTestDatabase& database){ - static constexpr std::array CASES{{ - {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::FromTop}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/NewGameBagOptions_True.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::FromTop}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/JubilifeTownMapNew_True.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::FromTop}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaMenuThreeNew_True.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = true}}, - {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/Home_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldSandgemMart_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/OverworldOreburghMine_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroDialog_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/IntroBarry_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaOldManDialog_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::FromTop}, - .expectation = {.detected = false}}, - {.input = {.image = "PokemonBDSP/MenuDetector/FloaromaCloudShadows_False.png", .columns = Columns::BelowNewTags}, - .expectation = {.detected = false}}, - }}; - for (const MenuCase& test : CASES){ + for (const MenuCase& test : MENU_CASES){ database.add(test); } } diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp new file mode 100644 index 0000000000..4db0232e56 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp @@ -0,0 +1,220 @@ +/* BDSP RNG Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "PokemonBDSP_RngFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const uint8_t BDSP_HEIGHT_MIN = 0; +const uint8_t BDSP_HEIGHT_MAX = 255; + + +BdspRngFilterRow::BdspRngFilterRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , misc(static_cast(parent_table).feature_flags) + , height( + LockMode::UNLOCK_WHILE_RUNNING, + BDSP_HEIGHT_MIN, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MIN, BDSP_HEIGHT_MIN, + BDSP_HEIGHT_MIN, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MAX + ) + , iv_hp(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_atk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_def(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spatk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spdef(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_speed(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) +{ + if (misc.feature_flags.action){ + PA_ADD_OPTION(misc.action); + } + if (misc.feature_flags.shiny){ + PA_ADD_OPTION(misc.shiny); + } + if (misc.feature_flags.gender){ + PA_ADD_OPTION(misc.gender); + } + if (misc.feature_flags.nature){ + PA_ADD_OPTION(misc.nature); + } + PA_ADD_OPTION(height); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} +std::unique_ptr BdspRngFilterRow::clone() const{ + std::unique_ptr ret(new BdspRngFilterRow(parent())); + ret->misc.set(misc); + ret->height.set(height); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} +bool BdspRngFilterRow::match_iv( + const IntegerRangeCell& desired, const IvRange& actual +){ + uint8_t lo, hi; + desired.current_values(lo, hi); + if (lo == 0 && hi == 31){ + return true; + } + if (actual.high < (int8_t)lo){ + return false; + } + if ((int8_t)hi < actual.low){ + return false; + } + return true; +} +bool BdspRngFilterRow::matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + if (!misc.matches(shiny, gender, nature)){ + return false; + } + + uint8_t height_lo, height_hi; + this->height.current_values(height_lo, height_hi); + if (height < height_lo || height_hi < height){ + return false; + } + + if (!match_iv(iv_hp, ivs.hp)){ + return false; + } + if (!match_iv(iv_atk, ivs.attack)){ + return false; + } + if (!match_iv(iv_def, ivs.defense)){ + return false; + } + if (!match_iv(iv_spatk, ivs.spatk)){ + return false; + } + if (!match_iv(iv_spdef, ivs.spdef)){ + return false; + } + if (!match_iv(iv_speed, ivs.speed)){ + return false; + } + + return true; +} + + +BdspRngFilterTable::BdspRngFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags +) + : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) + , feature_flags(p_feature_flags) +{} +std::vector BdspRngFilterTable::make_header() const{ + std::vector ret; + if (feature_flags.action){ + ret.emplace_back("Action"); + } + if (feature_flags.shiny){ + ret.emplace_back("Shininess"); + } + if (feature_flags.gender){ + ret.emplace_back("Gender"); + } + if (feature_flags.nature){ + ret.emplace_back("Nature"); + } + + ret.emplace_back("Height"); + + ret.emplace_back("HP"); + ret.emplace_back("Atk"); + ret.emplace_back("Def"); + ret.emplace_back("SpAtk"); + ret.emplace_back("SpDef"); + ret.emplace_back("Spd"); + + return ret; +} +BdspRngFilterSnapshot BdspRngFilterTable::make_snapshot() const{ + return BdspRngFilterSnapshot(copy_snapshot()); +} +void set_default_shiny_row(BdspRngFilterTable& table){ + std::vector> defaults; + auto row = std::make_unique(table); + row->misc.shiny.set(StatsHuntShinyFilter::Shiny); + defaults.emplace_back(std::move(row)); + table.set_default(std::move(defaults)); + table.restore_defaults(); +} +StatsHuntAction BdspRngFilterTable::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + return make_snapshot().get_action(shiny, gender, nature, height, ivs); +} + + +BdspRngFilterSnapshot::BdspRngFilterSnapshot(std::vector> rows) + : m_rows(std::move(rows)) +{} +StatsHuntAction BdspRngFilterSnapshot::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + StatsHuntAction action = StatsHuntAction::Discard; + for (size_t c = 0; c < m_rows.size(); c++){ + const BdspRngFilterRow& filter = *m_rows[c]; + + if (!filter.matches(shiny, gender, nature, height, ivs)){ + continue; + } + + StatsHuntAction filter_action = filter.misc.action; + + // No action matched so far. Take the current action and continue. + if (action == StatsHuntAction::Discard){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log( + "Multiple filters matched with conflicting actions. Stopping program...", + COLOR_RED + ); + return StatsHuntAction::StopProgram; + } + } + return action; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h new file mode 100644 index 0000000000..652bc73753 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h @@ -0,0 +1,106 @@ +/* BDSP RNG Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngFilter_H +#define PokemonAutomation_PokemonBDSP_RngFilter_H + +#include +#include +#include +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/IntegerRangeOption.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class BdspRngFilterTable; +class BdspRngFilterRow : public EditableTableRow{ +public: + BdspRngFilterRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + bool matches( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +private: + static bool match_iv(const IntegerRangeCell& desired, const Pokemon::IvRange& actual); + +public: + Pokemon::StatsHuntRowMisc misc; + + IntegerRangeCell height; + + IntegerRangeCell iv_hp; + IntegerRangeCell iv_atk; + IntegerRangeCell iv_def; + IntegerRangeCell iv_spatk; + IntegerRangeCell iv_spdef; + IntegerRangeCell iv_speed; +}; + + +// The table copied once. Calling get_action() on the table itself clones every row on +// every call, which is far too slow for a scan running over millions of advances. +class BdspRngFilterSnapshot{ +public: + explicit BdspRngFilterSnapshot(std::vector> rows); + + Pokemon::StatsHuntAction get_action( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +private: + std::vector> m_rows; +}; + + +class BdspRngFilterTable : public EditableTableOption_t{ +public: + BdspRngFilterTable( + const std::string& label, + const Pokemon::StatsHuntMiscFeatureFlags& p_feature_flags + ); + virtual std::vector make_header() const override; + + BdspRngFilterSnapshot make_snapshot() const; + + Pokemon::StatsHuntAction get_action( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +public: + const Pokemon::StatsHuntMiscFeatureFlags feature_flags; +}; + + +// Makes the table's default, and its current content, one row: a shiny of +// any nature, gender and IVs. An empty table matches nothing, so a program +// that stops on a match must seed its table with this. +void set_default_shiny_row(BdspRngFilterTable& table); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp index 7f1b00688e..a9f0675086 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -41,6 +41,7 @@ #include "Programs/RngManipulation/PokemonBDSP_BedroomSeedFinder.h" #include "Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.h" +#include "Programs/RngManipulation/PokemonBDSP_StarterRng.h" #include "Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h" #include "Programs/TestPrograms/PokemonBDSP_SoundListener.h" @@ -67,6 +68,7 @@ void add_beta_and_developer_panels(std::vector& ret){ ret.emplace_back("---- Untested/Beta/WIP ----"); ret.emplace_back(make_SingleSwitchProgram()); ret.emplace_back(make_SingleSwitchProgram()); + ret.emplace_back(make_SingleSwitchProgram()); } if (STATIC_GLOBALS.DEVELOPER_MODE){ ret.emplace_back("---- Developer Tools ----"); diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 4b6a4ff384..efb7aaaf5e 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -29,6 +29,7 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" #include "Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h" +#include "Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -62,6 +63,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_SimFailureCases(database); add_tests_AutoStory_FaultSweep(database); add_tests_AutoStory_StoryActions(database); + add_tests_StarterRng(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp index e7328cb336..d66a5899c6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp @@ -118,6 +118,16 @@ void azure_flute_if_there(VideoStream& stream, ProControllerContext& context){ +// 00.02 with Run Starter RNG in AutoStory: runs Starter RNG from the +// Verity Lakefront (17, 14) start save through the Starly battle and +// Rowan's scene, ending on the VerityLakefront overworld at (17, 14..15). +Pokemon::Outcome starter_rng(StoryEnv& story, Pokemon::RunState&, const Pokemon::StoryStep&){ + if (!story.run_starter_rng){ + return Pokemon::outcome_failed("starter_rng_not_configured", "Starter RNG is not configured on StoryEnv."); + } + return story.run_starter_rng(); +} + // 00.04: Dawn's catching tutorial on Route 202: her lines and her demo // battle, B for 70 s. void catch_tutorial(VideoStream& stream, ProControllerContext& context){ @@ -134,6 +144,7 @@ void add_lake_events(StoryEvents& events){ events.emplace("azure_flute_if_there", console_event(azure_flute_if_there)); events.emplace("starter_briefcase", console_event(starter_briefcase)); events.emplace("choose_starter", choose_starter); + events.emplace("starter_rng", starter_rng); events.emplace("catch_tutorial", console_event(catch_tutorial)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index f99b5e105e..6a27b819ab 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -9,11 +9,13 @@ #include #include #include +#include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/StaticGlobals.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "Pokemon/AutoStory/Pokemon_StoryPreflight.h" +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "Pokemon/AutoStory/Pokemon_StoryRun.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" @@ -21,6 +23,7 @@ #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/Options/Pokemon_GameLanguages.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" @@ -60,6 +63,14 @@ Pokemon::StoryRowsShown rows_shown(){ return STATIC_GLOBALS.DEVELOPER_MODE ? Pokemon::StoryRowsShown::DEVELOPER : Pokemon::StoryRowsShown::USER; } +// What the user does around Starter RNG when the run stops for it: the +// option's help and the run's closing message. +constexpr std::string_view STARTER_RNG_HANDOFF_TEXT = + "At the end of 00.01 save at the Verity Lakefront (17, 14), facing Lake Verity's entrance, and stop. " + "Run the Starter RNG program from that save (Start point: Verity Lakefront). " + "When it is done, close the Summary page and the menu, let Rowan's scene finish so the player stands " + "on the Verity Lakefront overworld, save, and start AutoStory at 00.03."; + // The start and end dropdowns' entries: segments 00 and 01 joined, 00.00 // to 01.11. The options hold a reference to it. const StringSelectDatabase& checkpoint_database(){ @@ -73,9 +84,11 @@ const StringSelectDatabase& checkpoint_database(){ return database; } -std::set rows_that_stop(const std::vector& rows){ - std::set ids; - for (const StoryCheckpoint& row : rows){ +// The rows whose failure ends the program: the rows that save nothing and +// retry nothing, and the plan's own (Starter RNG's, which resets by itself). +std::set rows_that_stop(const StoryRunPlan& plan){ + std::set ids = plan.fatal_rows; + for (const StoryCheckpoint& row : plan.rows){ if (row.on_failure == StoryFailure::STOP){ ids.insert(row.id); } @@ -125,6 +138,10 @@ std::string verify_story_checkpoint( } // namespace +BDSPAutoStory::~BDSPAutoStory(){ + STARTER_RNG.run().remove_listener(*this); +} + BDSPAutoStory::BDSPAutoStory() : RUN(checkpoint_database(), Pokemon::Gen8ToGen9Languages_Database()) , NEW_GAME_INTRO( @@ -144,7 +161,16 @@ BDSPAutoStory::BDSPAutoStory() LockMode::LOCK_WHILE_RUNNING, StarterChoice::CHIMCHAR ) + , STOP_FOR_STARTER_RNG( + std::format( + "Stop for Starter RNG:
Off by default. Ignored while Run Starter RNG in AutoStory is on. {}", + STARTER_RNG_HANDOFF_TEXT + ), + LockMode::LOCK_WHILE_RUNNING, + false + ) , NOTIFICATIONS({ + &STARTER_RNG.notification_shiny(), &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_RECOVERABLE, &NOTIFICATION_ERROR_FATAL, @@ -154,7 +180,23 @@ BDSPAutoStory::BDSPAutoStory() PA_ADD_OPTION(NEW_GAME_INTRO); PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(STOP_FOR_STARTER_RNG); + add_option(STARTER_RNG.run(), "RUN_STARTER_RNG"); + add_option(STARTER_RNG.player_model(), "STARTER_RNG_PLAYER_MODEL"); + add_option(STARTER_RNG.max_resets(), "MAX_RESETS"); + add_option(STARTER_RNG.filters(), "STARTER_RNG_FILTERS"); PA_ADD_OPTION(NOTIFICATIONS); + + BDSPAutoStory::on_config_value_changed(this); + STARTER_RNG.run().add_listener(*this); +} + +// Run Starter RNG takes precedence over Stop for Starter RNG: the stop +// option is greyed out while it is on, and the plan ignores it. +void BDSPAutoStory::on_config_value_changed(void*){ + const bool run_in_story = STARTER_RNG.run(); + STARTER_RNG.set_details_visible(run_in_story); + STOP_FOR_STARTER_RNG.set_visibility(run_in_story ? ConfigOptionState::DISABLED : ConfigOptionState::ENABLED); } namespace{ @@ -265,30 +307,56 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo // The reads that use text (Location.h) take the game's language from here. set_story_language(RUN.language()); - StoryEnv story{env, context, STARTER, PLAYER_NAME}; + StoryEnv story{env, context, STARTER, PLAYER_NAME, {}}; + if (STARTER_RNG.run()){ + story.run_starter_rng = make_starter_rng_hook( + env, context, STARTER_RNG, STARTER_RNG.config(RUN.language(), STARTER), NOTIFICATION_ERROR_RECOVERABLE + ); + } ConsoleStory executor(story); - executor.set_stop_rows(rows_that_stop(checkpoints)); + const StoryRunPlan plan = plan_story_run( + checkpoints, first, last, + StoryHandoffs{.starter_rng = Pokemon::rng_handoff_mode({.stop = STOP_FOR_STARTER_RNG, .run = STARTER_RNG.run()})} + ); + executor.set_stop_rows(rows_that_stop(plan)); + run_plan(env, context, plan, first == 0 && NEW_GAME_INTRO, executor); +} + +void BDSPAutoStory::run_plan( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StoryRunPlan& plan, bool new_game, ConsoleStory& executor +){ // A start with a save always loads it first, so the run never walks // from wherever the game was left (console B, 2026-11-11: a run from // 00.04b walked from 00.04d's position). - const bool new_game = first == 0 && NEW_GAME_INTRO; const Pokemon::StoryStart start = new_game ? Pokemon::StoryStart::NEW_GAME : Pokemon::StoryStart::FROM_SAVE; if (new_game && RUN.VERIFY.policy()){ throw UserSetupError(env.console, "Verify mode reloads the start's save between runs: turn off \"Start a new game first\"."); } - std::set saved = saved_before_the_run(checkpoints, first, start); - Pokemon::Segment segment = make_story_segment(checkpoints, executor, saved); + if (plan.stop != StoryHandoff::NONE && RUN.VERIFY.policy()){ + throw UserSetupError(env.console, "Verify mode repeats the start's checkpoint, and its extra save at the end of 00.01 would overwrite the Verity Lakefront save: turn off \"Stop for Starter RNG\"."); + } + std::set saved = saved_before_the_run(plan.rows, 0, start); + Pokemon::Segment segment = make_story_segment(plan.rows, executor, saved); Pokemon::StoryGameHooks game = story_game(env, context); Pokemon::RunState state; - start_story(env, context, checkpoints[first], start, game, state); + start_story(env, context, plan.rows.front(), start, game, state); if (const std::optional verify = RUN.VERIFY.policy()){ - const std::string summary = verify_story_checkpoint(checkpoints[first].id, *verify, segment, game, state); + const std::string summary = verify_story_checkpoint(plan.rows.front().id, *verify, segment, game, state); send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, summary); return; } const std::string done = run_story( - Pokemon::SegmentRange{checkpoints[first].id, checkpoints[last].id}, RUN.policy(), segment, game, state, env + Pokemon::SegmentRange{plan.rows.front().id, plan.rows.back().id}, RUN.policy(), segment, game, state, env ); + if (plan.stop == StoryHandoff::STARTER_RNG){ + const std::string handoff = Pokemon::report_rng_handoff_stop( + env.console, std::format("Stopped for Starter RNG. {}", STARTER_RNG_HANDOFF_TEXT), {}, + [&](const std::string& line){ env.console.overlay().add_log(line); } + ); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, handoff); + return; + } send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, done); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index 70a8182d08..8a64ab8402 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -19,7 +19,10 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "PokemonBDSP_AutoStory_ConsoleStory.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" #include "PokemonBDSP_AutoStory_StoryCheckpoint.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -36,19 +39,31 @@ class BDSPAutoStory_Descriptor : public SingleSwitchProgramDescriptor{ // Single-switch program instance executing BDSP story automation. -class BDSPAutoStory : public SingleSwitchProgramInstance{ +class BDSPAutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ public: using Descriptor = BDSPAutoStory_Descriptor; + ~BDSPAutoStory(); BDSPAutoStory(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; private: + virtual void on_config_value_changed(void* object) override; + + // Starts the plan's story and runs it to its end or its stop. + void run_plan( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StoryRunPlan& plan, bool new_game, ConsoleStory& executor + ); + // The start and end checkpoints, attempts, checks and language. Pokemon::StoryRunOptions RUN; BooleanCheckBoxOption NEW_GAME_INTRO; StringOption PLAYER_NAME; EnumDropdownOption STARTER; + // The RNG program the run stops for (StoryHandoff), or runs in 00.02. + BooleanCheckBoxOption STOP_FOR_STARTER_RNG; + StoryStarterRngOptions STARTER_RNG; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp new file mode 100644 index 0000000000..8ceb126ce8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp @@ -0,0 +1,174 @@ +/* BDSP AutoStory: Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +BdspStarter bdsp_starter_for_choice(StarterChoice choice){ + switch (choice){ + case StarterChoice::TURTWIG: + return BdspStarter::Turtwig; + case StarterChoice::CHIMCHAR: + return BdspStarter::Chimchar; + case StarterChoice::PIPLUP: + return BdspStarter::Piplup; + } + return BdspStarter::Chimchar; +} + + +StoryStarterRngOptions::StoryStarterRngOptions() + : RUN( + "Run Starter RNG in AutoStory:
Off by default. In 00.02, run Starter RNG from the Verity Lakefront " + "save using the stop conditions below, then continue the story at 00.03. " + "Takes precedence over Stop for Starter RNG. If it fails the program stops: it does not reload 00.02.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , MAX_RESETS( + "Starter RNG Maximum Resets:
0 means no limit.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 9999 + ) + , FILTERS( + "Starter RNG Stop Conditions:
Stop Starter RNG when the starter matches any row in this table.", + Pokemon::StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) +{ + set_default_shiny_row(FILTERS); +} + +void StoryStarterRngOptions::set_details_visible(bool visible){ + const ConfigOptionState state = visible ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN; + PLAYER_MODEL.set_visibility(state); + MAX_RESETS.set_visibility(state); + FILTERS.set_visibility(state); +} + +StoryStarterRngConfig StoryStarterRngOptions::config(Language language, StarterChoice starter) const{ + return StoryStarterRngConfig{ + .language = language, + .player_model = PLAYER_MODEL.model_number(), + .starter = starter, + .max_resets = MAX_RESETS, + }; +} + + +StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config, const BdspRngFilterSnapshot& filters){ + StarterRngSettings settings; + settings.language = config.language; + settings.player_model = config.player_model; + settings.start_point = BdspStartPoint::Lakefront; + settings.starter = bdsp_starter_for_choice(config.starter); + settings.filters = &filters; + settings.max_resets = config.max_resets; + settings.reset_first = false; + settings.finish_battle_on_shiny = true; + settings.close_summary_after_read = true; + return settings; +} + +std::string starter_rng_failure(const StarterRngRunResult& result){ + switch (result.outcome){ + case StarterRngOutcome::HIT: + return ""; + case StarterRngOutcome::SHINY: + if (!result.settled){ + return "Caught a shiny starter, but the Starly battle or Rowan's scene did not finish: " + "stopped with the shiny in the party; the game is not on the Verity Lakefront overworld."; + } + return ""; + case StarterRngOutcome::OUT_OF_RESETS: + case StarterRngOutcome::ABANDONED: + break; + } + if (result.last_failure_reason.empty()){ + return std::format("Starter RNG stopped after {} reset(s) without hitting a target.", result.resets_used); + } + return result.last_failure_reason; +} + + +Pokemon::RngHandoffResult starter_rng_handoff_result(const StarterRngRunResult& result){ + Pokemon::RngHandoffResult handoff; + handoff.failure = starter_rng_failure(result); + if (handoff.failure.empty()){ + handoff.summary = std::format( + "after {} reset(s) on advance {}: {}.", + result.resets_used, result.target_advance, result.target.to_string() + ); + } + return handoff; +} + + +namespace{ + +// What the hook keeps between its calls: the filters, copied once so that +// edits made while running do not apply, and the aim that Starter RNG's +// calibration builds up across them. +struct StarterRngHookState{ + StarterRngHookState(StoryStarterRngOptions& options, const StoryStarterRngConfig& config) + : filters(options.filters().make_snapshot()) + , settings(make_starter_rng_settings(config, filters)) + {} + + RngAim aim; + BdspRngFilterSnapshot filters; + StarterRngSettings settings; +}; + +} // namespace + + +std::function make_starter_rng_hook( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryStarterRngOptions& options, const StoryStarterRngConfig& config, + EventNotificationOption& error_notification +){ + if (options.filters().current_rows() == 0){ + throw UserSetupError( + env.console, + "Starter RNG Stop Conditions is empty, so no starter would ever match: add a row, such as a shiny of any nature." + ); + } + std::shared_ptr state = std::make_shared(options, config); + return [&env, &context, &options, &error_notification, state]() -> Pokemon::Outcome{ + uint64_t resets_logged = 0; + StarterRngAttemptIO io; + io.notification_shiny = &options.notification_shiny(); + io.notification_error = &error_notification; + io.on_reset = [&]{ + resets_logged++; + env.console.overlay().add_log(std::format("Starter RNG: try {}", resets_logged)); + }; + return Pokemon::run_rng_handoff(env.logger(), "Starter RNG", [&]{ + const StarterRngRunResult result = run_starter_rng_attempts(env, context, state->settings, io, state->aim); + return starter_rng_handoff_result(result); + }); + }; +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h new file mode 100644 index 0000000000..c2ca7c7cab --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -0,0 +1,99 @@ +/* BDSP AutoStory: Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + * Run Starter RNG in AutoStory: its options, and the action that 00.02 runs + * in place of its Lake Verity steps (the Starter RNG program's reset loop, + * PokemonBDSP_StarterRngAttempts.h, called from the story). + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StarterRng_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StarterRng_H + +#include +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" +#include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_AutoStory_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Maps AutoStory's starter option to Starter RNG's starter enum. +BdspStarter bdsp_starter_for_choice(StarterChoice choice); + + +// What the story tells Starter RNG about the game it plays. +struct StoryStarterRngConfig{ + Language language = Language::English; + // The player's appearance, 1 to 8: the lake's eye templates depend on it. + uint8_t player_model = 1; + StarterChoice starter = StarterChoice::CHIMCHAR; + uint16_t max_resets = 0; +}; + + +// AutoStory's options for Starter RNG. Only RUN is always shown; the rest +// show while it is on. +class StoryStarterRngOptions{ +public: + StoryStarterRngOptions(); + + void set_details_visible(bool visible); + // The options' values, for a story in `language` with `starter`. + StoryStarterRngConfig config(Language language, StarterChoice starter) const; + + BooleanCheckBoxOption& run(){ return RUN; } + PlayerModelOption& player_model(){ return PLAYER_MODEL; } + SimpleIntegerOption& max_resets(){ return MAX_RESETS; } + BdspRngFilterTable& filters(){ return FILTERS; } + EventNotificationOption& notification_shiny(){ return NOTIFICATION_SHINY; } + +private: + BooleanCheckBoxOption RUN; + PlayerModelOption PLAYER_MODEL; + SimpleIntegerOption MAX_RESETS; + BdspRngFilterTable FILTERS; + EventNotificationOption NOTIFICATION_SHINY; +}; + + +// Starter RNG's settings for the run in 00.02: from the Verity Lakefront +// save, through the Starly battle and Rowan's scene on a shiny or not, to +// the Lakefront overworld with the menu closed. +StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config, const BdspRngFilterSnapshot& filters); + +// Why the story cannot go on after Starter RNG ended as `result`; empty if +// it can: a starter was caught and the game stands on the Lakefront. +std::string starter_rng_failure(const StarterRngRunResult& result); + +// Starter RNG's end as the shared handoff contract has it +// (Pokemon_StoryRngHandoff.h): starter_rng_failure() and, on success, the +// resets used and the target hit. +Pokemon::RngHandoffResult starter_rng_handoff_result(const StarterRngRunResult& result); + +// The action 00.02 runs. Throws a UserSetupError now if the filter table is +// empty. The action itself throws when Starter RNG fails, so that no row +// retry reruns the whole reset loop. +std::function make_starter_rng_hook( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryStarterRngOptions& options, const StoryStarterRngConfig& config, + EventNotificationOption& error_notification +); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h index e6cdd9f387..a3284b6971 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryCheckpoint.h @@ -13,6 +13,7 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryCheckpoint_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryCheckpoint_H +#include #include #include #include @@ -63,6 +64,8 @@ struct StoryEnv{ ProControllerContext& context; StarterChoice starter = StarterChoice::CHIMCHAR; std::string player_name; + // Runs Starter RNG at 00.02's starter pick; empty when the option is off. + std::function run_starter_rng; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 6c20e4f57e..b7fe9c4a4e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -7,6 +7,8 @@ * */ +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "PokemonBDSP_AutoStory_StoryData.h" #include "PokemonBDSP_AutoStory_StoryTable.h" @@ -15,11 +17,85 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +namespace{ + +// 00.02 is the Lake Verity starter and Starly battle checkpoint, which Run +// Starter RNG in AutoStory replaces with the game event STARTER_RNG_ACTION. +constexpr std::string_view STARTER_RNG_CHECKPOINT_ROW = "00.02"; +constexpr std::string_view STARTER_RNG_ACTION = "starter_rng"; + +// `row` with a save appended at its end, where the next checkpoint starts: +// in BDSP rows normally save at their start, so a run that stops after +// 00.01 for Starter RNG makes 00.02's Lakefront save before stopping. As +// every start save does, it checks that the save card names `saves_in` +// (the next row's), and stops the program if not. +StoryCheckpoint with_handoff_save(StoryCheckpoint row, const std::string& saves_in){ + Pokemon::StoryStep save; + save.kind = Pokemon::StoryStepKind::SAVE; + save.name = "save_for_starter_rng"; + save.args.emplace(SAVES_IN_ARG, saves_in); + save.why = "the save at the Verity Lakefront where Starter RNG starts"; + if (!row.steps.empty()){ + const Pokemon::StoryStep& last = row.steps.back(); + if (last.pose_after){ + save.pose_after = last.pose_after; + }else if (last.kind == Pokemon::StoryStepKind::ROUTE){ + const Pokemon::GridPose& target = Pokemon::story_arg(last.args, "target"); + save.pose_after = Pokemon::TileDeclared{ + .map = target.map, .tiles = target.tiles, .facing = target.facing + }; + } + } + row.steps.push_back(std::move(save)); + return row; +} + +// `row` (00.02) with its Lake Verity steps replaced by the in-program +// Starter RNG action, keeping 00.02's start save at VerityLakefront (17, 14) +// and its end pose at VerityLakefront (17, 14..15). +StoryCheckpoint with_starter_rng_step(StoryCheckpoint row){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::string(STARTER_RNG_ACTION); + step.action = std::string(STARTER_RNG_ACTION); + step.why = "Starter RNG at Lake Verity through the Starly battle and Rowan's scene"; + if (!row.steps.empty()){ + step.pose_after = row.steps.back().pose_after; + } + row.steps = {std::move(step)}; + return row; +} + +} // namespace + + const std::vector& story_checkpoints(){ static const std::vector checkpoints = load_bdsp_story({}).checkpoints; return checkpoints; } +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.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng == Pokemon::RngHandoffMode::STOP){ + const std::string saves_in = c + 1 < checkpoints.size() ? checkpoints[c + 1].saves_in : std::string(); + plan.rows.push_back(with_handoff_save(row, saves_in)); + plan.stop = StoryHandoff::STARTER_RNG; + return plan; + } + if (row.id == STARTER_RNG_CHECKPOINT_ROW && handoffs.starter_rng == Pokemon::RngHandoffMode::RUN){ + plan.rows.push_back(with_starter_rng_step(row)); + plan.fatal_rows.insert(row.id); + continue; + } + plan.rows.push_back(row); + } + return plan; +} + } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 39bfeffd90..f88decdac8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -14,8 +14,11 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H +#include +#include #include #include +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "PokemonBDSP_AutoStory_StoryCheckpoint.h" namespace PokemonAutomation{ @@ -33,6 +36,45 @@ inline constexpr std::string_view RUNNING_SHOES_ROW = "00.03"; // Story step name in which Mom gives the Running Shoes. inline constexpr std::string_view RUNNING_SHOES_STEP = "rowan_and_dawn"; +// 00.01 ends at the Verity Lakefront (17, 14) facing north, where 00.02 and +// Starter RNG (Start point: Verity Lakefront) start. +inline constexpr std::string_view STARTER_RNG_HANDOFF_ROW = "00.01"; + +// An upstream RNG program the user may run part-way through the story. +enum class StoryHandoff{ + NONE, + // The run stops after 00.01 saves at the Verity Lakefront (17, 14), + // facing Lake Verity's entrance, where Starter RNG starts. + STARTER_RNG, +}; + +// The handoffs a run stops for or runs in-program (AutoStory's options). +struct StoryHandoffs{ + // STOP: the run stops after 00.01 for the user's Starter RNG. RUN: 00.02 + // runs it in the program. The mode of the options: Pokemon::rng_handoff_mode(). + Pokemon::RngHandoffMode starter_rng = Pokemon::RngHandoffMode::OFF; +}; + +// What a run from table row `first` to `last` does. +struct StoryRunPlan{ + // The checkpoints to run, in order. Copies, not pointers: a row the plan + // changes (the handoff save) must not change the table, and the run's + // steps capture these rows, which outlive the call. + std::vector rows; + // NONE: the run ends after `rows`. STARTER_RNG: the run stops after + // `rows`, the last of which (00.01) saves at the Verity Lakefront. + StoryHandoff stop = StoryHandoff::NONE; + // Rows whose failure ends the program though they save at their start: + // a failed 00.02 with Run Starter RNG, whose reset loop is the retry. + std::set fatal_rows; +}; + +// The rows of `table` from `first` to `last`, both inclusive, as a +// run with `handoffs` takes them: a run that reaches 00.01 with +// `handoffs.starter_rng` STOP saves at the Verity Lakefront at the end of +// 00.01 and stops there for Starter RNG. +StoryRunPlan plan_story_run(const std::vector& table, size_t first, size_t last, const StoryHandoffs& handoffs = {}); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 33ee03e9f7..f4dfd8f0b8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Filesystem/FileIO.h" @@ -32,6 +33,7 @@ #include "PokemonBDSP_AutoStory_StoryCheckpoint.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_TableRoutes.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -267,6 +269,57 @@ UnitTestResult test_line_5_recovery_pins_the_wall_nearest_the_goal(Logger& logge return true; } +// plan_story_run() with Starter RNG handoff: off leaves the range unchanged; +// on stops after 00.01 with a save at the Verity Lakefront (17, 14) facing +// north, where 00.02 and Starter RNG start; starting past 00.01 runs on. +UnitTestResult test_plan_story_run_starter_rng(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan full = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::OFF}); + if (full.stop != StoryHandoff::NONE || full.rows.size() != table.size()){ + return "With Starter RNG handoff off, expected the full table with no stop."; + } + const StoryRunPlan handoff = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); + if (handoff.stop != StoryHandoff::STARTER_RNG || handoff.rows.size() != 2 || + handoff.rows[0].id != "00.00" || handoff.rows[1].id != "00.01" + ){ + return "Expected a 00.00..01.11 run with Starter RNG handoff to stop after 00.01."; + } + const StoryCheckpoint& lakefront_row = handoff.rows.back(); + const std::vector problems = Pokemon::lint_story_checkpoint(lakefront_row); + if (!problems.empty()){ + return std::format("00.01 with Starter RNG handoff save: {}", problems[0]); + } + if (lakefront_row.steps.empty() || lakefront_row.steps.back().kind != StoryStepKind::SAVE || + lakefront_row.steps.back().name != "save_for_starter_rng" + ){ + return "Expected 00.01 with Starter RNG handoff to end with save_for_starter_rng."; + } + // The save card is checked as every other start save is: it must name + // 00.02's map. + const auto saves_in = lakefront_row.steps.back().args.find(SAVES_IN_ARG); + const std::string* card = saves_in == lakefront_row.steps.back().args.end() ? nullptr : std::get_if(&saves_in->second); + if (card == nullptr || *card != table[2].saves_in || table[2].saves_in.empty()){ + return std::format( + "Expected the handoff save to check the card for \"{}\", got \"{}\".", + table[2].saves_in, card == nullptr ? "" : *card + ); + } + const std::optional end = end_pose(lakefront_row); + const std::optional next_start = table[2].start + ? std::make_optional(Pokemon::pose_of(*table[2].start)) + : std::nullopt; + if (!end || !next_start || end->map != "VerityLakefront" || + Pokemon::to_string(*end) != Pokemon::to_string(*next_start) + ){ + return "Expected 00.01's Starter RNG handoff save to end at 00.02's VerityLakefront (17, 14) start pose."; + } + const StoryRunPlan from_0002 = plan_story_run(table, 2, 4, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); + if (from_0002.stop != StoryHandoff::NONE || from_0002.rows.size() != 3 || from_0002.rows.front().id != "00.02"){ + return "Expected a run starting at 00.02 to pass through without stopping for 00.01's handoff."; + } + return true; +} + // Why `planned` may slide into a door or a warp, or "": an open leg (not to // a wall) that may end on the tile before one, walking toward it. A part of // a tile too far takes the warp (lab-B 2026-11-08 15:31 to 15:54: 01.05's @@ -609,6 +662,116 @@ UnitTestResult test_route_plans_golden(Logger& logger){ "and review the file's diff. " + differences; } +// plan_story_run() with Run Starter RNG in AutoStory: 00.02 runs the +// starter_rng event after its Verity Lakefront start save and ends where +// 00.03 starts; the handoff stop is not taken. +UnitTestResult test_plan_story_run_in_program(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan in_program = plan_story_run( + table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} + ); + if (in_program.stop != StoryHandoff::NONE || in_program.rows.size() != table.size()){ + return "With Run Starter RNG in AutoStory on, expected the full table with no handoff stop."; + } + const StoryCheckpoint& rng_row = in_program.rows[2]; + const std::vector rng_problems = Pokemon::lint_story_checkpoint(rng_row); + if (!rng_problems.empty()){ + return std::format("00.02 with Run Starter RNG in AutoStory: {}", rng_problems[0]); + } + if (rng_row.id != "00.02" || rng_row.saves_in != "Verity Lakefront" || rng_row.steps.size() != 1 || + rng_row.steps[0].kind != StoryStepKind::GAME || rng_row.steps[0].action != "starter_rng" || + !story_events().contains(rng_row.steps[0].action) + ){ + return "Expected 00.02 with Run Starter RNG in AutoStory to run the starter_rng game event after its Verity Lakefront start save."; + } + const std::optional rng_end = end_pose(rng_row); + const std::optional row0003_start = table[3].start + ? std::make_optional(Pokemon::pose_of(*table[3].start)) + : std::nullopt; + if (!rng_end || !row0003_start || Pokemon::to_string(*rng_end) != Pokemon::to_string(*row0003_start)){ + return "Expected 00.02's starter_rng step to end at 00.03's VerityLakefront (17, 14..15) start pose."; + } + if (bdsp_starter_for_choice(StarterChoice::TURTWIG) != BdspStarter::Turtwig || + bdsp_starter_for_choice(StarterChoice::CHIMCHAR) != BdspStarter::Chimchar || + bdsp_starter_for_choice(StarterChoice::PIPLUP) != BdspStarter::Piplup + ){ + return "Expected StarterChoice to map 1-to-1 to BdspStarter."; + } + return true; +} + + +// The Starter RNG run's settings: the player's model, the starter and the +// reset limit come from AutoStory's options, and the run ends where 00.03 +// starts (Lakefront overworld, menu closed). +UnitTestResult test_starter_rng_settings(Logger&){ + BdspRngFilterTable table("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + set_default_shiny_row(table); + const BdspRngFilterSnapshot filters = table.make_snapshot(); + const StoryStarterRngConfig config{ + .language = Language::French, .player_model = 5, .starter = StarterChoice::PIPLUP, .max_resets = 7 + }; + const StarterRngSettings settings = make_starter_rng_settings(config, filters); + if (settings.player_model != 5){ + return std::format("Expected the story's player model 5 to reach Starter RNG, got {}.", settings.player_model); + } + if (settings.starter != BdspStarter::Piplup || settings.language != Language::French || settings.max_resets != 7){ + return "Expected the starter, language and reset limit to come from the story's options."; + } + if (settings.filters != &filters || settings.start_point != BdspStartPoint::Lakefront){ + return "Expected the filter snapshot and the Verity Lakefront start point."; + } + if (settings.reset_first || !settings.finish_battle_on_shiny || !settings.close_summary_after_read){ + return "Expected a run that starts from the loaded save and leaves the Lakefront overworld on a shiny or not."; + } + return true; +} + +// What Starter RNG ending means for the story: a starter in hand and the +// game on the Lakefront lets it go on; anything else stops it with a reason. +UnitTestResult test_starter_rng_failure(Logger&){ + StarterRngRunResult result; + result.outcome = StarterRngOutcome::HIT; + if (!starter_rng_failure(result).empty()){ + return "Expected a hit to let the story go on."; + } + result.outcome = StarterRngOutcome::SHINY; + if (!starter_rng_failure(result).empty()){ + return "Expected a settled shiny to let the story go on."; + } + result.settled = false; + if (starter_rng_failure(result).empty()){ + return "Expected a shiny that did not settle (the game is mid-scene) to stop the story."; + } + for (const StarterRngOutcome outcome : {StarterRngOutcome::ABANDONED, StarterRngOutcome::OUT_OF_RESETS}){ + StarterRngRunResult failed; + failed.outcome = outcome; + failed.resets_used = 3; + if (starter_rng_failure(failed).empty()){ + return "Expected a run with no starter to stop the story."; + } + } + return true; +} + +// A failed Run Starter RNG ends the program: 00.02's row retry would rerun +// the whole reset loop. Without it no row is fatal on top of the table's. +UnitTestResult test_starter_rng_row_is_fatal(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan in_program = plan_story_run( + table, 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} + ); + if (in_program.fatal_rows != std::set{"00.02"}){ + return "Expected 00.02 to be fatal when Run Starter RNG in AutoStory is on."; + } + const StoryRunPlan plain = plan_story_run(table, 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); + const StoryRunPlan off = plan_story_run(table, 0, 3); + if (!plain.fatal_rows.empty() || !off.fatal_rows.empty()){ + return "Expected no fatal rows unless Run Starter RNG in AutoStory is on."; + } + return true; +} + struct AutoStoryStoryTableInput{ std::string name; @@ -681,6 +844,26 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"01.08: the walk below the Ravaged Path keeps off the youngster's row (lab-B, 2026-11-08)", test_ravaged_path_keeps_off_the_youngster}, .expectation = {}, }, + { + .input = {"Starter RNG handoff: stops after 00.01 saved at the Verity Lakefront", test_plan_story_run_starter_rng}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: 00.02 runs the starter_rng event", test_plan_story_run_in_program}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: settings come from the story's options", test_starter_rng_settings}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: what lets the story go on", test_starter_rng_failure}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: a failed 00.02 ends the program", test_starter_rng_row_is_fatal}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index 919d99af30..95a1aa6ec0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -23,6 +24,7 @@ #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "Utils/PokemonBDSP_AutoStory_Walk.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" #include "Utils/PokemonBDSP_AutoStory_WalkResult.h" #include "Utils/PokemonBDSP_AutoStory_WalkScreen.h" @@ -301,6 +303,86 @@ UnitTestResult test_location_banner_showing(Logger& logger){ +// walk_view_shift(): a step scrolls the whole view; scenery that moves on +// its own does not. Synthetic 384x216 screens of 8-pixel blocks in mixed +// colours, as grass and flowers are, with one change each. +uint32_t scenery_at(int x, int y){ + const uint32_t block = (uint32_t)((x >> 3) * 73856093u) ^ (uint32_t)((y >> 3) * 19349663u); + const uint32_t hashed = block * 2654435761u; + return 0xff000000 | (hashed & 0x00ffffff); +} +ImageRGB32 scenery(int shift_x, int shift_y){ + ImageRGB32 screen(384, 216); + for (int y = 0; y < 216; y++){ + for (int x = 0; x < 384; x++){ + screen.pixel(x, y) = scenery_at(x + shift_x + 1000, y + shift_y + 1000); + } + } + return screen; +} +// Each colour channel of the pixels in [x0, x1) x [y0, y1) times `scale`, +// or set to `fill` if given. +void paint(ImageRGB32& screen, int x0, int y0, int x1, int y1, double scale, uint32_t fill = 0){ + for (int y = y0; y < y1; y++){ + for (int x = x0; x < x1; x++){ + uint32_t p = screen.pixel(x, y); + if (fill != 0){ + screen.pixel(x, y) = fill; + continue; + } + uint32_t out = 0xff000000; + for (int shift = 0; shift < 24; shift += 8){ + out |= (uint32_t)(((p >> shift) & 0xff) * scale) << shift; + } + screen.pixel(x, y) = out; + } + } +} + +UnitTestResult test_view_shift(Logger&){ + const ImageRGB32 before = scenery(0, 0); + struct Case{ + std::string name; + ImageRGB32 after; + bool scrolled; + }; + std::vector cases; + cases.push_back({"the same view", scenery(0, 0), false}); + cases.push_back({"a step east: the view scrolls 16 pixels west", scenery(16, 0), true}); + cases.push_back({"a step south", scenery(0, 12), true}); + { + // r83, r84: a cloud's shadow over the top of the view. + ImageRGB32 shadow = scenery(0, 0); + paint(shadow, 0, 0, 384, 90, 0.6); + cases.push_back({"a cloud shadow over the top third", std::move(shadow), false}); + } + { + // Jubilife's TV screens, the mine's conveyors. + ImageRGB32 tv = scenery(0, 0); + paint(tv, 20, 20, 110, 80, 0, 0xffffffff); + cases.push_back({"a TV lights up in a corner", std::move(tv), false}); + } + { + // A turn changes only the player's sprite. + ImageRGB32 turned = scenery(0, 0); + paint(turned, 175, 75, 210, 150, 0, 0xffff4040); + cases.push_back({"the player turns", std::move(turned), false}); + } + for (const Case& item : cases){ + const ViewShift shift = walk_view_shift(before, item.after); + if (shift.scrolled() != item.scrolled){ + return std::format("{}: {} (shift {}, {}; difference {:.1f} unshifted, {:.1f} shifted).", + item.name, item.scrolled ? "did not read as a scroll" : "read as a scroll", + shift.dx, shift.dy, shift.unshifted, shift.shifted); + } + } + const ViewShift east = walk_view_shift(before, scenery(16, 0)); + if (east.dx != -8 || east.dy != 0){ + return std::format("A 16-pixel scroll west read as ({}, {}) on the half-size copy, expected (-8, 0).", east.dx, east.dy); + } + return true; +} + // pokemon_center_on_screen(): the Center's warm floor in a room. r79 read // Jubilife's yellow plaza as a Center and called a won battle lost. UnitTestResult test_pokemon_center_on_screen(Logger&){ @@ -467,6 +549,10 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .input = {"a Pokemon Center is its floor in a room, not a yellow plaza", test_pokemon_center_on_screen}, .expectation = {}, }, + { + .input = {"a step scrolls the view; moving scenery does not", test_view_shift}, + .expectation = {}, + }, { .input = {"a wild battle on an open leg's taps, placed by its screen events", test_leg_battle_place}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp index 709786d144..2f08d38751 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp @@ -164,7 +164,7 @@ void dpad_tiles(VideoStream& stream, ProControllerContext& context, DpadPosition context.wait_for_all_requests(); const VideoSnapshot after = stream.video().snapshot(); const double change = before && after ? walk_screen_change(*before.frame, *after.frame) : 100; - if (change > 30){ + if (!before || !after || tap_moved(*before.frame, *after.frame, 30)){ moved++; continue; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index dc3b944230..67b5a248bc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -499,6 +499,57 @@ UnitTestResult test_start_and_end(Logger&){ if (!report.completed || one.begun() != std::vector{"00.02"}){ return "Expected 00.02 alone:" + joined(one.begun()); } + // With Stop for Starter RNG on, a 00.00..01.11 run stops after 00.01 + // saves at the Verity Lakefront (17, 14) facing north. + Simulation handoff_sim; + const StoryRunPlan plan = plan_story_run( + story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP} + ); + Pokemon::Segment handoff_segment = make_story_segment(plan.rows, handoff_sim.game, handoff_sim.saved); + Pokemon::SegmentHooks hooks; + hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; + RunState handoff_state; + const Pokemon::SegmentReport handoff_report = Pokemon::run_segment( + {.from = plan.rows.front().id, .to = plan.rows.back().id}, handoff_sim.policy, handoff_segment, hooks, handoff_state + ); + if (!handoff_report.completed || plan.stop != StoryHandoff::STARTER_RNG || + handoff_sim.begun() != std::vector{"00.00", "00.01"} || + handoff_sim.count("00.01/save_for_starter_rng") != 1 || + handoff_sim.count("card for 00.01: Verity Lakefront") != 1 || + handoff_state.pose.map != "VerityLakefront" || + Pokemon::tiles_of(handoff_state.pose) != std::vector{{17, 14}} + ){ + return std::format("Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14), checking the Verity Lakefront card:{}", joined(handoff_sim.trace)); + } + return true; +} + +// With Run Starter RNG in AutoStory on, 00.02 saves at the Verity +// Lakefront, runs 00.02/starter_rng, and chains into 00.03. +UnitTestResult test_run_starter_rng_in_story(Logger&){ + Pokemon::SegmentHooks hooks; + hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; + Simulation in_program_sim; + const StoryRunPlan in_program_plan = plan_story_run( + story_checkpoints(), 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} + ); + Pokemon::Segment in_program_segment = make_story_segment(in_program_plan.rows, in_program_sim.game, in_program_sim.saved); + RunState in_program_state; + const Pokemon::SegmentReport in_program_report = Pokemon::run_segment( + {.from = "00.00", .to = "00.03"}, in_program_sim.policy, in_program_segment, hooks, in_program_state + ); + if (!in_program_report.completed || + in_program_sim.begun() != std::vector{"00.00", "00.01", "00.02", "00.03"} || + in_program_sim.count("save in 00.02") != 1 || + in_program_sim.count("card for 00.02: Verity Lakefront") != 1 || + in_program_sim.count("00.02/starter_rng") != 1 || + in_program_sim.count("00.02/choose_starter") != 0 + ){ + return std::format( + "Expected 00.02 with Run Starter RNG in AutoStory to save at Verity Lakefront, run 00.02/starter_rng, and continue to 00.03:{}", + joined(in_program_sim.trace) + ); + } return true; } @@ -709,6 +760,10 @@ const AutoStoryStorySimulationCase AUTO_STORY_STORY_SIMULATION_CASES[] = { .input = {"start and end checkpoints", test_start_and_end}, .expectation = {}, }, + { + .input = {"Run Starter RNG in AutoStory chains 00.02 into 00.03", test_run_starter_rng_in_story}, + .expectation = {}, + }, { .input = {"a blackout in 00.04b's training resets to its save", test_training_blackout}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index ea3d3af19a..b01254e464 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -23,6 +23,7 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_AutoStory_Indoors.h" #include "PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_LocationBannerWatcher.h" #include "PokemonBDSP_AutoStory_Walk.h" @@ -113,6 +114,70 @@ WarpFade WarpFadeWatch::push(const Pokemon::TransitionSample& sample){ } +namespace detail{ +bool ViewShift::scrolled() const{ + constexpr double LEAST_DIFFERENCE = 3; // standing still in the video: 0 to 1.5 + return (dx != 0 || dy != 0) && unshifted >= LEAST_DIFFERENCE && unshifted >= 2 * shifted; +} + +ViewShift walk_view_shift(const ImageViewRGB32& before, const ImageViewRGB32& after){ + constexpr int W = 192; + constexpr int H = 108; + // A step scrolls 2 to 10 pixels of the copy in 300 ms. + constexpr int REACH = 12; + const ImageRGB32 a = before.scale_to(W, H); + const ImageRGB32 b = after.scale_to(W, H); + // The player's box, which moves with the camera, not with the scenery. + auto in_player_box = [](int x, int y){ + return x >= W * 42 / 100 && x < W * 58 / 100 && y >= H * 30 / 100 && y < H * 75 / 100; + }; + auto difference = [&](int dx, int dy){ + uint64_t sum = 0; + size_t count = 0; + for (int y = REACH; y < H - REACH; y++){ + for (int x = REACH; x < W - REACH; x++){ + if (in_player_box(x, y)){ + continue; + } + const uint32_t p = a.pixel(x - dx, y - dy); + const uint32_t q = b.pixel(x, y); + for (int shift = 0; shift < 24; shift += 8){ + const int c = (int)((p >> shift) & 0xff) - (int)((q >> shift) & 0xff); + sum += c < 0 ? -c : c; + } + count += 3; + } + } + return (double)sum / (double)count; + }; + ViewShift best; + best.unshifted = difference(0, 0); + best.shifted = best.unshifted; + for (int dy = -REACH; dy <= REACH; dy++){ + for (int dx = -REACH; dx <= REACH; dx++){ + if (dx == 0 && dy == 0){ + continue; + } + const double d = difference(dx, dy); + if (d < best.shifted){ + best.shifted = d; + best.dx = dx; + best.dy = dy; + } + } + } + return best; +} + +bool tap_moved(const ImageViewRGB32& before, const ImageViewRGB32& after, double line){ + if (indoors(after)){ + return walk_screen_change(before, after) >= line; + } + return walk_view_shift(before, after).scrolled(); +} +} // namespace detail + + namespace{ // The battle's text box, held for 250ms. @@ -442,7 +507,11 @@ class WalkUntil{ m_before = std::move(after); return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } - const bool still = still_chunk(change); + // Taps count what scrolled the view, not scenery that moved (r84: + // cloud shadows read as steps). + const bool still = m_spec.input == WalkInput::TAPS + ? !tap_moved(*m_before.frame, *after.frame, still_line(change)) + : change < still_line(change); if (!still){ // A quiet tap and then a moving one: the first moved too. What // blocks a tap still blocks the next; the view barely changed @@ -464,12 +533,11 @@ class WalkUntil{ // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old // woman), over the fixed line of 16, so for taps "still" is also // anything under 40% of the walk's own steps. - bool still_chunk(double change){ + double still_line(double change){ m_largest = std::max(m_largest, change); - const double line = m_spec.input == WalkInput::TAPS + return m_spec.input == WalkInput::TAPS ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * m_largest) : WALK_BLOCKED_CHANGE; - return change < line; } // What hold()'s watcher `ret` saw (see after_watchers()). @@ -532,7 +600,7 @@ class WalkUntil{ ){ VideoSnapshot after = snapshot_or_fail(m_stream, m_spec.label); const double change = walk_screen_change(*m_before_still.frame, *after.frame); - if (!still_chunk(change)){ + if (tap_moved(*m_before_still.frame, *after.frame, still_line(change))){ m_result.moved_chunks++; } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h index acb7daf3b4..a5b0fe8c4f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h @@ -36,6 +36,47 @@ constexpr double WALK_TAP_BLOCKED_CHANGE = 16.0; // More than walking changes in 400ms: a new scene, such as a battle opening. constexpr double WALK_SCENE_CHANGE = 120.0; +namespace detail{ + +// How the view scrolled between two frames, on 192x108 copies: the shift +// (dx, dy) of `before` that best lines up with `after`, leaving out the +// middle where the player stands, and the mean difference per colour +// channel (0 to 255) with and without it. Outside, the camera follows the +// player, so a step scrolls everything one way; a TV, a conveyor, a +// passer-by or a cloud shadow changes part of the view with no common +// scroll. In r83's and r84's Floaroma video, frames 300 ms apart while +// standing (screen changes up to 57, cloud shadows, text boxes) never read +// as scrolled; walking read a shift 2 to 6 times better than none. +struct ViewShift{ + int dx = 0; + int dy = 0; + double unshifted = 0; + double shifted = 0; + + // A shift lines up at least twice as well as none, and none leaves a + // real difference. + bool scrolled() const; +}; + +// Calculates the view scroll shift between before and after images. +ViewShift walk_view_shift(const ImageViewRGB32& before, const ImageViewRGB32& after); + +// Whether the player moved between `before` and `after`, frames around a +// D-pad tap. Outside: only if the view scrolled. Inside, the camera can +// stay put while the player crosses a room (the house's 1F), so there a +// screen change of at least `line` counts, as it did before. +bool tap_moved(const ImageViewRGB32& before, const ImageViewRGB32& after, double line); + +} // namespace detail + +// View scroll shift calculation. +using detail::ViewShift; +// Calculates the view scroll shift between before and after images. +using detail::walk_view_shift; +// Whether the player moved between before and after frames. +using detail::tap_moved; + + // Whether two frames show different scenes: a change walking cannot make // (WALK_SCENE_CHANGE). UNKNOWN without both frames. Pokemon::SceneChange walk_scenes_differ(const Pokemon::TransitionSample& before, const Pokemon::TransitionSample& after); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp new file mode 100644 index 0000000000..2e11e5261b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp @@ -0,0 +1,77 @@ +/* BDSP RNG Aim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "PokemonBDSP_RngAim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +uint64_t aimed_advance(uint64_t press, uint64_t span, int64_t bias){ + int64_t advance = (int64_t)(press + span) + bias; + return advance < 0 ? 0 : (uint64_t)advance; +} + +int64_t press_for_advance(uint64_t target, uint64_t span, int64_t bias){ + return (int64_t)target - (int64_t)span - bias; +} + + +RngAim::RngAim(size_t minimum_samples, double threshold) + : m_minimum_samples(minimum_samples) + , m_threshold(threshold) +{} + +void RngAim::reset(){ + m_bias = 0; + m_offsets.clear(); +} + +bool RngAim::record_offset(Logger& logger, int64_t offset, bool enabled){ + m_offsets.emplace_back(offset); + if (!enabled || m_offsets.size() < m_minimum_samples){ + return false; + } + double mean = 0; + for (int64_t o : m_offsets){ + mean += (double)o; + } + mean /= (double)m_offsets.size(); + if (std::abs(mean) < m_threshold){ + return false; + } + int64_t shift = (int64_t)std::llround(mean); + if (shift == 0){ + return false; + } + m_bias += shift; + logger.log( + std::to_string(m_offsets.size()) + " measured attempt(s) average " + + tostr_fixed(mean, 2) + " advance(s) off, so the aim shifts by " + + std::to_string(shift) + " to " + std::to_string(m_bias) + ".", + COLOR_BLUE + ); + m_offsets.clear(); + return true; +} + +std::string RngAim::describe_correction() const{ + if (m_bias == 0){ + return ""; + } + return ", plus " + std::to_string(m_bias) + " measured"; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h new file mode 100644 index 0000000000..608f448315 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h @@ -0,0 +1,52 @@ +/* BDSP RNG Aim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngAim_H +#define PokemonAutomation_PokemonBDSP_RngAim_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The advance where a press will generate the target Pokemon +uint64_t aimed_advance(uint64_t press, uint64_t span, int64_t bias); + +// The press that would reach "target" through a schedule of a certain length +int64_t press_for_advance(uint64_t target, uint64_t span, int64_t bias); + + +class RngAim{ +public: + explicit RngAim(size_t minimum_samples = 3, double threshold = 1.0); + + int64_t bias() const{ return m_bias; } + + void reset(); + + bool record_offset(Logger& logger, int64_t offset, bool enabled); + + std::string describe_correction() const; + +private: + size_t m_minimum_samples; + double m_threshold; + + int64_t m_bias = 0; + std::vector m_offsets; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp new file mode 100644 index 0000000000..1e427daf5a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp @@ -0,0 +1,188 @@ +/* BDSP RNG Calibration + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_RngCalibration.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +NatureAdjustment bdsp_nature_adjustment(uint8_t nature, size_t stat_index){ + if (nature >= 25 || stat_index >= 5){ + return NatureAdjustment::NEUTRAL; + } + size_t raised = nature / 5; + size_t lowered = nature % 5; + if (raised == lowered){ + // Hardy, Docile, Serious, Bashful, Quirky. + return NatureAdjustment::NEUTRAL; + } + if (stat_index == raised){ + return NatureAdjustment::POSITIVE; + } + if (stat_index == lowered){ + return NatureAdjustment::NEGATIVE; + } + return NatureAdjustment::NEUTRAL; +} + + +// The nature index orders stats [Atk, Def, Spe, SpA, SpD]; +static const size_t NATURE_INDEX_ATTACK = 0; +static const size_t NATURE_INDEX_DEFENSE = 1; +static const size_t NATURE_INDEX_SPEED = 2; +static const size_t NATURE_INDEX_SPATK = 3; +static const size_t NATURE_INDEX_SPDEF = 4; + + +StatReads bdsp_expected_stats( + const BdspPokemonResult& generated, + const BaseStats& base_stats, + uint8_t level +){ + StatReads ret; + ret.hp = (int16_t)calc_stats_hp(base_stats.hp, level, generated.ivs.hp, 0); + ret.attack = (int16_t)calc_stats_nonhp( + base_stats.attack, level, generated.ivs.attack, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_ATTACK) + ); + ret.defense = (int16_t)calc_stats_nonhp( + base_stats.defense, level, generated.ivs.defense, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_DEFENSE) + ); + ret.spatk = (int16_t)calc_stats_nonhp( + base_stats.spatk, level, generated.ivs.spatk, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPATK) + ); + ret.spdef = (int16_t)calc_stats_nonhp( + base_stats.spdef, level, generated.ivs.spdef, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPDEF) + ); + ret.speed = (int16_t)calc_stats_nonhp( + base_stats.speed, level, generated.ivs.speed, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPEED) + ); + return ret; +} + + +bool advances_between( + const Xorshift128State& from, + const Xorshift128State& to, + uint64_t search_max, + uint64_t& advances +){ + Xorshift128 rng(from); + for (uint64_t c = 0; c <= search_max; c++){ + if (rng.state() == to){ + advances = c; + return true; + } + rng.next(); + } + return false; +} + + +const BaseStats& starter_base_stats(BdspStarter starter){ + // Order: HP, Atk, Def, SpA, SpD, Spe. + static const BaseStats TURTWIG {55, 68, 64, 45, 55, 31}; + static const BaseStats CHIMCHAR{44, 58, 44, 58, 44, 61}; + static const BaseStats PIPLUP {53, 51, 53, 61, 56, 40}; + switch (starter){ + case BdspStarter::Turtwig: return TURTWIG; + case BdspStarter::Chimchar: return CHIMCHAR; + case BdspStarter::Piplup: return PIPLUP; + } + return TURTWIG; +} + + +// A reading of -1 was not taken, so it rules nothing out. +static bool stat_fits(int16_t observed, int16_t expected){ + return observed < 0 || observed == expected; +} + + +bool consistent_with( + const BdspPokemonResult& generated, + const BdspObservedStarter& observed +){ + if (observed.nature != NatureCheckerValue::UnableToDetect + && bdsp_nature_to_checker_value(generated.nature) != observed.nature + ){ + return false; + } + if (observed.gender_known && generated.gender != observed.gender){ + return false; + } + if (observed.shiny_known && (generated.shiny != BdspShiny::None) != observed.shiny){ + return false; + } + + StatReads expected = bdsp_expected_stats(generated, observed.base_stats, observed.level); + return stat_fits(observed.stats.hp, expected.hp) + && stat_fits(observed.stats.attack, expected.attack) + && stat_fits(observed.stats.defense, expected.defense) + && stat_fits(observed.stats.spatk, expected.spatk) + && stat_fits(observed.stats.spdef, expected.spdef) + && stat_fits(observed.stats.speed, expected.speed); +} + + +BdspHitIdentification identify_hit_advance( + const Xorshift128State& state, + const BdspStaticTemplate& tmpl, + uint64_t intended_advance, + uint64_t radius, + const BdspObservedStarter& observed +){ + BdspHitIdentification ret; + + uint64_t first = intended_advance > radius ? intended_advance - radius : 0; + uint64_t last = intended_advance + radius; + + BdspStaticSearcher searcher(state, tmpl, 0); + + std::vector matches = searcher.scan( + first, last, + [&](const BdspPokemonResult& candidate){ return consistent_with(candidate, observed); } + ); + ret.candidates = matches.size(); + + if (ret.candidates == 0){ + ret.failure_reason = "no advance within " + std::to_string(radius) + + " of " + std::to_string(intended_advance) + + " produces that Pokemon. Either the recovered state was wrong, or the press " + "missed by more than the search covered."; + return ret; + } + if (ret.candidates > 1){ + ret.failure_reason = std::to_string(ret.candidates) + + " advances fit what was read ("; + for (size_t c = 0; c < matches.size(); c++){ + ret.failure_reason += (c == 0 ? "" : ", ") + std::to_string(matches[c].advances); + } + ret.failure_reason += "), so which one was hit cannot be told apart here."; + return ret; + } + + ret.success = true; + ret.advance = matches[0].advances; + ret.offset = (int64_t)ret.advance - (int64_t)intended_advance; + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h new file mode 100644 index 0000000000..8687e695de --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h @@ -0,0 +1,79 @@ +/* BDSP RNG Calibration + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngCalibration_H +#define PokemonAutomation_PokemonBDSP_RngCalibration_H + +#include +#include +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +Pokemon::NatureAdjustment bdsp_nature_adjustment(uint8_t nature, size_t stat_index); + +Pokemon::StatReads bdsp_expected_stats( + const Pokemon::BdspPokemonResult& generated, + const Pokemon::BaseStats& base_stats, + uint8_t level +); + +struct BdspObservedStarter{ + Pokemon::NatureCheckerValue nature = Pokemon::NatureCheckerValue::UnableToDetect; + Pokemon::BdspGender gender = Pokemon::BdspGender::Genderless; + bool gender_known = false; + Pokemon::StatReads stats; + Pokemon::BaseStats base_stats; + uint8_t level = 5; + bool shiny = false; + bool shiny_known = false; +}; + + +struct BdspHitIdentification{ + bool success = false; + uint64_t advance = 0; + int64_t offset = 0; + size_t candidates = 0; + std::string failure_reason; +}; + + +BdspHitIdentification identify_hit_advance( + const Pokemon::Xorshift128State& state, + const Pokemon::BdspStaticTemplate& tmpl, + uint64_t intended_advance, + uint64_t radius, + const BdspObservedStarter& observed +); + + +bool advances_between( + const Pokemon::Xorshift128State& from, + const Pokemon::Xorshift128State& to, + uint64_t search_max, + uint64_t& advances +); + + +const Pokemon::BaseStats& starter_base_stats(BdspStarter starter); + +bool consistent_with( + const Pokemon::BdspPokemonResult& generated, + const BdspObservedStarter& observed +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp new file mode 100644 index 0000000000..6827c5a889 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp @@ -0,0 +1,130 @@ +/* BDSP RNG Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_RngExecution.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +static size_t first_free_blink(const BdspTimelineContext& timeline){ + size_t before_blinks = 1 + (timeline.plus_one_on_menu_close ? 1 : 0) + + timeline.advance_delay + timeline.pokemon_models; + size_t last_waited = before_blinks + timeline.advance_delay_2_after_events - 1; + return last_waited + 1 + timeline.advance_delay_2; +} + + +static size_t timeline_depth(const BdspTimelineContext& timeline, size_t max_schedules){ + return first_free_blink(timeline) + 4 * max_schedules + 2; +} + +void schedule_span_bounds( + const BdspTimelineContext& timeline, size_t max_schedules, + uint64_t& lowest, uint64_t& highest +){ + lowest = first_free_blink(timeline) + 1 + timeline.advances_after_accept; + highest = timeline_depth(timeline, max_schedules) - 1 + timeline.advances_after_accept; +} + + +std::vector schedule_presses( + const Pokemon::Xorshift128State& state, + const BdspTimelineContext& timeline, + const NavigationTimings& timings, + uint64_t press, + size_t max_schedules +){ + std::vector schedules; + + size_t first_free = first_free_blink(timeline); + size_t last_waited = first_free - 1 - timeline.advance_delay_2; + + Pokemon::Xorshift128 rng(state); + rng.advance(press); + BdspTimelineResult simulated = simulate_timeline( + rng, timeline, timeline_depth(timeline, max_schedules) + ); + const std::vector& at = simulated.advance_times; + if (at.size() < first_free + 2){ + return schedules; + } + + // The second press goes between the last blink it waits for and the next. + double starly = (at[last_waited] + at[last_waited + 1]) / 2; + if (starly < timings.ready_seconds){ + return schedules; + } + double earliest_select = starly + timings.move_seconds; + + for (size_t blink = first_free; + blink + 1 < at.size() && schedules.size() < max_schedules; + blink++ + ){ + double gap_start = at[blink]; + double gap_end = at[blink + 1]; + + // Centred in the gap when there is room, pushed as late as the navigation + // demands when there is not. + double select_at = std::max( + (gap_start + gap_end - timings.prompt_seconds) / 2, earliest_select + ); + double confirm_at = select_at + timings.prompt_seconds; + if (select_at - gap_start < timings.guard_seconds + || gap_end - confirm_at < timings.guard_seconds + ){ + continue; + } + + schedules.push_back(PressSchedule{ + /*span*/ blink + 1 + timeline.advances_after_accept, + /*starly_seconds*/ starly, + /*select_seconds*/ select_at, + /*confirm_seconds*/ confirm_at, + /*blinks_before_confirm*/ blink + 1 - first_free, + }); + } + + return schedules; +} + + +bool wait_until_moment(ProControllerContext& context, Logger& logger, WallClock when){ + context.wait_for_all_requests(); + + WallClock now = current_time(); + if (when < now){ + double late = std::chrono::duration_cast>( + now - when + ).count(); + logger.log( + "The moment passed " + tostr_fixed(late, 3) + " seconds ago. " + "Abandoning the attempt rather than starting late.", + COLOR_ORANGE + ); + return false; + } + + Milliseconds wait = std::chrono::duration_cast(when - now); + pbf_wait(context, wait); + logger.log("Waiting " + std::to_string(wait.count()) + " ms for the timeline.", + COLOR_BLUE); + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h new file mode 100644 index 0000000000..c5ab0d7ebe --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h @@ -0,0 +1,59 @@ +/* BDSP RNG Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngExecution_H +#define PokemonAutomation_PokemonBDSP_RngExecution_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct PressSchedule{ + uint64_t span = 0; + double starly_seconds = 0; + double select_seconds = 0; + double confirm_seconds = 0; + uint64_t blinks_before_confirm = 0; +}; + +struct NavigationTimings{ + double ready_seconds = 0; + double move_seconds = 0; + double prompt_seconds = 0; + double guard_seconds = 0.30; +}; + + +void schedule_span_bounds( + const BdspTimelineContext& timeline, size_t max_schedules, + uint64_t& lowest, uint64_t& highest +); + +std::vector schedule_presses( + const Pokemon::Xorshift128State& state, + const BdspTimelineContext& timeline, + const NavigationTimings& timings, + uint64_t press, + size_t max_schedules +); + + +bool wait_until_moment(ProControllerContext& context, Logger& logger, WallClock when); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp new file mode 100644 index 0000000000..b0d9785d0a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp @@ -0,0 +1,155 @@ +/* BDSP RNG Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonBDSP_RngTargets.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +static BdspStaticTemplate starter_template(){ + BdspStaticTemplate ret; + ret.species = "starter"; + ret.level = 5; + ret.guaranteed_ivs = 0; + ret.ability_kind = 3; + ret.gender_ratio = 31; // Seven males to one female. + return ret; +} + +static BdspStaticTemplate legendary_template(const char* species, uint8_t level){ + BdspStaticTemplate ret; + ret.species = species; + ret.level = level; + ret.guaranteed_ivs = 3; + ret.ability_kind = 3; + ret.gender_ratio = 255; // Genderless. + return ret; +} + + +static const BdspRngTargetInfo& target_table(BdspRngTarget target){ + static const BdspRngTargetInfo STARTER{ + "starter", "Starter", + starter_template(), + BdspTimelineContext{ + /*npcs*/ 0, + /*pokemon_models*/ 2, + /*white_delay_seconds*/ 0.0, + /*advance_delay*/ 41, + /*advance_delay_2*/ 48, + /*advance_delay_2_after_events*/ 10, + /*plus_one_on_menu_close*/ false, + /*advances_after_accept*/ 65, + }, + /*observation_npcs*/ 2, + /*has_timeline*/ true, + }; + + static const BdspRngTargetInfo DIALGA{ + "dialga", "Dialga", + legendary_template("dialga", 47), + BdspTimelineContext{1, 1, 2.0, 0, 0, 10, false}, + /*observation_npcs*/ 1, + /*has_timeline*/ true, + }; + static const BdspRngTargetInfo PALKIA{ + "palkia", "Palkia", + legendary_template("palkia", 47), + BdspTimelineContext{1, 1, 2.0, 0, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo GIRATINA{ + "giratina", "Giratina", + legendary_template("giratina", 47), + BdspTimelineContext{1, 1, 2.0, 2, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo REGIROCK{ + "regirock", "Regirock", + legendary_template("regirock", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + static const BdspRngTargetInfo REGICE{ + "regice", "Regice", + legendary_template("regice", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + static const BdspRngTargetInfo REGISTEEL{ + "registeel", "Registeel", + legendary_template("registeel", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo CRESSELIA{ + "cresselia", "Cresselia", + [](){ + BdspStaticTemplate ret = legendary_template("cresselia", 50); + ret.gender_ratio = 254; // Always female. + ret.roamer = true; + return ret; + }(), + BdspTimelineContext{}, + 1, false, + }; + + static const BdspRngTargetInfo TRAINER_ID{ + "trainer-id", "Trainer ID / SID", + BdspStaticTemplate{}, + BdspTimelineContext{}, + /*observation_npcs*/ 0, + /*has_timeline*/ false, + }; + + switch (target){ + case BdspRngTarget::Starter: return STARTER; + case BdspRngTarget::Dialga: return DIALGA; + case BdspRngTarget::Palkia: return PALKIA; + case BdspRngTarget::Giratina: return GIRATINA; + case BdspRngTarget::Regirock: return REGIROCK; + case BdspRngTarget::Regice: return REGICE; + case BdspRngTarget::Registeel: return REGISTEEL; + case BdspRngTarget::Cresselia: return CRESSELIA; + case BdspRngTarget::TrainerId: return TRAINER_ID; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG target."); +} + +const BdspRngTargetInfo& bdsp_rng_target_info(BdspRngTarget target){ + return target_table(target); +} + + +const EnumDropdownDatabase& BdspRngTarget_Database(){ + static const EnumDropdownDatabase database{ + {BdspRngTarget::Starter, "starter", "Starter"}, + {BdspRngTarget::Dialga, "dialga", "Dialga"}, + {BdspRngTarget::Palkia, "palkia", "Palkia"}, + {BdspRngTarget::Giratina, "giratina", "Giratina"}, + {BdspRngTarget::Regirock, "regirock", "Regirock"}, + {BdspRngTarget::Regice, "regice", "Regice"}, + {BdspRngTarget::Registeel, "registeel", "Registeel"}, + {BdspRngTarget::Cresselia, "cresselia", "Cresselia"}, + {BdspRngTarget::TrainerId, "trainer-id", "Trainer ID / SID"}, + }; + return database; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h new file mode 100644 index 0000000000..f3f557f881 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h @@ -0,0 +1,52 @@ +/* BDSP RNG Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngTargets_H +#define PokemonAutomation_PokemonBDSP_RngTargets_H + +#include +#include +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspRngTarget{ + Starter, + Dialga, + Palkia, + Giratina, + Regirock, + Regice, + Registeel, + Cresselia, + TrainerId, +}; + + +struct BdspRngTargetInfo{ + const char* slug; + const char* display_name; + Pokemon::BdspStaticTemplate pokemon; + BdspTimelineContext timeline; + uint8_t observation_npcs; + bool has_timeline; +}; + + +const BdspRngTargetInfo& bdsp_rng_target_info(BdspRngTarget target); + +const EnumDropdownDatabase& BdspRngTarget_Database(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp new file mode 100644 index 0000000000..99d0dfee73 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp @@ -0,0 +1,140 @@ +/* BDSP RNG Timeline + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "PokemonBDSP_BlinkModel.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +enum class TimelineEventType : uint8_t{ + NpcTick = 0, + PokemonBlink = 1, +}; + +struct TimelineEvent{ + double time_seconds; + TimelineEventType type; + uint8_t index; + + // Member order is the tie-break + auto operator<=>(const TimelineEvent&) const = default; +}; + +using TimelineQueue = std::priority_queue< + TimelineEvent, std::vector, std::greater +>; + +} + + +static void spend_advances( + BdspTimelineResult& result, Xorshift128& rng, + double now_seconds, uint64_t count +){ + for (uint64_t c = 0; c < count; c++){ + rng.next(); + result.advance_times.emplace_back(now_seconds); + } +} + + +BdspTimelineResult simulate_timeline( + Xorshift128 rng, + const BdspTimelineContext& context, + uint64_t max_advances +){ + BdspTimelineResult result; + double now = 0.0; + + spend_advances(result, rng, now, 1); + if (context.plus_one_on_menu_close){ + spend_advances(result, rng, now, 1); + } + + now += context.white_delay_seconds; + + spend_advances(result, rng, now, context.advance_delay); + + TimelineQueue queue; + for (uint8_t c = 0; c < context.npcs; c++){ + queue.push(TimelineEvent{now + BDSP_NPC_TICK_SECONDS, TimelineEventType::NpcTick, c}); + } + for (uint8_t c = 0; c < context.pokemon_models; c++){ + double interval = bdsp_pokemon_blink_interval(rng.next()); + result.advance_times.emplace_back(now); + queue.push(TimelineEvent{now + interval, TimelineEventType::PokemonBlink, c}); + } + + uint64_t events_handled = 0; + bool second_delay_spent = false; + + while (result.advance_times.size() < max_advances){ + if (queue.empty()){ + result.end_state = rng.state(); + return result; + } + + TimelineEvent event = queue.top(); + queue.pop(); + now = event.time_seconds; + + if (context.advance_delay_2 != 0 + && !second_delay_spent + && events_handled >= context.advance_delay_2_after_events + ){ + spend_advances(result, rng, now, context.advance_delay_2); + second_delay_spent = true; + } + + switch (event.type){ + case TimelineEventType::NpcTick: + rng.next(); + result.advance_times.emplace_back(now); + event.time_seconds += BDSP_NPC_TICK_SECONDS; + break; + + case TimelineEventType::PokemonBlink: + event.time_seconds += bdsp_pokemon_blink_interval(rng.next()); + result.advance_times.emplace_back(now); + break; + } + + queue.push(event); + events_handled++; + } + + result.end_state = rng.state(); + result.reached_target = true; + return result; +} + + +bool time_of_advance(const BdspTimelineResult& result, uint64_t advance, double& seconds){ + if (advance >= result.advance_times.size()){ + return false; + } + seconds = result.advance_times[(size_t)advance]; + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h new file mode 100644 index 0000000000..17bfffa6c7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h @@ -0,0 +1,57 @@ +/* BDSP RNG Timeline + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngTimeline_H +#define PokemonAutomation_PokemonBDSP_RngTimeline_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP_BlinkModel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct BdspTimelineContext{ + uint8_t npcs = 1; + uint8_t pokemon_models = 0; + double white_delay_seconds = 0; + uint32_t advance_delay = 0; + uint32_t advance_delay_2 = 0; + uint32_t advance_delay_2_after_events = 10; + bool plus_one_on_menu_close = false; + uint32_t advances_after_accept = 0; +}; + + +struct BdspTimelineResult{ + std::vector advance_times; + Pokemon::Xorshift128State end_state; + bool reached_target = false; + uint64_t advances() const{ return advance_times.size(); } + double duration_seconds() const{ + return advance_times.empty() ? 0.0 : advance_times.back(); + } +}; + + +BdspTimelineResult simulate_timeline( + Pokemon::Xorshift128 rng, + const BdspTimelineContext& context, + uint64_t max_advances +); + +bool time_of_advance(const BdspTimelineResult& result, uint64_t advance, double& seconds); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp new file mode 100644 index 0000000000..e1eb1da88e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp @@ -0,0 +1,255 @@ +/* BDSP Starter Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +const Milliseconds AFTER_BRIEFCASE = 4000ms; +const Milliseconds PRE_BRIEFCASE_DURATION = 18200ms; +const Milliseconds PROMPT_ANIMATION = 1000ms; +const Milliseconds SCHEDULING_SLACK = 100ms; + + +uint8_t starter_cursor_steps(BdspStarter starter){ + switch (starter){ + case BdspStarter::Turtwig: return 0; + case BdspStarter::Chimchar: return 1; + case BdspStarter::Piplup: return 2; + } + return 0; +} + +const char* starter_slug(BdspStarter starter){ + switch (starter){ + case BdspStarter::Turtwig: return "turtwig"; + case BdspStarter::Chimchar: return "chimchar"; + case BdspStarter::Piplup: return "piplup"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + +// behind the house to the north +void navigate_bedroom_to_skip_spot(Logger& logger, ProControllerContext& context){ + logger.log("Leaving the bedroom for the spot where advances pass quickly."); + pbf_mash_button(context, BUTTON_B, 1000ms); // exit dialogue with the Switch + pbf_wait(context, 1000ms); + pbf_press_dpad(context, DPAD_RIGHT, 1200ms, 1500ms); + pbf_press_dpad(context, DPAD_DOWN, 2300ms, 500ms); + pbf_press_dpad(context, DPAD_LEFT, 1100ms, 1000ms); + pbf_press_dpad(context, DPAD_DOWN, 750ms, 4000ms); + pbf_press_dpad(context, DPAD_LEFT, 850ms, 1000ms); + pbf_press_dpad(context, DPAD_UP, 4100ms, 1000ms); + pbf_press_dpad(context, DPAD_RIGHT, 950ms, 500ms); + context.wait_for_all_requests(); +} + + +void navigate_skip_spot_to_lakefront(Logger& logger, ProControllerContext& context){ + logger.log("Walking from the skip spot to the lakefront."); + pbf_press_dpad(context, DPAD_LEFT, 1350ms, 500ms); + pbf_press_dpad(context, DPAD_UP, 5000ms, 0ms); + + // Clearing the dialogue with Barry + pbf_mash_button(context, BUTTON_B, 5000ms); + pbf_wait(context, 1000ms); + + pbf_press_dpad(context, DPAD_UP, 600ms, 1000ms); + pbf_press_dpad(context, DPAD_LEFT, 8500ms, 1000ms); + pbf_press_dpad(context, DPAD_UP, 1950ms, 1000ms); + context.wait_for_all_requests(); +} + + +void navigate_to_lake_blinks(Logger& logger, ProControllerContext& context){ + logger.log("Walking into the lake, then advancing to the lake blink position."); + pbf_move_left_joystick(context, {0.0, 1.0}, 1600ms, 0ms); + + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 4000ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 4500ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + context.wait_for_all_requests(); +} + +void navigate_to_pre_briefcase(Logger& logger, ProControllerContext& context){ + logger.log("Advancing to the pre-briefcase position."); + + // total duration equal to PRE_BRIEFCASE_DURATION (above) + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 3500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + context.wait_for_all_requests(); +} + + +const Milliseconds BRIEFCASE_PRESS_TO_STARLY_READY = + 80ms + AFTER_BRIEFCASE + 100ms; +const Milliseconds SELECT_PRESS_TO_CONFIRM_READY = + 80ms + PROMPT_ANIMATION + 100ms + 200ms; + +static Milliseconds starly_press_to_select_ready(BdspStarter starter){ + return 80ms + 5500ms + 100ms + 1200ms + + starter_cursor_steps(starter) * (100ms + 600ms); +} + + +// The whole blind button press sequence +bool issue_starter_sequence( + ProControllerContext& context, + BdspStarter starter, + double starly_seconds, + double select_seconds, + double confirm_seconds, + std::string& failure_reason +){ + auto to_ms = [](double seconds){ + return std::chrono::duration_cast( + std::chrono::duration(seconds) + ); + }; + + // Where the run stands after each fixed stretch, + // measured from the moment the briefcase press is completed + Milliseconds starly_at = to_ms(starly_seconds); + Milliseconds select_at = to_ms(select_seconds); + Milliseconds confirm_at = to_ms(confirm_seconds); + Milliseconds after_dialog = BRIEFCASE_PRESS_TO_STARLY_READY; + Milliseconds after_starly = starly_at + starly_press_to_select_ready(starter); + Milliseconds after_select = select_at + SELECT_PRESS_TO_CONFIRM_READY; + + auto too_tight = [&](const char* what, Milliseconds needed, Milliseconds have){ + failure_reason = std::string(what) + " is scheduled " + + std::to_string((needed - have).count()) + + " ms before the navigation ahead of it can finish"; + return false; + }; + if (starly_at < after_dialog){ + return too_tight("the Starly press", after_dialog, starly_at); + } + if (select_at < after_starly){ + return too_tight("the selecting press", after_starly, select_at); + } + if (confirm_at < after_select){ + return too_tight("the confirming press", after_select, confirm_at); + } + + // The briefcase press + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // Past the briefcase dialogue + pbf_wait(context, AFTER_BRIEFCASE); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + + // The Starly press + pbf_wait(context, starly_at - after_dialog); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // Open the briefcase and hover over the chosen ball + pbf_wait(context, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + pbf_wait(context, 1200ms); + for (uint8_t c = 0; c < starter_cursor_steps(starter); c++){ + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 600ms); + } + + // The selecting press, then the cursor onto "Yes" + pbf_wait(context, select_at - after_starly); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + pbf_wait(context, PROMPT_ANIMATION); + pbf_press_dpad(context, DPAD_UP, 100ms, 200ms); + + // The confirming press + pbf_wait(context, confirm_at - after_select); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // battle start + pbf_wait(context, 3000ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + + context.wait_for_all_requests(); + return true; +} + + +// Where the blind run leaves off. Feedback-driven, since nothing past the +// confirming press is timed against the RNG. +bool clear_starter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Mashing A through the battle."); + EndBattleWatcher battle_over; + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 180s); + }, + {{battle_over}} + ); + if (ret < 0){ + env.log("The battle never ended.", COLOR_RED); + return false; + } + env.log("Battle over."); + return true; +} + + +double seconds_to_move_to_starter(BdspStarter starter){ + return std::chrono::duration_cast>( + starly_press_to_select_ready(starter) - 80ms + ).count(); +} + +// kept as short as the prompt animation allows to avoid extra blinks from the starter +double seconds_from_select_to_confirm(){ + return std::chrono::duration_cast>( + SELECT_PRESS_TO_CONFIRM_READY + SCHEDULING_SLACK + ).count(); +} + + +double seconds_to_pre_briefcase(){ + return std::chrono::duration_cast>( + PRE_BRIEFCASE_DURATION + ).count(); +} + + +double seconds_from_briefcase_to_starly_ready(){ + return std::chrono::duration_cast>( + BRIEFCASE_PRESS_TO_STARLY_READY + ).count(); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h new file mode 100644 index 0000000000..dacda12b65 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h @@ -0,0 +1,102 @@ +/* BDSP Starter Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterNavigation_H +#define PokemonAutomation_PokemonBDSP_StarterNavigation_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStarter{ + Turtwig, + Chimchar, + Piplup, +}; + + +uint8_t starter_cursor_steps(BdspStarter starter); +const char* starter_slug(BdspStarter starter); + + +// Measured over 14 attempts spanning 40k to 734k advances, +/-0.01% +const double BDSP_SKIP_ADVANCES_PER_MINUTE = 19653; + +// Measured over the same attempts, +/-29 +const double BDSP_SKIP_NAVIGATION_ADVANCES = 6902; + +// How far short of the target to stop quickly skipping advances +const double BDSP_SKIP_BUFFER_BASE = 750; +const double BDSP_SKIP_BUFFER_PER_ADVANCE = 0.0002; +inline uint64_t bdsp_skip_buffer(double advances_skipped){ + return (uint64_t)(BDSP_SKIP_BUFFER_BASE + BDSP_SKIP_BUFFER_PER_ADVANCE * advances_skipped); +} + + +const double BDSP_SKIP_RATE_SIGMA = 0.0001; +const double BDSP_SKIP_SCATTER_SIGMA = 67; +inline double bdsp_skip_landing_sigma(double advances_skipped){ + double from_rate = BDSP_SKIP_RATE_SIGMA * advances_skipped; + return std::sqrt(from_rate * from_rate + BDSP_SKIP_SCATTER_SIGMA * BDSP_SKIP_SCATTER_SIGMA); +} + + +inline uint64_t bdsp_lake_advances_needed(double advances_skipped){ + return bdsp_skip_buffer(advances_skipped) + + (uint64_t)(2 * bdsp_skip_landing_sigma(advances_skipped)); +} + + +void navigate_bedroom_to_skip_spot(Logger& logger, ProControllerContext& context); + +void navigate_skip_spot_to_lakefront(Logger& logger, ProControllerContext& context); + + +void navigate_to_lake_blinks(Logger& logger, ProControllerContext& context); + +void navigate_to_pre_briefcase(Logger& logger, ProControllerContext& context); + + +bool issue_starter_sequence( + ProControllerContext& context, + BdspStarter starter, + double starly_seconds, + double select_seconds, + double confirm_seconds, + std::string& failure_reason +); + + +// Mash A until the battle with the wild Starly is over. +bool clear_starter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +double seconds_to_move_to_starter(BdspStarter starter); + + +double seconds_from_select_to_confirm(); + + +double seconds_from_briefcase_to_starly_ready(); + + +double seconds_to_pre_briefcase(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp new file mode 100644 index 0000000000..1d19e14261 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp @@ -0,0 +1,207 @@ +/* BDSP Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" +#include "PokemonBDSP_StarterRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const size_t CALIBRATION_MIN_SAMPLES = 3; +const double CALIBRATION_THRESHOLD = 1.0; + + +StarterRng_Descriptor::StarterRng_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:StarterRng", + STRING_POKEMON + " BDSP", "Starter RNG", + "", + "Starter RNG manipulation using blinks.", + PanelQualityStanding::OFFICIAL_BETA, + ProgramControllerClass::StandardController_RequiresPrecision, + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS + ) +{} + +std::unique_ptr StarterRng_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +StarterRng::StarterRng() + : m_aim(CALIBRATION_MIN_SAMPLES, CALIBRATION_THRESHOLD) + , LANGUAGE( + "Game Language:", + summary_nature_languages(), + LockMode::LOCK_WHILE_RUNNING, true + ) + , START_POINT( + "Start point:
" + "Where you have saved your game. Starting from the bedroom allows the possibility to skip advances quickly.", + { + {BdspStartPoint::Lakefront, "lakefront", "Verity Lakefront"}, + {BdspStartPoint::Bedroom, "bedroom", "Bedroom"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BdspStartPoint::Lakefront + ) + , STARTER( + "Starter:
", + { + {BdspStarter::Turtwig, "turtwig", "Turtwig"}, + {BdspStarter::Chimchar, "chimchar", "Chimchar"}, + {BdspStarter::Piplup, "piplup", "Piplup"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BdspStarter::Turtwig + ) + , FILTERS( + "Stop Conditions:
" + "If the " + STRING_POKEMON + " matches any one of these filters, the program will " + "stop.
", + StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , COLLECTION_DISPLAY(true) + , MAX_RESETS( + "Maximum resets:
" + "Set this to zero to keep going until a shiny is caught.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 1000 + ) + , MAX_TARGET_WAIT_MINUTES( + "Wait at most (minutes) for a target:
" + "Time limit for waiting at Verity Lake. Rarer targets will require longer " + "wait times.", + LockMode::LOCK_WHILE_RUNNING, + 30, 5, 1440 + ) + , MAX_SKIP_MINUTES( + "Skip at most (minutes):
" + "Time limit for skipping advances in Twinleaf Town.", + LockMode::LOCK_WHILE_RUNNING, + 30, 5, 1440 + ) + , AUTO_CALIBRATE( + "Correct the timing automatically:
" + "Shift the target advances when several attempts miss.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , USE_SOUND_DETECTION( + "Use sound detection:", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TAKE_VIDEO( + "Take Video:
" + "Record a video when the shiny is found.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + set_default_shiny_row(FILTERS); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(PLAYER_MODEL); + PA_ADD_OPTION(START_POINT); + PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(FILTERS); + PA_ADD_OPTION(COLLECTION_DISPLAY); + PA_ADD_OPTION(STATE_DISPLAY); + PA_ADD_OPTION(TARGET_DISPLAY); + PA_ADD_OPTION(MAX_RESETS); + PA_ADD_OPTION(MAX_TARGET_WAIT_MINUTES); + PA_ADD_OPTION(MAX_SKIP_MINUTES); + PA_ADD_OPTION(AUTO_CALIBRATE); + PA_ADD_OPTION(USE_SOUND_DETECTION); + PA_ADD_OPTION(TAKE_VIDEO); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); + + START_POINT.add_listener(*this); + StarterRng::on_config_value_changed(this); +} + + +void StarterRng::on_config_value_changed(void*){ + MAX_SKIP_MINUTES.set_visibility( + START_POINT == BdspStartPoint::Bedroom + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN + ); +} + + +void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StarterRng_Descriptor::Stats& stats = env.current_stats(); + + require_player(env.console, context, BUTTON_B); + + m_aim.reset(); + + BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); + StarterRngSettings settings{ + .language = LANGUAGE, + .player_model = PLAYER_MODEL.model_number(), + .start_point = START_POINT, + .starter = STARTER, + .wanted = [&filters](const BdspPokemonResult& result){ + return starter_wanted(filters, result); + }, + .filters = &filters, + .max_resets = MAX_RESETS, + .max_target_wait_minutes = MAX_TARGET_WAIT_MINUTES, + .max_skip_minutes = MAX_SKIP_MINUTES, + .auto_calibrate = AUTO_CALIBRATE, + .use_sound_detection = USE_SOUND_DETECTION, + .take_video = TAKE_VIDEO, + .reset_first = false, + .finish_battle_on_shiny = false, + .close_summary_after_read = false, + }; + StarterRngAttemptIO io{ + .collection_display = &COLLECTION_DISPLAY, + .state_display = &STATE_DISPLAY, + .target_display = &TARGET_DISPLAY, + .notification_shiny = &NOTIFICATION_SHINY, + .notification_error = &NOTIFICATION_ERROR_RECOVERABLE, + .stats = &stats, + }; + + run_starter_rng_attempts(env, context, settings, io, m_aim); + + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h new file mode 100644 index 0000000000..ba081486b2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h @@ -0,0 +1,82 @@ +/* BDSP Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRng_H +#define PokemonAutomation_PokemonBDSP_StarterRng_H + +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngDisplays.h" +#include "PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_StarterRngAttempts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StarterRng_Descriptor(); + + using Stats = StarterRngStats; + virtual std::unique_ptr make_stats() const override; +}; + + +class StarterRng : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + using Descriptor = StarterRng_Descriptor; + StarterRng(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + RngAim m_aim; + +private: + OCR::LanguageOCROption LANGUAGE; + PlayerModelOption PLAYER_MODEL; + EnumDropdownOption START_POINT; + EnumDropdownOption STARTER; + + BdspRngFilterTable FILTERS; + + BlinkCollectionDisplay COLLECTION_DISPLAY; + RngStateDisplay STATE_DISPLAY; + RngTargetDisplay TARGET_DISPLAY; + + SimpleIntegerOption MAX_RESETS; + SimpleIntegerOption MAX_TARGET_WAIT_MINUTES; + SimpleIntegerOption MAX_SKIP_MINUTES; + + BooleanCheckBoxOption AUTO_CALIBRATE; + + BooleanCheckBoxOption USE_SOUND_DETECTION; + BooleanCheckBoxOption TAKE_VIDEO; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp new file mode 100644 index 0000000000..472708f58f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -0,0 +1,767 @@ +/* BDSP Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_BlinkScenes.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP_BlinkRecovery.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_RngTargets.h" +#include "PokemonBDSP_RngTimeline.h" +#include "PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_SummaryNavigation.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +const size_t LAKE_BLINKS_PRESS_RETRIES = 10; + +const double GAP_GUARD_SECONDS = 0.30; + +const uint64_t HIT_SEARCH_RADIUS = 20; +const size_t MAX_SCHEDULES = 8; + +const uint64_t SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE = 200000; + + +std::function resolve_wanted_predicate( + const StarterRngSettings& settings +){ + if (settings.wanted){ + return settings.wanted; + } + if (settings.filters != nullptr){ + const BdspRngFilterSnapshot* filters = settings.filters; + return [filters](const BdspPokemonResult& result){ + return starter_wanted(*filters, result); + }; + } + return [](const BdspPokemonResult& result){ + return result.shiny != BdspShiny::None; + }; +} + + +BdspSkipResult skip_advances_from_bedroom( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const std::function& wanted_fn, + BlinkCollectionDisplay& collection_display, + RngStateDisplay& state_display, + RngTargetDisplay& target_display +){ + BdspSkipResult skip; + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + // Expected wait duration at the lake after a long skip + double longest_skip = settings.max_skip_minutes * BDSP_SKIP_ADVANCES_PER_MINUTE; + double lake_minutes = bdsp_lake_advances_needed(longest_skip) + * BDSP_NPC_TICK_SECONDS / (target_info.observation_npcs * 60.0); + if (lake_minutes > settings.max_target_wait_minutes){ + throw UserSetupError(env.logger(), + "A skip of up to " + std::to_string(settings.max_skip_minutes) + + " minutes can leave up to " + + tostr_fixed(lake_minutes, 1) + " minutes of waiting at the lake, but the target " + "wait is capped at " + std::to_string(settings.max_target_wait_minutes) + + ". Raise the target wait to at least " + + std::to_string((uint16_t)std::ceil(lake_minutes)) + + " minutes, or lower the skip limit." + ); + } + + env.log("Starting in the bedroom."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); // open dialogue box + context.wait_for_all_requests(); + + std::vector setups = bedroom_eye_templates(settings.player_model); + std::vector eyes = load_eye_templates(setups); + + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig bedroom_config; + bedroom_config.npcs = 1; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, collection_display, bedroom_config + ); + if (!recovery.success){ + skip.failure_reason = "could not determine the RNG state in the bedroom: " + + recovery.failure_reason; + return skip; + } + skip.state = recovery.state; + env.log("Bedroom RNG state: " + recovery.state.to_string(), COLOR_BLUE); + state_display.set_state(recovery.state, recovery.clock.anchor_advance); + state_display.set_confidence_unique(); + + // take into account remaining navigation time and the desired buffer + uint64_t soonest = recovery.clock.advance_at(current_time()) + + (uint64_t)BDSP_SKIP_NAVIGATION_ADVANCES + bdsp_skip_buffer(0); + uint64_t furthest = soonest + + (uint64_t)(settings.max_skip_minutes * BDSP_SKIP_ADVANCES_PER_MINUTE); + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + std::vector hits = searcher.scan( + soonest, furthest, + wanted_fn, + true, &context + ); + if (hits.empty()){ + skip.failure_reason = "no target within " + std::to_string(settings.max_skip_minutes) + + " minutes of skipping"; + return skip; + } + const BdspRngHit& hit = hits[0]; + skip.target_advance = hit.advances; + target_display.set_target(hit.result, hit.advances); + + uint64_t start = recovery.clock.advance_at(current_time()); + + // The buffer depends on how far the skip runs, so size it from the raw distance. + double raw_skip = (double)hit.advances - (double)start - BDSP_SKIP_NAVIGATION_ADVANCES; + uint64_t buffer = bdsp_skip_buffer(raw_skip); + double to_skip = raw_skip - (double)buffer; + if (to_skip < 0){ + to_skip = 0; + } + double wait_seconds = to_skip * 60 / BDSP_SKIP_ADVANCES_PER_MINUTE; + skip.buffer = buffer; + + env.log("Target advance " + std::to_string(hit.advances) + ": " + hit.result.to_string(), + COLOR_BLUE); + env.log("Skipping " + std::to_string((uint64_t)to_skip) + " advances from " + + std::to_string(start) + ", which is " + tostr_fixed(wait_seconds, 1) + + "s on the spot, stopping " + std::to_string(buffer) + + " advances short to avoid overshooting.", COLOR_BLUE); + + navigate_bedroom_to_skip_spot(env.logger(), context); + + WallClock leave_at = current_time() + std::chrono::duration_cast( + std::chrono::duration(wait_seconds) + ); + + while (current_time() + 2s < leave_at){ + WallClock now = current_time(); + WallClock until = std::min(leave_at - 2s, now + 180s); + pbf_wait(context, std::chrono::duration_cast(until - now)); + context.wait_for_all_requests(); + } + WallClock now = current_time(); + if (now < leave_at){ + pbf_wait(context, std::chrono::duration_cast(leave_at - now)); + context.wait_for_all_requests(); + } + + navigate_skip_spot_to_lakefront(env.logger(), context); + skip.success = true; + return skip; +} + + +void report_skip_arrival( + SingleSwitchProgramEnvironment& env, + const BdspSkipResult& skip, + const BlinkRecovery& arrival +){ + // Generous enough to catch an overshoot, and a match is unique anyway. + uint64_t search_max = skip.target_advance + SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE; + uint64_t travelled = 0; + if (!advances_between(skip.state, arrival.state, search_max, travelled)){ + env.log( + "Could not place the lake state against the bedroom one, so the skip " + "cannot be measured this attempt.", + COLOR_ORANGE + ); + return; + } + + uint64_t here = travelled + arrival.clock.advance_at(current_time()); + int64_t short_by = (int64_t)skip.target_advance - (int64_t)here; + env.log( + "Skip landed on advance " + std::to_string(here) + " of " + + std::to_string(skip.target_advance) + ": " + + (short_by >= 0 + ? std::to_string(short_by) + " short, aimed for " + std::to_string(skip.buffer) + : "OVERSHOT by " + std::to_string(-short_by)), + short_by >= 0 ? COLOR_BLUE : COLOR_ORANGE + ); +} + +} // namespace + + +StarterRngStats::StarterRngStats() + : resets(m_stats["Resets"]) + , missed(m_stats["Missed"]) + , hits(m_stats["Hit"]) + , shinies(m_stats["Shiny"]) + , errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back(Stat("Missed", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Hit", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Shiny", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Errors", HIDDEN_IF_ZERO)); +} + + +bool starter_wanted( + const BdspRngFilterSnapshot& filters, + const BdspPokemonResult& pokemon +){ + auto exactly = [](uint8_t iv){ + return IvRange{(int8_t)iv, (int8_t)iv}; + }; + IvRanges ivs; + ivs.hp = exactly(pokemon.ivs.hp); + ivs.attack = exactly(pokemon.ivs.attack); + ivs.defense = exactly(pokemon.ivs.defense); + ivs.spatk = exactly(pokemon.ivs.spatk); + ivs.spdef = exactly(pokemon.ivs.spdef); + ivs.speed = exactly(pokemon.ivs.speed); + + StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; + switch (pokemon.gender){ + case BdspGender::Male: + gender = StatsHuntGenderFilter::Male; + break; + case BdspGender::Female: + gender = StatsHuntGenderFilter::Female; + break; + default: + break; + } + + return filters.get_action( + pokemon.shiny != BdspShiny::None, + gender, + bdsp_nature_to_checker_value(pokemon.nature), + pokemon.height, + ivs + ) != StatsHuntAction::Discard; +} + + +bool resolve_starter_rng_step( + const BdspStarterAttemptResult& attempt, + uint64_t resets_used, + uint16_t max_resets, + StarterRngRunResult& result +){ + result.resets_used = resets_used; + if (attempt.target_advance != 0){ + result.target = attempt.target; + result.target_advance = attempt.target_advance; + } + if (!attempt.failure_reason.empty()){ + result.last_failure_reason = attempt.failure_reason; + } + + if (attempt.outcome == BdspAttemptOutcome::Hit){ + result.settled = attempt.settled; + result.outcome = attempt.shiny + ? StarterRngOutcome::SHINY + : StarterRngOutcome::HIT; + return true; + } + + if (max_resets != 0 && resets_used >= max_resets){ + result.outcome = attempt.outcome == BdspAttemptOutcome::Abandoned + ? StarterRngOutcome::ABANDONED + : StarterRngOutcome::OUT_OF_RESETS; + return true; + } + + return false; +} + + +// Leaves the game as the settings ask after a shiny: battle finished and, if +// asked, the starter summary read and the menu closed. False if a step failed. +static bool settle_after_shiny( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngSettings& settings +){ + if (!settings.finish_battle_on_shiny){ + return true; + } + if (!clear_starter_battle(env, context)){ + return false; + } + if (settings.close_summary_after_read){ + if (!open_menu(env, context)){ + return false; + } + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + } + return true; +} + +BdspStarterAttemptResult run_starter_rng_attempt( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +){ + BlinkCollectionDisplay fallback_collection(true); + RngStateDisplay fallback_state; + RngTargetDisplay fallback_target; + + BlinkCollectionDisplay& collection_display = io.collection_display != nullptr + ? *io.collection_display + : fallback_collection; + RngStateDisplay& state_display = io.state_display != nullptr + ? *io.state_display + : fallback_state; + RngTargetDisplay& target_display = io.target_display != nullptr + ? *io.target_display + : fallback_target; + + collection_display.reset(); + state_display.reset(); + target_display.reset(); + + auto record_miss = [&](){ + if (io.stats != nullptr){ + io.stats->missed++; + } + if (io.on_miss){ + io.on_miss(); + } + }; + auto record_hit = [&](){ + if (io.stats != nullptr){ + io.stats->hits++; + } + if (io.on_hit){ + io.on_hit(); + } + }; + auto record_shiny = [&](){ + if (io.stats != nullptr){ + io.stats->shinies++; + } + if (io.on_shiny){ + io.on_shiny(); + } + }; + auto record_error = [&](){ + if (io.stats != nullptr){ + io.stats->errors++; + } + if (io.on_error){ + io.on_error(); + } + }; + + auto abandon = [&](const std::string& reason) -> BdspStarterAttemptResult{ + env.log("Abandoning this attempt: " + reason, COLOR_ORANGE); + target_display.set_note(reason); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Abandoned, + .failure_reason = reason, + }; + }; + + std::function wanted_fn = resolve_wanted_predicate(settings); + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + BdspSkipResult skip; + if (settings.start_point == BdspStartPoint::Bedroom){ + skip = skip_advances_from_bedroom( + env, context, settings, wanted_fn, + collection_display, state_display, target_display + ); + if (!skip.success){ + return abandon(skip.failure_reason); + } + } + + navigate_to_lake_blinks(env.logger(), context); + + std::vector setups = lake_eye_templates(settings.player_model); + std::vector eyes = load_eye_templates(setups); + + // The rival's dialogue box being up is what says the pair have stopped walking. + ShortDialogDetector dialog; + BlinkSceneConfig scene; + scene.frame_filter = [&dialog](const ImageViewRGB32& frame){ + return dialog.detect(frame); + }; + scene.press_retries = LAKE_BLINKS_PRESS_RETRIES; + + if (!wait_for_blink_scene(env, context, setups, eyes, scene, "Lake blinks")){ + return abandon("never reached the lake blink position"); + } + + // Now blink watchers can be created safely + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig blink_config; + blink_config.npcs = target_info.observation_npcs; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, collection_display, blink_config + ); + if (!recovery.success){ + return abandon("could not determine the RNG state: " + recovery.failure_reason); + } + + uint64_t seed0 = 0; + uint64_t seed1 = 0; + xorshift128_state_to_seed_pair(recovery.state, seed0, seed1); + env.log("RNG state: " + recovery.state.to_string(), COLOR_BLUE); + env.log("PokeFinder seeds: " + tostr_hex_padded(16, seed0) + + " " + tostr_hex_padded(16, seed1), COLOR_BLUE); + env.log("Tick fitted at " + tostr_default(recovery.clock.tick_seconds) + "s over " + + std::to_string(recovery.events) + " rolls.", COLOR_BLUE); + env.log("Anchored on advance " + std::to_string(recovery.clock.anchor_advance) + + "; now at advance " + std::to_string(recovery.clock.advance_at(current_time())) + + ".", COLOR_BLUE); + state_display.set_state(recovery.state, recovery.clock.anchor_advance); + state_display.set_confidence_unique(); + + if (skip.success){ + report_skip_arrival(env, skip, recovery); + } + + const BdspTimelineContext& timeline = target_info.timeline; + + NavigationTimings timings; + timings.ready_seconds = seconds_from_briefcase_to_starly_ready(); + timings.move_seconds = seconds_to_move_to_starter(settings.starter) + 0.25; // small buffer + timings.prompt_seconds = seconds_from_select_to_confirm(); + timings.guard_seconds = GAP_GUARD_SECONDS; + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + + // A press cannot be sooner than the walk to the pre-briefcase position takes + double lead_seconds = seconds_to_pre_briefcase() + 15; + uint64_t lead_advances = (uint64_t)( + lead_seconds * recovery.clock.npcs / recovery.clock.tick_seconds + ) + 1; + + TargetSearchRequest search; + search.state = recovery.state; + search.timeline = timeline; + search.timings = timings; + search.pokemon = target_info.pokemon; + search.npcs = recovery.clock.npcs; + search.tick_seconds = recovery.clock.tick_seconds; + search.bias = aim.bias(); + search.first_press = recovery.clock.advance_at(current_time()) + lead_advances; + search.window_advances = (uint64_t)( + (double)settings.max_target_wait_minutes * 60 * recovery.clock.npcs / recovery.clock.tick_seconds + ); + search.max_schedules = MAX_SCHEDULES; + search.wanted = wanted_fn; + + TargetSelectionResult selection = select_target(search); + + if (selection.matches_found != 0){ + env.log( + std::to_string(selection.matches_found) + " matching advance(s) in " + + std::to_string(selection.advances_scanned), + COLOR_BLUE + ); + } + if (!selection.success){ + return abandon(selection.failure_reason); + } + + uint64_t press_advance = selection.press_advance; + uint64_t target_advance = selection.target_advance; + const PressSchedule& schedule = selection.schedule; + const BdspPokemonResult& target = selection.target; + + double wait_seconds = std::chrono::duration_cast>( + recovery.clock.time_of_advance(press_advance) - current_time() + ).count(); + env.log("Target advance " + std::to_string(target_advance) + ": " + target.to_string(), + COLOR_BLUE); + env.log("Pressing at advance " + std::to_string(press_advance) + ", in " + + tostr_default(wait_seconds) + "s.", COLOR_BLUE); + env.log("Schedule spans " + std::to_string(schedule.span) + " advances, confirming after " + + std::to_string(schedule.blinks_before_confirm) + " Starly blink(s), " + + tostr_default(schedule.confirm_seconds) + "s in" + + aim.describe_correction() + ".", COLOR_BLUE); + target_display.set_target(target, target_advance); + + hold_and_reanchor( + env, context, watchers, callbacks, recovery, blink_config, + press_advance, lead_seconds, state_display + ); + + navigate_to_pre_briefcase(env.logger(), context); + + // FIRST PRESS, centred in the advance rather than aimed right at the beginning of it + WallClock briefcase_time = recovery.clock.middle_of_advance(press_advance); + + while (current_time() + 3s < briefcase_time){ + state_display.set_advances(recovery.clock.advance_at(current_time())); + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + } + + state_display.set_advances(press_advance); + + env.log("Timeline starts at advance " + std::to_string(press_advance) + + ". Blind from here: Starly press at " + tostr_default(schedule.starly_seconds) + + "s, selecting at " + tostr_default(schedule.select_seconds) + + "s, confirming at " + tostr_default(schedule.confirm_seconds) + + "s, on advance " + std::to_string(target_advance - timeline.advances_after_accept) + + ".", COLOR_BLUE); + + std::string sequence_failure; + if (!wait_until_moment(context, env.logger(), briefcase_time)){ + return abandon("the briefcase press moment passed before it could be sent"); + } + if (!issue_starter_sequence( + context, settings.starter, + schedule.starly_seconds, schedule.select_seconds, schedule.confirm_seconds, + sequence_failure + )){ + return abandon(sequence_failure); + } + env.log("Timeline finished; the starter should be in hand.", COLOR_BLUE); + + state_display.set_advances(target_advance); + + // Check what was actually obtained. + DoublesShinyDetection wild; + ShinyDetectionResult own; + detect_shiny_battle( + env, env.console, context, + wild, own, + io.notification_error != nullptr ? *io.notification_error : EventNotificationOption_NOOP(), + YOUR_POKEMON, + 30s, + settings.use_sound_detection + ); + bool shiny_known = own.shiny_type != ShinyType::UNKNOWN; + + if (is_likely_shiny(own.shiny_type)){ + record_shiny(); + if (io.notification_shiny != nullptr){ + send_program_notification( + env, *io.notification_shiny, + COLOR_STAR_SHINY, "Shiny Starter", + {{"Advance", std::to_string(target_advance)}, {"Details", target.to_string()}}, + "", own.get_best_screenshot() + ); + } + if (settings.take_video){ + pbf_wait(context, 5000ms); + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); + context.wait_for_all_requests(); + } + const bool settled = settle_after_shiny(env, context, settings); + if (!settled){ + record_error(); + } + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = true, + .target = target, + .target_advance = target_advance, + .settled = settled, + }; + } + + BdspObservedStarter observed; + if (!clear_starter_battle(env, context) + || !read_observed_pokemon( + env, context, settings.language, + starter_base_stats(settings.starter), 5, false, shiny_known, observed + ) + ){ + record_error(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Unverifiable, + .shiny = false, + .target = target, + .target_advance = target_advance, + .failure_reason = "could not verify the obtained starter", + }; + } + + if (settings.close_summary_after_read){ + if (!close_starter_summary(env, context)){ + record_error(); + } + } + + BdspHitIdentification hit = identify_hit_advance( + recovery.state, target_info.pokemon, target_advance, HIT_SEARCH_RADIUS, observed + ); + if (!hit.success){ + env.log("Could not tell which advance that was: " + hit.failure_reason, COLOR_ORANGE); + if (consistent_with(target, observed)){ + env.log("What was read matches the target, so it counts as a hit.", COLOR_BLUE); + record_hit(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; + } + env.log("What was read is not the target, so it counts as a miss.", COLOR_ORANGE); + record_miss(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = target, + .target_advance = target_advance, + .failure_reason = hit.failure_reason, + }; + } + if (aim.record_offset(env.logger(), hit.offset, settings.auto_calibrate)){ + target_display.set_correction(aim.bias()); + } + + if (hit.offset == 0){ + env.log("Landed on advance " + std::to_string(target_advance) + ", as aimed.", + COLOR_BLUE); + record_hit(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; + } + + env.log( + "Landed on advance " + std::to_string(hit.advance) + " instead of " + + std::to_string(target_advance) + " — " + + (hit.offset > 0 ? "late by " : "early by ") + + std::to_string(hit.offset > 0 ? hit.offset : -hit.offset) + " advance(s).", + COLOR_ORANGE + ); + record_miss(); + + BdspPokemonResult actual = searcher.generate(hit.advance); + if (wanted_fn(actual)){ + env.log("It passes the filter anyway, so this one will do. Stopping.", COLOR_BLUE); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = actual, + .target_advance = hit.advance, + }; + } + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; +} + + +StarterRngRunResult run_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +){ + StarterRngRunResult result; + bool reset = settings.reset_first; + uint64_t resets = 0; + BdspStarterAttemptResult last_attempt; + + while (true){ + if (settings.max_resets != 0 && resets >= settings.max_resets){ + env.log("Reached the reset limit.", COLOR_ORANGE); + resolve_starter_rng_step(last_attempt, resets, settings.max_resets, result); + break; + } + resets++; + + bool started = true; + if (reset){ + go_home(env.console, context); + if (!reset_game_from_home( + env, env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + )){ + started = false; + } + } + + if (started){ + reset = true; + last_attempt = run_starter_rng_attempt(env, context, settings, io, aim); + }else{ + last_attempt = BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Abandoned, + .failure_reason = "failed to reset the game from the Home screen", + }; + } + + if (io.stats != nullptr){ + io.stats->resets++; + } + if (io.on_reset){ + io.on_reset(); + } + env.update_stats(); + + if (last_attempt.outcome == BdspAttemptOutcome::Hit){ + resolve_starter_rng_step(last_attempt, resets, settings.max_resets, result); + break; + } + if (!last_attempt.failure_reason.empty()){ + result.last_failure_reason = last_attempt.failure_reason; + } + result.resets_used = resets; + if (last_attempt.target_advance != 0){ + result.target = last_attempt.target; + result.target_advance = last_attempt.target_advance; + } + } + + env.update_stats(); + return result; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h new file mode 100644 index 0000000000..1e88d9b277 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h @@ -0,0 +1,216 @@ +/* BDSP Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRngAttempts_H +#define PokemonAutomation_PokemonBDSP_StarterRngAttempts_H + +#include +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngDisplays.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStartPoint{ + Lakefront, + Bedroom, +}; + + +struct BdspSkipResult{ + bool success = false; + Pokemon::Xorshift128State state; + uint64_t target_advance = 0; + uint64_t buffer = 0; + std::string failure_reason; +}; + + +enum class BdspAttemptOutcome{ + Abandoned, + Missed, + Hit, + Unverifiable, +}; + + +struct StarterRngStats : public StatsTracker{ + StarterRngStats(); + + std::atomic& resets; + std::atomic& missed; + std::atomic& hits; + std::atomic& shinies; + std::atomic& errors; +}; + + +// Evaluates whether a generated starter satisfies the filter snapshot. +// Takes a snapshot rather than the table because scanning millions of +// advances cannot afford cloning the table on every query. +bool starter_wanted( + const BdspRngFilterSnapshot& filters, + const Pokemon::BdspPokemonResult& pokemon +); + + +// Settings for a Starter RNG attempt loop. +// +// In-game state traversal after the starter is chosen and the wild Starly +// battle begins at Lake Verity: +// - Shiny hit (`Outcome::SHINY`): +// `detect_shiny_battle(...)` finishes at the start of the Starly battle. +// * When `finish_battle_on_shiny == false` (standalone `StarterRng` default): +// returns immediately while still inside the Starly battle at Lake Verity. +// * When `finish_battle_on_shiny == true` (for AutoStory): +// calls `clear_starter_battle(env, context)`, which mashes A until +// `EndBattleWatcher` detects the black-screen battle exit transition, and +// when `close_summary_after_read == true` also advances through Rowan's +// post-battle scene (`open_menu`) to `VerityLakefront (17, 14..15)` and +// closes the X menu so both `SHINY` and `HIT` end on the `VerityLakefront` +// overworld ready for checkpoint `00.03`. +// - Non-shiny starter (`clear_starter_battle` + `read_observed_pokemon`): +// 1. `clear_starter_battle(env, context)` mashes A until `EndBattleWatcher` +// detects the end of the Starly battle. +// 2. `read_observed_pokemon(...)` calls `open_menu(env, context)`, which +// mashes `B, B, X` until `MenuWatcher` detects the overworld X menu. +// Because the X menu cannot open during the post-battle Lake Verity +// cutscene or the warp out of the lake, `open_menu` advances through +// all of Rowan's and Barry's post-battle dialogue (`after_starly`) and +// the warp back to `VerityLakefront (17, 14..15)`, then opens the X menu +// once the player has overworld control on `VerityLakefront`. +// 3. `open_starter_summary(env, context)` selects `POKEMON` (one entry left +// on the 2-icon pre-Pokedex X menu), opens the starter's Summary screen, +// reads Nature & Gender on the 2nd tab (Trainer Memo), and presses Right +// to read the 6 stats on the 3rd tab (Skills/Stats). +// * When `close_summary_after_read == false` (standalone `StarterRng` default): +// leaves the game on the 3rd tab of the starter's Summary screen. +// * When `close_summary_after_read == true` (for AutoStory): +// calls `close_starter_summary(env, context)` after reading the summary, +// which presses B back to the X menu and X to close it, leaving the +// player standing on the `VerityLakefront` overworld at `(17, 14..15)` +// (with `after_starly` already completed, ready for checkpoint `00.03`). +struct StarterRngSettings{ + Language language = Language::English; + uint8_t player_model = 1; + BdspStartPoint start_point = BdspStartPoint::Lakefront; + BdspStarter starter = BdspStarter::Turtwig; + + // Predicate for target selection and hit verification. If `wanted` is + // empty and `filters` is non-null, `starter_wanted(*filters, ...)` is used. + std::function wanted; + const BdspRngFilterSnapshot* filters = nullptr; + + uint16_t max_resets = 0; + uint16_t max_target_wait_minutes = 30; + uint16_t max_skip_minutes = 30; + + bool auto_calibrate = true; + bool use_sound_detection = true; + bool take_video = true; + + bool reset_first = false; + bool finish_battle_on_shiny = false; + bool close_summary_after_read = false; +}; + + +struct StarterRngAttemptIO{ + BlinkCollectionDisplay* collection_display = nullptr; + RngStateDisplay* state_display = nullptr; + RngTargetDisplay* target_display = nullptr; + EventNotificationOption* notification_shiny = nullptr; + EventNotificationOption* notification_error = nullptr; + StarterRngStats* stats = nullptr; + + std::function on_reset; + std::function on_miss; + std::function on_hit; + std::function on_shiny; + std::function on_error; +}; + + +enum class StarterRngOutcome{ + HIT, + SHINY, + OUT_OF_RESETS, + ABANDONED, +}; + + +struct StarterRngRunResult{ + using Outcome = StarterRngOutcome; + using enum StarterRngOutcome; + + Outcome outcome = Outcome::ABANDONED; + Pokemon::BdspPokemonResult target{}; + uint64_t target_advance = 0; + uint64_t resets_used = 0; + std::string last_failure_reason; + // False when a shiny was caught but the game was not left where + // `finish_battle_on_shiny` and `close_summary_after_read` promise: the + // caller must not go on from it. + bool settled = true; +}; + + +struct BdspStarterAttemptResult{ + BdspAttemptOutcome outcome = BdspAttemptOutcome::Abandoned; + bool shiny = false; + Pokemon::BdspPokemonResult target{}; + uint64_t target_advance = 0; + std::string failure_reason; + // See StarterRngRunResult::settled. + bool settled = true; +}; + + +// Pure helper that maps the latest attempt result and reset count to a +// finished `StarterRngRunResult` when the loop should terminate, or returns +// `false` when the loop should continue to the next reset. +bool resolve_starter_rng_step( + const BdspStarterAttemptResult& attempt, + uint64_t resets_used, + uint16_t max_resets, + StarterRngRunResult& result +); + + +BdspStarterAttemptResult run_starter_rng_attempt( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +); + + +StarterRngRunResult run_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp new file mode 100644 index 0000000000..c561e57bc1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp @@ -0,0 +1,362 @@ +/* BDSP Starter RNG Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_StarterRng_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +struct StarterTableRow{ + BdspStarter starter; + std::string slug; + uint8_t cursor_steps; + BaseStats base_stats; + double move_seconds; +}; + +const std::vector STARTER_TABLE_ROWS = { + { + .starter = BdspStarter::Turtwig, + .slug = "turtwig", + .cursor_steps = 0, + .base_stats = {55, 68, 64, 45, 55, 31}, + .move_seconds = 6.8, + }, + { + .starter = BdspStarter::Chimchar, + .slug = "chimchar", + .cursor_steps = 1, + .base_stats = {44, 58, 44, 58, 44, 61}, + .move_seconds = 7.5, + }, + { + .starter = BdspStarter::Piplup, + .slug = "piplup", + .cursor_steps = 2, + .base_stats = {53, 51, 53, 61, 56, 40}, + .move_seconds = 8.2, + }, +}; + + +UnitTestResult test_starter_tables(Logger&){ + for (const StarterTableRow& row : STARTER_TABLE_ROWS){ + const std::string got_slug = starter_slug(row.starter); + if (got_slug != row.slug){ + return std::format("starter_slug mismatch: got {}, expected {}", got_slug, row.slug); + } + const uint8_t got_steps = starter_cursor_steps(row.starter); + if (got_steps != row.cursor_steps){ + return std::format( + "starter_cursor_steps({}) = {}, expected {}", + row.slug, got_steps, row.cursor_steps + ); + } + const BaseStats& stats = starter_base_stats(row.starter); + if (stats.hp != row.base_stats.hp + || stats.attack != row.base_stats.attack + || stats.defense != row.base_stats.defense + || stats.spatk != row.base_stats.spatk + || stats.spdef != row.base_stats.spdef + || stats.speed != row.base_stats.speed + ){ + return std::format( + "starter_base_stats({}) = {}/{}/{}/{}/{}/{}, expected {}/{}/{}/{}/{}/{}", + row.slug, + stats.hp, stats.attack, stats.defense, stats.spatk, stats.spdef, stats.speed, + row.base_stats.hp, row.base_stats.attack, row.base_stats.defense, + row.base_stats.spatk, row.base_stats.spdef, row.base_stats.speed + ); + } + const double move_s = seconds_to_move_to_starter(row.starter); + if (std::abs(move_s - row.move_seconds) > 1e-9){ + return std::format( + "seconds_to_move_to_starter({}) = {}, expected {}", + row.slug, move_s, row.move_seconds + ); + } + } + return true; +} + + +UnitTestResult test_skip_buffer_and_landing_math(Logger&){ + if (bdsp_skip_buffer(0.0) != 750){ + return std::format("bdsp_skip_buffer(0) = {}, expected 750", bdsp_skip_buffer(0.0)); + } + if (bdsp_skip_buffer(100000.0) != 770){ + return std::format("bdsp_skip_buffer(100000) = {}, expected 770", bdsp_skip_buffer(100000.0)); + } + + const double sigma0 = bdsp_skip_landing_sigma(0.0); + if (std::abs(sigma0 - 67.0) > 1e-9){ + return std::format("bdsp_skip_landing_sigma(0) = {}, expected 67.0", sigma0); + } + + const uint64_t lake0 = bdsp_lake_advances_needed(0.0); + if (lake0 != 750 + 2 * 67){ + return std::format("bdsp_lake_advances_needed(0) = {}, expected {}", lake0, 750 + 2 * 67); + } + + // At 1,000,000 advances skipped: buffer = 750 + 200 = 950, + // sigma = sqrt(100^2 + 67^2) = sqrt(14489) ~ 120.37, 2*sigma = 240, total = 1190. + const uint64_t lake1m = bdsp_lake_advances_needed(1000000.0); + if (lake1m != 1190){ + return std::format("bdsp_lake_advances_needed(1e6) = {}, expected 1190", lake1m); + } + return true; +} + + +UnitTestResult test_aim_and_calibration(Logger& logger){ + if (aimed_advance(1000, 200, 0) != 1200){ + return "aimed_advance(1000, 200, 0) != 1200"; + } + if (aimed_advance(1000, 200, 3) != 1203){ + return "aimed_advance(1000, 200, 3) != 1203"; + } + if (press_for_advance(1203, 200, 3) != 1000){ + return "press_for_advance(1203, 200, 3) != 1000"; + } + + RngAim aim(3, 1.0); + if (aim.bias() != 0){ + return "initial bias != 0"; + } + if (aim.record_offset(logger, 2, true) || aim.record_offset(logger, 2, true)){ + return "should not adjust before 3 samples"; + } + if (!aim.record_offset(logger, 2, true)){ + return "expected adjustment on 3rd sample of +2"; + } + if (aim.bias() != 2){ + return std::format("bias after three +2 offsets = {}, expected 2", aim.bias()); + } + return true; +} + + +// A shiny whose post-battle scene did not finish still ends the loop (the +// shiny must not be reset away), and says so. +UnitTestResult test_shiny_unsettled(Logger&){ + BdspStarterAttemptResult shiny{ + .outcome = BdspAttemptOutcome::Hit, .shiny = true, .target_advance = 9, .settled = false + }; + StarterRngRunResult result; + if (!resolve_starter_rng_step(shiny, 1, 3, result) || result.outcome != StarterRngOutcome::SHINY){ + return "expected a shiny to end the loop"; + } + if (result.settled){ + return "expected the unsettled shiny to say that the game is not settled"; + } + shiny.settled = true; + StarterRngRunResult settled; + if (!resolve_starter_rng_step(shiny, 1, 3, settled) || !settled.settled){ + return "expected a settled shiny to be settled"; + } + return true; +} + +UnitTestResult test_attempt_loop_transitions(Logger&){ + BdspPokemonResult sample_target{}; + sample_target.ec = 0x12345678; + sample_target.pid = 0x87654321; + sample_target.nature = 3; + + // 1. Miss when below max_resets continues the loop. + { + StarterRngRunResult result; + BdspStarterAttemptResult miss{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = sample_target, + .target_advance = 1500, + }; + if (resolve_starter_rng_step(miss, 1, 3, result)){ + return "expected loop to continue on miss 1 of 3"; + } + if (result.resets_used != 1 || result.target_advance != 1500){ + return "expected resets_used = 1 and target_advance = 1500 after miss"; + } + } + + // 2. Non-shiny hit stops with Outcome::HIT. + { + StarterRngRunResult result; + BdspStarterAttemptResult hit{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = sample_target, + .target_advance = 1505, + }; + if (!resolve_starter_rng_step(hit, 2, 3, result)){ + return "expected loop to terminate on non-shiny hit"; + } + if (result.outcome != StarterRngOutcome::HIT + || result.resets_used != 2 + || result.target_advance != 1505 + || result.target.pid != sample_target.pid + ){ + return "unexpected result fields on non-shiny hit"; + } + } + + // 3. Shiny hit stops with Outcome::SHINY. + { + StarterRngRunResult result; + BdspStarterAttemptResult shiny_hit{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = true, + .target = sample_target, + .target_advance = 2048, + }; + if (!resolve_starter_rng_step(shiny_hit, 1, 0, result)){ + return "expected loop to terminate on shiny hit"; + } + if (result.outcome != StarterRngOutcome::SHINY + || result.resets_used != 1 + || result.target_advance != 2048 + ){ + return "unexpected result fields on shiny hit"; + } + } + + // 4. Miss reaching max_resets stops with Outcome::OUT_OF_RESETS. + { + StarterRngRunResult result; + BdspStarterAttemptResult miss{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = sample_target, + .target_advance = 1600, + }; + if (!resolve_starter_rng_step(miss, 3, 3, result)){ + return "expected loop to terminate when resets_used == max_resets"; + } + if (result.outcome != StarterRngOutcome::OUT_OF_RESETS || result.resets_used != 3){ + return "expected OUT_OF_RESETS on miss at reset limit"; + } + } + + // 5. Abandoned attempt reaching max_resets stops with Outcome::ABANDONED and preserves reason. + { + StarterRngRunResult result; + BdspStarterAttemptResult abandoned{ + .outcome = BdspAttemptOutcome::Abandoned, + .shiny = false, + .failure_reason = "no matching target within the allowed wait time", + }; + if (!resolve_starter_rng_step(abandoned, 1, 1, result)){ + return "expected loop to terminate on abandoned single attempt"; + } + if (result.outcome != StarterRngOutcome::ABANDONED + || result.resets_used != 1 + || result.last_failure_reason != "no matching target within the allowed wait time" + ){ + return "expected ABANDONED with failure_reason preserved"; + } + } + + return true; +} + + +// The default filter row: a table that has it stops for a shiny of any +// nature and gender, and no other starter; an empty table never stops, which +// is why a caller must seed it. +UnitTestResult test_default_shiny_row(Logger&){ + BdspRngFilterTable empty("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + BdspPokemonResult shiny{}; + shiny.shiny = BdspShiny::Star; + shiny.nature = 7; + BdspPokemonResult plain{}; + plain.nature = 7; + if (starter_wanted(empty.make_snapshot(), shiny)){ + return "an empty filter table must not match a shiny"; + } + + BdspRngFilterTable table("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + set_default_shiny_row(table); + if (table.current_rows() != 1){ + return std::format("expected one default row, got {}", table.current_rows()); + } + const BdspRngFilterSnapshot snapshot = table.make_snapshot(); + if (!starter_wanted(snapshot, shiny)){ + return "the default row must match a shiny of any nature"; + } + shiny.nature = 20; + if (!starter_wanted(snapshot, shiny)){ + return "the default row must match a shiny of another nature"; + } + if (starter_wanted(snapshot, plain)){ + return "the default row must not match a non-shiny"; + } + return true; +} + + +struct StarterRngTestCase{ + std::string name; + std::function body; +}; + +class Test_StarterRng : public UnitTest{ +public: + explicit Test_StarterRng(StarterRngTestCase test_case) + : UnitTest("PokemonBDSP::StarterRng - " + test_case.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StarterRngTestCase m_case; +}; + +const StarterRngTestCase STARTER_RNG_CASES[] = { + {"per-starter tables and timings", test_starter_tables}, + {"bedroom skip buffer and landing math", test_skip_buffer_and_landing_math}, + {"aim offset and calibration bias", test_aim_and_calibration}, + {"attempt loop outcome resolution", test_attempt_loop_transitions}, + {"default filter row is shiny of any nature", test_default_shiny_row}, + {"a shiny that did not settle ends the loop unsettled", test_shiny_unsettled}, +}; + +} // namespace + + +void add_tests_StarterRng(UnitTestDatabase& database){ + for (const StarterRngTestCase& test_case : STARTER_RNG_CASES){ + database.add(test_case); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h new file mode 100644 index 0000000000..be4c4fa2dd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h @@ -0,0 +1,23 @@ +/* BDSP Starter RNG Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRng_Tests_H +#define PokemonAutomation_PokemonBDSP_StarterRng_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void add_tests_StarterRng(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp new file mode 100644 index 0000000000..3d9737b4ee --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp @@ -0,0 +1,185 @@ +/* BDSP Summary Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" +#include "PokemonBDSP_SummaryNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; + + +const size_t MENU_ATTEMPTS = 3; + + +bool open_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Mashing B through dialogue, trying the menu as we go."); + MenuWatcher menu(COLOR_RED, true); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 40; c++){ + pbf_press_button(context, BUTTON_B, 100ms, 700ms); + pbf_press_button(context, BUTTON_B, 100ms, 700ms); + pbf_press_button(context, BUTTON_X, 100ms, 1200ms); + } + }, + {{menu}} + ); + if (ret < 0){ + env.log("Never got back to the overworld menu.", COLOR_RED); + return false; + } + env.log("Menu is open."); + return true; +} + + +bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + for (size_t attempt = 0; attempt < MENU_ATTEMPTS; attempt++){ + pbf_wait(context, 1200ms); + context.wait_for_all_requests(); + + env.log("Moving one entry left, then opening it."); + pbf_press_dpad(context, DPAD_LEFT, 160ms, 840ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + + pbf_press_button(context, BUTTON_A, 100ms, 1000ms); + context.wait_for_all_requests(); + + SelectionArrowFinder arrow(env.console, {0.360, 0.110, 0.200, 0.290}, COLOR_RED); + if (wait_until(env.console, context, 10s, {{arrow}}) >= 0){ + break; + } + if (attempt + 1 >= MENU_ATTEMPTS){ + env.log("Never reached the party from the menu.", COLOR_RED); + return false; + } + env.log("That was not the party. Backing out and trying again.", COLOR_ORANGE); + bool back_at_menu = false; + for (size_t c = 0; c < 5 && !back_at_menu; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + MenuWatcher menu(COLOR_RED, true); + back_at_menu = wait_until(env.console, context, 2s, {{menu}}) >= 0; + } + if (!back_at_menu){ + env.log("Backing out never returned to the menu.", COLOR_RED); + return false; + } + } + + env.log("Opening the summary."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + context.wait_for_all_requests(); + + env.log("Moving to the Trainer Memo page."); + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 1500ms); + context.wait_for_all_requests(); + return true; +} + + +bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + return open_menu(env, context) + && open_starter_summary(env, context); +} + + +bool close_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Backing out of the summary screen to the overworld."); + bool back_at_menu = false; + for (size_t c = 0; c < 6 && !back_at_menu; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + MenuWatcher menu(COLOR_RED, true); + back_at_menu = wait_until(env.console, context, 2s, {{menu}}) >= 0; + } + if (!back_at_menu){ + env.log("Never returned to the X menu from the summary.", COLOR_ORANGE); + return false; + } + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + return true; +} + + +bool read_observed_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + Language language, + const Pokemon::BaseStats& base_stats, + uint8_t level, + bool shiny, + bool shiny_known, + BdspObservedStarter& observed +){ + if (!navigate_to_summary(env, context)){ + env.log("Could not reach the summary, so this attempt says nothing about timing.", + COLOR_ORANGE); + return false; + } + + SummaryReader reader; + + // 2nd page: nature and gender + { + VideoSnapshot memo = env.console.video().snapshot(); + observed.nature = reader.read_nature(env.logger(), language, memo); + Pokemon::BdspGender gender = reader.read_gender(env.logger(), memo); + observed.gender = gender; + observed.gender_known = gender != Pokemon::BdspGender::Genderless; + } + // 3rd page: stats + { + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 1500ms); + context.wait_for_all_requests(); + VideoSnapshot skills = env.console.video().snapshot(); + observed.stats = reader.read_stats(env.logger(), skills); + } + observed.base_stats = base_stats; + observed.level = level; + observed.shiny = shiny; + observed.shiny_known = shiny_known; + + auto stat = [](int16_t value){ + return value < 0 ? std::string("?") : std::to_string(value); + }; + bool nature_read = observed.nature != Pokemon::NatureCheckerValue::UnableToDetect; + env.log( + "Read from the summary: nature " + + (nature_read + ? Pokemon::NATURE_CHECKER_VALUE_STRINGS().get_string(observed.nature) + : std::string("UNREAD")) + + ", gender " + + (observed.gender_known + ? std::string(Pokemon::bdsp_gender_name(observed.gender)) + : std::string("UNREAD")) + + ", stats " + stat(observed.stats.hp) + "/" + stat(observed.stats.attack) + + "/" + stat(observed.stats.defense) + "/" + stat(observed.stats.spatk) + + "/" + stat(observed.stats.spdef) + "/" + stat(observed.stats.speed) + ".", + nature_read && observed.gender_known ? COLOR_BLUE : COLOR_ORANGE + ); + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h new file mode 100644 index 0000000000..0c1933c3d5 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h @@ -0,0 +1,44 @@ +/* BDSP Summary Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_SummaryNavigation_H +#define PokemonAutomation_PokemonBDSP_SummaryNavigation_H + +#include "CommonFramework/Language.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonBDSP_RngCalibration.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +bool open_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +// Backs out of the Pokemon summary screen (3rd page -> party -> X menu -> overworld). +bool close_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool read_observed_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + Language language, + const Pokemon::BaseStats& base_stats, + uint8_t level, + bool shiny, + bool shiny_known, + BdspObservedStarter& observed +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp new file mode 100644 index 0000000000..39420aa7fc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp @@ -0,0 +1,122 @@ +/* BDSP Target Selection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +TargetSelectionResult select_target(const TargetSearchRequest& request){ + TargetSelectionResult result; + + if (!request.wanted){ + result.failure_reason = "No filter was supplied, so nothing can be searched for."; + return result; + } + + BdspStaticSearcher searcher(request.state, request.pokemon, 0); + + // How many advances the scene can spend between the press and the generation + uint64_t lowest_span = 0; + uint64_t highest_span = 0; + schedule_span_bounds(request.timeline, request.max_schedules, lowest_span, highest_span); + + int64_t last_press = (int64_t)(request.first_press + request.window_advances); + + // One sweep, walking the RNG forward rather than jumping to each advance. + uint64_t scan_from = (uint64_t)std::max( + 0, (int64_t)request.first_press + (int64_t)lowest_span + request.bias + ); + uint64_t scan_to = (uint64_t)std::max( + 0, last_press + (int64_t)highest_span + request.bias + ); + std::map wanted_targets; + for (const BdspRngHit& hit : searcher.scan(scan_from, scan_to, request.wanted)){ + wanted_targets.emplace(hit.advances, hit.result); + } + + result.advances_scanned = scan_to - scan_from + 1; + result.matches_found = wanted_targets.size(); + + if (wanted_targets.empty()){ + result.failure_reason = "no matches found within " + + std::to_string(result.advances_scanned) + " advances."; + return result; + } + + uint8_t press_step = request.npcs == 0 ? 1 : request.npcs; + std::set candidate_presses; + for (const auto& item : wanted_targets){ + int64_t lowest_press = std::max( + press_for_advance(item.first, highest_span, request.bias), + (int64_t)request.first_press + ); + int64_t highest_press = std::min( + press_for_advance(item.first, lowest_span, request.bias), + last_press + ); + for (int64_t press = lowest_press; press <= highest_press; press++){ + if (press % press_step != 0){ + continue; + } + candidate_presses.insert((uint64_t)press); + } + } + + double seconds_per_advance = request.tick_seconds / (double)press_step; + bool found = false; + double best_seconds = 0; + for (uint64_t press : candidate_presses){ + double press_at_seconds = (double)(press - request.first_press) * seconds_per_advance; + if (found && press_at_seconds >= best_seconds){ + break; + } + for (const PressSchedule& option : schedule_presses( + request.state, request.timeline, request.timings, press, request.max_schedules + )){ + auto hit = wanted_targets.find(aimed_advance(press, option.span, request.bias)); + if (hit == wanted_targets.end()){ + continue; + } + if (!found || press_at_seconds + option.confirm_seconds < best_seconds){ + found = true; + best_seconds = press_at_seconds + option.confirm_seconds; + result.press_advance = press; + result.schedule = option; + result.target = hit->second; + } + // the first hit is the best this press has to offer + break; + } + } + if (!found){ + // Around one advance in fifty is unreachable due to rapid blinks + result.failure_reason = std::to_string(wanted_targets.size()) + + " matching advance(s) in range, but none reachable"; + return result; + } + + result.target_advance = aimed_advance( + result.press_advance, result.schedule.span, request.bias + ); + result.success = true; + return result; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h new file mode 100644 index 0000000000..7c1fb044d0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h @@ -0,0 +1,57 @@ +/* BDSP Target Selection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_TargetSelection_H +#define PokemonAutomation_PokemonBDSP_TargetSelection_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct TargetSearchRequest{ + Pokemon::Xorshift128State state; + BdspTimelineContext timeline; + NavigationTimings timings; + Pokemon::BdspStaticTemplate pokemon; + uint8_t npcs = 1; + double tick_seconds = BDSP_NPC_TICK_SECONDS; + int64_t bias = 0; + uint64_t first_press = 0; + uint64_t window_advances = 0; + size_t max_schedules = 8; + std::function wanted; +}; + + +struct TargetSelectionResult{ + bool success = false; + uint64_t press_advance = 0; + uint64_t target_advance = 0; + PressSchedule schedule; + Pokemon::BdspPokemonResult target; + size_t matches_found = 0; + uint64_t advances_scanned = 0; + std::string failure_reason; +}; + + +TargetSelectionResult select_target(const TargetSearchRequest& request); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 264016949b..a913dff128 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1833,6 +1833,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Launch.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Launch_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Launch_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -2010,6 +2012,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h Source/PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.cpp Source/PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h + Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp + Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -2080,12 +2084,34 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_BlinkRecovery.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngDisplays.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngDisplays.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp