diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 1cbb9d1c8c..db7e926dd4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -5,6 +5,7 @@ */ #include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" @@ -44,9 +45,18 @@ #include "Overworld/PokemonFRLG_OverworldRoute.h" #include "Overworld/PokemonFRLG_OverworldWalk.h" #include "Overworld/PokemonFRLG_PlayerFacingReader.h" +#include "Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryExport_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -67,6 +77,17 @@ static void add_tests_AutoStoryReaders(UnitTestDatabase& database){ add_tests_AutoStoryScreenEvents(database); } +// The RNG plan: its targets, attempts and the Starter RNG loop. +static void add_tests_RngPlanning(UnitTestDatabase& database){ + add_tests_RngTargetSearch(database); + add_tests_RngPlanInputs(database); + add_tests_RngPlan(database); + add_tests_RngPlanTracker(database); + add_tests_RngPlanLog(database); + add_tests_RngSteps(database); + add_tests_StarterRngLoop(database); +} + void add_tests(UnitTestDatabase& database){ add_tests_AdvanceWhiteDialogDetector(database); add_tests_AdvanceBattleDialogDetector(database); @@ -108,6 +129,9 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStoryExport(database); add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); + add_tests_AutoStoryRngLoop(database); + add_tests_NamingScreen(database); + add_tests_RngPlanning(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 65d0de1d1a..e24fbe39ee 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -5,9 +5,11 @@ */ #include +#include #include #include "Common/Cpp/Exceptions.h" #include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" @@ -17,7 +19,16 @@ #include "Pokemon/Options/Pokemon_GameLanguages.h" #include "Pokemon/Pokemon_Strings.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStory.h" @@ -67,6 +78,13 @@ const std::string KEEP_START_FRAME_TEXT = } // namespace +const std::string RUN_STARTER_RNG_TEXT = + "Run Starter RNG in AutoStory:
Off by default. Instead of stopping for them, run SID Helper's steps on the " + "new game's keyboard when the RNG plan has no SID, and Starter RNG's attempts from a save south of the table at the " + "end of 00.04, as the RNG plan lists them. A shiny Squirtle goes on to the rival's battle, saves after it and the run " + "goes on; otherwise the run stops with the save south of the table.
" + "SID Helper's timing needs the text speed and button settings already saved, as with Stop for SID Helper."; + AutoStory::AutoStory() : RUN(checkpoint_database(), Pokemon::FireRedLeafGreenLanguages_Database()) , NEW_GAME_FROM_TITLE( @@ -75,15 +93,44 @@ AutoStory::AutoStory() LockMode::LOCK_WHILE_RUNNING, true ) + , PLAYER_NAME( + false, + "Player name:
Typed on the new game's keyboard (00.01). Empty keeps the game's default name. " + "The rival always keeps the default name.", + LockMode::LOCK_WHILE_RUNNING, + "Kosmos", "" + ) + , STOP_FOR_SID_HELPER( + "Stop for SID Helper:
Off by default. At 00.01, stop on the player's keyboard with the name typed and OK not pressed, " + "where the SID Helper program starts. After SID Helper, start AutoStory at 00.01b, with the game as SID Helper left it " + "(the Trainer Card, or HOME): it closes the card, sets the options and saves in the bedroom.
" + "SID Helper needs the text speed and button settings already saved. On a cartridge with that save, choose NEW GAME " + "by hand and start AutoStory on the first message.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , STOP_FOR_STARTER_RNG( + "Stop for Starter RNG:
Off by default. At the end of 00.04, save south of the table facing Squirtle's ball " + "and stop, where the Starter RNG program starts. After Starter RNG, save right after the rival's battle without moving " + "and start AutoStory at 00.05, listing the targets to try from the RNG plan.
" + "With this off, 00.04 and 00.04b run as one checkpoint, as before.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , RUN_STARTER_RNG(RUN_STARTER_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) + , NOTIFICATION_SHINY("Shiny found", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) , KEEP_START_FRAME(KEEP_START_FRAME_TEXT, LockMode::LOCK_WHILE_RUNNING, false) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) + , NOTIFICATIONS({&NOTIFICATION_SHINY, &NOTIFICATION_STATUS_UPDATE, &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_FATAL}) { PA_ADD_OPTION(RUN); PA_ADD_OPTION(NEW_GAME_FROM_TITLE); PA_ADD_OPTION(KEEP_START_FRAME); + PA_ADD_OPTION(PLAYER_NAME); + PA_ADD_OPTION(STOP_FOR_SID_HELPER); + PA_ADD_OPTION(STOP_FOR_STARTER_RNG); + PA_ADD_OPTION(RUN_STARTER_RNG); + PA_ADD_OPTION(RNG_PLAN); PA_ADD_OPTION(NOTIFICATIONS); } @@ -106,6 +153,17 @@ static void check_start_save( namespace{ +// Before the new game starts: a name the keyboard can't type is the user's to fix. +void check_player_name(ConsoleHandle& console, const std::string& name){ + if (name.empty()){ + return; + } + const std::string error = naming_text_error(name, NamingScreenKind::PLAYER); + if (!error.empty()){ + throw UserSetupError(console, "Player name: " + error); + } +} + // The story's state for a run from `checkpoint`: its supplies, the checks // level, and the program's start frames, the first start check keeping // the screen as its frame if `keep_start_frame` (a save made by hand). @@ -166,6 +224,11 @@ void load_verify_save( "Verify mode reloads the checkpoint's save between runs: " + checkpoint.id + " starts a new game and has none." ); } + if (checkpoint.live_start){ + throw UserSetupError(env.console, + "Verify mode reloads the checkpoint's save between runs: " + checkpoint.id + " starts from the game as it is, with no save." + ); + } env.console.log("Verify mode: loading the save for " + checkpoint.id + "."); soft_reset(env.console, context); story.has_save = true; @@ -205,55 +268,384 @@ void verify_story_checkpoint( } // namespace -void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (const std::optional verify = RUN.VERIFY.policy()){ - verify_story_checkpoint(env, context, RUN, *verify, NOTIFICATION_PROGRAM_FINISH); +// The options' problems, before anything is pressed. +static void check_setup( + ConsoleHandle& console, const std::vector& checkpoints, size_t first, size_t last, + bool new_game_from_title, const std::string& player_name +){ + if (first > last || last >= checkpoints.size()){ + throw UserSetupError(console, "The start checkpoint must not come after the end checkpoint."); + } + if (first == 0 && !new_game_from_title){ + throw UserSetupError(console, "Checkpoint 00.01 starts a new game: start on the title screen with no save."); + } + if (first == 0){ + check_player_name(console, player_name); + } +} + +static void throw_if_failed(const Pokemon::SegmentReport& report){ + if (report.completed){ return; } - const std::vector& checkpoints = story_checkpoints(); - const size_t first = RUN.start_index(); - const size_t last = RUN.end_index(); - if (first > last || last >= checkpoints.size()){ - throw UserSetupError(env.console, "The start checkpoint must not come after the end checkpoint."); + throw OperationFailedException( + ErrorReportMode::NO_ERROR_REPORT, + std::format( + "AutoStory stopped at {} {}: {}", + report.failed_checkpoint, report.failed_event, Pokemon::to_string(report.failure) + ) + ); +} + +// Gets the game to where checkpoint `first` starts: a new game from the +// title screen, the game as another program left it, or the checkpoint's +// save loaded. +static void prepare_start( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::vector& checkpoints, size_t first, StoryEnv& story +){ + const StoryCheckpoint& checkpoint = checkpoints[first]; + if (!checkpoint.start){ + return; } - if (first == 0 && !NEW_GAME_FROM_TITLE){ - throw UserSetupError(env.console, "Checkpoint 00.01 starts a new game: start on the title screen with no save."); + if (checkpoint.live_start){ + env.console.log(checkpoint.id + " starts from the game as it is: no save to load."); + return; } + env.console.log("Loading the save for " + checkpoint.id + "."); + soft_reset(env.console, context); + story.has_save = true; + check_start_save(env, story, checkpoints[first]); + read_lead_moves(story, checkpoints[first].menu); + read_bag_supplies(story, checkpoints[first].menu); +} - StoryEnv story = story_env(env, context, checkpoints[first], RUN.check_level(), KEEP_START_FRAME); - if (!(first == 0 && NEW_GAME_FROM_TITLE)){ - env.console.log("Loading the save for " + checkpoints[first].id + "."); - soft_reset(env.console, context); - story.has_save = true; - check_start_save(env, story, checkpoints[first]); - read_lead_moves(story, checkpoints[first].menu); - read_bag_supplies(story, checkpoints[first].menu); +// The run stopped for an RNG program, as its option asked: the user's +// turn, with what to do next, and the lines that go with it (the RNG +// plan's attempts). +static void stop_for_handoff( + SingleSwitchProgramEnvironment& env, EventNotificationOption& notification, + const std::string& message, const std::vector& lines = {} +){ + env.console.log(message, COLOR_BLUE); + env.console.overlay().add_log(message); + std::string full = message; + for (const std::string& line : lines){ + env.console.log(line, COLOR_BLUE); + env.console.overlay().add_log(line); + full += "\n" + line; } + send_program_finished_notification(env, notification, full); +} - story.language = RUN.language(); - StoryExecutor executor(story); - Pokemon::Segment segment = make_story_segment(checkpoints, executor); +static void stop_for_sid_helper( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + EventNotificationOption& notification, const std::string& player_name +){ + play_new_game_to_player_name(env.console, context, player_name); + stop_for_handoff(env, notification, + "Stopped for SID Helper: the player's name is typed and OK is not pressed. Run SID Helper now, " + "enter its Target Advances and # Candidate SIDs in the RNG plan, then start AutoStory at 00.01b." + ); +} + +// The TID for the Starter RNG plan: the RNG plan's, or read off the +// Trainer Card (START, the player's entry), which is then closed again. +// Before the first Pokemon, as under the ball, the player's entry is second. +static uint16_t starter_rng_tid( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanOptions& options, Language language +){ + std::optional tid = options.tid_override(env.console); + if (tid){ + env.console.log(rng_log_tid(*tid, false)); + return *tid; + } + navigate_to_trainer_card(env.console, context); + tid = try_read_trainer_card_tid(env.console, context, language); + if (!tid){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "Couldn't read the TID on the Trainer Card, so there is no Starter RNG plan. Nothing was saved: " + "type the TID into the RNG plan's TID option and start AutoStory at 00.04 again.", + env.console + ); + } + close_trainer_card(env.console, context); + env.console.log(rng_log_tid(*tid, true)); + return *tid; +} + +// The Starter RNG attempts. Run under the ball before 00.04 saves there, so +// a failure ends the run with 00.03's save kept. +static StarterRngPlanned plan_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanOptions& options, Language language +){ + const uint16_t tid = starter_rng_tid(env, context, options, language); + try{ + return StarterRngPlanned{.tid = tid, .attempts = options.plan(env.console, language, tid)}; + }catch (UserSetupError& e){ + throw UserSetupError(env.console, e.message() + " Nothing was saved: fix the RNG plan and start AutoStory at 00.04 again."); + } +} + +// Has the last checkpoint of `segment` call `before` just before it saves. +static void before_last_save(Pokemon::Segment& segment, std::function before){ + Pokemon::CheckpointSpec& spec = segment.checkpoints.back(); + spec.build = [build = std::move(spec.build), before]() mutable{ + Pokemon::Checkpoint checkpoint = build(); + checkpoint.save = [save = std::move(checkpoint.save), before](Pokemon::RunState& state) mutable{ + before(); + return save(state); + }; + return checkpoint; + }; +} + +// The attempts are the user's to run, with Run Starter RNG in AutoStory off. +// TODO: LeafGreen and Bulbasaur/Charmander, with AutoStory's starter choice. +static void stop_for_starter_rng( + SingleSwitchProgramEnvironment& env, EventNotificationOption& notification, + const std::string& sound, const std::vector& attempts +){ + stop_for_handoff(env, notification, + "Stopped for Starter RNG: saved south of the table, facing Squirtle's ball. " + "Run Starter RNG (Squirtle, FireRed, Sound " + sound + ") with attempt 1's Target Seed and Advances. " + "If it hits the target and it isn't shiny, load this save and run the next attempt. If it is shiny, " + "its SID is the one listed (or one of them): enter it as the RNG plan's SID. " + "Then save right after the rival's battle, without moving, and start AutoStory at 00.05.", + attempts + ); +} + +static size_t checkpoint_index(const std::vector& checkpoints, const std::string& id){ + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == id){ + return c; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint " + id + "."); +} + +// Runs `rows` as one segment, calling `before` (if set) just before the +// last row saves. Throws if a checkpoint fails for good. +static void run_story_rows( + SingleSwitchProgramEnvironment& env, StoryEnv& story, StoryExecutor& executor, + const std::vector& rows, const Pokemon::SegmentPolicy& policy, + std::function before +){ + Pokemon::Segment segment = make_story_segment(rows, executor); + if (before){ + before_last_save(segment, std::move(before)); + } Pokemon::SegmentHooks hooks = story_hooks(env, story); Pokemon::RunState state; const Pokemon::SegmentReport report = run_segment( - Pokemon::SegmentRange{checkpoints[first].id, checkpoints[last].id}, RUN.policy(), segment, hooks, state + Pokemon::SegmentRange{rows.front().id, rows.back().id}, policy, segment, hooks, state ); Pokemon::record_story_counts(report.story_counts(), env.current_stats()); env.update_stats(); - if (!report.completed){ - throw OperationFailedException( - ErrorReportMode::NO_ERROR_REPORT, - std::format( - "AutoStory stopped at {} {}: {}", - report.failed_checkpoint, report.failed_event, Pokemon::to_string(report.failure) - ) + throw_if_failed(report); +} + +// SID Helper's steps in the program, from the player's keyboard: the name +// typed, then the intro at SID Helper's timing into the bedroom, and the +// Trainer Card opened to read the TID. Ends on the card, where 00.01b +// starts. +static void set_sid_in_program( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& player_name, const StarterRngPlanOptions& options, Language language +){ + const uint32_t target_advances = options.SID_HELPER_ADVANCES; + if (target_advances % 2 == 0){ + throw UserSetupError(env.console, "RNG plan: SID Helper's Target Advances must be odd."); + } + play_new_game_to_player_name(env.console, context, player_name); + const SidTiming timing = sid_timing(language, target_advances); + env.log("SID Helper's steps: delay " + std::to_string(timing.delay_ms) + "ms"); + set_sid_from_name_screen(context, timing); + finish_intro_animations(env, context); + + navigate_to_trainer_card(env.console, context); + const std::optional tid = try_read_trainer_card_tid(env.console, context, language); + if (!tid){ + env.console.log("Couldn't read the TID on the Trainer Card; 00.04 reads it again.", COLOR_ORANGE); + return; + } + env.console.log(rng_log_tid(*tid, true)); + env.console.log(rng_log_sid_helper(*tid, target_advances, options.helper_candidates(*tid))); +} + +namespace{ + +// Run Starter RNG in AutoStory: the time caps, Starter RNG's default Max +// Resets per try, and an attempt's misses before the run stops. +const StarterRngLoopLimits STARTER_RNG_LIMITS{ + .attempt_time = std::chrono::hours(3), + .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, +}; + +} // namespace + +// Starter RNG's attempts in the program, from the save south of the table. +// Returns true for a shiny Squirtle, on the target or not, the game on its +// summary; otherwise the run has stopped with what to do next. A shiny that +// confirms the SID writes it into the RNG plan's SID option. +static bool run_starter_rng_in_program( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanned& planned, StarterRngPlanOptions& options, Language language, + const StarterRngNotifications& notifications, EventNotificationOption& finished +){ + RngPlanTracker tracker( + planned.attempts, options.plan_candidates(env.console, planned.tid), options.SHINY_REQUIRED, STARTER_RNG_LIMITS.max_retries + ); + // The settings file gets the calibration saved after each reset when + // the program's panel is closed or the app quits. + RngStopCalibrationOptions& calibration = options.CALIBRATION; + ConsoleStarterRngSteps console_steps(env, context, StarterRngConsoleSettings{ + .language = language, .sound = options.SOUND, .calibration = calibration.calibration(calibration.STARTER_INGAME), + }, notifications); + CalibrationSavingSteps steps(console_steps, calibration, calibration.STARTER_INGAME); + RngPlanLogger logger(env.console); + const StarterRngLoopResult result = run_starter_rng_plan( + logger, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) + ); + const std::string confirmed_sid = result.sid ? std::to_string(*result.sid) : ""; + if (result.end == StarterRngLoopEnd::SHINY && result.sid && static_cast(options.SID) != confirmed_sid){ + // Kept in AutoStory's settings, so the next run plans for it and skips SID + // Helper's steps. Deferred: a per-save record keyed by TID (e.g. UserSettings/ + // FRLG-Saves.json: TID -> SID, version, language) that any FRLG RNG program + // could read, once a second program needs the SID. + options.SID.set(confirmed_sid); + env.console.log( + "AutoStory: set the RNG plan's SID to " + confirmed_sid + ". The settings file gets it " + "when the program's panel is closed or the app quits.", COLOR_BLUE ); } - env.console.log("AutoStory: done through " + checkpoints[last].id + "."); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + const std::string message = starter_rng_loop_message(result); + if (result.end != StarterRngLoopEnd::SHINY && result.end != StarterRngLoopEnd::SHINY_OFF_TARGET){ + stop_for_handoff(env, finished, message); + return false; + } + env.console.log(message, COLOR_BLUE); + env.console.overlay().add_log(message); + return true; +} + +// After a shiny Squirtle: off its summary, then the rival's battle, which +// saves (00.04b), and the rows after it to `last`. Until that save, a +// reload would load the save under the ball and lose the shiny, so a +// failure stops the run instead. Returns the last row's id. +static std::string run_after_shiny_starter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const Pokemon::SegmentPolicy& policy, size_t ball_row, size_t last +){ + const std::vector rows = rows_after_starter_rng(story_checkpoints(), ball_row, last); + // As Starter RNG leaves the summary for the overworld. + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + env.console.log("The shiny Squirtle isn't saved until " + rows.front().id + " saves after the rival's battle. " + "If it fails before then, the run stops without reloading: save by hand.", COLOR_BLUE); + story.has_save = false; + run_story_rows(env, story, executor, rows, policy, nullptr); + return rows.back().id; } +// The run is done through `done_through`. The finish message also gives +// the SID when Starter RNG set it, from `sid_before` to `sid_after`. +static void send_story_finished( + SingleSwitchProgramEnvironment& env, EventNotificationOption& finished, + const std::string& done_through, const std::string& sid_before, const std::string& sid_after +){ + std::string message = "AutoStory: done through " + done_through + "."; + if (sid_after != sid_before){ + message += " Starter RNG confirmed the SID, " + sid_after + ", and saved it as the RNG plan's SID."; + } + env.console.log(message); + send_program_finished_notification(env, finished, message); +} + +StoryHandoffs AutoStory::story_handoffs() const{ + // Running Starter RNG here splits 00.04 at the ball as its stop does, + // and sets the SID at 00.01 when it isn't known. + return StoryHandoffs{ + .sid_helper = RUN_STARTER_RNG ? static_cast(RNG_PLAN.SID).empty() : bool(STOP_FOR_SID_HELPER), + .starter_rng = STOP_FOR_STARTER_RNG || RUN_STARTER_RNG, + }; +} + +void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (const std::optional verify = RUN.VERIFY.policy()){ + verify_story_checkpoint(env, context, RUN, *verify, NOTIFICATION_PROGRAM_FINISH); + return; + } + const std::vector& checkpoints = story_checkpoints(); + size_t first = RUN.start_index(); + const size_t last = RUN.end_index(); + const std::string player_name = PLAYER_NAME; + check_setup(env.console, checkpoints, first, last, NEW_GAME_FROM_TITLE, player_name); + const StoryHandoffs handoffs = story_handoffs(); + const std::string sid_before = RNG_PLAN.SID; + StoryRunPlan plan = plan_story_run(checkpoints, first, last, handoffs); + if (plan.stop == StoryHandoff::SID_HELPER && !RUN_STARTER_RNG){ + stop_for_sid_helper(env, context, NOTIFICATION_PROGRAM_FINISH, player_name); + return; + } + if (plan.stop != StoryHandoff::NONE){ + // The options' text, before anything is pressed. + RNG_PLAN.check(env.console); + } + if (plan.stop == StoryHandoff::SID_HELPER){ + set_sid_in_program(env, context, player_name, RNG_PLAN, RUN.language()); + first = checkpoint_index(checkpoints, "00.01b"); + plan = plan_story_run(checkpoints, first, last, handoffs); + } + StoryEnv story = story_env(env, context, checkpoints[first], RUN.check_level(), KEEP_START_FRAME); + story.player_name = player_name; + prepare_start(env, context, checkpoints, first, story); + story.language = RUN.language(); + StoryExecutor executor(story); + StarterRngPlanned planned; + std::function before; + if (plan.stop == StoryHandoff::STARTER_RNG){ + before = [&]{ planned = plan_starter_rng_attempts(env, context, RNG_PLAN, RUN.language()); }; + } + run_story_rows(env, story, executor, plan.rows, RUN.policy(), std::move(before)); + std::string done_through = plan.rows.back().id; + if (plan.stop == StoryHandoff::STARTER_RNG){ + std::optional done = after_starter_ball( + env, context, story, executor, planned, checkpoint_index(checkpoints, done_through) + ); + if (!done){ + return; + } + done_through = *done; + } + send_story_finished(env, NOTIFICATION_PROGRAM_FINISH, done_through, sid_before, RNG_PLAN.SID); +} + +std::optional AutoStory::after_starter_ball( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const StarterRngPlanned& planned, size_t ball_row +){ + if (!RUN_STARTER_RNG){ + stop_for_starter_rng(env, NOTIFICATION_PROGRAM_FINISH, RNG_PLAN.sound_name(), rng_attempt_lines(planned.attempts)); + return std::nullopt; + } + const StarterRngNotifications notifications{ + .shiny = NOTIFICATION_SHINY, .status_update = NOTIFICATION_STATUS_UPDATE, .error_recoverable = NOTIFICATION_ERROR_RECOVERABLE, + }; + if (!run_starter_rng_in_program(env, context, planned, RNG_PLAN, RUN.language(), notifications, NOTIFICATION_PROGRAM_FINISH)){ + return std::nullopt; + } + return run_after_shiny_starter(env, context, story, executor, RUN.policy(), ball_row, RUN.end_index()); +} + + } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h index 285a2c16b8..481f37c211 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h @@ -12,12 +12,18 @@ #ifndef PokemonAutomation_PokemonFRLG_AutoStory_H #define PokemonAutomation_PokemonFRLG_AutoStory_H +#include +#include #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/StringOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -43,10 +49,31 @@ class AutoStory : public SingleSwitchProgramInstance{ ) override{} private: + // The RNG programs' handoffs the run takes, from the options. + StoryHandoffs story_handoffs() const; + // After 00.04 saved under Squirtle's ball (row `ball_row`): the stop + // for Starter RNG, or its attempts run here and, for a shiny, the run + // on to the end checkpoint. Returns the last checkpoint run, or nothing + // once the run has stopped. + std::optional after_starter_ball( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const StarterRngPlanned& planned, size_t ball_row + ); + // The start and end checkpoints, attempts, checks and language, as in // every game's AutoStory. Pokemon::StoryRunOptions RUN; BooleanCheckBoxOption NEW_GAME_FROM_TITLE; + StringOption PLAYER_NAME; + // The RNG programs the run stops for (StoryHandoff). + BooleanCheckBoxOption STOP_FOR_SID_HELPER; + BooleanCheckBoxOption STOP_FOR_STARTER_RNG; + // Runs SID Helper's steps and Starter RNG's attempts in the program + // instead of stopping for them. + BooleanCheckBoxOption RUN_STARTER_RNG; + StarterRngPlanOptions RNG_PLAN; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; // The save loaded was made by hand: keep the screen as its start frame. BooleanCheckBoxOption KEEP_START_FRAME; EventNotificationsOption NOTIFICATIONS; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 74d8f117b1..512f9b96b2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -16,6 +16,8 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/Images/SolidColorTest.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_ItemListReader.h" @@ -26,6 +28,7 @@ #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_SelectionArrowDetector.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" #include "PokemonFRLG_AutoStoryActions.h" @@ -168,18 +171,28 @@ void open_start_menu_row(ConsoleHandle& console, ProControllerContext& context, // without an arrow, and the arrow at the end of Oak's lines may be missed, // so a message box gets A every 1.5 s whatever it shows. The player's name // is asked on the keyboard straight away: B deletes whatever a stray A -// typed and START jumps to OK, which confirms the empty name as the -// default. The rival's is asked on a list with NEW NAME first, where A -// would open the keyboard: the cursor goes to the first preset name (the -// game's default rival, GREEN in FireRed, RED in LeafGreen) and A picks -// it, then YES confirms it (pokefirered oak_speech.c). If the keyboard -// opens anyway, the list was missed, and the empty name is confirmed -// there instead, which also names the rival GREEN. +// typed, then the name is typed, or START jumps to OK, which confirms the +// empty name as the default. The rival's is asked on a list with NEW NAME +// first, where A would open the keyboard: the cursor goes to the first +// preset name (the game's default rival, GREEN in FireRed, RED in +// LeafGreen) and A picks it, then YES confirms it (pokefirered +// oak_speech.c). If the keyboard opens anyway, the list was missed, and +// the empty name is confirmed there instead, which also names the rival +// GREEN. class NewGameIntro{ public: - NewGameIntro(ConsoleHandle& console, ProControllerContext& context) + // Where the intro stops: the bedroom, or the player's keyboard with the + // name typed and OK not pressed (for SID Helper). + enum class End{ + BEDROOM, + PLAYER_NAME_TYPED, + }; + + NewGameIntro(ConsoleHandle& console, ProControllerContext& context, std::string player_name, End end) : m_console(console) , m_context(context) + , m_player_name(std::move(player_name)) + , m_end(end) {} void run(){ @@ -189,7 +202,7 @@ class NewGameIntro{ m_last_press = m_last_dialog; while (current_time() < deadline){ if (step()){ - m_console.log("New game: the bedroom."); + m_console.log(m_end == End::BEDROOM ? "New game: the bedroom." : "New game: the player's name is typed, OK not pressed."); return; } } @@ -228,6 +241,12 @@ class NewGameIntro{ pbf_wait(m_context, POLL); return false; } + if (m_end == End::PLAYER_NAME_TYPED && m_keyboards_seen == 0 && NamingScreenDetector(COLOR_RED).detect(screen)){ + m_keyboards_seen++; + clear_stray_keys(); + type_player_name(false); + return true; + } if (names(screen)){ m_last_dialog = current_time(); m_last_press = m_last_dialog; @@ -262,12 +281,12 @@ class NewGameIntro{ switch (intro_name_step(shown, m_keyboards_seen, m_presets_picked)){ case IntroNameStep::PLAYER_KEYBOARD: m_keyboards_seen++; - enter_empty_name(); + enter_name(true); return true; case IntroNameStep::RIVAL_KEYBOARD: m_keyboards_seen++; m_console.log("New game: the rival's keyboard opened, so the name list was missed.", COLOR_ORANGE); - enter_empty_name(); + enter_name(false); return true; case IntroNameStep::RIVAL_PRESET: pick_rival_preset(*list_row); @@ -317,18 +336,46 @@ class NewGameIntro{ return false; } - void enter_empty_name(){ - m_console.log("New game: the keyboard, confirming an empty name."); + // B deletes whatever a stray A typed; the cursor stays on its key. + void clear_stray_keys(){ for (int c = 0; c < 8; c++){ press(m_context, BUTTON_B, 340ms); } - press(m_context, BUTTON_PLUS, 500ms); - press(m_context, BUTTON_A, 2000ms); + } + + void enter_name(bool player){ + clear_stray_keys(); + if (!player || m_player_name.empty()){ + m_console.log("New game: the keyboard, confirming an empty name."); + press(m_context, BUTTON_PLUS, 500ms); + press(m_context, BUTTON_A, 2000ms); + m_context.wait_for_all_requests(); + return; + } + type_player_name(true); + // Past the keyboard's fade, so it isn't taken for the rival's. + pbf_wait(m_context, 2000ms); m_context.wait_for_all_requests(); } + void type_player_name(bool confirm){ + if (m_player_name.empty()){ + return; + } + const bool typed = confirm + ? type_name(m_console, m_context, m_player_name, NamingScreenKind::PLAYER) + : type_name_without_confirming(m_console, m_context, m_player_name, NamingScreenKind::PLAYER); + if (!typed){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "play_new_game_intro(): the keyboard closed before the name was typed.", m_console + ); + } + } + ConsoleHandle& m_console; ProControllerContext& m_context; + const std::string m_player_name; + const End m_end; WallClock m_last_dialog; WallClock m_last_press; bool m_dialog_seen = false; @@ -834,9 +881,25 @@ void buy_items( mash_until_overworld(console, context, 20000ms); } -void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context){ +void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name){ console.log("New game: from the title screen."); - NewGameIntro(console, context).run(); + NewGameIntro(console, context, player_name, NewGameIntro::End::BEDROOM).run(); +} + +void play_new_game_to_player_name(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name){ + console.log("New game: from the title screen to the player's keyboard, for SID Helper."); + NewGameIntro(console, context, player_name, NewGameIntro::End::PLAYER_NAME_TYPED).run(); +} + +void close_trainer_card(ConsoleHandle& console, ProControllerContext& context){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (screen && HomeMenuDetector(console, COLOR_RED).detect(screen)){ + console.log("After SID Helper: on HOME, back to the game."); + resume_game_from_home(console, context); + } + // B closes the card, then the START menu. + mash_until_overworld(console, context, 20000ms); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h index f7e1c14774..d4d723063b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCheckpoints.h @@ -35,13 +35,58 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ +// An upstream RNG program the user may run part-way through the story. +// Each is off unless its option is on. +enum class StoryHandoff{ + NONE, + // The checkpoint's new game stops on the player's keyboard, the name + // typed and OK not pressed, which is where SID Helper starts. + SID_HELPER, + // The checkpoint saves south of the table, facing the starter's ball, + // which is where Starter RNG starts. With the handoff off, it runs on + // into the next checkpoint as one, as the story did before the split. + STARTER_RNG, +}; + // A shared checkpoint with what FRLG adds to it. struct StoryCheckpoint : public Pokemon::StoryCheckpoint{ // The healing items at its start, for a run that loads its save. Supplies supplies; // The START menu at its end, when it saves. StartMenu menu = StartMenu::FULL; + // Starts from the game as another program left it, loading no save: + // the way back into the story after an RNG program. A run that starts + // before it passes over it. + bool live_start = false; + // The RNG program the user may run at this checkpoint. + StoryHandoff handoff = StoryHandoff::NONE; +}; + +// The handoffs a run stops for (AutoStory's options). +struct StoryHandoffs{ + bool sid_helper = false; + bool starter_rng = false; }; + +// What a run from table row `first` to `last` does. +struct StoryRunPlan{ + // The checkpoints to run, in order. + std::vector rows; + // NONE: the run ends after `rows`. SID_HELPER: `rows` is empty; the run + // plays the new game to the player's keyboard and stops there. + // STARTER_RNG: the run stops after `rows`, the last of which saves at + // the starter's ball. + StoryHandoff stop = StoryHandoff::NONE; +}; + +// The rows of `checkpoints` from `first` to `last`, both inclusive, as a +// run with `handoffs` takes them: live-start rows only when the run +// starts there, a run that reaches a handoff that is on stops for it, and +// a STARTER_RNG row whose handoff is off is joined with the row after it, +// under its own id. +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs +); // `legs` from `start` as route steps for the walker, each checked against // the map: nothing if a step is blocked or leaves the map. A leg ends "to // wall" if the next step its way is blocked. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 4fa57e85d2..594c9d162b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -411,7 +411,7 @@ ConsoleAction console_action_of(StoryActionId id){ switch (id){ case StoryActionId::NEW_GAME: return [](StoryEnv& env, RunState&, const StoryStep&){ - play_new_game_intro(env.console, env.context); + play_new_game_intro(env.console, env.context, env.player_name); return Pokemon::outcome_ok(); }; case StoryActionId::ROUTE: @@ -485,13 +485,69 @@ Pokemon::StoryAction StoryExecutor::console_action(StoryActionId id){ }, .needs_console = true}; } if (id == StoryActionId::GAME){ - return {.act = [](const StoryStep& step, RunState&){ return Pokemon::unsupported_step(step); }, .needs_console = true}; + return {.act = [this](const StoryStep& step, RunState& state){ return game(state, step); }, .needs_console = true}; } const ConsoleAction action = console_action_of(id); return {.act = [this, action](const StoryStep& step, RunState& state){ return action(m_env, state, step); }, .needs_console = true}; } +Outcome StoryExecutor::game(RunState&, const StoryStep& step){ + if (step.action == CLOSE_TRAINER_CARD){ + close_trainer_card(m_env.console, m_env.context); + return Pokemon::outcome_ok(); + } + return Pokemon::unsupported_step(step); +} + + +namespace{ + +// `first` and `second` as one checkpoint: `first`'s id, start and +// supplies, `second`'s title and START menu, both rows' steps. +StoryCheckpoint joined_rows(const StoryCheckpoint& first, const StoryCheckpoint& second){ + StoryCheckpoint row = second; + row.id = first.id; + row.start = first.start; + row.supplies = first.supplies; + row.live_start = first.live_start; + row.steps = first.steps; + row.steps.insert(row.steps.end(), second.steps.begin(), second.steps.end()); + return row; +} + +} // namespace + +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs +){ + StoryRunPlan plan; + for (size_t c = first; c <= last && c < checkpoints.size(); c++){ + const StoryCheckpoint& row = checkpoints[c]; + if (row.live_start && c != first){ + continue; + } + if (row.handoff == StoryHandoff::SID_HELPER && handoffs.sid_helper){ + plan.rows.clear(); + plan.stop = StoryHandoff::SID_HELPER; + return plan; + } + if (row.handoff == StoryHandoff::STARTER_RNG && handoffs.starter_rng){ + plan.rows.emplace_back(row); + plan.stop = StoryHandoff::STARTER_RNG; + return plan; + } + if (row.handoff == StoryHandoff::STARTER_RNG && c + 1 < checkpoints.size()){ + plan.rows.emplace_back(joined_rows(row, checkpoints[c + 1])); + c++; + continue; + } + plan.rows.emplace_back(row); + } + return plan; +} + + std::string check_save_place(StoryEnv& env, const std::string& start_map){ if (save_card_place(start_map).empty()){ return ""; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h index 418c6f2c31..a1871d87f8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h @@ -59,6 +59,9 @@ struct StoryEnv{ // The game's language, for reading item names. In one the readers have // no names for, the checks fall back to positions and counts. Language language = Language::English; + // The name the new game's intro types for the player; empty keeps the + // game's default name. + std::string player_name = {}; // The map the checkpoint under way starts on, where its save is: a // reload checks the save card against it. std::string start_map = {}; @@ -114,6 +117,9 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome run(const StoryStep& step, Pokemon::RunState& state) override; private: + // A GAME step by its action. CLOSE_TRAINER_CARD: back from SID Helper + // (close_trainer_card()). + Pokemon::Outcome game(Pokemon::RunState& state, const StoryStep& step); // How the console does `id`. Pokemon::StoryAction console_action(StoryActionId id); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h index 735cc17aa6..bba79024fe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryIntro.h @@ -58,10 +58,21 @@ constexpr size_t RIVAL_PRESET_TRIES = 3; // Determines the next input step in character/rival naming sequence. IntroNameStep intro_name_step(IntroNameScreen screen, size_t keyboards_seen, size_t presets_picked); // From the title screen of a game with no save, to the bedroom: the -// controls pages, Oak's speech, BOY, the default name for the player (an -// empty name confirmed) and the rival's first preset name. Returns on the -// overworld. -void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context); +// controls pages, Oak's speech, BOY, `player_name` typed on the player's +// keyboard, and the rival's first preset name. An empty `player_name` +// keeps the player's default name (an empty name confirmed). Returns on +// the overworld. Throws UserSetupError if the game can't take the name +// (naming_text_error()). +void play_new_game_intro(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name); + +// play_new_game_intro() up to the player's keyboard: `player_name` typed, +// OK not pressed, which is where SID Helper starts. Empty types nothing. +void play_new_game_to_player_name(ConsoleHandle& console, ProControllerContext& context, const std::string& player_name); + +// From the Trainer Card SID Helper leaves open, or from HOME (its "go +// home when done"): back to the game, the card and the START menu closed. +// Returns on the overworld. +void close_trainer_card(ConsoleHandle& console, ProControllerContext& context); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h index 553ac917bc..bd0678bf3c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h @@ -54,6 +54,9 @@ struct StoryPose{ // has the Running Shoes (00.10 on). inline const std::string RUN_VARIANT = "run"; +// The GAME step that closes the Trainer Card SID Helper leaves open. +inline const std::string CLOSE_TRAINER_CARD = "close_trainer_card"; + // How `step`, a ROUTE or LEGS, moves the player: RUN_VARIANT runs. MoveSpeed move_speed(const StoryStep& step); // The maps the story plans on: every map to Brock, with the objects the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp new file mode 100644 index 0000000000..add7a07d36 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -0,0 +1,119 @@ +/* AutoStory RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// "-" for none. +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text.empty() ? "-" : text; +} + +} // namespace + +std::string starter_rng_loop_message(const StarterRngLoopResult& result){ + const std::string sids = join_sids(result.remaining_sids); + switch (result.end){ + case StarterRngLoopEnd::SHINY: + if (result.sid){ + return std::format("Starter RNG: shiny Squirtle. The SID is {}: saved as the RNG plan's SID, so AutoStory skips SID Helper's steps next time.", *result.sid); + } + if (result.remaining_sids.empty()){ + return "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates."; + } + return std::format("Starter RNG: shiny Squirtle. The SID is one of {}.", sids); + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return std::format( + "Starter RNG: shiny Squirtle, but not the planned target, so it doesn't tell the SID. SIDs left: {}.", sids + ); + case StarterRngLoopEnd::TARGET: + return "Starter RNG hit the target (shiny not required). Nothing was saved after it: the game is where " + "Starter RNG's calibration left it. Play to the rival's battle and save by hand, then start AutoStory at 00.05."; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return std::format( + "Starter RNG: every planned attempt hit its target and none was shiny. SIDs left: {}. " + "The save is still south of the table: raise the RNG plan's max attempts and start AutoStory at 00.04 again.", sids + ); + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "Starter RNG: every attempt left missed its target more often than the retries allow, or Starter RNG " + "refused its timings (see the log). The save is still south of the table: check the RNG plan's sound setting " + "and start AutoStory at 00.04 again."; + case StarterRngLoopEnd::OUT_OF_TIME: + return std::format( + "Starter RNG: out of time after {} attempts. The save is still south of the table: start AutoStory at 00.04 again.", + result.attempts_run + ); + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG loop end."); +} + + +CalibrationSavingSteps::CalibrationSavingSteps( + StarterRngLoopSteps& steps, RngStopCalibrationOptions& calibration, FloatingPointOption& ingame +) + : m_steps(steps) + , m_calibration(calibration) + , m_ingame(ingame) +{} + +WallClock CalibrationSavingSteps::now(){ + return m_steps.now(); +} + +StarterRngResult CalibrationSavingSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ + StarterRngAttemptCall saving = call; + saving.on_reset = [&](const StarterRngProgress& progress){ + m_calibration.save(progress.calibrations, m_ingame); + if (call.on_reset){ + call.on_reset(progress); + } + }; + return m_steps.run_attempt(attempt, saving); +} + + +std::vector rows_after_starter_rng( + const std::vector& checkpoints, size_t ball_row, size_t last +){ + if (ball_row + 1 >= checkpoints.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint after the starter's ball."); + } + StoryCheckpoint row = checkpoints[ball_row + 1]; + auto taken = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ + return step.name == "rival_takes_bulbasaur"; + }); + if (taken == row.steps.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, row.id + " has no rival_takes_bulbasaur step."); + } + row.steps.erase(row.steps.begin(), taken + 1); + row.title = "after Starter RNG in AutoStory: the rival's battle"; + + std::vector rows{std::move(row)}; + if (last > ball_row + 1){ + StoryRunPlan rest = plan_story_run(checkpoints, ball_row + 2, last, StoryHandoffs{}); + rows.insert(rows.end(), rest.rows.begin(), rest.rows.end()); + } + return rows; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h new file mode 100644 index 0000000000..6161bf4305 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -0,0 +1,74 @@ +/* AutoStory RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + * AutoStory's Starter RNG stop, run in the program with the Starter RNG + * loop (RngManipulation/PokemonFRLG_StarterRngLoop.h) from the save under + * Squirtle's ball: the plan it runs, what the run says when the loop + * ends, and the rows it takes after a shiny. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The Starter RNG plan, for the TID it was made for. +struct StarterRngPlanned{ + uint16_t tid = 0; + std::vector attempts; +}; + +// What the run says when the loop ends with `result`. +std::string starter_rng_loop_message(const StarterRngLoopResult& result); + + +// `steps`, with the calibration of each reset also kept in the RNG plan's +// calibration, with `ingame` as the stop's in-game advances offset, so the +// next run starts from it. +class CalibrationSavingSteps : public StarterRngLoopSteps{ +public: + CalibrationSavingSteps(StarterRngLoopSteps& steps, RngStopCalibrationOptions& calibration, FloatingPointOption& ingame); + + virtual WallClock now() override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; + +private: + StarterRngLoopSteps& m_steps; + RngStopCalibrationOptions& m_calibration; + FloatingPointOption& m_ingame; +}; + + +// The rows a run takes after a shiny from the loop, which leaves the player +// under Squirtle's ball with the rival's ball taken: the row after +// `ball_row` (00.04b) from its step after "rival_takes_bulbasaur", then +// the rows after it to `last` as plan_story_run() takes them. Throws +// InternalProgramError for a table without that row or step. +std::vector rows_after_starter_rng( + const std::vector& checkpoints, size_t ball_row, size_t last +); + + +// Registers AutoStory RNG loop unit tests. +void add_tests_AutoStoryRngLoop(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp new file mode 100644 index 0000000000..c164ec0bef --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -0,0 +1,239 @@ +/* AutoStory RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + * What the run says after a shiny, and the rows it takes then. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct AutoStoryRngLoopInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct AutoStoryRngLoopExpectation{ + std::string_view description; +}; + +struct AutoStoryRngLoopTestCase{ + AutoStoryRngLoopInput input; + AutoStoryRngLoopExpectation expectation; +}; + +class Test_AutoStoryRngLoop : public UnitTest{ +public: + explicit Test_AutoStoryRngLoop(AutoStoryRngLoopTestCase scenario) + : UnitTest("PokemonFRLG::AutoStoryRngLoop - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryRngLoopTestCase m_scenario; +}; + + + +// What the run says after a shiny, by what it tells of the SID. +UnitTestResult test_shiny_messages(){ + struct Case{ + StarterRngLoopResult result; + std::string expected; + }; + const std::vector cases = { + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 2, .remaining_sids = {300}, .sid = uint16_t(300)}, + .expected = "Starter RNG: shiny Squirtle. The SID is 300: saved as the RNG plan's SID, so AutoStory skips SID Helper's steps next time.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle. The SID is one of 100,200.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle, but not the planned target, so it doesn't tell the SID. " + "SIDs left: 100,200.", + }, + }; + for (const Case& item : cases){ + const std::string got = starter_rng_loop_message(item.result); + if (got != item.expected){ + return "Expected \"" + item.expected + "\", got \"" + got + "\"."; + } + } + return true; +} + + +// After a shiny, 00.04b picks up at the rival's trigger and runs on. +UnitTestResult test_rows_after_shiny(){ + const std::vector& checkpoints = story_checkpoints(); + size_t ball_row = 0; + size_t parcel_row = 0; + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == "00.04"){ + ball_row = c; + } + if (checkpoints[c].id == "00.05"){ + parcel_row = c; + } + } + struct Case{ + size_t last; + std::string ids; + }; + const std::vector cases = { + {.last = ball_row, .ids = "00.04b"}, + {.last = ball_row + 1, .ids = "00.04b"}, + {.last = parcel_row, .ids = "00.04b,00.05"}, + }; + for (const Case& item : cases){ + const std::vector rows = rows_after_starter_rng(checkpoints, ball_row, item.last); + std::string ids; + for (const StoryCheckpoint& row : rows){ + ids += (ids.empty() ? "" : ",") + row.id; + } + const std::string first_step = rows.front().steps.empty() ? "" : rows.front().steps.front().name; + if (ids != item.ids || first_step != "above_rival_trigger"){ + return std::format( + "Expected rows {} starting at above_rival_trigger; got {} starting at {}", item.ids, ids, first_step + ); + } + } + return true; +} + + +std::string calibration_text(const RngCalibrations& calibration){ + return std::format("{}/{}/{}", calibration.seed_offset, calibration.csf_offset, calibration.ingame_offset); +} + +// Starter RNG starts from the RNG plan's calibration: the console's seed +// and Continue Screen Frames offsets, and Starter RNG's in-game offset. +UnitTestResult test_starter_calibration_from_options(){ + StarterRngPlanOptions options; + RngStopCalibrationOptions& calibration = options.CALIBRATION; + const RngCalibrations zero{.seed_offset = 0, .csf_offset = 0, .ingame_offset = 0}; + if (calibration.calibration(calibration.STARTER_INGAME) != zero){ + return "Expected no calibration by default; got " + calibration_text(calibration.calibration(calibration.STARTER_INGAME)); + } + calibration.SEED.set(17); + calibration.CSF.set(0.5); + calibration.STARTER_INGAME.set(-1.2); + const RngCalibrations expected{.seed_offset = 17 / FRLG_FRAME_DURATION, .csf_offset = 0.5, .ingame_offset = -1.2}; + const RngCalibrations got = calibration.calibration(calibration.STARTER_INGAME); + if (got != expected){ + return std::format("Expected calibration {}; got {}", calibration_text(expected), calibration_text(got)); + } + return true; +} + +// Steps whose one try resets once for each calibration in `resets`. +class ResettingSteps : public StarterRngLoopSteps{ +public: + explicit ResettingSteps(std::vector resets) : m_resets(std::move(resets)) {} + virtual WallClock now() override{ return WallClock{}; } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ + for (size_t c = 0; c < m_resets.size(); c++){ + call.on_reset(StarterRngProgress{.resets = c + 1, .calibrations = m_resets[c]}); + } + return StarterRngResult{.outcome = StarterRngOutcome::out_of_resets, .pokemon = std::nullopt}; + } + +private: + std::vector m_resets; +}; + +// Each reset's calibration is kept in the RNG plan before the loop hears +// of the reset, so a run stopped after it keeps it. +UnitTestResult test_starter_calibration_saved(){ + StarterRngPlanOptions options; + RngStopCalibrationOptions& calibration = options.CALIBRATION; + ResettingSteps resetting({ + {.seed_offset = 0.5, .csf_offset = 0.25, .ingame_offset = -0.5}, + {.seed_offset = 1.0, .csf_offset = 0.5, .ingame_offset = -1.2}, + }); + CalibrationSavingSteps steps(resetting, calibration, calibration.STARTER_INGAME); + std::vector csf_at_reset; + steps.run_attempt(RngAttempt{}, StarterRngAttemptCall{ + .index = 0, .deadline = WallClock{}, .max_resets = 2, + .on_reset = [&](const StarterRngProgress&){ csf_at_reset.emplace_back(calibration.CSF); }, + }); + if (csf_at_reset != std::vector{0.25, 0.5}){ + std::string got; + for (double csf : csf_at_reset){ + got += std::format(" {}", csf); + } + return "Expected the CSF offset saved at each reset as 0.25 0.5; got" + got; + } + // The seed offset is kept in ms: 1.0 frame is 16.7 ms. + if (int64_t(calibration.SEED) != 17 || double(calibration.STARTER_INGAME) != -1.2){ + return std::format( + "Expected seed 17 ms and Starter RNG in-game -1.2 saved; got {} ms and {}", + int64_t(calibration.SEED), double(calibration.STARTER_INGAME) + ); + } + return true; +} + +const AutoStoryRngLoopTestCase AUTO_STORY_RNG_LOOP_CASES[] = { + { + .input = {.name = "shiny messages", .body = test_shiny_messages}, + .expectation = {.description = "formats notifications for shiny starter encounters"}, + }, + { + .input = {.name = "rows after a shiny", .body = test_rows_after_shiny}, + .expectation = {.description = "plans continuation rows following shiny discovery"}, + }, + { + .input = {.name = "Starter RNG starts from the RNG plan's calibration", .body = test_starter_calibration_from_options}, + .expectation = {.description = "initializes starter calibrations from program options"}, + }, + { + .input = {.name = "Starter RNG saves its calibration after each reset", .body = test_starter_calibration_saved}, + .expectation = {.description = "persists calibration adjustments across reset cycles"}, + }, +}; + +} // namespace + + +void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ + for (const auto& scenario : AUTO_STORY_RNG_LOOP_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp new file mode 100644 index 0000000000..a92f1bf0f9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp @@ -0,0 +1,199 @@ +/* AutoStory RNG Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngStopCalibrationOptions::RngStopCalibrationOptions() + : GroupOption("RNG Calibration (this console)", LockMode::LOCK_WHILE_RUNNING) + , SEED( + "Seed Calibration (ms):
As in Starter RNG's RNG Calibration. Each RNG stop starts from it, " + "and saves what it learns after every reset.", + LockMode::LOCK_WHILE_RUNNING, 0 + ) + , CSF( + "Continue Screen Frames Calibration:
As in Starter RNG's RNG Calibration, kept as the seed's is.", + LockMode::LOCK_WHILE_RUNNING, 0.0 + ) + , STARTER_INGAME( + "Starter RNG's In-Game Advances Calibration:
As in Starter RNG's RNG Calibration, " + "for Squirtle only: each RNG stop keeps its own.", + LockMode::LOCK_WHILE_RUNNING, 0.0 + ) +{ + PA_ADD_OPTION(SEED); + PA_ADD_OPTION(CSF); + PA_ADD_OPTION(STARTER_INGAME); +} + +RngCalibrations RngStopCalibrationOptions::calibration(const FloatingPointOption& ingame) const{ + return RngCalibrations{ + .seed_offset = double(int64_t(SEED)) / FRLG_FRAME_DURATION, + .csf_offset = CSF, + .ingame_offset = ingame, + }; +} + +void RngStopCalibrationOptions::save(const RngCalibrations& calibration, FloatingPointOption& ingame){ + // In ms, as RngCalibrationDisplay::set_calibrations() shows it. + SEED.set(int64_t(std::round(calibration.seed_offset * FRLG_FRAME_DURATION))); + CSF.set(calibration.csf_offset); + ingame.set(calibration.ingame_offset); +} + + +StarterRngPlanOptions::StarterRngPlanOptions() + : GroupOption("RNG Plan (Stop for Starter RNG)", LockMode::LOCK_WHILE_RUNNING) + , SOUND( + "Sound:
The in-game sound setting, as in Starter RNG. It picks the seeds.", + {{SoundSetting::Mono, "mono", "Mono"}, {SoundSetting::Stereo, "stereo", "Stereo"}}, + LockMode::LOCK_WHILE_RUNNING, SoundSetting::Mono + ) + , TID( + false, "TID:
Empty: read from the Trainer Card at the stop. Set it only if that read fails.", + LockMode::LOCK_WHILE_RUNNING, "", "" + ) + , SID( + false, + "SID:
The SID, once known. Empty: plan for the SIDs SID Helper lists, from the two options below. " + "Run Starter RNG in AutoStory fills it in when a shiny Squirtle confirms the SID.", + LockMode::LOCK_WHILE_RUNNING, "", "" + ) + , SID_HELPER_ADVANCES( + "SID Helper's Target Advances:
As set in SID Helper.", + LockMode::LOCK_WHILE_RUNNING, 3001, 2275 + ) + , SID_HELPER_CANDIDATES( + "SID Helper's # Candidate SIDs:
As set in SID Helper. The middle one counts as the likeliest.", + LockMode::LOCK_WHILE_RUNNING, 5, 1, 11 + ) + , SHINY_REQUIRED( + "Shiny required:
Only targets shiny for a SID candidate, tried until one comes out shiny. " + "Off: the quickest target that passes the natures and IVs.", + LockMode::LOCK_WHILE_RUNNING, true + ) + , NATURES(false, "Natures:
Separated by commas. Empty: any nature.", LockMode::LOCK_WHILE_RUNNING, "", "Modest, Timid") + , MIN_IVS( + false, "Minimum IVs:
HP/Atk/Def/SpA/SpD/Spe.", + LockMode::LOCK_WHILE_RUNNING, "0/0/0/0/0/0", "0/0/0/0/0/0" + ) + , MAX_ATTEMPTS("Max attempts:
The most targets to list.", LockMode::LOCK_WHILE_RUNNING, 5, 1, 20) +{ + PA_ADD_OPTION(SOUND); + PA_ADD_OPTION(TID); + PA_ADD_OPTION(SID); + PA_ADD_OPTION(SID_HELPER_ADVANCES); + PA_ADD_OPTION(SID_HELPER_CANDIDATES); + PA_ADD_OPTION(SHINY_REQUIRED); + PA_ADD_OPTION(NATURES); + PA_ADD_OPTION(MIN_IVS); + PA_ADD_OPTION(MAX_ATTEMPTS); + PA_ADD_OPTION(CALIBRATION); +} + +std::string StarterRngPlanOptions::sound_name() const{ + return SOUND == SoundSetting::Stereo ? "Stereo" : "Mono"; +} + +std::optional StarterRngPlanOptions::tid_override(Logger& logger) const{ + const std::string text = TID; + if (text.empty()){ + return std::nullopt; + } + const std::optional tid = parse_trainer_id(text); + if (!tid){ + throw UserSetupError(logger, "RNG plan: the TID must be a number from 0 to 65535, or empty."); + } + return tid; +} + +std::optional StarterRngPlanOptions::sid(Logger& logger) const{ + const std::string text = SID; + if (text.empty()){ + return std::nullopt; + } + const std::optional sid = parse_trainer_id(text); + if (!sid){ + throw UserSetupError(logger, "RNG plan: the SID must be a number from 0 to 65535, or empty."); + } + return sid; +} + +RngTargetFilters StarterRngPlanOptions::filters(Logger& logger) const{ + const std::optional> natures = parse_natures(NATURES); + if (!natures){ + throw UserSetupError(logger, "RNG plan: natures must be nature names separated by commas, e.g. \"Modest, Timid\"."); + } + const std::optional min_ivs = parse_ivs(MIN_IVS); + if (!min_ivs){ + throw UserSetupError(logger, "RNG plan: minimum IVs must be six numbers from 0 to 31, e.g. \"0/0/0/31/0/31\"."); + } + RngTargetFilters filters; + filters.natures = *natures; + filters.min_ivs = *min_ivs; + filters.shiny_required = SHINY_REQUIRED; + return filters; +} + +void StarterRngPlanOptions::check(Logger& logger) const{ + tid_override(logger); + sid(logger); + filters(logger); +} + +std::vector StarterRngPlanOptions::helper_candidates(uint16_t tid) const{ + return sid_helper_candidates(tid, SID_HELPER_ADVANCES, SID_HELPER_CANDIDATES); +} + +std::vector StarterRngPlanOptions::plan_candidates(Logger& logger, uint16_t tid) const{ + const std::optional known = sid(logger); + return known ? std::vector{{*known, 1}} : helper_candidates(tid); +} + +std::vector StarterRngPlanOptions::plan(Logger& logger, Language language, uint16_t tid) const{ + // SID Helper's candidates are logged even with the SID known, to place + // it among them (rng_log_confirmed()). + const std::vector helper = helper_candidates(tid); + logger.log(rng_log_sid_helper(tid, SID_HELPER_ADVANCES, helper)); + const std::optional known = sid(logger); + if (known){ + logger.log(rng_log_confirmed(tid, *known, helper)); + } + + const std::vector attempts = plan_starter_rng(StarterRngPlanInputs{ + // TODO: LeafGreen, once AutoStory plays it. + .firered = true, + .language = language, + .sound = SOUND, + .tid = tid, + .candidates = plan_candidates(logger, tid), + .filters = filters(logger), + .max_attempts = MAX_ATTEMPTS, + }); + if (attempts.empty()){ + throw UserSetupError(logger, + "RNG plan: no Starter RNG target passes the natures, minimum IVs and shiny options for TID " + std::to_string(tid) + "." + ); + } + for (size_t c = 0; c < attempts.size(); c++){ + logger.log(rng_log_attempt(c, attempts[c])); + } + return attempts; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h new file mode 100644 index 0000000000..44d73a275c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h @@ -0,0 +1,101 @@ +/* AutoStory RNG Options + * + * From: https://github.com/PokemonAutomation/ + * + * The RNG plan options: what AutoStory's Starter RNG stop searches targets + * with (RngManipulation/PokemonFRLG_RngPlan.h). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRngOptions_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRngOptions_H + +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Language.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// This console's RNG calibration, as Starter RNG's RNG Calibration shows +// it, for AutoStory's RNG stops to start from: the seed and Continue +// Screen Frames offsets, the same for every stop, and an in-game advances +// offset for each stop. +class RngStopCalibrationOptions : public GroupOption{ +public: + RngStopCalibrationOptions(); + + // The calibration in frames for the stop whose in-game advances offset + // `ingame` keeps. + RngCalibrations calibration(const FloatingPointOption& ingame) const; + // Keeps `calibration` as calibration() returns it. Called after each + // reset, so a stopped run keeps what it learned. + void save(const RngCalibrations& calibration, FloatingPointOption& ingame); + +public: + SimpleIntegerOption SEED; + FloatingPointOption CSF; + // Starter RNG's in-game advances offset. + FloatingPointOption STARTER_INGAME; +}; + + +// User options for Starter RNG plan execution. +class StarterRngPlanOptions : public GroupOption{ +public: + StarterRngPlanOptions(); + + // Throws UserSetupError for a TID, SID, natures or IVs it can't read, + // before the run presses anything. + void check(Logger& logger) const; + // The TID typed in, or nothing to read it from the Trainer Card. + std::optional tid_override(Logger& logger) const; + + // The attempts these options ask for, for TID "tid" in a FireRed game + // in "language", logged as "RngPlan:" lines. Throws UserSetupError + // when no target passes. + std::vector plan(Logger& logger, Language language, uint16_t tid) const; + // SID Helper's candidates for "tid", from the two SID Helper options. + std::vector helper_candidates(uint16_t tid) const; + // The SIDs plan() plans for: the SID if set, else helper_candidates(). + std::vector plan_candidates(Logger& logger, uint16_t tid) const; + // The sound setting as Starter RNG's dropdown shows it. + std::string sound_name() const; + +public: + EnumDropdownOption SOUND; + StringOption TID; + StringOption SID; + SimpleIntegerOption SID_HELPER_ADVANCES; + SimpleIntegerOption SID_HELPER_CANDIDATES; + BooleanCheckBoxOption SHINY_REQUIRED; + StringOption NATURES; + StringOption MIN_IVS; + SimpleIntegerOption MAX_ATTEMPTS; + RngStopCalibrationOptions CALIBRATION; + +private: + RngTargetFilters filters(Logger& logger) const; + std::optional sid(Logger& logger) const; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp index 20cbaf91ce..a0272973e9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -165,6 +165,7 @@ class FakeGame : public Pokemon::StoryStepExecutor{ case StoryStepKind::MASH: case StoryStepKind::BATTLE: case StoryStepKind::HEAL: + case StoryStepKind::GAME: return Pokemon::outcome_ok(); default: return Pokemon::unsupported_step(step); @@ -248,9 +249,11 @@ class FakeGame : public Pokemon::StoryStepExecutor{ }; -// One simulated run, segment built as the program builds it: each -// checkpoint saves at its end (hooks.save stands for save_game()). +// One simulated run, segment built as the program builds it: the rows a +// run takes with every handoff off, each saving at its end (hooks.save +// stands for save_game()). struct Simulation{ + std::vector rows = plan_story_run(story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{}).rows; FakeGame game; std::vector lines; // Where each save stood: the end of its checkpoint. @@ -260,7 +263,7 @@ struct Simulation{ Pokemon::SegmentReport run(const Pokemon::SegmentRange& range){ Pokemon::Segment segment; segment.id = "00"; - for (const StoryCheckpoint& data : story_checkpoints()){ + for (const StoryCheckpoint& data : rows){ segment.checkpoints.push_back(Pokemon::CheckpointSpec{ .id = data.id, .title = data.title, .saves = true, .build = [this, &data]{ @@ -347,15 +350,15 @@ UnitTestResult test_whole_story(){ return "Expected the whole story through:" + joined(sim.lines); } std::vector ids; - for (const StoryCheckpoint& data : story_checkpoints()){ + for (const StoryCheckpoint& data : sim.rows){ ids.push_back(data.id); } if (sim.begun() != ids || sim.saves.size() != ids.size()){ return "Expected each checkpoint once, in order, each saving at its end:" + joined(sim.game.trace); } // Each checkpoint starts where the save before it stands. - for (size_t c = 1; c < story_checkpoints().size(); c++){ - const StoryCheckpoint& data = story_checkpoints()[c]; + for (size_t c = 1; c < sim.rows.size(); c++){ + const StoryCheckpoint& data = sim.rows[c]; const std::optional start = story_pose(*start_pose(data)); const std::optional saved = story_pose(sim.saves[c - 1].second); const bool same = start && saved && start->map == saved->map && start->tile == saved->tile diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp index b628fbcb5b..51691bb0ca 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepTable.cpp @@ -5,6 +5,7 @@ */ #include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryStepTable.h" namespace PokemonAutomation{ @@ -75,6 +76,7 @@ std::span story_action_specs(){ run.name = "run"; specs.push_back(std::move(run)); } + specs.push_back({.kind = StoryStepKind::GAME, .name = CLOSE_TRAINER_CARD, .args = {}}); return specs; }(); return SPECS; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp index 8c9b714717..fd11956d35 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp @@ -35,6 +35,17 @@ StartMenu read_start_menu(std::string_view name, std::string_view source){ throw ParseException(std::format("{}: unknown START menu {}", source, name)); } +// The wire names of the handoffs. +StoryHandoff read_handoff(std::string_view name, std::string_view source){ + if (name == "sid_helper"){ + return StoryHandoff::SID_HELPER; + } + if (name == "starter_rng"){ + return StoryHandoff::STARTER_RNG; + } + throw ParseException(std::format("{}: unknown handoff {}", source, name)); +} + // `object`'s fields, each of which must be one of `keys`. void only_fields(const JsonObject& object, std::initializer_list keys, std::string_view source){ for (const auto& [key, unused] : object){ @@ -126,9 +137,15 @@ StoryCheckpoint read_story_checkpoint_file(const JsonValue& value, std::string_v StoryCheckpoint checkpoint; std::set note_keys; const Pokemon::ExecutionReader read_execution = [&](const JsonObject& execution, std::string_view where){ - only_fields(execution, {"menu", "supplies", "lead", "notes"}, where); + only_fields(execution, {"menu", "supplies", "lead", "handoff", "live_start", "notes"}, where); checkpoint.menu = read_start_menu(execution.get_string_throw("menu", std::string(where)), where); checkpoint.supplies = read_supplies(execution, where); + if (execution.get_value("handoff") != nullptr){ + checkpoint.handoff = read_handoff(execution.get_string_throw("handoff", std::string(where)), where); + } + if (execution.get_value("live_start") != nullptr){ + checkpoint.live_start = execution.get_boolean_throw("live_start", std::string(where)); + } note_keys = read_note_keys(execution, where); }; static_cast(checkpoint) = Pokemon::read_authored_checkpoint( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h index 62cbb37513..c96fab5a14 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h @@ -18,6 +18,10 @@ * its start, for a run that loads its save; * "lead" optional: "after_brock", the starter as the story left * it by Brock (story_lead_after_brock()); + * "handoff" optional: sid_helper or starter_rng, the RNG program + * the user may run there (StoryCheckpoint::handoff); + * "live_start" optional, true: it starts from the game as another + * program left it (StoryCheckpoint::live_start); * "notes" optional: {"checkpoint" or a step's id: [lines]}, the * reasons behind a step that a reader of the file needs. * The program doesn't read them. @@ -52,7 +56,9 @@ const std::vector>& autostory_checkpoint_jso // action args it doesn't take, or has notes for a step it doesn't have. StoryCheckpoint read_story_checkpoint_file(const JsonValue& value, std::string_view source); -// Checkpoints 00.01 to 00.10, in order: every file in StoryData/. +// Checkpoints 00.01 to 00.10, in order: every file in StoryData/. With +// 00.01b, the way back in after SID Helper, after 00.01, and 00.04 split +// in two at Squirtle's ball for Starter RNG: 00.04 and 00.04b. const std::vector& story_checkpoints(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index 5768edbd81..7772c9dc93 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -227,8 +228,8 @@ UnitTestResult check_checkpoint(const StoryCheckpoint& checkpoint, StoryPose& po UnitTestResult test_routes_and_chain(){ const std::vector& checkpoints = story_checkpoints(); - if (checkpoints.size() != 10 || checkpoints[0].start){ - return "Expected 10 checkpoints, the first from a new game."; + if (checkpoints.size() != 12 || checkpoints[0].start){ + return "Expected 12 checkpoints, the first from a new game."; } StoryPose pose; for (size_t c = 0; c < checkpoints.size(); c++){ @@ -574,6 +575,188 @@ UnitTestResult test_intro_names(){ return true; } + +size_t row_index(std::string_view id){ + const std::vector& checkpoints = story_checkpoints(); + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == id){ + return c; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint " + std::string(id)); +} + +std::string joined_ids(const std::vector& rows){ + std::string text; + for (const StoryCheckpoint& row : rows){ + text += (text.empty() ? "" : " ") + row.id; + } + return text; +} + +std::string handoff_name(StoryHandoff handoff){ + switch (handoff){ + case StoryHandoff::NONE: + return "none"; + case StoryHandoff::SID_HELPER: + return "SID Helper"; + case StoryHandoff::STARTER_RNG: + return "Starter RNG"; + } + return "?"; +} + +struct RunPlanInput{ + std::string name = ""; + std::string first = ""; + // The table's last row if empty. + std::string last = ""; + StoryHandoffs handoffs = {}; +}; + +struct RunPlanExpectation{ + std::string expected_ids = ""; + StoryHandoff expected_stop = StoryHandoff::NONE; +}; + +struct RunPlanTestCase{ + RunPlanInput input; + RunPlanExpectation expectation; +}; + +class Test_RunPlan : public UnitTest{ +public: + explicit Test_RunPlan(RunPlanTestCase scenario) + : UnitTest("PokemonFRLG::AutoStory - run plan: " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + const size_t last = m_scenario.input.last.empty() ? story_checkpoints().size() - 1 : row_index(m_scenario.input.last); + const StoryRunPlan plan = plan_story_run(story_checkpoints(), row_index(m_scenario.input.first), last, m_scenario.input.handoffs); + const std::string ids = joined_ids(plan.rows); + if (ids != m_scenario.expectation.expected_ids || plan.stop != m_scenario.expectation.expected_stop){ + return "Expected rows \"" + m_scenario.expectation.expected_ids + "\", stop " + handoff_name(m_scenario.expectation.expected_stop) + + "; got \"" + ids + "\", stop " + handoff_name(plan.stop) + "."; + } + return true; + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + const RunPlanTestCase m_scenario; +}; + +const RunPlanTestCase RUN_PLAN_CASES[] = { + { + .input = {.name = "handoffs off: the story as before", .first = "00.01"}, + .expectation = {.expected_ids = "00.01 00.02 00.03 00.04 00.05 00.06 00.07 00.08 00.09 00.10"}, + }, + { + .input = {.name = "handoffs off: a range", .first = "00.02", .last = "00.04"}, + .expectation = {.expected_ids = "00.02 00.03 00.04"}, + }, + { + .input = {.name = "SID Helper: 00.01 stops on the keyboard", .first = "00.01", .handoffs = {.sid_helper = true}}, + .expectation = {.expected_ids = "", .expected_stop = StoryHandoff::SID_HELPER}, + }, + { + .input = {.name = "SID Helper: back in at 00.01b", .first = "00.01b", .last = "00.03", .handoffs = {.sid_helper = true}}, + .expectation = {.expected_ids = "00.01b 00.02 00.03"}, + }, + { + .input = {.name = "00.01b runs when started at, option off", .first = "00.01b", .last = "00.02"}, + .expectation = {.expected_ids = "00.01b 00.02"}, + }, + { + .input = {.name = "SID Helper: a later start passes over it", .first = "00.02", .last = "00.03", .handoffs = {.sid_helper = true}}, + .expectation = {.expected_ids = "00.02 00.03"}, + }, + { + .input = {.name = "handoffs off: an end at 00.04 still takes the rival's battle", .first = "00.03", .last = "00.04"}, + .expectation = {.expected_ids = "00.03 00.04"}, + }, + { + .input = {.name = "Starter RNG: stops after 00.04's save", .first = "00.02", .handoffs = {.starter_rng = true}}, + .expectation = {.expected_ids = "00.02 00.03 00.04", .expected_stop = StoryHandoff::STARTER_RNG}, + }, + { + .input = {.name = "00.04b runs from its own save", .first = "00.04b", .last = "00.05"}, + .expectation = {.expected_ids = "00.04b 00.05"}, + }, + { + .input = {.name = "Starter RNG: a later start doesn't stop", .first = "00.05", .last = "00.06", .handoffs = {.starter_rng = true}}, + .expectation = {.expected_ids = "00.05 00.06"}, + }, + { + .input = {.name = "both handoffs, back in after SID Helper", .first = "00.01b", .handoffs = {.sid_helper = true, .starter_rng = true}}, + .expectation = {.expected_ids = "00.01b 00.02 00.03 00.04", .expected_stop = StoryHandoff::STARTER_RNG}, + }, +}; + +void add_tests_RunPlan(UnitTestDatabase& database){ + for (const auto& scenario : RUN_PLAN_CASES){ + database.add(scenario); + } +} + +std::string step_names(const StoryCheckpoint& checkpoint){ + std::string text; + for (const StoryStep& step : checkpoint.steps){ + text += (text.empty() ? "" : " ") + step.name; + } + return text; +} + +// With Starter RNG's handoff off, 00.04 and 00.04b run as the one 00.04 +// the story had before the split: from the lab's table to the rival's +// battle, saving once with the starter's START menu. +UnitTestResult test_starter_rows_joined(){ + const std::vector& checkpoints = story_checkpoints(); + const StoryRunPlan plan = plan_story_run(checkpoints, row_index("00.04"), row_index("00.04b"), StoryHandoffs{}); + const std::string expected_steps = + "below_squirtle squirtle_ball choose_squirtle no_nickname rival_takes_bulbasaur above_rival_trigger rival_trigger rival_battle"; + if (plan.rows.size() != 1){ + return "Expected one checkpoint, got \"" + joined_ids(plan.rows) + "\"."; + } + const StoryCheckpoint& row = plan.rows[0]; + if (row.id != "00.04" || row.title != "Squirtle, then the rival's battle" || step_names(row) != expected_steps){ + return "Expected 00.04 \"Squirtle, then the rival's battle\": " + expected_steps + + "; got " + row.id + " \"" + row.title + "\": " + step_names(row); + } + const std::optional start = story_pose(Pokemon::pose_of(*row.start)); + if (!start || start->map != "PalletTown_ProfessorOaksLab" || !(start->tile == TilePos{6, 4}) || row.menu != StartMenu::BEFORE_POKEDEX){ + return "Expected the joined 00.04 to start at the table (6, 4) and save with the starter's START menu."; + } + // Split, 00.04 saves under the ball facing it, before the starter. + const StoryCheckpoint& to_ball = checkpoints[row_index("00.04")]; + const std::optional ball = story_pose(Pokemon::pose_of(*checkpoints[row_index("00.04b")].start)); + if (to_ball.handoff != StoryHandoff::STARTER_RNG || to_ball.menu != StartMenu::BEFORE_POKEMON + || !ball || !(ball->tile == TilePos{9, 5}) || ball->facing != Direction::NORTH + ){ + return "Expected 00.04 to end under Squirtle's ball (9, 5) facing north, saving before the starter."; + } + return true; +} + +// The way back in after SID Helper loads no save and starts where 00.01 +// leaves the player, so 00.02 follows it unchanged. +UnitTestResult test_after_sid_helper_row(){ + const StoryCheckpoint& sid = story_checkpoints()[row_index("00.01b")]; + if (!sid.live_start || story_checkpoints()[0].handoff != StoryHandoff::SID_HELPER){ + return "Expected 00.01 to be SID Helper's handoff and 00.01b to start from the live game."; + } + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + if (checkpoint.live_start != (checkpoint.id == "00.01b")){ + return checkpoint.id + ": only 00.01b starts from the live game."; + } + } + return true; +} + // set_options()'s RIGHT presses from each value an old save can leave: // on console B a save with FAST and SET became SLOW and SHIFT when the // presses assumed MID and SHIFT. @@ -615,6 +798,14 @@ UnitTestResult test_option_presses(){ } const AutoStoryTestCase AUTO_STORY_CASES[] = { + { + .input = {.name = "00.01b: back in after SID Helper", .body = test_after_sid_helper_row}, + .expectation = {.description = "resumes story after SID Helper row"}, + }, + { + .input = {.name = "00.04 and 00.04b: one checkpoint with Starter RNG off", .body = test_starter_rows_joined}, + .expectation = {.description = "joins starter checkpoint rows when Starter RNG is disabled"}, + }, { .input = {.name = "every route plans, and checkpoints chain", .body = test_routes_and_chain}, .expectation = {.description = "verifies route planning validity across all chained checkpoints"}, @@ -669,6 +860,7 @@ const AutoStoryTestCase AUTO_STORY_CASES[] = { void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_RunPlan(database); for (const auto& scenario : AUTO_STORY_CASES){ database.add(scenario); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json index 3e47c1be6b..4a051b5b16 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01.plan.json @@ -9,7 +9,7 @@ "id": "intro", "kind": "new_game", "declared_after": {"map": "PalletTown_PlayersHouse_2F", "tiles": [[6, 6]], "facing": "north"}, - "why": "Oak's speech, BOY, default names, rival GREEN" + "why": "Oak's speech, BOY, the player's name (default if none is set), rival GREEN" }, { "id": "options", @@ -20,6 +20,7 @@ }, "execution": { "menu": "before_pokemon", + "handoff": "sid_helper", "notes": { "intro": [ "new_game.c: the bedroom at (6, 6), facing the TV." diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01b.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01b.plan.json new file mode 100644 index 0000000000..e64cad0a98 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.01b.plan.json @@ -0,0 +1,33 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.01b", + "title": "after SID Helper: close the Trainer Card, save in the bedroom", + "start": {"map": "PalletTown_PlayersHouse_2F", "tiles": [[6, 6]], "facing": "north"}, + "events": [ + { + "id": "close_trainer_card", + "kind": "game_action", + "action": "close_trainer_card", + "declared_after": {"map": "PalletTown_PlayersHouse_2F", "tiles": [[6, 6]], "facing": "north"}, + "why": "the Trainer Card SID Helper left open, or HOME" + }, + { + "id": "options", + "kind": "options", + "why": "fast text; no switch prompt between a trainer's Pokemon" + } + ] + }, + "execution": { + "menu": "before_pokemon", + "live_start": true, + "notes": { + "checkpoint": [ + "SID Helper confirms the name, finishes the intro and reads the Trainer Card from the START menu, without moving the player or saving." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json index db5ea566e7..a49a93050b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04.plan.json @@ -3,7 +3,7 @@ "game": "frlg", "checkpoint": { "id": "00.04", - "title": "Squirtle, then the rival's battle", + "title": "to Squirtle's ball, south of the table", "start": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[6, 4]], "facing": "north"}, "events": [ { @@ -13,65 +13,15 @@ "target": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[9, 5]], "facing": "north"} }, "why": "under Squirtle's ball (9, 4)" - }, - { - "id": "squirtle_ball", - "kind": "talk", - "why": "\"So, you want the WATER POKEMON SQUIRTLE?\"" - }, - { - "id": "choose_squirtle", - "kind": "answer", - "why": "take Squirtle" - }, - { - "id": "no_nickname", - "kind": "answer", - "args": { - "yes": false - }, - "why": "\"give a nickname?\" NO" - }, - { - "id": "rival_takes_bulbasaur", - "kind": "scene", - "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[9, 5]], "facing": "north"}, - "why": "the rival picks his ball; the player still faces the table (console B, 2026-11-01)" - }, - { - "id": "above_rival_trigger", - "kind": "route", - "args": { - "target": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 7]], "facing": "south"} - }, - "why": "short of the rival's trigger row 8" - }, - { - "id": "rival_trigger", - "kind": "step", - "args": { - "direction": "south" - }, - "why": "\"Wait, let's check out our POKEMON!\"" - }, - { - "id": "rival_battle", - "kind": "battle", - "args": { - "may_lose": true, - "trainer": "TRAINER_RIVAL_OAKS_LAB_BULBASAUR", - "foes": ["bulbasaur"] - }, - "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 8]], "facing": "south"}, - "why": "the tutorial battle; losing goes on too" } ] }, "execution": { - "menu": "before_pokedex", + "menu": "before_pokemon", + "handoff": "starter_rng", "notes": { - "rival_battle": [ - "The rival leaves; PlayerWatchRivalExitAfterBattleRight ends facing down." + "checkpoint": [ + "Starter RNG starts from a save south of the table, facing the ball." ] } }, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04b.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04b.plan.json new file mode 100644 index 0000000000..9480ed6556 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-00.04b.plan.json @@ -0,0 +1,71 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "frlg", + "checkpoint": { + "id": "00.04b", + "title": "Squirtle, then the rival's battle", + "start": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[9, 5]], "facing": "north"}, + "events": [ + { + "id": "squirtle_ball", + "kind": "talk", + "why": "\"So, you want the WATER POKEMON SQUIRTLE?\"" + }, + { + "id": "choose_squirtle", + "kind": "answer", + "why": "take Squirtle" + }, + { + "id": "no_nickname", + "kind": "answer", + "args": { + "yes": false + }, + "why": "\"give a nickname?\" NO" + }, + { + "id": "rival_takes_bulbasaur", + "kind": "scene", + "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[9, 5]], "facing": "north"}, + "why": "the rival picks his ball; the player still faces the table (console B, 2026-11-01)" + }, + { + "id": "above_rival_trigger", + "kind": "route", + "args": { + "target": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 7]], "facing": "south"} + }, + "why": "short of the rival's trigger row 8" + }, + { + "id": "rival_trigger", + "kind": "step", + "args": { + "direction": "south" + }, + "why": "\"Wait, let's check out our POKEMON!\"" + }, + { + "id": "rival_battle", + "kind": "battle", + "args": { + "may_lose": true, + "trainer": "TRAINER_RIVAL_OAKS_LAB_BULBASAUR", + "foes": ["bulbasaur"] + }, + "declared_after": {"map": "PalletTown_ProfessorOaksLab", "tiles": [[7, 8]], "facing": "south"}, + "why": "the tutorial battle; losing goes on too" + } + ] + }, + "execution": { + "menu": "before_pokedex", + "notes": { + "rival_battle": [ + "The rival leaves; PlayerWatchRivalExitAfterBattleRight ends facing down." + ] + } + }, + "metadata": {"phase": "testing"} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp new file mode 100644 index 0000000000..ece34d24c1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp @@ -0,0 +1,106 @@ +/* Naming Screen + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_NamingScreenDetector.h" +#include "PokemonFRLG_NamingScreen.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// The game reads new presses once per frame and starts repeating a held direction after +// about 40 frames, so a short hold with a release of several frames is one press each. +constexpr Milliseconds PRESS_HOLD = 80ms; +constexpr Milliseconds MOVE_RELEASE = 120ms; +constexpr Milliseconds KEY_RELEASE = 200ms; +// The page swap animation runs 32 frames (about 530 ms) with input disabled. +constexpr Milliseconds PAGE_SWAP_RELEASE = 900ms; +// After the last character fits, the cursor animates to OK with input disabled. +constexpr Milliseconds START_RELEASE = 500ms; + +void press(ProControllerContext& context, NamingAction action){ + switch (action){ + case NamingAction::UP: + pbf_press_dpad(context, DPAD_UP, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::DOWN: + pbf_press_dpad(context, DPAD_DOWN, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::LEFT: + pbf_press_dpad(context, DPAD_LEFT, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::RIGHT: + pbf_press_dpad(context, DPAD_RIGHT, PRESS_HOLD, MOVE_RELEASE); + return; + case NamingAction::A: + pbf_press_button(context, BUTTON_A, PRESS_HOLD, KEY_RELEASE); + return; + case NamingAction::SELECT: + pbf_press_button(context, BUTTON_MINUS, PRESS_HOLD, PAGE_SWAP_RELEASE); + return; + case NamingAction::START: + pbf_press_button(context, BUTTON_PLUS, PRESS_HOLD, START_RELEASE); + return; + } +} + +void check_name(ConsoleHandle& console, const std::string& text, NamingScreenKind kind){ + const std::string error = naming_text_error(text, kind); + if (!error.empty()){ + throw UserSetupError(console, error); + } +} + +bool press_on_naming_screen( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind, const std::vector& actions +){ + NamingScreenWatcher naming_screen(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, std::chrono::seconds(5), {naming_screen}) < 0){ + console.log("Naming screen not found. Not typing \"" + text + "\".", COLOR_RED); + return false; + } + + console.log("Typing " + std::string(naming_screen_kind_name(kind)) + " name \"" + text + "\": " + to_string(actions)); + for (NamingAction action : actions){ + press(context, action); + } + context.wait_for_all_requests(); + return true; +} + +} // namespace + + +bool type_name( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +){ + check_name(console, text, kind); + return press_on_naming_screen(console, context, text, kind, plan_naming_input(text, kind)); +} + +bool type_name_without_confirming( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +){ + check_name(console, text, kind); + return press_on_naming_screen(console, context, text, kind, plan_naming_keys(text, kind)); +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h new file mode 100644 index 0000000000..3db414aedc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h @@ -0,0 +1,43 @@ +/* Naming Screen + * + * From: https://github.com/PokemonAutomation/ + * + * Types a name on the in-game naming screen (player, rival, box, Pokemon nickname). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreen_H +#define PokemonAutomation_PokemonFRLG_NamingScreen_H + +#include +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_NamingScreenKeyboard.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Types `text` on a naming screen that was just opened (cursor on "A", nothing typed) and +// presses OK. Returns once OK is pressed; what follows (e.g. "So your name is ...?") is up to +// the caller. +// Returns false, without pressing anything, if the naming screen is not on screen. +// Throws UserSetupError if the game can't take `text` (see naming_text_error()). +bool type_name( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +); + +// Like type_name(), but leaves the name on screen with OK not pressed, for a program that +// confirms the name itself (SID Helper presses PLUS then A on its own timing). +bool type_name_without_confirming( + ConsoleHandle& console, ProControllerContext& context, + const std::string& text, NamingScreenKind kind +); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h new file mode 100644 index 0000000000..abd8760670 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h @@ -0,0 +1,65 @@ +/* Naming Screen Cursor + * + * From: https://github.com/PokemonAutomation/ + * + * The naming screen's cursor and the presses that move it, as + * pret/pokefirered src/naming_screen.c moves them (see PokemonFRLG_NamingScreenKeys.h). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenCursor_H +#define PokemonAutomation_PokemonFRLG_NamingScreenCursor_H + +#include +#include +#include +#include +#include "PokemonFRLG_NamingScreenKeys.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The cursor, as the game tracks it. +struct NamingCursor{ + NamingScreenPage page = NamingScreenPage::UPPER; + // Key row (0-3), or button (0-2) when on the button column. + uint8_t row = 0; + // Key column, or NAMING_SCREEN_KEY_COLUMNS[page] for the button column. + uint8_t column = 0; + // The game's tButtonId: the key row to return to when leaving the middle button. + uint8_t remembered_row = 0; + + bool operator==(const NamingCursor& other) const = default; +}; +// String representation of cursor coordinates. +std::string to_string(const NamingCursor& cursor); + + +// Input action on the naming screen keyboard. +enum class NamingAction : uint8_t{ + UP, + DOWN, + LEFT, + RIGHT, + A, + SELECT, // next page + START, // move the cursor to OK +}; +// String representation of naming action. +std::string_view naming_action_name(NamingAction action); +// Space-separated action names, e.g. "LEFT LEFT A START A". +std::string to_string(const std::vector& actions); + + +// Where the cursor ends up after one press (HandleDpadMovement, MainState_WaitPageSwap, +// MoveCursorToOKButton). A leaves the cursor in place. +NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp new file mode 100644 index 0000000000..68a3234e06 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp @@ -0,0 +1,358 @@ +/* Naming Screen Keyboard + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_NamingScreenKeyboard.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +size_t naming_screen_max_chars(NamingScreenKind kind){ + switch (kind){ + case NamingScreenKind::PLAYER: return 7; + case NamingScreenKind::RIVAL: return 7; + case NamingScreenKind::BOX: return 8; + case NamingScreenKind::POKEMON: return 10; + } + return 0; +} +std::string_view naming_screen_kind_name(NamingScreenKind kind){ + switch (kind){ + case NamingScreenKind::PLAYER: return "player"; + case NamingScreenKind::RIVAL: return "rival"; + case NamingScreenKind::BOX: return "box"; + case NamingScreenKind::POKEMON: return "Pokemon"; + } + return "?"; +} + +std::string to_string(const NamingCursor& cursor){ + static constexpr std::string_view PAGE_NAMES[] = {"UPPER", "LOWER", "SYMBOLS"}; + return std::format( + "{} row {} column {} (remembered row {})", + PAGE_NAMES[(size_t)cursor.page], cursor.row, cursor.column, cursor.remembered_row + ); +} + +std::string_view naming_action_name(NamingAction action){ + switch (action){ + case NamingAction::UP: return "UP"; + case NamingAction::DOWN: return "DOWN"; + case NamingAction::LEFT: return "LEFT"; + case NamingAction::RIGHT: return "RIGHT"; + case NamingAction::A: return "A"; + case NamingAction::SELECT: return "SELECT"; + case NamingAction::START: return "START"; + } + return "?"; +} +std::string to_string(const std::vector& actions){ + std::string ret; + for (NamingAction action : actions){ + if (!ret.empty()){ + ret += ' '; + } + ret += naming_action_name(action); + } + return ret; +} + + +namespace{ + +constexpr uint8_t BUTTON_COUNT = 3; +// sKeyRowToButtonRow and sButtonRowToKeyRow in HandleDpadMovement(). +constexpr uint8_t KEY_ROW_TO_BUTTON[NAMING_SCREEN_KEY_ROWS] = {0, 1, 1, 2}; +constexpr uint8_t BUTTON_TO_KEY_ROW[BUTTON_COUNT] = {0, 0, 3}; + +uint8_t key_columns(NamingScreenPage page){ + return NAMING_SCREEN_KEY_COLUMNS[(size_t)page]; +} + +// Wraps the row after a move: three buttons on the button column, four key rows elsewhere. +void wrap_row(NamingCursor& cursor, bool on_button_column, int y){ + if (on_button_column){ + if (y < 0){ + y = BUTTON_COUNT - 1; + } + if (y >= BUTTON_COUNT){ + y = 0; + } + // The game reuses tButtonId here, so the middle button can return to row 1 or 2. + if (y == 0){ + cursor.remembered_row = NAMING_SCREEN_BUTTON_BACK; + }else if (y == BUTTON_COUNT - 1){ + cursor.remembered_row = NAMING_SCREEN_BUTTON_OK; + } + }else{ + if (y < 0){ + y = NAMING_SCREEN_KEY_ROWS - 1; + } + if (y >= (int)NAMING_SCREEN_KEY_ROWS){ + y = 0; + } + } + cursor.row = (uint8_t)y; +} + +NamingCursor move(NamingCursor cursor, int dx, int dy){ + const int columns = key_columns(cursor.page); + const int previous_x = cursor.column; + int x = cursor.column + dx; + int y = cursor.row + dy; + + // Wrap X. The button column is part of the ring. + if (x < 0){ + x = columns; + } + if (x > columns){ + x = 0; + } + + // Moving onto or off the button column. + if (dx != 0){ + if (x == columns){ + cursor.remembered_row = (uint8_t)y; + y = KEY_ROW_TO_BUTTON[y]; + }else if (previous_x == columns){ + y = y == BUTTON_COUNT / 2 ? cursor.remembered_row : BUTTON_TO_KEY_ROW[y]; + } + } + + cursor.column = (uint8_t)x; + wrap_row(cursor, x == columns, y); + return cursor; +} + +NamingCursor next_page(NamingCursor cursor){ + const bool on_button_column = cursor.column == key_columns(cursor.page); + cursor.page = (NamingScreenPage)(((size_t)cursor.page + 1) % NAMING_SCREEN_PAGES); + const uint8_t columns = key_columns(cursor.page); + if (on_button_column || cursor.column >= columns){ + cursor.column = on_button_column ? columns : columns - 1; + } + return cursor; +} + +std::string_view key_at(const NamingCursor& cursor){ + if (cursor.column >= key_columns(cursor.page)){ + return {}; + } + return NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; +} + + +struct KeyAlias{ + std::string_view typed; + std::string_view key; +}; +// Other spellings of a key's character. +constexpr KeyAlias KEY_ALIASES[] = { + {"\xE2\x80\x99", "'"}, // right single quote: the apostrophe key types it +}; + +bool text_has_at(const std::string& text, size_t position, std::string_view str){ + return text.compare(position, str.size(), str) == 0; +} + +// A key typing the text at a position, and how many bytes of the text it covers. +struct KeyMatch{ + std::string_view key; + size_t length = 0; +}; + +// `best`, or the longest key of `row` that types the text at `position` if it is longer. +KeyMatch longer_match(KeyMatch best, std::span row, const std::string& text, size_t position){ + for (std::string_view key : row){ + if (key.size() > best.length && text_has_at(text, position, key)){ + best = {key, key.size()}; + } + } + return best; +} + +// The key text at `position` in `text`; an empty key if no key types it. +KeyMatch key_text_at(const std::string& text, size_t position){ + KeyMatch best; + for (const auto& page : NAMING_SCREEN_KEYS){ + for (const auto& row : page){ + best = longer_match(best, row, text, position); + } + } + for (const KeyAlias& alias : KEY_ALIASES){ + if (alias.typed.size() > best.length && text_has_at(text, position, alias.typed)){ + best = {alias.key, alias.typed.size()}; + } + } + return best; +} + +// The UTF-8 character at `position`, for error messages. +std::string utf8_char_at(const std::string& text, size_t position){ + const unsigned char lead = (unsigned char)text[position]; + size_t length = 1; + if (lead >= 0xF0){ + length = 4; + }else if (lead >= 0xE0){ + length = 3; + }else if (lead >= 0xC0){ + length = 2; + } + return text.substr(position, length); +} + +// Splits `text` into the keys that type it. Returns the error, or "" on success. +std::string split_into_keys(const std::string& text, std::vector& keys){ + keys.clear(); + for (size_t position = 0; position < text.size();){ + const KeyMatch match = key_text_at(text, position); + if (match.key.empty()){ + return "\"" + text + "\" has a character the naming screen can't type: \"" + + utf8_char_at(text, position) + "\" (byte " + std::to_string(position) + "). " + "It types A-Z, a-z, 0-9, space and . , ! ? / - ' and the game's " + "male/female signs, ellipsis and curly quotes."; + } + keys.emplace_back(match.key); + position += match.length; + } + return ""; +} + + +size_t state_index(const NamingCursor& cursor){ + return (((size_t)cursor.page * (NAMING_SCREEN_MAX_KEY_COLUMNS + 1) + cursor.column) + * NAMING_SCREEN_KEY_ROWS + cursor.row) * NAMING_SCREEN_KEY_ROWS + cursor.remembered_row; +} +constexpr size_t STATE_COUNT = + NAMING_SCREEN_PAGES * (NAMING_SCREEN_MAX_KEY_COLUMNS + 1) * NAMING_SCREEN_KEY_ROWS * NAMING_SCREEN_KEY_ROWS; + +// Breadth-first search over cursor states for the fewest presses that reach a key typing `key`. +// Appends the moves and returns the cursor on that key. +NamingCursor append_moves_to_key(const NamingCursor& start, std::string_view key, std::vector& actions){ + // START is left out: it only jumps to OK, which the plan uses once at the end. + static const NamingAction MOVES[] = { + NamingAction::UP, NamingAction::DOWN, NamingAction::LEFT, NamingAction::RIGHT, NamingAction::SELECT, + }; + struct Visit{ + bool seen = false; + size_t parent = 0; + NamingAction action = NamingAction::A; + }; + std::vector visits(STATE_COUNT); + std::vector queue{start}; + visits[state_index(start)].seen = true; + + for (size_t head = 0; head < queue.size(); head++){ + const NamingCursor cursor = queue[head]; + if (key_at(cursor) == key){ + std::vector path; + for (size_t index = state_index(cursor); index != state_index(start); index = visits[index].parent){ + path.emplace_back(visits[index].action); + } + actions.insert(actions.end(), path.rbegin(), path.rend()); + return cursor; + } + for (NamingAction action : MOVES){ + const NamingCursor next = apply_naming_action(cursor, action); + Visit& visit = visits[state_index(next)]; + if (!visit.seen){ + visit.seen = true; + visit.parent = state_index(cursor); + visit.action = action; + queue.emplace_back(next); + } + } + } + // Every key is reachable, so this is a bug. + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No path to naming screen key: {}", key)); +} + +} // namespace + + +NamingCursor apply_naming_action(const NamingCursor& cursor, NamingAction action){ + switch (action){ + case NamingAction::UP: return move(cursor, 0, -1); + case NamingAction::DOWN: return move(cursor, 0, 1); + case NamingAction::LEFT: return move(cursor, -1, 0); + case NamingAction::RIGHT: return move(cursor, 1, 0); + case NamingAction::SELECT: return next_page(cursor); + case NamingAction::START:{ + NamingCursor ret = cursor; + ret.column = key_columns(cursor.page); + ret.row = NAMING_SCREEN_BUTTON_OK; + return ret; + } + case NamingAction::A: + return cursor; + } + return cursor; +} + + +std::string naming_text_error(const std::string& text, NamingScreenKind kind){ + std::vector keys; + std::string error = split_into_keys(text, keys); + if (!error.empty()){ + return error; + } + bool only_spaces = true; + for (std::string_view key : keys){ + only_spaces &= key == " "; + } + if (only_spaces){ + return "The name \"" + text + "\" is empty or only spaces, so the game would not keep it."; + } + const size_t max_chars = naming_screen_max_chars(kind); + if (keys.size() > max_chars){ + return std::format( + "\"{}\" is {} characters, but a {} name holds at most {}.", + text, keys.size(), naming_screen_kind_name(kind), max_chars + ); + } + return ""; +} + +std::vector plan_naming_keys( + const std::string& text, NamingScreenKind kind, const NamingCursor& start +){ + const std::string error = naming_text_error(text, kind); + if (!error.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, error); + } + std::vector keys; + split_into_keys(text, keys); + + std::vector actions; + NamingCursor cursor = start; + for (std::string_view key : keys){ + cursor = append_moves_to_key(cursor, key, actions); + actions.emplace_back(NamingAction::A); + } + return actions; +} + +std::vector plan_naming_input( + const std::string& text, NamingScreenKind kind, const NamingCursor& start +){ + std::vector actions = plan_naming_keys(text, kind, start); + // When the last key fills the name, the game moves the cursor to OK by itself; START is + // then harmless. + actions.emplace_back(NamingAction::START); + actions.emplace_back(NamingAction::A); + return actions; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h new file mode 100644 index 0000000000..132dbeb3bd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h @@ -0,0 +1,64 @@ +/* Naming Screen Keyboard + * + * From: https://github.com/PokemonAutomation/ + * + * The in-game keyboard used to name the player, the rival, PC boxes and Pokemon, and a + * planner that turns a name into button presses. Pure data and logic: no console needed. + * + * Everything here follows pret/pokefirered src/naming_screen.c at commit + * ce6406d8c2eaf46d543c8a2606de0c3cb1951982 (English game). The decomp includes the Switch + * revision (REVISION >= 0xA), so the layout is the one on the Switch release. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_H +#define PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_H + +#include +#include +#include +#include +#include +#include "PokemonFRLG_NamingScreenCursor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Which naming screen is open; it sets how many characters fit (NamingScreenTemplate.maxChars). +enum class NamingScreenKind : uint8_t{ + PLAYER, // PLAYER_NAME_LENGTH + RIVAL, // PLAYER_NAME_LENGTH + BOX, // BOX_NAME_LENGTH + POKEMON, // POKEMON_NAME_LENGTH, for caught Pokemon and the nickname rater +}; +// Maximum character length for the given naming screen type. +size_t naming_screen_max_chars(NamingScreenKind kind); +// Display name for naming screen kind. +std::string_view naming_screen_kind_name(NamingScreenKind kind); + +// Why the game can't take `text` as a name of this kind, or "" if it can: a character with +// no key, more characters than fit, or nothing but spaces (the game then keeps no name). +std::string naming_text_error(const std::string& text, NamingScreenKind kind); + +// The presses that type `text` from `start` without confirming it: the shortest moves to +// each character's key, then A. The name stays on screen with OK not pressed, which is where +// SID Helper starts. +// Throws InternalProgramError if naming_text_error() rejects `text`; check that first. +std::vector plan_naming_keys( + const std::string& text, NamingScreenKind kind, const NamingCursor& start = NamingCursor() +); + +// plan_naming_keys(), then START and A to press OK. +std::vector plan_naming_input( + const std::string& text, NamingScreenKind kind, const NamingCursor& start = NamingCursor() +); + + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp new file mode 100644 index 0000000000..17806b6788 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp @@ -0,0 +1,620 @@ +/* Naming Screen Keyboard Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_NamingScreenKeyboard.h" +#include "PokemonFRLG_NamingScreenKeyboard_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + + +// Naming screen keyboard: cursor moves, plans and text checks, against pokefirered's +// src/naming_screen.c. + +struct NamingCursorInput{ + std::string name = ""; + NamingCursor start = {}; + std::vector actions = {}; +}; + +struct NamingCursorExpectation{ + NamingCursor expected = {}; +}; + +struct NamingCursorScenario{ + NamingCursorInput input; + NamingCursorExpectation expectation; +}; + +class Test_NamingCursor : public UnitTest{ +public: + explicit Test_NamingCursor(NamingCursorScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen cursor - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + NamingCursor cursor = m_scenario.input.start; + for (NamingAction action : m_scenario.input.actions){ + cursor = apply_naming_action(cursor, action); + } + if (cursor != m_scenario.expectation.expected){ + return "After " + to_string(m_scenario.input.actions) + ": expected " + to_string(m_scenario.expectation.expected) + + ", got " + to_string(cursor); + } + return true; + } + +private: + const NamingCursorScenario m_scenario; +}; + +const NamingCursorScenario NAMING_CURSOR_CASES[] = { + // Crossing and moving on the button column. + { + .input = { + .name = "left from A goes to the page button", + .actions = {NamingAction::LEFT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "left and right return to A", + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "row 1 crosses the button column", + .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "row 2 crosses the button column", + .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0, .remembered_row = 2}, + }, + }, + { + .input = { + .name = "row 3 crosses the OK button", + .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0, .remembered_row = 2}, + }, + }, + { + .input = { + .name = "right from the last column wraps through the buttons", + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, + .actions = {NamingAction::RIGHT, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "moving on the button column forgets row 2", + .start = {.page = NamingScreenPage::UPPER, .row = 2, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::UP, NamingAction::DOWN, NamingAction::RIGHT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 1, .column = 0, .remembered_row = 1}, + }, + }, + // Wrap-around on the keys and the button column. + { + .input = { + .name = "button column wraps over three buttons", + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::UP}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 2, .column = 8, .remembered_row = 2}, + }, + }, + { + .input = { + .name = "rows wrap up", + .actions = {NamingAction::UP}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + }, + }, + { + .input = { + .name = "rows wrap down", + .start = {.page = NamingScreenPage::UPPER, .row = 3, .column = 0}, + .actions = {NamingAction::DOWN}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "symbols page has six key columns", + .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::LEFT, NamingAction::LEFT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 5, .remembered_row = 1}, + }, + }, + // SELECT and START. + { + .input = { + .name = "SELECT goes to lower case", + .actions = {NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::LOWER, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "SELECT twice goes to symbols", + .actions = {NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "SELECT three times returns to upper case", + .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 0}, + }, + }, + { + .input = { + .name = "SELECT moves the cursor into the symbols columns", + .start = {.page = NamingScreenPage::UPPER, .row = 0, .column = 7}, + .actions = {NamingAction::SELECT, NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::UPPER, .row = 0, .column = 5}, + }, + }, + { + .input = { + .name = "SELECT keeps the cursor on the button column", + .start = {.page = NamingScreenPage::UPPER, .row = 1, .column = 8, .remembered_row = 1}, + .actions = {NamingAction::SELECT, NamingAction::SELECT}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 1, .column = 6, .remembered_row = 1}, + }, + }, + { + .input = { + .name = "START goes to OK", + .start = {.page = NamingScreenPage::LOWER, .row = 1, .column = 3}, + .actions = {NamingAction::START}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::LOWER, .row = 2, .column = 8}, + }, + }, + { + .input = { + .name = "START goes to OK on symbols", + .start = {.page = NamingScreenPage::SYMBOLS, .row = 0, .column = 0}, + .actions = {NamingAction::START}, + }, + .expectation = { + .expected = {.page = NamingScreenPage::SYMBOLS, .row = 2, .column = 6}, + }, + }, +}; + +void add_tests_NamingCursor(UnitTestDatabase& database){ + for (const NamingCursorScenario& scenario : NAMING_CURSOR_CASES){ + database.add(scenario); + } +} + + +struct NamingPlanInput{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingPlanExpectation{ + // What the game shows when it differs from `text` (another spelling of a key). + std::string typed = ""; + // The exact plan, when the shortest one is unique; "" to skip. + std::string expected_actions = ""; + // The number of presses, including A and the final START A; 0 to skip. + size_t expected_presses = 0; +}; + +struct NamingPlanScenario{ + NamingPlanInput input; + NamingPlanExpectation expectation; +}; + +std::string replay_naming_plan( + const std::vector& actions, + const std::string& plan, + const NamingPlanScenario& scenario +){ + std::string typed; + NamingCursor cursor; + for (size_t i = 0; i < actions.size(); i++){ + cursor = apply_naming_action(cursor, actions[i]); + if (actions[i] != NamingAction::A){ + continue; + } + const uint8_t columns = NAMING_SCREEN_KEY_COLUMNS[(size_t)cursor.page]; + if (i + 1 == actions.size()){ + if (cursor.column != columns || cursor.row != NAMING_SCREEN_BUTTON_OK){ + return "The last A is not on OK but on " + to_string(cursor) + ": " + plan; + } + break; + } + if (cursor.column >= columns){ + return "A pressed on the button column at " + to_string(cursor) + ": " + plan; + } + typed += NAMING_SCREEN_KEYS[(size_t)cursor.page][cursor.row][cursor.column]; + } + const std::string& expected = scenario.expectation.typed.empty() ? scenario.input.text : scenario.expectation.typed; + if (typed != expected){ + return "Expected the plan to type \"" + expected + "\", it types \"" + typed + "\": " + plan; + } + return ""; +} + +class Test_NamingPlan : public UnitTest{ +public: + explicit Test_NamingPlan(NamingPlanScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen plan - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector actions = plan_naming_input(m_scenario.input.text, m_scenario.input.kind); + const std::string plan = to_string(actions); + if (!m_scenario.expectation.expected_actions.empty() && plan != m_scenario.expectation.expected_actions){ + return "Expected plan: " + m_scenario.expectation.expected_actions + "\nActual plan: " + plan; + } + if (m_scenario.expectation.expected_presses != 0 && actions.size() != m_scenario.expectation.expected_presses){ + return "Expected " + std::to_string(m_scenario.expectation.expected_presses) + " presses, got " + + std::to_string(actions.size()) + ": " + plan; + } + std::string replay_error = replay_naming_plan(actions, plan, m_scenario); + if (!replay_error.empty()){ + return replay_error; + } + return true; + } + +private: + const NamingPlanScenario m_scenario; +}; + +const NamingPlanScenario NAMING_PLAN_CASES[] = { + { + .input = {.name = "starts on A", .text = "A"}, + .expectation = {.expected_actions = "A START A"}, + }, + { + .input = {.name = "next key", .text = "AB"}, + .expectation = {.expected_actions = "A RIGHT A START A"}, + }, + { + .input = {.name = "next row", .text = "AG"}, + .expectation = {.expected_actions = "A DOWN A START A"}, + }, + { + .input = {.name = "rows wrap", .text = "T"}, + .expectation = {.expected_actions = "UP A START A"}, + }, + { + .input = { + .name = "columns wrap through the button column", + .text = ".", + }, + .expectation = {.expected_actions = "LEFT LEFT A START A"}, + }, + { + .input = {.name = "lower case page", .text = "a"}, + .expectation = {.expected_actions = "SELECT A START A"}, + }, + { + .input = {.name = "symbols page", .text = "0"}, + .expectation = {.expected_actions = "SELECT SELECT A START A"}, + }, + { + .input = { + .name = "page change moves the cursor into the symbols columns", + .text = ".4", + }, + .expectation = {.expected_actions = "LEFT LEFT A SELECT SELECT LEFT A START A"}, + }, + { + .input = {.name = "both ways round", .text = "Z"}, + .expectation = {.expected_presses = 7}, + }, + { + .input = {.name = "male sign", .text = "\xE2\x99\x82"}, + .expectation = {.expected_presses = 9}, + }, + { + .input = {.name = "full player name", .text = "ABCDEFG"}, + .expectation = {.expected_presses = 19}, + }, + { + .input = {.name = "mixed case", .text = "Gary"}, + .expectation = {.expected_presses = 16}, + }, + { + .input = {.name = "space", .text = "A B"}, + .expectation = {.expected_presses = 12}, + }, + { + .input = {.name = "full nickname", .text = "BULBASAURS", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "female sign", .text = "NIDORAN\xE2\x99\x80", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "box name", .text = "BOX 1-2!", .kind = NamingScreenKind::BOX}, + .expectation = {}, + }, + { + .input = {.name = "rival", .text = "Blue?", .kind = NamingScreenKind::RIVAL}, + .expectation = {}, + }, + { + .input = { + .name = "symbols row 4", + .text = "\xE2\x80\xA6\xE2\x80\x9C\xE2\x80\x9D\xE2\x80\x98'", + .kind = NamingScreenKind::POKEMON, + }, + .expectation = {}, + }, + { + .input = {.name = "curly apostrophe", .text = "IT\xE2\x80\x99S"}, + .expectation = {.typed = "IT'S"}, + }, +}; + +void add_tests_NamingPlan(UnitTestDatabase& database){ + for (const NamingPlanScenario& scenario : NAMING_PLAN_CASES){ + database.add(scenario); + } +} + + +struct NamingKeysInput{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingKeysExpectation{ + // The exact plan, when the shortest one is unique; "" to skip. + std::string expected_actions = ""; +}; + +struct NamingKeysScenario{ + NamingKeysInput input; + NamingKeysExpectation expectation; +}; + +// plan_naming_keys() stops before OK: it is plan_naming_input() without the final START A. +class Test_NamingKeys : public UnitTest{ +public: + explicit Test_NamingKeys(NamingKeysScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen keys only - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string keys = to_string(plan_naming_keys(m_scenario.input.text, m_scenario.input.kind)); + if (!m_scenario.expectation.expected_actions.empty() && keys != m_scenario.expectation.expected_actions){ + return "Expected keys: " + m_scenario.expectation.expected_actions + "\nActual keys: " + keys; + } + const std::string input = to_string(plan_naming_input(m_scenario.input.text, m_scenario.input.kind)); + if (input != keys + " START A"){ + return "Expected the confirmed plan to be \"" + keys + " START A\", got \"" + input + "\""; + } + return true; + } + +private: + const NamingKeysScenario m_scenario; +}; + +const NamingKeysScenario NAMING_KEYS_CASES[] = { + { + .input = {.name = "one key", .text = "A"}, + .expectation = {.expected_actions = "A"}, + }, + { + .input = {.name = "next key", .text = "AB"}, + .expectation = {.expected_actions = "A RIGHT A"}, + }, + { + .input = {.name = "lower case page", .text = "a"}, + .expectation = {.expected_actions = "SELECT A"}, + }, + { + .input = {.name = "full player name", .text = "ABCDEFG"}, + .expectation = {}, + }, + { + .input = {.name = "mixed case", .text = "Kosmos"}, + .expectation = {}, + }, +}; + +void add_tests_NamingKeys(UnitTestDatabase& database){ + for (const NamingKeysScenario& scenario : NAMING_KEYS_CASES){ + database.add(scenario); + } +} + + +struct NamingTextInput{ + std::string name = ""; + std::string text = ""; + NamingScreenKind kind = NamingScreenKind::PLAYER; +}; + +struct NamingTextExpectation{ + // A part of the expected error; "" if the text is fine. + std::string expected_error = ""; +}; + +struct NamingTextScenario{ + NamingTextInput input; + NamingTextExpectation expectation; +}; + +class Test_NamingText : public UnitTest{ +public: + explicit Test_NamingText(NamingTextScenario scenario) + : UnitTest("PokemonFRLG::NamingScreen text - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = naming_text_error(m_scenario.input.text, m_scenario.input.kind); + if (m_scenario.expectation.expected_error.empty()){ + if (!error.empty()){ + return "Expected \"" + m_scenario.input.text + "\" to be accepted, got: " + error; + } + return true; + } + if (error.find(m_scenario.expectation.expected_error) == std::string::npos){ + return "Expected an error containing \"" + m_scenario.expectation.expected_error + "\", got: \"" + error + "\""; + } + try{ + plan_naming_input(m_scenario.input.text, m_scenario.input.kind); + }catch (InternalProgramError&){ + return true; + } + return "Expected plan_naming_input() to throw for \"" + m_scenario.input.text + "\""; + } + +private: + const NamingTextScenario m_scenario; +}; + +const NamingTextScenario NAMING_TEXT_CASES[] = { + { + .input = {.name = "player name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::PLAYER}, + .expectation = {}, + }, + { + .input = {.name = "player name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "at most 7"}, + }, + { + .input = {.name = "rival name of 7", .text = "ABCDEFG", .kind = NamingScreenKind::RIVAL}, + .expectation = {}, + }, + { + .input = {.name = "rival name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::RIVAL}, + .expectation = {.expected_error = "at most 7"}, + }, + { + .input = {.name = "box name of 8", .text = "ABCDEFGH", .kind = NamingScreenKind::BOX}, + .expectation = {}, + }, + { + .input = {.name = "box name of 9", .text = "ABCDEFGHI", .kind = NamingScreenKind::BOX}, + .expectation = {.expected_error = "at most 8"}, + }, + { + .input = {.name = "nickname of 10", .text = "ABCDEFGHIJ", .kind = NamingScreenKind::POKEMON}, + .expectation = {}, + }, + { + .input = {.name = "nickname of 11", .text = "ABCDEFGHIJK", .kind = NamingScreenKind::POKEMON}, + .expectation = {.expected_error = "at most 10"}, + }, + { + .input = { + .name = "symbols count as one character", + .text = "\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82\xE2\x99\x82", + .kind = NamingScreenKind::PLAYER, + }, + .expectation = {}, + }, + { + .input = {.name = "unknown character", .text = "Ash@", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "type: \"@\""}, + }, + { + .input = {.name = "unknown accented character", .text = "Jos\xC3\xA9", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "type: \"\xC3\xA9\""}, + }, + { + .input = {.name = "empty", .text = "", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "empty"}, + }, + { + .input = {.name = "only spaces", .text = " ", .kind = NamingScreenKind::PLAYER}, + .expectation = {.expected_error = "only spaces"}, + }, +}; + +void add_tests_NamingText(UnitTestDatabase& database){ + for (const NamingTextScenario& scenario : NAMING_TEXT_CASES){ + database.add(scenario); + } +} + +} // namespace + + +void add_tests_NamingScreen(UnitTestDatabase& database){ + add_tests_NamingCursor(database); + add_tests_NamingPlan(database); + add_tests_NamingKeys(database); + add_tests_NamingText(database); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h new file mode 100644 index 0000000000..7eb7c2b2b8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h @@ -0,0 +1,25 @@ +/* Naming Screen Keyboard Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_Tests_H +#define PokemonAutomation_PokemonFRLG_NamingScreenKeyboard_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers the naming screen keyboard's tests: cursor moves, plans and +// text checks, against pokefirered's src/naming_screen.c. +void add_tests_NamingScreen(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h new file mode 100644 index 0000000000..fc0c6622bd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h @@ -0,0 +1,80 @@ +/* Naming Screen Keys + * + * From: https://github.com/PokemonAutomation/ + * + * The in-game keyboard's layout, as pret/pokefirered src/naming_screen.c at commit + * ce6406d8c2eaf46d543c8a2606de0c3cb1951982 (English game) has it. The decomp includes the + * Switch revision (REVISION >= 0xA), so the layout is the one on the Switch release. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_NamingScreenKeys_H +#define PokemonAutomation_PokemonFRLG_NamingScreenKeys_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The keyboard pages, in the order SELECT cycles through them. The screen opens on UPPER. +enum class NamingScreenPage : uint8_t{ + UPPER, + LOWER, + SYMBOLS, +}; +// Total page count on naming screen. +constexpr size_t NAMING_SCREEN_PAGES = 3; +// Number of key rows per page. +constexpr size_t NAMING_SCREEN_KEY_ROWS = 4; +// Maximum key columns across pages. +constexpr size_t NAMING_SCREEN_MAX_KEY_COLUMNS = 8; + +// Key columns on each page (sPageColumnCounts). The button column (page / back / OK) comes +// right after the last key column, so on a page with N key columns it is column N. +constexpr uint8_t NAMING_SCREEN_KEY_COLUMNS[NAMING_SCREEN_PAGES] = {8, 8, 6}; + +// The text each key types, in UTF-8 (sKeyboardChars), indexed [page][row][column]. +// Empty: no key (past the page's last column). +// The decomp pads each row with byte 0x00, which is a space in the game's charmap, and the +// keyboard labels draw a blank there: those cells type a space just like the spaces in rows 0-1. +// The apostrophe key types the game's right single quote (charmap 0xB4). +constexpr std::string_view NAMING_SCREEN_KEYS + [NAMING_SCREEN_PAGES][NAMING_SCREEN_KEY_ROWS][NAMING_SCREEN_MAX_KEY_COLUMNS] = { + { // UPPER + {"A", "B", "C", "D", "E", "F", " ", "."}, + {"G", "H", "I", "J", "K", "L", " ", ","}, + {"M", "N", "O", "P", "Q", "R", "S", " "}, + {"T", "U", "V", "W", "X", "Y", "Z", " "}, + }, + { // LOWER + {"a", "b", "c", "d", "e", "f", " ", "."}, + {"g", "h", "i", "j", "k", "l", " ", ","}, + {"m", "n", "o", "p", "q", "r", "s", " "}, + {"t", "u", "v", "w", "x", "y", "z", " "}, + }, + { // SYMBOLS + {"0", "1", "2", "3", "4", " ", "", ""}, + {"5", "6", "7", "8", "9", " ", "", ""}, + {"!", "?", "\xE2\x99\x82", "\xE2\x99\x80", "/", "-", "", ""}, // ! ? male female / - + {"\xE2\x80\xA6", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x98", "'", " ", "", ""}, // ellipsis, double quotes, left single quote, ' + }, +}; + +// The three buttons in the button column, top to bottom. +// Button index for switching character pages. +constexpr uint8_t NAMING_SCREEN_BUTTON_PAGE = 0; +// Button index for backspacing a character. +constexpr uint8_t NAMING_SCREEN_BUTTON_BACK = 1; +// Button index for confirming naming input. +constexpr uint8_t NAMING_SCREEN_BUTTON_OK = 2; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp new file mode 100644 index 0000000000..623f97c947 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp @@ -0,0 +1,105 @@ +/* Trainer Card + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_TrainerCardDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h" +#include "PokemonFRLG_StartMenuNavigation.h" +#include "PokemonFRLG_TrainerCard.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void navigate_to_trainer_card(ConsoleHandle& console, ProControllerContext& context){ + int errors = 0; + while (true){ + if (errors >= 5){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "navigate_to_trainer_card(): failed 5 times to navigate to the Trainer Card", console + ); + } + + open_start_menu(console, context); + + // the positions are different before recieving a Pokemon and Pokedex + bool cursor = move_cursor_to_position( + console, context, SelectionArrowPositionStartMenu(1) + ); + if (!cursor){ + errors++; + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + } + + TrainerCardWatcher trainer_card(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + }, + { trainer_card } + ); + + if (ret < 0){ + console.log("navigate_to_trainer_card(): failed to detect Trainer Card"); + errors++; + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + } + + break; + } +} + +namespace{ + +template +auto read_on_card(ConsoleHandle& console, ProControllerContext& context, Read read){ + TrainerIdReader reader; + VideoOverlaySet overlays(console.overlay()); + reader.make_overlays(overlays); + + VideoSnapshot screen = console.video().snapshot(); + console.log("Trainer Card detected."); + console.log("Reading TID..."); + auto tid = read(reader, screen); + + context.wait_for_all_requests(); + + return tid; +} + +} // namespace + +uint16_t read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language){ + uint16_t tid = read_on_card(console, context, [&](TrainerIdReader& reader, const VideoSnapshot& screen){ + return reader.read_tid(console.logger(), language, screen); + }); + console.log("TID: " + std::to_string(tid)); + return tid; +} + +std::optional try_read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language){ + std::optional tid = read_on_card(console, context, [&](TrainerIdReader& reader, const VideoSnapshot& screen){ + return reader.try_read_tid(console.logger(), language, screen); + }); + console.log(tid ? "TID: " + std::to_string(*tid) : std::string("TID: not read")); + return tid; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h new file mode 100644 index 0000000000..16307cfce4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h @@ -0,0 +1,41 @@ +/* Trainer Card + * + * From: https://github.com/PokemonAutomation/ + * + * Opening the Trainer Card from the overworld and reading the TID on it, + * as SID Helper does. Shared with AutoStory, which reads the TID for its + * Starter RNG plan. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_TrainerCard_H +#define PokemonAutomation_PokemonFRLG_TrainerCard_H + +#include +#include +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// From the overworld, START then the player's entry, until the card shows. +// The entry is second only before the first Pokemon and the Pokedex. +// Throws OperationFailedException after 5 failed tries. +void navigate_to_trainer_card(ConsoleHandle& console, ProControllerContext& context); + +// The TID on the Trainer Card on screen. An unreadable TID comes back as +// TrainerIdReader::read_tid() returns it. +uint16_t read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language); +// Nothing when the TID can't be read. +std::optional try_read_trainer_card_tid(ConsoleHandle& console, ProControllerContext& context, Language language); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp index a05d693683..3144110055 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -722,11 +722,10 @@ void EggRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ + run_precheck(env, context); EggRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - // prepare database of base stats and gender thresholds RngStatsDatabase STATS_DATA("PokemonFRLG/BaseStats.json"); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h index 5462ee2eac..921d9b862a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.h @@ -14,12 +14,12 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonFramework/Options/LabelCellOption.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Options/Pokemon_NameSelectOption.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_RngStatsDatabase.h" #include "PokemonFRLG_RngDisplays.h" #include "PokemonFRLG_RngLoopRoutines.h" @@ -56,9 +56,16 @@ class EggRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class EggRng : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a daycare egg. +class EggRng : public RngProgramInstance, public ConfigOption::Listener{ public: using Descriptor = EggRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ + if (STARTING_POINT == EggProgramState::pickup_calibration){ + return 2; + } + return 3; + } ~EggRng(); EggRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp index 3341d8cef2..c81241ddbe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp @@ -231,11 +231,10 @@ void GiftRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ + run_precheck(env, context); GiftRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h index 3df8e600ac..fc18d1b111 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h @@ -12,10 +12,10 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -29,9 +29,11 @@ class GiftRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class GiftRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a gift Pokemon. +class GiftRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = GiftRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~GiftRng(); GiftRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp index 16065cbda0..961217cacd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.cpp @@ -242,11 +242,10 @@ void RngHelper::program(SingleSwitchProgramEnvironment& env, ProControllerContex /* * Settings: Text Speed fast */ + run_precheck(env, context); RngHelper_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - bool shiny_found = false; static const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h index 3f4e694065..cbecd81a9e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h @@ -13,9 +13,9 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" +#include "PokemonFRLG_RngProgram.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -28,9 +28,12 @@ class RngHelper_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class RngHelper : public SingleSwitchProgramInstance{ +// Soft resets with given timings to hit a target seed and frame. +class RngHelper : public RngProgramInstance{ public: using Descriptor = RngHelper_Descriptor; + // The manual tool: the user sets the target and the party, so no check. + virtual size_t free_party_slots_needed() const override{ return 0; } RngHelper(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; virtual void start_program_border_check( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h new file mode 100644 index 0000000000..b329e8214c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h @@ -0,0 +1,51 @@ +/* RNG Method 1 + * + * From: https://github.com/PokemonAutomation/ + * + * The Gen 3 LCRNG and the Method 1 Pokemon it generates: PID, IVs, shininess + * and Hidden Power. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngMethod1_H +#define PokemonAutomation_PokemonFRLG_RngMethod1_H + +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The Gen 3 LCRNG: state * 0x41C64E6D + 0x6073. +uint32_t lcrng_next(uint32_t state); +// Steps the Gen 3 LCRNG backward by one advance. +uint32_t lcrng_previous(uint32_t state); +// How many lcrng_next() calls take "from" to "to". The LCRNG has a single cycle of +// 2^32 states, so every pair has exactly one distance. +uint32_t lcrng_distance(uint32_t from, uint32_t to); + +// The static, gift or starter Pokemon (Method 1) generated from "state", the RNG state +// just before the PID is rolled: the next two calls give the low and high PID halves, +// the two after that the IVs (HP/Atk/Def, then Spe/SpA/SpD). +Pokemon::AdvPokemonResult method1_pokemon(uint32_t state); + +// Determines shiny type (none, star, square) from PID and trainer IDs. +Pokemon::AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid); + +// Calculated Hidden Power typing and base power. +struct HiddenPower{ + std::string type; + uint8_t power; +}; +// Calculates Hidden Power attributes from individual values. +HiddenPower hidden_power(const Pokemon::AdvIVs& ivs); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp new file mode 100644 index 0000000000..eae30812ce --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp @@ -0,0 +1,159 @@ +/* RNG Plan + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_BlindNavigation.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +std::vector sid_helper_candidates(uint16_t tid, uint32_t target_advances, uint8_t count){ + // As SidHelper's get_sid_messages(): from "count / 2" steps before the target. + const int start = -int(count) / 2; + const int end = start + int(count); + const int farthest = std::max(-start, end - 1); + + std::vector candidates; + AdvRngSearcher searcher(tid, uint64_t(int64_t(target_advances) + 2 * start)); + for (int i = start; i < end; i++){ + candidates.push_back({uint16_t(searcher.state.s0 >> 16), double(farthest + 1 - std::abs(i))}); + searcher.advance_state(); + searcher.advance_state(); + } + return candidates; +} + + +namespace{ + +// "targets" with only the shiny candidates still "left", and their share of +// the weight left. +std::vector rescore( + const std::vector& targets, + const std::vector& candidates, + const std::vector& left +){ + double total = 0; + for (size_t c = 0; c < candidates.size(); c++){ + if (left[c]){ + total += candidates[c].weight; + } + } + std::vector scored; + scored.reserve(targets.size()); + for (const RngTarget& target : targets){ + RngTarget copy = target; + copy.shiny_for.clear(); + double weight = 0; + for (const ShinyCandidate& shiny : target.shiny_for){ + if (left[shiny.candidate]){ + copy.shiny_for.push_back(shiny); + weight += candidates[shiny.candidate].weight; + } + } + copy.shiny_probability = total > 0 ? weight / total : 0; + scored.emplace_back(std::move(copy)); + } + return scored; +} + +RngAttempt make_attempt(const RngTarget& target, const std::vector& candidates){ + RngAttempt attempt{target, {}}; + for (const ShinyCandidate& shiny : target.shiny_for){ + attempt.sids.push_back(candidates[shiny.candidate].sid); + } + return attempt; +} + +} // namespace + + +std::vector plan_rng_attempts( + const std::vector& targets, + const std::vector& candidates, + bool shiny_required, + size_t max_attempts +){ + std::vector attempts; + if (targets.empty() || max_attempts == 0){ + return attempts; + } + std::vector left(candidates.size(), true); + + if (!shiny_required){ + // With no shiny chance, rank_rng_targets() sorts by time alone. + std::vector by_time = targets; + for (RngTarget& target : by_time){ + target.shiny_probability = 0; + } + rank_rng_targets(by_time); + const uint32_t quickest = by_time.front().state; + for (const RngTarget& target : rescore(targets, candidates, left)){ + if (target.state == quickest){ + attempts.push_back(make_attempt(target, candidates)); + break; + } + } + return attempts; + } + + while (attempts.size() < max_attempts){ + std::vector scored = rescore(targets, candidates, left); + rank_rng_targets(scored); + const RngTarget& best = scored.front(); + if (best.shiny_for.empty()){ + break; + } + for (const ShinyCandidate& shiny : best.shiny_for){ + left[shiny.candidate] = false; + } + attempts.push_back(make_attempt(best, candidates)); + if (std::find(left.begin(), left.end(), true) == left.end()){ + break; + } + } + return attempts; +} + + +int64_t starter_rng_seed_wait_ms(const InitialSeedEntry& seed){ + return int64_t(seed.seed_time_ms) + STARTER_RNG_FIXED_SEED_OFFSET_MS; +} + +bool starter_rng_can_wait_for(const InitialSeedEntry& seed){ + return starter_rng_seed_wait_ms(seed) >= STARTER_RNG_MIN_SEED_WAIT_MS; +} + +int64_t starter_rng_ingame_ms(uint64_t advances){ + const int64_t frames = int64_t(advances) - int64_t(STARTER_RNG_CONTINUE_SCREEN_FRAMES) + + fixed_advances_offset(PokemonFRLG_RngTarget::starters); + return int64_t(frames * FRLG_FRAME_DURATION / 2); +} + +std::vector plan_starter_rng(const StarterRngPlanInputs& inputs){ + const SeedsDatabase database(seeds_json_path(inputs.firered, inputs.language)); + // Only the English lists hold the blackout button's seeds (initial_seed_entries()). + const bool english_list = inputs.language != Language::Japanese; + std::vector seeds = initial_seed_entries(database, inputs.sound, "Help", english_list); + std::erase_if(seeds, [](const InitialSeedEntry& seed){ return !starter_rng_can_wait_for(seed); }); + + RngTargetFilters filters = inputs.filters; + filters.min_advances = std::max(filters.min_advances, STARTER_RNG_PLAN_MIN_ADVANCES); + const std::vector targets = search_rng_targets(seeds, inputs.tid, inputs.candidates, filters); + return plan_rng_attempts(targets, inputs.candidates, filters.shiny_required, inputs.max_attempts); +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h new file mode 100644 index 0000000000..cfb2fb4edf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h @@ -0,0 +1,91 @@ +/* RNG Plan + * + * From: https://github.com/PokemonAutomation/ + * + * Which Starter RNG targets to ask for, in order, when the SID is + * only narrowed down to SID Helper's candidates, and what to do after each + * one. The loop is the one PokemonFRLG_RngTargetSearch.h describes: + * - Shiny, and the target was hit: the SID is one of those the target is + * shiny for. With one left, it is confirmed and later targets can be + * searched with it alone. + * - Shiny, but not the target (another advance): it says nothing about + * the SID. The plan ends with the shiny. + * - Nature and IVs match, but not shiny: the target was hit, so the SIDs it + * is shiny for are wrong. Go on to the next attempt. + * - Nature or IVs differ: the target was missed. Run it again, up to the + * retries, then go on to the next attempt. + * + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlan_H +#define PokemonAutomation_PokemonFRLG_RngPlan_H + +#include +#include +#include +#include "CommonFramework/Language.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngTimings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The SIDs SID Helper lists for "tid": "count" of them, 2 advances apart, +// centered on "target_advances", as its get_sid_messages() lists them. The +// middle one, where SID Helper aims, weighs the most, and each step away one +// less, so the outermost weigh 1. +std::vector sid_helper_candidates(uint16_t tid, uint32_t target_advances, uint8_t count); + + +// An individual RNG calibration attempt. +struct RngAttempt{ + RngTarget target; + // The SIDs the target is shiny for, of those the attempts before it + // leave. Empty when the target isn't shiny for any of them. + std::vector sids; +}; + +// The attempts to make, in order, for SID candidates "candidates" (the ones +// "targets" were searched with). Each is the best target by +// rank_rng_targets() over the candidates the attempts before it leave, so a +// target shiny for several candidates comes before one shiny for one, unless +// it takes much longer. Stops after "max_attempts", or once no target is +// shiny for a candidate left. +// +// With "shiny_required" off, a hit ends the plan whether it is shiny or not, +// so the plan is the one quickest target. +std::vector plan_rng_attempts( + const std::vector& targets, + const std::vector& candidates, + bool shiny_required, + size_t max_attempts +); + + +// What Starter RNG's targets are searched with. +struct StarterRngPlanInputs{ + bool firered; + Language language; + SoundSetting sound; + uint16_t tid; + std::vector candidates; + RngTargetFilters filters; + size_t max_attempts; +}; + +// Minimum advance threshold for planning starter attempts. +inline constexpr uint64_t STARTER_RNG_PLAN_MIN_ADVANCES = STARTER_RNG_MIN_ADVANCES + STARTER_RNG_INGAME_MARGIN_ADVANCES; + +// The attempts for Starter RNG, from the seed list of the version and +// language in Help button mode, the one Starter RNG uses. +std::vector plan_starter_rng(const StarterRngPlanInputs& inputs); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp new file mode 100644 index 0000000000..67163884ef --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp @@ -0,0 +1,106 @@ +/* RNG Plan Inputs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonFRLG_RngPlanInputs.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +std::string trim(const std::string& text){ + const size_t first = text.find_first_not_of(' '); + if (first == std::string::npos){ + return ""; + } + const size_t last = text.find_last_not_of(' '); + return text.substr(first, last - first + 1); +} + +std::vector split(const std::string& text, char separator){ + std::vector parts; + size_t start = 0; + while (true){ + const size_t next = text.find(separator, start); + parts.push_back(trim(text.substr(start, next == std::string::npos ? std::string::npos : next - start))); + if (next == std::string::npos){ + return parts; + } + start = next + 1; + } +} + +} // namespace + + +std::optional parse_trainer_id(const std::string& text){ + const std::string digits = trim(text); + if (digits.empty() || digits.size() > 5 || !std::all_of(digits.begin(), digits.end(), [](char ch){ return ch >= '0' && ch <= '9'; })){ + return std::nullopt; + } + const int value = std::stoi(digits); + if (value > 0xffff){ + return std::nullopt; + } + return uint16_t(value); +} + +std::optional parse_ivs(const std::string& text){ + const std::vector parts = split(text, '/'); + if (parts.size() != 6){ + return std::nullopt; + } + uint8_t values[6]; + for (size_t c = 0; c < 6; c++){ + const std::string& part = parts[c]; + if (part.empty() || part.size() > 2 || !std::all_of(part.begin(), part.end(), [](char ch){ return ch >= '0' && ch <= '9'; })){ + return std::nullopt; + } + const int value = std::stoi(part); + if (value > 31){ + return std::nullopt; + } + values[c] = uint8_t(value); + } + AdvIVs ivs; + ivs.hp = values[0]; + ivs.attack = values[1]; + ivs.defense = values[2]; + ivs.spatk = values[3]; + ivs.spdef = values[4]; + ivs.speed = values[5]; + return ivs; +} + +std::string ivs_to_string(const AdvIVs& ivs){ + return std::format("{}/{}/{}/{}/{}/{}", ivs.hp, ivs.attack, ivs.defense, ivs.spatk, ivs.spdef, ivs.speed); +} + +std::optional> parse_natures(const std::string& text){ + std::vector natures; + if (trim(text).empty()){ + return natures; + } + for (const std::string& name : split(text, ',')){ + const AdvNature nature = string_to_nature(name); + if (nature == AdvNature::Any){ + return std::nullopt; + } + natures.push_back(nature); + } + return natures; +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h new file mode 100644 index 0000000000..ee606b7b07 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h @@ -0,0 +1,40 @@ +/* RNG Plan Inputs + * + * From: https://github.com/PokemonAutomation/ + * + * The TID, IVs and natures an RNG plan is typed in with, as text. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanInputs_H +#define PokemonAutomation_PokemonFRLG_RngPlanInputs_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// A TID or SID typed as a number from 0 to 65535. Nothing for any other text. +std::optional parse_trainer_id(const std::string& text); + +// "HP/Atk/Def/SpA/SpD/Spe", as Ten Lines and the RNG programs list IVs. +// Nothing for text that isn't six numbers from 0 to 31. +std::optional parse_ivs(const std::string& text); +// Formats IV values as a comma-separated string. +std::string ivs_to_string(const Pokemon::AdvIVs& ivs); + +// Natures separated by commas ("Modest, Timid"). Empty text is any nature +// (no entries). Nothing for a name that isn't a nature. +std::optional> parse_natures(const std::string& text); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp new file mode 100644 index 0000000000..b20c68e28a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp @@ -0,0 +1,166 @@ +/* RNG Plan Inputs Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanInputs.h" +#include "PokemonFRLG_RngPlanInputs_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +struct RngPlanInputsInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanInputsExpectation{ + std::string_view description; +}; + +struct RngPlanInputsTestCase{ + RngPlanInputsInput input; + RngPlanInputsExpectation expectation; +}; + +class Test_RngPlanInputs : public UnitTest{ +public: + explicit Test_RngPlanInputs(RngPlanInputsTestCase scenario) + : UnitTest("PokemonFRLG::RngPlanInputs - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_scenario.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RngPlanInputsTestCase m_scenario; +}; + + +UnitTestResult test_parse_trainer_id(Logger&){ + struct Case{ + std::string text; + std::string expected; + }; + const Case cases[] = { + {.text = "64694", .expected = "64694"}, + {.text = " 0 ", .expected = "0"}, + {.text = "65535", .expected = "65535"}, + {.text = "65536", .expected = "none"}, + {.text = "", .expected = "none"}, + {.text = "-1", .expected = "none"}, + {.text = "12a", .expected = "none"}, + }; + for (const Case& item : cases){ + const std::optional sid = parse_trainer_id(item.text); + const std::string got = sid ? std::to_string(*sid) : "none"; + if (got != item.expected){ + return std::format("SID \"{}\": expected {}, got {}.", item.text, item.expected, got); + } + } + return true; +} + +UnitTestResult test_parse_ivs(Logger&){ + struct Case{ + std::string text; + std::string expected; + }; + const Case cases[] = { + {.text = "31/14/7/29/1/27", .expected = "31/14/7/29/1/27"}, + {.text = " 0 / 0/0/0/0/31 ", .expected = "0/0/0/0/0/31"}, + {.text = "31/0/0", .expected = "none"}, + {.text = "32/0/0/0/0/0", .expected = "none"}, + {.text = "a/0/0/0/0/0", .expected = "none"}, + {.text = "-1/0/0/0/0/0", .expected = "none"}, + {.text = "", .expected = "none"}, + }; + for (const Case& item : cases){ + const std::optional ivs = parse_ivs(item.text); + const std::string got = ivs ? ivs_to_string(*ivs) : "none"; + if (got != item.expected){ + return std::format("IVs \"{}\": expected {}, got {}.", item.text, item.expected, got); + } + } + return true; +} + +UnitTestResult test_parse_natures(Logger&){ + struct Case{ + std::string text; + std::string expected; + }; + const Case cases[] = { + {.text = "", .expected = "any"}, + {.text = " ", .expected = "any"}, + {.text = "Modest", .expected = "Modest"}, + {.text = "Modest, Timid", .expected = "Modest Timid"}, + {.text = "Modset", .expected = "none"}, + {.text = "Modest,", .expected = "none"}, + }; + for (const Case& item : cases){ + const std::optional> natures = parse_natures(item.text); + std::string got; + if (!natures){ + got = "none"; + }else if (natures->empty()){ + got = "any"; + }else{ + for (AdvNature nature : *natures){ + got += (got.empty() ? "" : " ") + nature_to_string(nature); + } + } + if (got != item.expected){ + return std::format("Natures \"{}\": expected {}, got {}.", item.text, item.expected, got); + } + } + return true; +} + +const RngPlanInputsTestCase RNG_PLAN_INPUTS_CASES[] = { + { + .input = {.name = "TID and SID text", .body = test_parse_trainer_id}, + .expectation = {.description = "parses TID and SID text formats"}, + }, + { + .input = {.name = "IVs text", .body = test_parse_ivs}, + .expectation = {.description = "parses six individual IV integer values"}, + }, + { + .input = {.name = "natures text", .body = test_parse_natures}, + .expectation = {.description = "parses comma-separated nature names"}, + }, +}; + +} // namespace + + +void add_tests_RngPlanInputs(UnitTestDatabase& database){ + for (const auto& scenario : RNG_PLAN_INPUTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h new file mode 100644 index 0000000000..836fcfee94 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h @@ -0,0 +1,24 @@ +/* RNG Plan Inputs Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanInputs_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlanInputs_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers RNG plan input parsing unit tests. +void add_tests_RngPlanInputs(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp new file mode 100644 index 0000000000..41228fb92c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp @@ -0,0 +1,137 @@ +/* RNG Plan Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h" +#include "PokemonFRLG_RngPlanLog.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text; +} + +} // namespace + +std::string rng_log_tid(uint16_t tid, bool from_card){ + return std::format("RngPlan: tid={} source={}", tid, from_card ? "card" : "option"); +} + +std::string rng_log_sid_helper(uint16_t tid, uint32_t target_advances, const std::vector& candidates){ + std::vector sids; + for (const SidCandidate& candidate : candidates){ + sids.push_back(candidate.sid); + } + return std::format("RngPlan: sid_helper tid={} target_advances={} candidates={}", tid, target_advances, join_sids(sids)); +} + +std::string rng_log_attempt(size_t index, const RngAttempt& attempt){ + return std::format( + "RngPlan: attempt={} seed={:04X} advances={} sids={} seed_wait_ms={} ingame_ms={}", + index + 1, attempt.target.seed.seed, attempt.target.advances, join_sids(attempt.sids), + starter_rng_seed_wait_ms(attempt.target.seed), starter_rng_ingame_ms(attempt.target.advances) + ); +} + +namespace{ + +std::string_view outcome_name(RngAttemptOutcome outcome){ + switch (outcome){ + case RngAttemptOutcome::SHINY: + return "shiny"; + case RngAttemptOutcome::SHINY_OFF_TARGET: + return "shiny_off_target"; + case RngAttemptOutcome::HIT_NOT_SHINY: + return "hit_not_shiny"; + case RngAttemptOutcome::MISSED: + return "missed"; + case RngAttemptOutcome::UNUSABLE: + return "unusable"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngAttemptOutcome."); +} + +std::string_view next_name(RngPlanNext next){ + switch (next){ + case RngPlanNext::RETRY: + return "retry"; + case RngPlanNext::NEXT_ATTEMPT: + return "next_attempt"; + case RngPlanNext::CONFIRM: + return "confirm"; + case RngPlanNext::STOP: + return "stop"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanNext."); +} + +} // namespace + +std::string rng_log_result(const RngResultLog& result){ + const std::optional& pokemon = result.pokemon; + return std::format( + "RngPlan: result attempt={} try={} outcome={} starter_rng={} nature={} ivs={} pid={} next={}", + result.index + 1, result.try_number, outcome_name(result.outcome), + result.detail.empty() ? "-" : result.detail, + pokemon ? nature_to_string(pokemon->nature) : "-", + pokemon ? ivs_to_string(pokemon->ivs) : "-", + pokemon ? std::format("{:08X}", pokemon->pid) : "-", + next_name(result.next) + ); +} + +std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates){ + size_t k = 0; + for (size_t c = 0; c < sid_helper_candidates.size(); c++){ + if (sid_helper_candidates[c].sid == sid){ + k = c + 1; + break; + } + } + return std::format("RngPlan: confirmed tid={} sid={} candidate={} of={}", tid, sid, k, sid_helper_candidates.size()); +} + + +std::vector rng_attempt_lines(const std::vector& attempts){ + std::vector lines; + for (size_t c = 0; c < attempts.size(); c++){ + const RngTarget& target = attempts[c].target; + std::string shiny; + if (attempts[c].sids.empty()){ + shiny = "not shiny for any SID candidate"; + }else{ + shiny = "shiny for SID"; + for (size_t s = 0; s < attempts[c].sids.size(); s++){ + shiny += (s == 0 ? " " : ", ") + std::to_string(attempts[c].sids[s]); + } + shiny += std::format(" ({:.0f}% of the candidates left)", target.shiny_probability * 100); + } + lines.push_back(std::format( + "Attempt {}: Target Seed {:04X}, Advances {}: {}, IVs {}, PID {:08X}, {}.", + c + 1, target.seed.seed, target.advances, + nature_to_string(target.pokemon.nature), ivs_to_string(target.pokemon.ivs), target.pokemon.pid, + shiny + )); + } + return lines; +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h new file mode 100644 index 0000000000..4d3b3f6e4f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h @@ -0,0 +1,82 @@ +/* RNG Plan Log + * + * From: https://github.com/PokemonAutomation/ + * + * The lines an RNG plan logs and shows: its attempts, and the "RngPlan:" + * lines below. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanLog_H +#define PokemonAutomation_PokemonFRLG_RngPlanLog_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// One line per attempt, for the log and the stop message: the Target Seed +// and Advances to give Starter RNG, the Pokemon, and the SIDs it is shiny for. +std::vector rng_attempt_lines(const std::vector& attempts); + + +// The data to rebuild how likely SID Helper's k-th candidate of N is (the +// 1-2-3-2-1 weights of sid_helper_candidates() are a guess), from the logs +// alone, and to follow AutoStory's Starter RNG loop. Every line starts with +// "RngPlan:"; grep for it. In the order a run logs them: +// RngPlan: tid= source= +// RngPlan: sid_helper tid= target_advances= candidates=,... +// RngPlan: attempt= seed= advances= sids=,... +// seed_wait_ms= ingame_ms= (Starter RNG's waits, before calibration) +// then, with Run Starter RNG in AutoStory, for each try of an attempt +// (rng_log_state() in PokemonFRLG_StarterRngLoop.h): +// RngPlan: state attempt=/ try=/ reset=/ seed= +// advances= sids=,... ruled_out=,... attempt_time=/ +// total_time=/ calibration=// +// (once at the try's start, then after every reset) +// RngPlan: result attempt= try= outcome= +// starter_rng= nature= ivs= +// pid= next= +// RngPlan: confirmed tid= sid= candidate= of= +// Lists that are empty print "-". +// "candidates" are in SID Helper's order; "candidate=k" counts from 1 in +// it, 0 when the SID wasn't among them. Count each TID's "confirmed" once: +// every later run with the SID set logs it again. While the user runs +// Starter RNG by hand, its own "Target Hit!" and "Missed target." lines +// are the attempts' results. +std::string rng_log_tid(uint16_t tid, bool from_card); +// Formats SID Helper summary line for log output. +std::string rng_log_sid_helper(uint16_t tid, uint32_t target_advances, const std::vector& candidates); +// Formats attempt parameters for log output. +std::string rng_log_attempt(size_t index, const RngAttempt& attempt); + +// Structured log summary of an RNG outcome. +struct RngResultLog{ + size_t index = 0; + // From 1. + size_t try_number = 1; + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + // How the RNG program put it ("out_of_resets"); empty for none. + std::string detail; + // The Pokemon hit, when known. + std::optional pokemon; + RngPlanNext next = RngPlanNext::STOP; +}; +// Formats RNG attempt result for logging. +std::string rng_log_result(const RngResultLog& result); +// Formats confirmed SID and candidate weights for logging. +std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp new file mode 100644 index 0000000000..f3d7894df5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp @@ -0,0 +1,132 @@ +/* RNG Plan Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanTestTargets.h" +#include "PokemonFRLG_RngPlanInputs.h" +#include "PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_RngPlanLog_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; +using namespace RngPlanTestTargets; + + +namespace{ + +struct RngPlanLogInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanLogExpectation{ + std::string_view description; +}; + +struct RngPlanLogTestCase{ + RngPlanLogInput input; + RngPlanLogExpectation expectation; +}; + +class Test_RngPlanLog : public UnitTest{ +public: + explicit Test_RngPlanLog(RngPlanLogTestCase scenario) + : UnitTest("PokemonFRLG::RngPlanLog - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_scenario.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RngPlanLogTestCase m_scenario; +}; + + +// The "RngPlan:" lines the candidate odds are rebuilt from. +UnitTestResult test_log_lines(Logger&){ + RngAttempt attempt{make_target(1, 50, {0, 1}), {100, 200}}; + attempt.target.seed.seed = 0x2ef6; + attempt.target.advances = 29364; + struct Case{ + std::string got; + std::string expected; + }; + const Case cases[] = { + {.got = rng_log_tid(43771, true), .expected = "RngPlan: tid=43771 source=card"}, + {.got = rng_log_tid(43771, false), .expected = "RngPlan: tid=43771 source=option"}, + {.got = rng_log_sid_helper(43771, 3001, CANDIDATES), .expected = "RngPlan: sid_helper tid=43771 target_advances=3001 candidates=100,200,300"}, + {.got = rng_log_attempt(0, attempt), .expected = std::format( + "RngPlan: attempt=1 seed=2EF6 advances=29364 sids=100,200 seed_wait_ms=49155 ingame_ms={}", starter_rng_ingame_ms(29364) + )}, + { + .got = rng_log_result(RngResultLog{ + .index = 1, .try_number = 2, .outcome = RngAttemptOutcome::HIT_NOT_SHINY, .detail = "target_hit", + .pokemon = attempt.target.pokemon, .next = RngPlanNext::NEXT_ATTEMPT, + }), + .expected = std::format( + "RngPlan: result attempt=2 try=2 outcome=hit_not_shiny starter_rng=target_hit nature={} ivs={} pid={:08X} next=next_attempt", + nature_to_string(attempt.target.pokemon.nature), ivs_to_string(attempt.target.pokemon.ivs), attempt.target.pokemon.pid + ), + }, + { + .got = rng_log_result(RngResultLog{ + .index = 0, .try_number = 1, .outcome = RngAttemptOutcome::MISSED, .detail = "out_of_resets", + .pokemon = std::nullopt, .next = RngPlanNext::RETRY, + }), + .expected = "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + }, + { + .got = rng_log_result(RngResultLog{ + .index = 2, .try_number = 3, .outcome = RngAttemptOutcome::SHINY_OFF_TARGET, .detail = "shiny_off_target", + .pokemon = std::nullopt, .next = RngPlanNext::STOP, + }), + .expected = "RngPlan: result attempt=3 try=3 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop", + }, + {.got = rng_log_confirmed(43771, 300, CANDIDATES), .expected = "RngPlan: confirmed tid=43771 sid=300 candidate=3 of=3"}, + {.got = rng_log_confirmed(43771, 7, CANDIDATES), .expected = "RngPlan: confirmed tid=43771 sid=7 candidate=0 of=3"}, + }; + for (const Case& item : cases){ + if (item.got != item.expected){ + return "Expected \"" + item.expected + "\", got \"" + item.got + "\"."; + } + } + return true; +} + +const RngPlanLogTestCase RNG_PLAN_LOG_CASES[] = { + { + .input = {.name = "RngPlan log lines", .body = test_log_lines}, + .expectation = {.description = "verifies structured RNG plan log lines formatting"}, + }, +}; + +} // namespace + + +void add_tests_RngPlanLog(UnitTestDatabase& database){ + for (const auto& scenario : RNG_PLAN_LOG_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h new file mode 100644 index 0000000000..b06f432443 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h @@ -0,0 +1,24 @@ +/* RNG Plan Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanLog_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlanLog_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers RNG plan logging unit tests. +void add_tests_RngPlanLog(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp new file mode 100644 index 0000000000..5fc1b663e6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp @@ -0,0 +1,61 @@ +/* RNG Plan Test Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_RngPlanTestTargets.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace RngPlanTestTargets{ + + +std::string join(const std::vector& values){ + std::string text; + for (uint16_t value : values){ + text += (text.empty() ? "" : ",") + std::to_string(value); + } + return "{" + text + "}"; +} + + +// SIDs 100, 200 and 300 weigh 3, 2 and 1. +const std::vector CANDIDATES = {{100, 3}, {200, 2}, {300, 1}}; + +// A target reached "seconds" after the reset, shiny for the candidates at +// "shiny" (indices into CANDIDATES). +RngTarget make_target(uint32_t state, uint64_t seconds, std::vector shiny){ + RngTarget target{}; + target.state = state; + target.seed = {uint16_t(state), seconds * 1000, SeedButton::A, BlackoutButton::None}; + target.advances = 0; + target.pokemon = method1_pokemon(state); + for (size_t candidate : shiny){ + target.shiny_for.push_back({candidate, AdvShinyType::Star}); + } + return target; +} + +// By expected wait per shiny over all three (weight 6): 1 = 50 s / (5/6) = 60, +// 2 = 20 s / (1/6) = 120, 3 = 40 s / (3/6) = 80. Then over SID 300 alone, 2 is +// the only one shiny for it. 4 is the quickest and shiny for none. +const std::vector TARGETS = { + make_target(1, 50, {0, 1}), + make_target(2, 20, {2}), + make_target(3, 40, {0}), + make_target(4, 5, {}), +}; + + +} // namespace RngPlanTestTargets + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h new file mode 100644 index 0000000000..e76decb033 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h @@ -0,0 +1,47 @@ +/* RNG Plan Test Targets + * + * From: https://github.com/PokemonAutomation/ + * + * Made-up SID candidates and targets the RNG plan tests share. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanTestTargets_H +#define PokemonAutomation_PokemonFRLG_RngPlanTestTargets_H + +#include +#include +#include +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace RngPlanTestTargets{ + + +// Formats vector of integer values as space-delimited string. +std::string join(const std::vector& values); + +// SIDs 100, 200 and 300 weigh 3, 2 and 1. +extern const std::vector CANDIDATES; + +// A target reached "seconds" after the reset, shiny for the candidates at +// "shiny" (indices into CANDIDATES). +RngTarget make_target(uint32_t state, uint64_t seconds, std::vector shiny); + +// By expected wait per shiny over all three (weight 6): 1 = 50 s / (5/6) = 60, +// 2 = 20 s / (1/6) = 120, 3 = 40 s / (3/6) = 80. Then over SID 300 alone, 2 is +// the only one shiny for it. 4 is the quickest and shiny for none. +extern const std::vector TARGETS; + + +} // namespace RngPlanTestTargets + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp new file mode 100644 index 0000000000..c857f65b93 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp @@ -0,0 +1,134 @@ +/* RNG Plan Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_RngPlanTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +RngAttemptOutcome classify_attempt(const RngTarget& target, const RngAttemptResult& result){ + const AdvIVs& want = target.pokemon.ivs; + const AdvIVs& got = result.ivs; + const bool same_ivs = want.hp == got.hp && want.attack == got.attack && want.defense == got.defense + && want.spatk == got.spatk && want.spdef == got.spdef && want.speed == got.speed; + const bool hit = result.nature == target.pokemon.nature && same_ivs; + if (result.shiny){ + return hit ? RngAttemptOutcome::SHINY : RngAttemptOutcome::SHINY_OFF_TARGET; + } + return hit ? RngAttemptOutcome::HIT_NOT_SHINY : RngAttemptOutcome::MISSED; +} + + +RngPlanTracker::RngPlanTracker( + std::vector attempts, + const std::vector& candidates, + bool shiny_required, + size_t max_retries +) + : m_attempts(std::move(attempts)) + , m_shiny_required(shiny_required) + , m_max_retries(max_retries) + , m_step(m_attempts.empty() ? RngPlanStep::OUT_OF_ATTEMPTS : RngPlanStep::RUN_ATTEMPT) +{ + for (const SidCandidate& candidate : candidates){ + m_remaining.push_back(candidate.sid); + } +} + +std::optional RngPlanTracker::confirmed_sid() const{ + if (m_step == RngPlanStep::GOT_SHINY && m_remaining.size() == 1){ + return m_remaining.front(); + } + return std::nullopt; +} + +bool RngPlanTracker::is_ruled_out(uint16_t sid) const{ + return std::find(m_remaining.begin(), m_remaining.end(), sid) == m_remaining.end(); +} + +bool RngPlanTracker::move_to_next_attempt(){ + for (size_t next = m_attempt + 1; next < m_attempts.size(); next++){ + const std::vector& next_sids = m_attempts[next].sids; + if (!m_shiny_required || !std::all_of(next_sids.begin(), next_sids.end(), [&](uint16_t sid){ return is_ruled_out(sid); })){ + m_attempt = next; + m_retries = 0; + return true; + } + } + return false; +} + +RngPlanStep RngPlanTracker::record(RngAttemptOutcome outcome){ + if (m_step != RngPlanStep::RUN_ATTEMPT){ + return m_step; + } + const std::vector& sids = m_attempts[m_attempt].sids; + switch (outcome){ + case RngAttemptOutcome::SHINY: + // The SID is one the target is shiny for. None of them: it wasn't + // among the candidates. + std::erase_if(m_remaining, [&](uint16_t sid){ return std::find(sids.begin(), sids.end(), sid) == sids.end(); }); + m_step = RngPlanStep::GOT_SHINY; + return m_step; + case RngAttemptOutcome::SHINY_OFF_TARGET: + m_step = RngPlanStep::GOT_SHINY_OFF_TARGET; + return m_step; + case RngAttemptOutcome::HIT_NOT_SHINY: + if (!m_shiny_required){ + m_step = RngPlanStep::GOT_TARGET; + return m_step; + } + m_remaining.erase( + std::remove_if(m_remaining.begin(), m_remaining.end(), [&](uint16_t sid){ + return std::find(sids.begin(), sids.end(), sid) != sids.end(); + }), + m_remaining.end() + ); + if (!move_to_next_attempt()){ + m_step = RngPlanStep::OUT_OF_ATTEMPTS; + } + return m_step; + case RngAttemptOutcome::MISSED: + // A miss rules nothing out. Too many: try the next attempt instead. + if (++m_retries <= m_max_retries){ + return m_step; + } + [[fallthrough]]; + case RngAttemptOutcome::UNUSABLE: + if (!move_to_next_attempt()){ + m_step = RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT; + } + return m_step; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngAttemptOutcome."); +} + + +RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return next_index == index ? RngPlanNext::RETRY : RngPlanNext::NEXT_ATTEMPT; + case RngPlanStep::GOT_SHINY: + return RngPlanNext::CONFIRM; + case RngPlanStep::GOT_SHINY_OFF_TARGET: + case RngPlanStep::GOT_TARGET: + case RngPlanStep::OUT_OF_ATTEMPTS: + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: + return RngPlanNext::STOP; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanStep."); +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h new file mode 100644 index 0000000000..6064306511 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h @@ -0,0 +1,121 @@ +/* RNG Plan Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * The step after each attempt of an RNG plan (PokemonFRLG_RngPlan.h), + * from what came out of it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanTracker_H +#define PokemonAutomation_PokemonFRLG_RngPlanTracker_H + +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What came out of one attempt. +enum class RngAttemptOutcome{ + // Shiny, with the target's nature and IVs. + SHINY, + // Shiny, but not the target, or not known to be. + SHINY_OFF_TARGET, + // The target's nature and IVs, not shiny. + HIT_NOT_SHINY, + // Another nature or other IVs: not the target. + MISSED, + // The attempt couldn't run (Starter RNG refused its timings). It rules + // nothing out; the next attempt runs instead. + UNUSABLE, +}; + +// Outcome details from an attempted RNG frame hit. +struct RngAttemptResult{ + bool shiny; + Pokemon::AdvNature nature; + Pokemon::AdvIVs ivs; +}; +// Classifies attempt result relative to target specifications. +RngAttemptOutcome classify_attempt(const RngTarget& target, const RngAttemptResult& result); + +// Current execution phase within the RNG plan state machine. +enum class RngPlanStep{ + // Run current_attempt(): the first, the next, or the same again after a miss. + RUN_ATTEMPT, + // Shiny, the target hit. remaining_sids() are the SIDs it can be. + GOT_SHINY, + // Shiny, not the target: the SIDs are as they were, none confirmed. + GOT_SHINY_OFF_TARGET, + // Shiny not required, and the target was hit. + GOT_TARGET, + // Every attempt was hit and none was shiny. + OUT_OF_ATTEMPTS, + // The last attempt still shiny for a SID left was missed more often + // than the retries allow, or couldn't run. (Missing an earlier one moves + // on to the next.) + MISSED_EVERY_ATTEMPT_LEFT, +}; + +// Follows the plan through the attempts' outcomes. +class RngPlanTracker{ +public: + RngPlanTracker( + std::vector attempts, + const std::vector& candidates, + bool shiny_required, + size_t max_retries + ); + + RngPlanStep step() const{ return m_step; } + size_t attempt_index() const{ return m_attempt; } + size_t attempt_count() const{ return m_attempts.size(); } + const RngAttempt& current_attempt() const{ return m_attempts[m_attempt]; } + // The SID candidates not ruled out, in the order given. + const std::vector& remaining_sids() const{ return m_remaining; } + // The SID, once a shiny leaves one candidate. + std::optional confirmed_sid() const; + + // The next step after the current attempt came out as "outcome". Once + // the plan has ended, the step stays as it is. + RngPlanStep record(RngAttemptOutcome outcome); + +private: + bool is_ruled_out(uint16_t sid) const; + // Moves to the next attempt still shiny for a SID left (with shiny + // required; else any next one). False if there is none. + bool move_to_next_attempt(); + + std::vector m_attempts; + bool m_shiny_required; + size_t m_max_retries; + std::vector m_remaining; + size_t m_attempt = 0; + size_t m_retries = 0; + RngPlanStep m_step; +}; + + +// What the loop does after an attempt's result. +enum class RngPlanNext{ + RETRY, + NEXT_ATTEMPT, + // Shiny and the target: go on with the story. + CONFIRM, + STOP, +}; +// The step after `index` came out as the tracker's `step` and its attempt +// is now `next_index`. +RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp new file mode 100644 index 0000000000..5aa505c7af --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp @@ -0,0 +1,288 @@ +/* RNG Plan Tracker Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The outcome of an attempt, and the step after each, on made-up targets. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanTestTargets.h" +#include "PokemonFRLG_RngPlanTracker.h" +#include "PokemonFRLG_RngPlanTracker_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; +using namespace RngPlanTestTargets; + + +namespace{ + +struct RngPlanTrackerInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanTrackerExpectation{ + std::string_view description; +}; + +struct RngPlanTrackerTestCase{ + RngPlanTrackerInput input; + RngPlanTrackerExpectation expectation; +}; + +class Test_RngPlanTracker : public UnitTest{ +public: + explicit Test_RngPlanTracker(RngPlanTrackerTestCase scenario) + : UnitTest("PokemonFRLG::RngPlanTracker - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_scenario.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RngPlanTrackerTestCase m_scenario; +}; + + +UnitTestResult test_classify(Logger&){ + const RngTarget hit = TARGETS[0]; + AdvIVs other_ivs = hit.pokemon.ivs; + other_ivs.speed = uint8_t((other_ivs.speed + 1) % 32); + const AdvNature other_nature = hit.pokemon.nature == AdvNature::Hardy ? AdvNature::Lonely : AdvNature::Hardy; + + struct Case{ + std::string name; + RngAttemptResult result; + RngAttemptOutcome expected; + }; + const Case cases[] = { + {.name = "shiny, the target", .result = {.shiny = true, .nature = hit.pokemon.nature, .ivs = hit.pokemon.ivs}, .expected = RngAttemptOutcome::SHINY}, + {.name = "shiny, not the target", .result = {.shiny = true, .nature = other_nature, .ivs = other_ivs}, .expected = RngAttemptOutcome::SHINY_OFF_TARGET}, + {.name = "same nature and IVs", .result = {.shiny = false, .nature = hit.pokemon.nature, .ivs = hit.pokemon.ivs}, .expected = RngAttemptOutcome::HIT_NOT_SHINY}, + {.name = "other IVs", .result = {.shiny = false, .nature = hit.pokemon.nature, .ivs = other_ivs}, .expected = RngAttemptOutcome::MISSED}, + {.name = "other nature", .result = {.shiny = false, .nature = other_nature, .ivs = hit.pokemon.ivs}, .expected = RngAttemptOutcome::MISSED}, + }; + for (const Case& item : cases){ + if (classify_attempt(hit, item.result) != item.expected){ + return item.name + ": classified wrong."; + } + } + return true; +} + + +std::string step_name(RngPlanStep step){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: return "RUN_ATTEMPT"; + case RngPlanStep::GOT_SHINY: return "GOT_SHINY"; + case RngPlanStep::GOT_SHINY_OFF_TARGET: return "GOT_SHINY_OFF_TARGET"; + case RngPlanStep::GOT_TARGET: return "GOT_TARGET"; + case RngPlanStep::OUT_OF_ATTEMPTS: return "OUT_OF_ATTEMPTS"; + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: return "MISSED_EVERY_ATTEMPT_LEFT"; + } + return "?"; +} + +struct TrackerCase{ + std::string name; + bool shiny_required; + std::vector outcomes; + // The step after each outcome, and the attempt run next. + std::vector steps; + std::vector attempts; + std::vector remaining; + std::optional confirmed; +}; +std::vector tracker_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "shiny at once: one of two SIDs", + .shiny_required = true, .outcomes = {SHINY}, + .steps = {GOT_SHINY}, .attempts = {0}, + .remaining = {100, 200}, .confirmed = std::nullopt, + }, + { + .name = "hit, then shiny: SID confirmed", + .shiny_required = true, .outcomes = {HIT_NOT_SHINY, SHINY}, + .steps = {RUN_ATTEMPT, GOT_SHINY}, .attempts = {1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "a miss retries the same target", + .shiny_required = true, .outcomes = {MISSED, MISSED, HIT_NOT_SHINY, MISSED}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT}, .attempts = {0, 0, 1, 1}, + .remaining = {300}, .confirmed = std::nullopt, + }, + }; +} +// Misses: retried, then the next attempt, mixed with hits and shinies. +std::vector tracker_retry_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "retries used up, then the next attempt", + .shiny_required = true, .outcomes = {MISSED, MISSED, MISSED, SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, GOT_SHINY}, .attempts = {0, 0, 1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "every attempt left missed too often", + .shiny_required = true, .outcomes = {MISSED, MISSED, MISSED, MISSED, MISSED, MISSED}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, MISSED_EVERY_ATTEMPT_LEFT}, + .attempts = {0, 0, 1, 1, 1, 1}, + .remaining = {100, 200, 300}, .confirmed = std::nullopt, + }, + { + .name = "shiny off the target confirms nothing", + .shiny_required = true, .outcomes = {HIT_NOT_SHINY, SHINY_OFF_TARGET, SHINY}, + .steps = {RUN_ATTEMPT, GOT_SHINY_OFF_TARGET, GOT_SHINY_OFF_TARGET}, .attempts = {1, 1, 1}, + .remaining = {300}, .confirmed = std::nullopt, + }, + }; +} +// Attempts that can't run. +std::vector tracker_unusable_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "an attempt that can't run moves on", + .shiny_required = true, .outcomes = {MISSED, UNUSABLE, SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, GOT_SHINY}, .attempts = {0, 1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "the last attempt can't run", + .shiny_required = true, .outcomes = {UNUSABLE, UNUSABLE}, + .steps = {RUN_ATTEMPT, MISSED_EVERY_ATTEMPT_LEFT}, .attempts = {1, 1}, + .remaining = {100, 200, 300}, .confirmed = std::nullopt, + }, + }; +} +std::vector tracker_mixed_cases(){ + using enum RngAttemptOutcome; + using enum RngPlanStep; + return { + { + .name = "miss, hit, misses, then shiny", + .shiny_required = true, .outcomes = {MISSED, HIT_NOT_SHINY, MISSED, MISSED, SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, GOT_SHINY}, .attempts = {0, 1, 1, 1, 1}, + .remaining = {300}, .confirmed = uint16_t(300), + }, + { + .name = "misses move on, then a hit ends the plan", + .shiny_required = true, .outcomes = {MISSED, MISSED, MISSED, MISSED, HIT_NOT_SHINY}, + .steps = {RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, RUN_ATTEMPT, OUT_OF_ATTEMPTS}, .attempts = {0, 0, 1, 1, 1}, + .remaining = {100, 200}, .confirmed = std::nullopt, + }, + { + .name = "every attempt hit, none shiny", + .shiny_required = true, .outcomes = {HIT_NOT_SHINY, HIT_NOT_SHINY}, + .steps = {RUN_ATTEMPT, OUT_OF_ATTEMPTS}, .attempts = {1, 1}, + .remaining = {}, .confirmed = std::nullopt, + }, + { + .name = "shiny not required: a hit ends it", + .shiny_required = false, .outcomes = {HIT_NOT_SHINY}, + .steps = {GOT_TARGET}, .attempts = {0}, + .remaining = {100, 200, 300}, .confirmed = std::nullopt, + }, + }; +} + +UnitTestResult check_tracker_case(const TrackerCase& item){ + RngPlanTracker tracker(plan_rng_attempts(TARGETS, CANDIDATES, true, 5), CANDIDATES, item.shiny_required, 2); + if (tracker.step() != RngPlanStep::RUN_ATTEMPT){ + return item.name + ": expected to start with RUN_ATTEMPT, got " + step_name(tracker.step()) + "."; + } + for (size_t c = 0; c < item.outcomes.size(); c++){ + const RngPlanStep step = tracker.record(item.outcomes[c]); + if (step != item.steps[c] || tracker.attempt_index() != item.attempts[c]){ + return std::format( + "{}: after outcome {}, expected {} at attempt {}, got {} at attempt {}.", + item.name, c, step_name(item.steps[c]), item.attempts[c], step_name(step), tracker.attempt_index() + ); + } + } + if (tracker.remaining_sids() != item.remaining || tracker.confirmed_sid() != item.confirmed){ + return std::format( + "{}: expected SIDs {} (confirmed {}), got {} (confirmed {}).", + item.name, join(item.remaining), item.confirmed ? std::to_string(*item.confirmed) : "none", + join(tracker.remaining_sids()), tracker.confirmed_sid() ? std::to_string(*tracker.confirmed_sid()) : "none" + ); + } + return true; +} + +UnitTestResult test_tracker(Logger&){ + std::vector cases = tracker_cases(); + for (auto* more : {tracker_retry_cases, tracker_unusable_cases, tracker_mixed_cases}){ + for (TrackerCase& item : more()){ + cases.push_back(std::move(item)); + } + } + for (const TrackerCase& item : cases){ + const UnitTestResult result = check_tracker_case(item); + if (result.result != UnitTestResult::PASSED){ + return result; + } + } + RngPlanTracker empty({}, CANDIDATES, true, 2); + if (empty.step() != RngPlanStep::OUT_OF_ATTEMPTS){ + return std::string("An empty plan: expected OUT_OF_ATTEMPTS, got ") + step_name(empty.step()) + "."; + } + // A shiny hit for a SID that is no candidate: none left, none confirmed. + RngPlanTracker outside({RngAttempt{make_target(1, 50, {}), {999}}}, CANDIDATES, true, 2); + outside.record(RngAttemptOutcome::SHINY); + if (outside.step() != RngPlanStep::GOT_SHINY || !outside.remaining_sids().empty() || outside.confirmed_sid()){ + return std::format( + "Shiny for no candidate: expected GOT_SHINY with no SID left, got {} with SIDs {}.", + step_name(outside.step()), join(outside.remaining_sids()) + ); + } + return true; +} + +const RngPlanTrackerTestCase RNG_PLAN_TRACKER_CASES[] = { + { + .input = {.name = "attempt outcome", .body = test_classify}, + .expectation = {.description = "classifies outcome of target attempt"}, + }, + { + .input = {.name = "step after each outcome", .body = test_tracker}, + .expectation = {.description = "evaluates state transitions after attempt outcomes"}, + }, +}; + +} // namespace + + +void add_tests_RngPlanTracker(UnitTestDatabase& database){ + for (const auto& scenario : RNG_PLAN_TRACKER_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h new file mode 100644 index 0000000000..a0406bf2f3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h @@ -0,0 +1,24 @@ +/* RNG Plan Tracker Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlanTracker_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlanTracker_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers RNG plan tracker unit tests. +void add_tests_RngPlanTracker(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp new file mode 100644 index 0000000000..be4b758989 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp @@ -0,0 +1,322 @@ +/* RNG Plan Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The attempt order on made-up targets; SID Helper's candidates and a + * Starter RNG plan from the FireRed seed list. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_RngPlanTestTargets.h" +#include "PokemonFRLG_RngPlan.h" +#include "PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_RngPlan_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; +using namespace RngPlanTestTargets; + + +namespace{ + +struct RngPlanInput{ + std::string name; + UnitTestResult (*body)(Logger&); +}; + +struct RngPlanExpectation{ + std::string_view description; +}; + +struct RngPlanTestCase{ + RngPlanInput input; + RngPlanExpectation expectation; +}; + +class Test_RngPlan : public UnitTest{ +public: + explicit Test_RngPlan(RngPlanTestCase scenario) + : UnitTest("PokemonFRLG::RngPlan - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_scenario.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RngPlanTestCase m_scenario; +}; + + +UnitTestResult test_sid_helper_candidates(Logger&){ + const uint16_t tid = 43771; + const uint32_t target_advances = 3001; + const std::vector candidates = sid_helper_candidates(tid, target_advances, 5); + + // The SID is the top half of the state after the TID seed is advanced + // once, then "advances" more times. + auto sid_at = [&](uint32_t advances){ + uint32_t state = tid; + for (uint32_t c = 0; c <= advances; c++){ + state = lcrng_next(state); + } + return uint16_t(state >> 16); + }; + const std::vector advances = {2997, 2999, 3001, 3003, 3005}; + const std::vector weights = {1, 2, 3, 2, 1}; + if (candidates.size() != advances.size()){ + return std::format("Expected {} candidates, got {}.", advances.size(), candidates.size()); + } + for (size_t c = 0; c < candidates.size(); c++){ + if (candidates[c].sid != sid_at(advances[c]) || candidates[c].weight != weights[c]){ + return std::format( + "Candidate {}: expected SID {} weight {}, got SID {} weight {}.", + c, sid_at(advances[c]), weights[c], candidates[c].sid, candidates[c].weight + ); + } + } + + const std::vector even = sid_helper_candidates(tid, target_advances, 4); + const std::vector even_weights = {1, 2, 3, 2}; + for (size_t c = 0; c < even.size() && c < even_weights.size(); c++){ + if (even.size() != even_weights.size() || even[c].sid != candidates[c].sid || even[c].weight != even_weights[c]){ + return std::format("Four candidates: expected the first four of five, weighing 1, 2, 3, 2; candidate {} differs.", c); + } + } + return true; +} + + +struct PlanCase{ + std::string name; + std::vector targets; + bool shiny_required; + size_t max_attempts; + std::vector states; + std::vector> sids; +}; +std::vector plan_cases(){ + const std::vector no_300 = {TARGETS[0], TARGETS[2], TARGETS[3]}; + return { + { + .name = "two candidates in one target first, then the last", + .targets = TARGETS, .shiny_required = true, .max_attempts = 5, + .states = {1, 2}, .sids = {{100, 200}, {300}}, + }, + { + .name = "capped at one attempt", + .targets = TARGETS, .shiny_required = true, .max_attempts = 1, + .states = {1}, .sids = {{100, 200}}, + }, + { + .name = "no target shiny for SID 300", + .targets = no_300, .shiny_required = true, .max_attempts = 5, + .states = {1}, .sids = {{100, 200}}, + }, + { + .name = "shiny not required: the quickest", + .targets = TARGETS, .shiny_required = false, .max_attempts = 5, + .states = {4}, .sids = {{}}, + }, + { + .name = "no targets", + .targets = {}, .shiny_required = true, .max_attempts = 5, + .states = {}, .sids = {}, + }, + }; +} + +UnitTestResult test_plan_order(Logger&){ + for (const PlanCase& item : plan_cases()){ + const std::vector attempts = plan_rng_attempts(item.targets, CANDIDATES, item.shiny_required, item.max_attempts); + std::vector states; + std::vector> sids; + for (const RngAttempt& attempt : attempts){ + states.push_back(attempt.target.state); + sids.push_back(attempt.sids); + } + if (states != item.states || sids != item.sids){ + std::string got; + for (size_t c = 0; c < attempts.size(); c++){ + got += std::format(" target {} {}", states[c], join(sids[c])); + } + return item.name + ": got" + (got.empty() ? " no attempts" : got) + "."; + } + } + return true; +} + + +// A plan from the FireRed (English) list: every attempt starts from a seed +// Starter RNG finds, takes at least its smallest Advances, and is shiny for +// the SIDs it lists, which no earlier attempt listed. +// Console B, 2026-11-02, FireRed English, Mono, Help: Starter RNG refused +// both of these as title screen waits under 30 s. AutoStory's plan for TID +// 55740 started with 11A3 at 945 advances (29,628 ms after Starter RNG's +// offsets); StarterRng by hand with 405C at 990 advances listed 30,488 ms +// from the table, 29,643 ms after them. Neither seed may start an attempt. +UnitTestResult test_starter_plan_seed_delay(Logger&){ + struct Case{ + uint16_t seed; + uint64_t table_ms; + }; + const Case cases[] = { + {.seed = 0x11a3, .table_ms = 30473}, + {.seed = 0x405c, .table_ms = 30488}, + }; + const SeedsDatabase database(seeds_json_path(true, Language::English)); + const std::vector seeds = initial_seed_entries(database, SoundSetting::Mono, "Help", true); + for (const Case& item : cases){ + auto entry = std::find_if(seeds.begin(), seeds.end(), [&](const InitialSeedEntry& seed){ return seed.seed == item.seed; }); + if (entry == seeds.end() || entry->seed_time_ms != item.table_ms){ + return std::format("Expected seed {:04X} at {} ms in the FireRed English list (Mono, Help).", item.seed, item.table_ms); + } + if (starter_rng_can_wait_for(*entry)){ + return std::format("Seed {:04X} ({} ms): expected too early for Starter RNG's title screen.", item.seed, item.table_ms); + } + } + + const uint16_t tid = 55740; + const std::vector attempts = plan_starter_rng(StarterRngPlanInputs{ + .firered = true, + .language = Language::English, + .sound = SoundSetting::Mono, + .tid = tid, + .candidates = sid_helper_candidates(tid, 3001, 5), + .filters = {}, + .max_attempts = 5, + }); + if (attempts.empty()){ + return "Expected attempts for TID 55740, got none."; + } + for (size_t c = 0; c < attempts.size(); c++){ + const InitialSeedEntry& seed = attempts[c].target.seed; + if (seed.seed == 0x11a3 || seed.seed == 0x405c || starter_rng_seed_wait_ms(seed) < 31500){ + return std::format("Attempt {}: seed {:04X} at {} ms is too early for the title screen.", c + 1, seed.seed, seed.seed_time_ms); + } + if (attempts[c].target.advances < 1660){ + return std::format("Attempt {}: {} advances leave no room for the in-game calibration.", c + 1, attempts[c].target.advances); + } + } + return true; +} + +// Starter RNG's in-game wait: 7,500 ms at its 940-advance minimum; console +// B's B579 target at 967 advances was 7,725 ms, which one miss's +// calibration (-720) cut under the minimum. Targets start 720 advances on. +UnitTestResult test_starter_ingame_wait(Logger&){ + struct Case{ + uint64_t advances; + int64_t ms; + }; + const Case cases[] = { + {.advances = 940, .ms = 7500}, + {.advances = 967, .ms = 7725}, + {.advances = 1660, .ms = 13500}, + }; + for (const Case& item : cases){ + if (starter_rng_ingame_ms(item.advances) != item.ms){ + return std::format("{} advances: expected {} ms in game, got {}.", item.advances, item.ms, starter_rng_ingame_ms(item.advances)); + } + } + if (STARTER_RNG_PLAN_MIN_ADVANCES != 1660){ + return std::format("Expected the plan's minimum at 1660 advances, got {}.", STARTER_RNG_PLAN_MIN_ADVANCES); + } + return true; +} + +UnitTestResult test_starter_plan(Logger&){ + const uint16_t tid = 43771; + StarterRngPlanInputs inputs{ + .firered = true, + .language = Language::English, + .sound = SoundSetting::Mono, + .tid = tid, + .candidates = sid_helper_candidates(tid, 3001, 5), + .filters = {}, + .max_attempts = 5, + }; + const std::vector attempts = plan_starter_rng(inputs); + if (attempts.empty()){ + return "Expected attempts for TID 43771 with five SID candidates, got none."; + } + + const SeedsDatabase database(seeds_json_path(true, Language::English)); + std::vector listed; + for (size_t c = 0; c < attempts.size(); c++){ + const RngAttempt& attempt = attempts[c]; + if (!database.find_seed(attempt.target.seed.seed, SoundSetting::Mono, 5).found){ + return std::format("Attempt {}: Starter RNG can't find Target Seed {:04X}.", c + 1, attempt.target.seed.seed); + } + if (attempt.target.advances < STARTER_RNG_PLAN_MIN_ADVANCES){ + return std::format("Attempt {}: Advances {} below the plan's {}.", c + 1, attempt.target.advances, STARTER_RNG_PLAN_MIN_ADVANCES); + } + if (attempt.sids.empty()){ + return std::format("Attempt {}: shiny for no SID candidate.", c + 1); + } + for (uint16_t sid : attempt.sids){ + if (shiny_type(attempt.target.pokemon.pid, tid, sid) == AdvShinyType::Normal){ + return std::format("Attempt {}: PID {:08X} not shiny for SID {}.", c + 1, attempt.target.pokemon.pid, sid); + } + if (std::find(listed.begin(), listed.end(), sid) != listed.end()){ + return std::format("Attempt {}: SID {} already listed by an earlier attempt.", c + 1, sid); + } + listed.push_back(sid); + } + } + if (rng_attempt_lines(attempts).size() != attempts.size()){ + return "Expected one line per attempt."; + } + return true; +} + +const RngPlanTestCase RNG_PLAN_CASES[] = { + { + .input = {.name = "SID Helper's candidates and weights", .body = test_sid_helper_candidates}, + .expectation = {.description = "evaluates SID Helper candidates and candidate weighting"}, + }, + { + .input = {.name = "attempt order", .body = test_plan_order}, + .expectation = {.description = "validates chronological ordering of plan attempts"}, + }, + { + .input = {.name = "Starter RNG plan from the FireRed list", .body = test_starter_plan}, + .expectation = {.description = "builds Starter RNG plan from FireRed seed list"}, + }, + { + .input = {.name = "Starter RNG plan: no seed too early for the title screen", .body = test_starter_plan_seed_delay}, + .expectation = {.description = "filters out seeds too early for title screen timing"}, + }, + { + .input = {.name = "Starter RNG plan: room for the in-game calibration", .body = test_starter_ingame_wait}, + .expectation = {.description = "allows sufficient margin for in-game calibration advances"}, + }, +}; + +} // namespace + + +void add_tests_RngPlan(UnitTestDatabase& database){ + for (const auto& scenario : RNG_PLAN_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h new file mode 100644 index 0000000000..66c39522e7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h @@ -0,0 +1,24 @@ +/* RNG Plan Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngPlan_Tests_H +#define PokemonAutomation_PokemonFRLG_RngPlan_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers RNG plan unit tests. +void add_tests_RngPlan(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp new file mode 100644 index 0000000000..a1014876d1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp @@ -0,0 +1,74 @@ +/* RNG Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon/Pokemon_Strings.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartySlot.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_RngProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +std::string not_enough_free_slots_message(size_t party_size, size_t free_slots_needed){ + if (free_slots_needed == 1){ + return std::format( + "Your party is full. Leave a party slot free so the program can check the {} it catches or receives.", + Pokemon::STRING_POKEMON + ); + } + return std::format( + "Your party has {} {}. Leave at least {} party slots free for the {} the program catches or receives.", + party_size, Pokemon::STRING_POKEMON, free_slots_needed, Pokemon::STRING_POKEMON + ); +} + +} // namespace + + +void RngProgramInstance::check_free_party_slots( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context +){ + const size_t free_slots_needed = free_party_slots_needed(); + if (free_slots_needed == 0){ + return; + } + Logger& logger = env.console.logger(); + logger.log("Checking for " + std::to_string(free_slots_needed) + " free party slot(s)..."); + try{ + open_party_menu_from_overworld(env.console, context); + }catch (OperationFailedException&){ + logger.log("Unable to open the party menu. Skipping the free party slot check.", COLOR_RED); + return; + } + context.wait_for_all_requests(); + constexpr size_t MAX_PARTY_SIZE = 6; + const size_t party_size = static_cast(detect_last_occupied_party_slot(env.console)) + 1; + if (MAX_PARTY_SIZE - party_size < free_slots_needed){ + throw UserSetupError(logger, not_enough_free_slots_message(party_size, free_slots_needed)); + } + logger.log("Party has enough free slots."); +} + +void RngProgramInstance::run_precheck( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context +){ + home_black_border_check(env.console, context); + check_free_party_slots(env, context); +} + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h new file mode 100644 index 0000000000..727ba9b099 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h @@ -0,0 +1,54 @@ +/* RNG Program + * + * From: https://github.com/PokemonAutomation/ + * + * Base class for the FRLG RNG programs. Each program states what the game + * must look like when it starts, and checks it first thing, so a setup + * mistake stops the run at once instead of failing in a misleading way many + * resets later. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngProgram_H +#define PokemonAutomation_PokemonFRLG_RngProgram_H + +#include +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Base class of the RNG programs. +class RngProgramInstance : public SingleSwitchProgramInstance{ +public: + using SingleSwitchProgramInstance::SingleSwitchProgramInstance; + + // How many free party slots the program needs: one for each Pokemon it + // catches or receives and then reads from the end of the party. In a full + // party that Pokemon would go to the PC instead. + virtual size_t free_party_slots_needed() const = 0; + +protected: + // Call first in program(), with the game on the overworld where the + // player saved: checks the party has the free slots + // free_party_slots_needed() asks for, then goes Home for the black + // border check. Throws UserSetupError if a check fails. + void run_precheck( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context + ); + +private: + void check_free_party_slots( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context + ); +}; + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp new file mode 100644 index 0000000000..ceb2bfa571 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp @@ -0,0 +1,327 @@ +/* RNG Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * SID Helper's intro timing per language, and Starter RNG's per-starter + * tables, as SID Helper and Starter RNG computed them before the steps + * moved out of the programs; and whether a shiny was the target. + * + */ + +#include +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "PokemonFRLG_SidSteps.h" +#include "PokemonFRLG_StarterRngAttempts.h" +#include "PokemonFRLG_RngSteps_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +struct SidTimingInput{ + Language language; + uint32_t target_advances; +}; + +struct SidTimingExpectation{ + uint64_t delay_ms; + bool extra_press_at_end; +}; + +struct SidTimingRow{ + SidTimingInput input; + SidTimingExpectation expectation; +}; + +// (target_advances - 2 * final text frames + 7) frames of 1000 / 59.999977 ms, +// halved since advances pass 2 by 2. +const std::vector SID_TIMING_ROWS = { + {.input = {.language = Language::English, .target_advances = 3001}, .expectation = {.delay_ms = 20916, .extra_press_at_end = false}}, + {.input = {.language = Language::English, .target_advances = 2275}, .expectation = {.delay_ms = 14866, .extra_press_at_end = false}}, + {.input = {.language = Language::Japanese, .target_advances = 3001}, .expectation = {.delay_ms = 21833, .extra_press_at_end = true}}, + {.input = {.language = Language::Italian, .target_advances = 3001}, .expectation = {.delay_ms = 21133, .extra_press_at_end = false}}, + {.input = {.language = Language::French, .target_advances = 3001}, .expectation = {.delay_ms = 21650, .extra_press_at_end = true}}, + {.input = {.language = Language::German, .target_advances = 3001}, .expectation = {.delay_ms = 21600, .extra_press_at_end = true}}, + {.input = {.language = Language::Spanish, .target_advances = 2275}, .expectation = {.delay_ms = 15650, .extra_press_at_end = true}}, +}; + +class Test_SidTiming : public UnitTest{ +public: + explicit Test_SidTiming(const SidTimingRow& row) + : UnitTest(std::format( + "PokemonFRLG::RngSteps - SID timing {} {}", + language_data(row.input.language).name, row.input.target_advances + )) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + SidTiming timing = sid_timing(m_row.input.language, m_row.input.target_advances); + if (timing.delay_ms != m_row.expectation.delay_ms || timing.extra_press_at_end != m_row.expectation.extra_press_at_end){ + return std::format( + "Expected delay {} ms, extra press {}; got {} ms, extra press {}", + m_row.expectation.delay_ms, m_row.expectation.extra_press_at_end, + timing.delay_ms, timing.extra_press_at_end + ); + } + return true; + } + +private: + SidTimingRow m_row; +}; + + +struct StarterInput{ + StarterSpecies starter; + std::string name; +}; + +struct StarterExpectation{ + BaseStats base_stats; + EVs rival_ev_yield; + int steps_left; +}; + +struct StarterRow{ + StarterInput input; + StarterExpectation expectation; +}; + +const std::vector STARTER_ROWS = { + { + .input = {.starter = StarterSpecies::bulbasaur, .name = "Bulbasaur"}, + .expectation = { + .base_stats = {45, 49, 49, 65, 65, 45}, + .rival_ev_yield = {0, 0, 0, 0, 0, 1}, + .steps_left = 2, + }, + }, + { + .input = {.starter = StarterSpecies::squirtle, .name = "Squirtle"}, + .expectation = { + .base_stats = {44, 48, 65, 50, 64, 43}, + .rival_ev_yield = {0, 0, 0, 1, 0, 0}, + .steps_left = 3, + }, + }, + { + .input = {.starter = StarterSpecies::charmander, .name = "Charmander"}, + .expectation = { + .base_stats = {39, 52, 43, 60, 50, 65}, + .rival_ev_yield = {0, 0, 1, 0, 0, 0}, + .steps_left = 4, + }, + }, +}; + +std::string to_string(const BaseStats& stats){ + return std::format("{}/{}/{}/{}/{}/{}", stats.hp, stats.attack, stats.defense, stats.spatk, stats.spdef, stats.speed); +} +std::string to_string(const EVs& evs){ + return std::format("{}/{}/{}/{}/{}/{}", evs.hp, evs.attack, evs.defense, evs.spatk, evs.spdef, evs.speed); +} + +class Test_StarterTables : public UnitTest{ +public: + explicit Test_StarterTables(const StarterRow& row) + : UnitTest("PokemonFRLG::RngSteps - Starter tables " + row.input.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::string expected = std::format( + "base stats {}, rival EVs {}, steps left {}", + to_string(m_row.expectation.base_stats), to_string(m_row.expectation.rival_ev_yield), m_row.expectation.steps_left + ); + std::string got = std::format( + "base stats {}, rival EVs {}, steps left {}", + to_string(starter_base_stats(m_row.input.starter)), + to_string(rival_ev_yield(m_row.input.starter)), + steps_left_to_lab_door(m_row.input.starter) + ); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + return true; + } + +private: + StarterRow m_row; +}; + + + +// A state's (seed, advance). +using SeedAdvance = std::pair; + +// Target: seed 0x70FE, advance 1000. +struct ShinyInput{ + std::string name; + std::vector hits; +}; + +struct ShinyExpectation{ + StarterRngOutcome expected; +}; + +struct ShinyRow{ + ShinyInput input; + ShinyExpectation expectation; +}; + +const std::vector SHINY_ROWS = { + {.input = {.name = "the target alone", .hits = {{0x70fe, 1000}}}, .expectation = {.expected = StarterRngOutcome::shiny_on_target}}, + {.input = {.name = "the target among others", .hits = {{0x70fe, 998}, {0x70fe, 1000}, {0x70ff, 1000}}}, .expectation = {.expected = StarterRngOutcome::shiny_on_target}}, + {.input = {.name = "another advance", .hits = {{0x70fe, 1002}}}, .expectation = {.expected = StarterRngOutcome::shiny_off_target}}, + {.input = {.name = "another seed", .hits = {{0x70fd, 1000}}}, .expectation = {.expected = StarterRngOutcome::shiny_off_target}}, + {.input = {.name = "no match", .hits = {}}, .expectation = {.expected = StarterRngOutcome::shiny}}, +}; + +std::string outcome_name(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: return "shiny"; + case StarterRngOutcome::shiny_on_target: return "shiny_on_target"; + case StarterRngOutcome::shiny_off_target: return "shiny_off_target"; + case StarterRngOutcome::target_hit: return "target_hit"; + case StarterRngOutcome::wild_shiny: return "wild_shiny"; + case StarterRngOutcome::out_of_resets: return "out_of_resets"; + case StarterRngOutcome::no_matches: return "no_matches"; + } + return "?"; +} + +class Test_IdentifyShiny : public UnitTest{ +public: + explicit Test_IdentifyShiny(const ShinyRow& row) + : UnitTest("PokemonFRLG::RngSteps - Shiny " + row.input.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::vector hits; + for (const auto& [seed, advance] : m_row.input.hits){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + hits.push_back(hit); + } + const StarterRngOutcome got = identify_shiny(0x70fe, 1000, hits); + if (got != m_row.expectation.expected){ + return std::string("Expected ") + outcome_name(m_row.expectation.expected) + ", got " + outcome_name(got); + } + return true; + } + +private: + ShinyRow m_row; +}; + + +AdvRngState state(uint16_t seed, uint64_t advance){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + return hit; +} + + +std::string state_text(const std::optional& state){ + return state ? std::format("{:04x}/{}", state->first, state->second) : "none"; +} + +struct ResetHitInput{ + std::string name; + // The reset's hits, and what update_history() left after it. + std::vector hits; + size_t uncertain = 0; + std::vector calibrated; +}; + +struct ResetHitExpectation{ + // The (seed, advance) taken as hit, if any. + std::optional expected; +}; + +struct ResetHitRow{ + ResetHitInput input; + ResetHitExpectation expectation; +}; + +const std::vector RESET_HIT_ROWS = { + { + .input = {.name = "one hit", .hits = {state(0x70fe, 1001)}, .uncertain = 0, .calibrated = {state(0x70fe, 1001)}}, + .expectation = {.expected = SeedAdvance{0x70fe, 1001}}, + }, + { + .input = {.name = "settled by the history", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 0, .calibrated = {state(0x70fd, 1004), state(0x70ff, 1003)}}, + .expectation = {.expected = SeedAdvance{0x70ff, 1003}}, + }, + { + .input = {.name = "a tie", .hits = {state(0x70fe, 998), state(0x70ff, 1003)}, .uncertain = 2, .calibrated = {state(0x70fd, 1004)}}, + .expectation = {.expected = std::nullopt}, + }, + { + .input = {.name = "no hits", .hits = {}, .uncertain = 0, .calibrated = {state(0x70fd, 1004)}}, + .expectation = {.expected = std::nullopt}, + }, +}; + +class Test_ResetHit : public UnitTest{ +public: + explicit Test_ResetHit(const ResetHitRow& row) + : UnitTest("PokemonFRLG::RngSteps - Reset hit " + row.input.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + RngUncertainHistory uncertain; + uncertain.results.resize(m_row.input.uncertain); + RngCalibrationHistory calibration; + calibration.results = m_row.input.calibrated; + const std::optional hit = reset_hit(uncertain, calibration, m_row.input.hits); + std::optional got; + if (hit){ + got = SeedAdvance{hit->seed, hit->advance}; + } + if (got != m_row.expectation.expected){ + return "Expected " + state_text(m_row.expectation.expected) + ", got " + state_text(got); + } + return true; + } + +private: + ResetHitRow m_row; +}; + +} // namespace + + +void add_tests_RngSteps(UnitTestDatabase& database){ + for (const SidTimingRow& row : SID_TIMING_ROWS){ + database.add(row); + } + for (const StarterRow& row : STARTER_ROWS){ + database.add(row); + } + for (const ShinyRow& row : SHINY_ROWS){ + database.add(row); + } + for (const ResetHitRow& row : RESET_HIT_ROWS){ + database.add(row); + } +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h new file mode 100644 index 0000000000..4d771cd519 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h @@ -0,0 +1,24 @@ +/* RNG Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngSteps_Tests_H +#define PokemonAutomation_PokemonFRLG_RngSteps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The pure parts of the SID steps and Starter RNG attempts. +void add_tests_RngSteps(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp new file mode 100644 index 0000000000..81556f0146 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp @@ -0,0 +1,417 @@ +/* RNG Target Search + * + * From: https://github.com/PokemonAutomation/ + * + * Ten Lines finds targets in two steps, and this does the same in one: + * 1. Searcher (src/wasm/src/searcher.cpp, search_seeds_static()): PokeFinder's + * StaticSearcher3 lists every RNG state whose Method 1 Pokemon passes the filters. + * 2. Initial Seed (src/wasm/src/initial_seed.cpp, frlg_seeds()): for a target state, + * the initial seeds from the seed table, ordered by the advances from the seed to + * the target. That is the LCRNG distance, since the game starts the RNG at the seed. + * + * The code here is written from that description, not copied from either project. + * + */ + +#include +#include +#include "PokemonFRLG_RngTargetSearch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +const uint32_t LCRNG_MULT = 0x41c64e6d; +const uint32_t LCRNG_ADD = 0x6073; +const uint32_t LCRNG_MULT_INVERSE = 0xeeb9eb65; +const uint32_t LCRNG_ADD_INVERSE = 0x0a3561a1; + +// The GBA frame rate, as Ten Lines uses it (SYSTEM_TIMING_DATA in src/tenLines/index.ts). +const double GBA_FRAMES_PER_SECOND = 16777216.0 / 280896.0; + +} // namespace + + +uint32_t lcrng_next(uint32_t state){ + return state * LCRNG_MULT + LCRNG_ADD; +} +uint32_t lcrng_previous(uint32_t state){ + return state * LCRNG_MULT_INVERSE + LCRNG_ADD_INVERSE; +} + +// Bit by bit: once the low k bits of "from" and "to" agree, only a jump of 2^k steps +// keeps them agreeing, and it flips bit k. So bit k of the distance is whether bit k +// still differs. +uint32_t lcrng_distance(uint32_t from, uint32_t to){ + uint32_t mult = LCRNG_MULT; + uint32_t add = LCRNG_ADD; + uint32_t distance = 0; + for (uint32_t bit = 1; from != to; bit <<= 1){ + if ((from ^ to) & bit){ + from = from * mult + add; + distance |= bit; + } + add *= mult + 1; + mult *= mult; + } + return distance; +} + + +AdvPokemonResult method1_pokemon(uint32_t state){ + uint32_t pid_low = lcrng_next(state); + uint32_t pid_high = lcrng_next(pid_low); + uint32_t iv_first = lcrng_next(pid_high); + uint32_t iv_second = lcrng_next(iv_first); + + uint32_t pid = (pid_high & 0xffff0000) | (pid_low >> 16); + iv_first >>= 16; + iv_second >>= 16; + + AdvIVs ivs; + ivs.hp = iv_first & 0x1f; + ivs.attack = (iv_first >> 5) & 0x1f; + ivs.defense = (iv_first >> 10) & 0x1f; + ivs.speed = iv_second & 0x1f; + ivs.spatk = (iv_second >> 5) & 0x1f; + ivs.spdef = (iv_second >> 10) & 0x1f; + + return {pid, uint8_t(pid & 0xff), AdvNature(pid % 25), AdvAbility(pid & 1), ivs}; +} + +AdvShinyType shiny_type(uint32_t pid, uint16_t tid, uint16_t sid){ + uint16_t value = uint16_t(pid >> 16) ^ uint16_t(pid) ^ tid ^ sid; + if (value == 0){ + return AdvShinyType::Square; + } + return value < 8 ? AdvShinyType::Star : AdvShinyType::Normal; +} + +HiddenPower hidden_power(const AdvIVs& ivs){ + static constexpr std::string_view TYPES[] = { + "Fighting", "Flying", "Poison", "Ground", "Rock", "Bug", "Ghost", "Steel", + "Fire", "Water", "Grass", "Electric", "Psychic", "Ice", "Dragon", "Dark", + }; + // Bit 0 of each IV picks the type, bit 1 the power, in the order HP, Atk, Def, Spe, + // SpA, SpD. + const uint8_t order[] = {ivs.hp, ivs.attack, ivs.defense, ivs.speed, ivs.spatk, ivs.spdef}; + int type_bits = 0; + int power_bits = 0; + for (int c = 0; c < 6; c++){ + type_bits |= (order[c] & 1) << c; + power_bits |= ((order[c] >> 1) & 1) << c; + } + return {std::string(TYPES[type_bits * 15 / 63]), uint8_t(power_bits * 40 / 63 + 30)}; +} + + +std::vector initial_seed_entries( + const SeedsDatabase& database, + SoundSetting sound, + const std::string& button_mode, + bool allow_blackout +){ + // Like SeedsDatabase::find_seed(), the first entry found wins a tie. + std::map earliest; + auto add = [&](const InitialSeedEntry& entry){ + auto iter = earliest.find(entry.seed); + if (iter == earliest.end() || entry.seed_time_ms < iter->second.seed_time_ms){ + earliest[entry.seed] = entry; + } + }; + + const std::vector& delays = database.delays(); + for (const SeedsDatabase::SeedColumn& column : database.columns()){ + if (column.sound != sound || column.button_mode != button_mode){ + continue; + } + for (size_t c = 0; c < column.seeds.size() && c < delays.size(); c++){ + uint16_t seed = column.seeds[c]; + add({seed, delays[c], column.seed_button, BlackoutButton::None}); + if (allow_blackout){ + add({uint16_t(seed - BLACKOUT_SEED_OFFSET), delays[c], column.seed_button, BlackoutButton::L}); + } + } + } + + std::vector entries; + entries.reserve(earliest.size()); + for (const auto& item : earliest){ + entries.emplace_back(item.second); + } + return entries; +} + + +namespace{ + +// Every 16-bit x times the LCRNG multiplier, sorted. A state with known top 16 bits +// "high" is (high << 16) + x, and its next state is lcrng_next(high << 16) + x * mult, +// so the states whose next state is in a range are a range of this table. +class LowBitsTable{ +public: + LowBitsTable(){ + m_products.reserve(0x10000); + for (uint32_t x = 0; x < 0x10000; x++){ + m_products.emplace_back(x * LCRNG_MULT, uint16_t(x)); + } + std::sort(m_products.begin(), m_products.end()); + } + + // Calls "found" with each state whose top 16 bits are "high" and whose next state + // is in [low, low + width). + template + void find_states(uint16_t high, uint32_t low, uint32_t width, Callback&& found) const{ + uint32_t top = uint32_t(high) << 16; + uint32_t start = low - lcrng_next(top); + uint64_t end = uint64_t(start) + width; + const uint64_t WRAP = uint64_t(1) << 32; + visit(top, start, std::min(end, WRAP), found); + if (end > WRAP){ + visit(top, 0, end - WRAP, found); + } + } + +private: + template + void visit(uint32_t top, uint64_t start, uint64_t end, Callback& found) const{ + auto iter = std::lower_bound( + m_products.begin(), m_products.end(), start, + [](const std::pair& item, uint64_t value){ return item.first < value; } + ); + for (; iter != m_products.end() && iter->first < end; ++iter){ + found(top | iter->second); + } + } + + std::vector> m_products; +}; + + +// Keeps the states whose Pokemon pass the filters, each with its nearest initial seed. +class TargetCollector{ +public: + TargetCollector( + const std::vector& seeds, + uint16_t tid, + const std::vector& candidates, + const RngTargetFilters& filters + ) + : m_tid(tid) + , m_candidates(candidates) + , m_filters(filters) + { + for (const InitialSeedEntry& entry : seeds){ + if (seed_time_allowed(entry.seed_time_ms)){ + m_seeds.push_back({lcrng_distance(0, entry.seed), entry}); + } + } + std::sort(m_seeds.begin(), m_seeds.end(), [](const SeedPosition& x, const SeedPosition& y){ + return x.distance < y.distance; + }); + for (const SidCandidate& candidate : candidates){ + m_total_weight += candidate.weight; + } + } + + void consider(uint32_t state){ + AdvPokemonResult pokemon = method1_pokemon(state); + if (!passes(pokemon)){ + return; + } + RngTarget target{state, {}, 0, pokemon, {}, 0}; + double weight = 0; + for (size_t c = 0; c < m_candidates.size(); c++){ + AdvShinyType type = shiny_type(pokemon.pid, m_tid, m_candidates[c].sid); + if (type != AdvShinyType::Normal){ + target.shiny_for.push_back({c, type}); + weight += m_candidates[c].weight; + } + } + if (m_filters.shiny_required && target.shiny_for.empty()){ + return; + } + if (!nearest_seed(state, target)){ + return; + } + target.shiny_probability = m_total_weight > 0 ? weight / m_total_weight : 0; + m_targets.emplace_back(std::move(target)); + } + + std::vector results(){ + std::sort(m_targets.begin(), m_targets.end(), [](const RngTarget& x, const RngTarget& y){ + return x.advances != y.advances ? x.advances < y.advances : x.state < y.state; + }); + return std::move(m_targets); + } + +private: + struct SeedPosition{ + uint32_t distance; + InitialSeedEntry entry; + }; + + bool seed_time_allowed(uint64_t time) const{ + if (time < m_filters.min_seed_time_ms){ + return false; + } + uint64_t gap = time > m_filters.avoided_seed_time_ms + ? time - m_filters.avoided_seed_time_ms + : m_filters.avoided_seed_time_ms - time; + return m_filters.avoided_seed_time_radius_ms == 0 || gap > m_filters.avoided_seed_time_radius_ms; + } + + bool passes(const AdvPokemonResult& pokemon) const{ + const std::vector& natures = m_filters.natures; + if (!natures.empty() && std::find(natures.begin(), natures.end(), pokemon.nature) == natures.end()){ + return false; + } + if (m_filters.ability != AdvAbility::Any && pokemon.ability != m_filters.ability){ + return false; + } + if (m_filters.gender != AdvGender::Any + && gender_from_gender_value(pokemon.gender, m_filters.gender_threshold) != m_filters.gender + ){ + return false; + } + const AdvIVs& ivs = pokemon.ivs; + const AdvIVs& min = m_filters.min_ivs; + return ivs.hp >= min.hp && ivs.attack >= min.attack && ivs.defense >= min.defense + && ivs.spatk >= min.spatk && ivs.spdef >= min.spdef && ivs.speed >= min.speed; + } + + // The seed with the fewest advances to "state" that are still at least the minimum: + // the one with the largest distance from 0 that is at most "state"'s, less the + // minimum, wrapping around the cycle. + bool nearest_seed(uint32_t state, RngTarget& target) const{ + if (m_seeds.empty()){ + return false; + } + uint32_t distance = lcrng_distance(0, state); + uint32_t latest = distance - uint32_t(m_filters.min_advances); + auto iter = std::upper_bound( + m_seeds.begin(), m_seeds.end(), latest, + [](uint32_t value, const SeedPosition& seed){ return value < seed.distance; } + ); + const SeedPosition& seed = iter == m_seeds.begin() ? m_seeds.back() : *(iter - 1); + uint64_t advances = uint32_t(distance - seed.distance); + if (advances < m_filters.min_advances || advances > m_filters.max_advances){ + return false; + } + target.seed = seed.entry; + target.advances = advances; + return true; + } + + const uint16_t m_tid; + const std::vector& m_candidates; + const RngTargetFilters& m_filters; + double m_total_weight = 0; + std::vector m_seeds; + std::vector m_targets; +}; + + +// Shiny Pokemon only: for each low PID half, the high halves that are shiny for a +// candidate are 8 aligned values, so each takes one lookup. +void search_shiny_states( + const LowBitsTable& table, + uint16_t tid, + const std::vector& candidates, + TargetCollector& collector +){ + std::vector shiny_values; + for (const SidCandidate& candidate : candidates){ + shiny_values.push_back((tid ^ candidate.sid) & 0xfff8); + } + std::sort(shiny_values.begin(), shiny_values.end()); + shiny_values.erase(std::unique(shiny_values.begin(), shiny_values.end()), shiny_values.end()); + + auto found = [&](uint32_t pid_low_state){ + collector.consider(lcrng_previous(pid_low_state)); + }; + for (uint32_t pid_low = 0; pid_low < 0x10000; pid_low++){ + for (uint16_t value : shiny_values){ + uint32_t pid_high = (pid_low & 0xfff8) ^ value; + table.find_states(uint16_t(pid_low), pid_high << 16, 8 << 16, found); + } + } +} + +// Any Pokemon, like PokeFinder's StaticSearcher3: every IV combination at or above the +// minimums gives the top 15 bits of the two IV calls. +void search_iv_states(const LowBitsTable& table, const AdvIVs& min_ivs, TargetCollector& collector){ + auto found = [&](uint32_t iv_first_state){ + collector.consider(lcrng_previous(lcrng_previous(lcrng_previous(iv_first_state)))); + }; + // HP, Atk, Def, Spe, SpA, SpD: the order the IVs sit in the two calls. + const uint8_t mins[6] = {min_ivs.hp, min_ivs.attack, min_ivs.defense, min_ivs.speed, min_ivs.spatk, min_ivs.spdef}; + uint8_t ivs[6]; + std::copy(mins, mins + 6, ivs); + while (true){ + uint16_t first = uint16_t(ivs[0] | (ivs[1] << 5) | (ivs[2] << 10)); + uint16_t second = uint16_t(ivs[3] | (ivs[4] << 5) | (ivs[5] << 10)); + for (uint16_t first_top : {uint16_t(0x0000), uint16_t(0x8000)}){ + for (uint32_t second_top : {0x0000, 0x8000}){ + table.find_states(first | first_top, (second | second_top) << 16, 0x10000, found); + } + } + int c = 0; + while (c < 6 && ivs[c] == 31){ + ivs[c] = mins[c]; + c++; + } + if (c == 6){ + return; + } + ivs[c]++; + } +} + +} // namespace + + +std::vector search_rng_targets( + const std::vector& seeds, + uint16_t tid, + const std::vector& candidates, + const RngTargetFilters& filters +){ + TargetCollector collector(seeds, tid, candidates, filters); + LowBitsTable table; + if (filters.shiny_required){ + search_shiny_states(table, tid, candidates, collector); + }else{ + search_iv_states(table, filters.min_ivs, collector); + } + return collector.results(); +} + + +void rank_rng_targets(std::vector& targets){ + auto time_ms = [](const RngTarget& target){ + return double(target.seed.seed_time_ms) + double(target.advances) * 1000.0 / GBA_FRAMES_PER_SECOND; + }; + std::stable_sort(targets.begin(), targets.end(), [&](const RngTarget& x, const RngTarget& y){ + bool x_shiny = x.shiny_probability > 0; + bool y_shiny = y.shiny_probability > 0; + if (x_shiny != y_shiny){ + return x_shiny; + } + if (!x_shiny){ + return time_ms(x) < time_ms(y); + } + return time_ms(x) / x.shiny_probability < time_ms(y) / y.shiny_probability; + }); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h new file mode 100644 index 0000000000..521a881cda --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h @@ -0,0 +1,134 @@ +/* RNG Target Search + * + * From: https://github.com/PokemonAutomation/ + * + * Finds static, gift and starter RNG targets (a Target Seed plus Advances, as + * Static/Gift/Starter RNG take them) for a trainer, the way the "Searcher" and + * "Initial Seed" tabs of Ten Lines do for FRLG on Switch: + * https://lincoln-lm.github.io/ten-lines + * https://github.com/Lincoln-LM/ten-lines + * + * How a program can use it to pick its own target when the SID is not known: + * 1. SID Helper reads the TID and narrows the SID down to a few weighted candidates. + * 2. search_rng_targets() with those candidates, then rank_rng_targets(). + * 3. Run Static/Gift/Starter RNG with the top target's seed and advances. + * 4. Read the result: + * - Shiny: the SID is one of the candidates the target is shiny for. If that is + * one candidate, the SID is confirmed. + * - Nature and IVs match, but not shiny: the target was hit, so every candidate it + * is shiny for is wrong. Drop them and search again. + * - Nature or IVs differ: the target was missed. Retry it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngTargetSearch_H +#define PokemonAutomation_PokemonFRLG_RngTargetSearch_H + +#include +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" +#include "PokemonFRLG_BlindNavigation.h" +#include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_RngMethod1.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// One way to reach an initial seed from the title screen. +struct InitialSeedEntry{ + // The seed reached, after the blackout offset. + uint16_t seed; + uint64_t seed_time_ms; + SeedButton seed_button; + BlackoutButton blackout_button; +}; + +// The initial seeds reachable with one sound setting and button mode, each by its +// earliest entry in the seed table. That is the entry Static/Gift/Starter RNG use for +// a Target Seed (SeedsDatabase::find_seed()). +// +// Holding a blackout button lowers the seed by BLACKOUT_SEED_OFFSET. Ten Lines lists +// that only for the English Switch tables in Help mode (HELD_BUTTON_OFFSETS["lg_nx"] +// and ["fr_nx"] in src/wasm/src/initial_seed.hpp), so pass "allow_blackout" only then. +std::vector initial_seed_entries( + const SeedsDatabase& database, + SoundSetting sound, + const std::string& button_mode, + bool allow_blackout +); + + +// Candidate SID with associated relative weight. +struct SidCandidate{ + uint16_t sid; + // Relative likelihood. The weights need not add up to 1. + double weight; +}; + +// Criteria for filtering acceptable RNG targets. +struct RngTargetFilters{ + // Empty: any nature. + std::vector natures; + Pokemon::AdvIVs min_ivs; + Pokemon::AdvGender gender = Pokemon::AdvGender::Any; + int16_t gender_threshold = 126; + Pokemon::AdvAbility ability = Pokemon::AdvAbility::Any; + // Shiny for at least one SID candidate. + bool shiny_required = true; + + // Total advances from the initial seed: the "Advances" of Ten Lines and of the RNG + // programs. They include the title and continue screens, so fewer of them are + // spent in game. + uint64_t min_advances = 0; + uint64_t max_advances = 1000000; + + uint64_t min_seed_time_ms = 0; + // Skip seed times within "avoided_seed_time_radius_ms" of this. + uint64_t avoided_seed_time_ms = 0; + uint64_t avoided_seed_time_radius_ms = 0; +}; + +// A candidate target evaluated for shininess against an SID candidate. +struct ShinyCandidate{ + // Index into the SID candidates. + size_t candidate; + Pokemon::AdvShinyType type; +}; + +// A target RNG state and its rolled attributes. +struct RngTarget{ + // The RNG state before the PID is rolled: the "Target" column of Ten Lines. + uint32_t state; + InitialSeedEntry seed; + uint64_t advances; + Pokemon::AdvPokemonResult pokemon; + // The candidates this target is shiny for. + std::vector shiny_for; + // Their share of the total candidate weight. + double shiny_probability; +}; + +// Every Method 1 result that passes "filters", each with the initial seed that reaches +// it in the fewest advances, sorted by advances. +std::vector search_rng_targets( + const std::vector& seeds, + uint16_t tid, + const std::vector& candidates, + const RngTargetFilters& filters +); + +// Sorts targets by expected wait per shiny: the time to the target (seed time plus +// advances at the GBA frame rate) divided by shiny_probability. A target shiny for +// every candidate beats one shiny for half of them unless it takes twice as long. +// Targets with no shiny candidate go last, by time. +void rank_rng_targets(std::vector& targets); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp new file mode 100644 index 0000000000..05fb861fb0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp @@ -0,0 +1,478 @@ +/* RNG Target Search Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The expected targets were found with Ten Lines (https://lincoln-lm.github.io/ten-lines) + * for LeafGreen (English) on Switch, TID 43771, SID 64694, Mono sound, Help button mode, + * Static 1: the lowest advances per target with total advances of at least 3,000 and + * seed times more than 3 seconds from 30,500 ms. + * + */ + +#include +#include +#include "CommonFramework/Language.h" +#include "PokemonFRLG_RngTargetSearch.h" +#include "PokemonFRLG_RngTargetSearch_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +const uint16_t TID = 43771; +const uint16_t SID = 64694; + +// One Ten Lines result: Target, PID, Shiny, Ability, IVs (HP/Atk/Def/SpA/SpD/Spe), +// Hidden Power, Initial Seed, Advances, Seed Time (ms), Buttons. +struct TenLinesRow{ + uint32_t state; + uint32_t pid; + std::string shiny; + int ability; + std::string ivs; + std::string hidden_power; + uint16_t seed; + uint64_t advances; + uint64_t seed_time_ms; + std::string buttons; +}; + +struct TenLinesGroup{ + std::string name; + std::vector natures; + AdvIVs min_ivs; + std::string rows; +}; + +// Ten Lines results, one per line, sorted by advances. +const std::string MODEST_ROWS = + "9435B76A,68F03EBD,Square,1,31/14/7/29/1/27,Dragon 39,2EF6,29364,52641,A/None\n" + "2E37261A,DB7C8D33,Star,1,28/16/6/30/11/29,Water 63,6E9A,50048,54054,A/Blackout R\n" + "C408B1DF,192D4F60,Square,0,25/8/10/29/0/28,Rock 32,02A8,53397,55259,Start/Blackout R\n" + "814DD9D3,84FBD2B6,Square,0,26/19/17/30/10/30,Flying 67,8EB6,58835,48990,Start/Blackout R\n" + "0D815228,8C45DA08,Square,0,29/5/29/31/22/25,Steel 60,A356,59258,64959,Start/Blackout R\n" + "016CB6DF,9C35CA7C,Star,0,29/11/29/30/20/27,Ground 46,A626,69439,48471,A/None\n" + "5DFAB16B,9FC1C98E,Star,0,26/1/0/30/27/28,Fire 61,2B48,77713,41805,A/None\n" + "0E710A6F,8E60D829,Star,1,26/1/9/31/10/25,Steel 61,47CD,89010,50903,A/None\n" + "74224D48,A59DF3D7,Star,1,26/28/22/31/10/30,Ground 68,2CE5,95029,51237,Start/Blackout R\n" + "18699F2D,4B0B1D46,Square,0,28/23/23/29/17/25,Dragon 33,A4C2,101793,47657,Start/Blackout R\n" + "19D01211,FB76AD3F,Star,1,31/16/12/30/22/30,Fighting 66,7DC6,103697,68622,A/Blackout R\n" + "BCDA4E7A,CF729938,Star,0,30/31/30/31/18/26,Rock 70,99D2,107880,36842,Start/None\n" + "1A5A9954,E80BBE43,Star,1,29/24/22/29/4/29,Bug 32,C1C1,107989,35490,A/None\n" + "5A6B83CC,ABF8FDB7,Star,1,27/30/3/31/17/30,Psychic 49,811D,119809,35822,A/Blackout R\n" + "50F06E45,D01B8656,Square,0,26/8/29/31/4/26,Rock 45,4C09,125356,67439,A/None\n" + "9F536DFD,C6FA90B7,Square,1,28/13/28/29/28/25,Ghost 30,1548,129923,66441,Start/None\n" + "2F82C0CA,21ED77A6,Star,0,25/16/4/29/1/31,Ice 35,4FDC,150758,39071,Start/None\n" + "4C7401EB,5AF00CBC,Star,0,30/12/0/30/21/26,Steel 45,45DC,155101,55440,Start/None\n" + "BE31CFCC,FA05AC4E,Star,0,30/22/21/30/3/29,Grass 62,D17C,158288,38405,Start/Blackout R\n" + "3F487560,7B922DDD,Star,1,30/21/5/31/21/27,Dragon 45,FF1C,171172,58240,A/None\n"; + +const std::string ADAMANT_ROWS = + "537A2752,A823FE6A,Star,0,25/29/15/17/31/27,Dark 57,B897,4437,35972,A/Blackout R\n" + "D9FDB041,B9B4EFFE,Star,0,27/31/19/11/5/31,Dark 49,D356,22897,60771,A/None\n" + "E9F88FDD,EAD6BC98,Star,0,30/29/1/29/23/31,Dragon 56,CE81,26060,33587,Start/None\n" + "C3B70E12,D96E8F26,Star,0,29/31/31/9/4/31,Steel 38,8AA1,30571,57386,Start/None\n" + "37BB3B92,BD83EBCB,Star,1,27/30/19/8/26/25,Ground 54,F054,33142,46390,Start/None\n" + "E8D67E1F,BEF4E8BB,Star,1,26/30/2/25/21/26,Electric 39,A9D1,39694,61024,A/Blackout R\n" + "DE925A82,083B5E70,Star,0,28/30/22/26/3/27,Water 69,4665,42695,49155,Start/Blackout R\n" + "D8713EE8,6E9838D2,Star,0,29/31/14/6/26/27,Poison 69,1233,48679,63991,Start/None\n" + "B50AB28B,EC3FBA76,Star,0,30/31/22/25/27/27,Ice 59,704A,61591,65705,A/None\n" + "0A550D9C,25487304,Star,0,30/29/14/5/27/31,Ice 58,B845,68937,53954,A/None\n" + "119C3777,633C3574,Star,0,26/29/4/26/18/30,Fighting 66,A39D,85194,58722,Start/Blackout R\n" + "315D5C57,AF63F92D,Star,1,30/29/23/13/21/29,Dragon 33,DE4C,95017,36725,A/None\n" + "66A23785,8397D5DA,Square,0,25/30/7/24/27/31,Grass 59,9DAC,95463,59324,A/None\n" + "A31E8DB4,462C1067,Star,1,31/31/17/9/22/28,Bug 52,0D4C,99560,36085,A/None\n" + "6109BF46,A9DAFF92,Star,0,26/31/30/6/2/30,Fighting 70,3136,103312,63359,A/None\n" + "3F5603C4,8C11DA5D,Star,1,25/29/6/6/24/29,Poison 42,D22E,111518,54657,Start/None\n"; + +const std::string NEUTRAL_ROWS = + "130195A8,AD7BFB36,Square,0,31/27/31/31/27/26,Ice 70,4381,17225,61908,Start/None\n" + "BE0D7E8F,6FA739E8,Star,0,31/21/25/29/26/25,Steel 50,C845,21690,41371,Start/None\n" + "1798BCE3,066A5027,Square,1,28/23/25/30/31/28,Water 61,3DDC,26549,44721,A/None\n" + "0602C959,EA14BC5F,Star,1,27/21/27/30/27/25,Electric 63,DA81,31480,46973,Start/None\n" + "5B31FD89,A635F07F,Star,1,31/22/19/31/22/31,Ghost 70,B8BB,48990,35972,A/None\n" + "0BA51887,D464822E,Star,0,25/16/17/31/28/28,Bug 40,3C95,59906,38258,A/Blackout R\n" + "61407261,751D2350,Square,0,30/18/16/31/30/28,Ground 62,B83C,61923,51625,Start/Blackout R\n" + "BBB6D222,9F67C92A,Square,0,30/28/25/30/24/31,Poison 45,1439,76611,62542,A/Blackout R\n" + "2C224D48,1D9D4BD7,Star,1,26/28/28/31/24/30,Ground 45,0210,83512,56705,Start/None\n" + "AC47BD6D,33D86591,Star,1,31/19/19/31/31/27,Dark 70,F483,101418,57476,A/Blackout R\n" + "0937DE0D,AB36FD7F,Star,1,27/18/18/30/19/29,Water 64,E588,103955,53106,A/None\n" + "30339DE2,E8A8BEE1,Star,1,27/17/25/29/19/29,Dark 50,47A0,126746,69310,A/Blackout R\n" + "E78F978E,C86B9E25,Star,1,25/20/31/29/23/29,Dragon 52,5A24,136290,33839,A/None\n" + "4A07D3EB,2CE57AA9,Star,1,25/26/24/30/27/25,Water 61,9754,145893,38338,Start/None\n"; + +std::vector groups(){ + AdvIVs modest; + modest.hp = 25; + modest.spatk = 29; + modest.speed = 25; + AdvIVs adamant; + adamant.hp = 25; + adamant.attack = 29; + adamant.speed = 25; + AdvIVs neutral = modest; + neutral.attack = neutral.defense = neutral.spdef = 16; + + using enum AdvNature; + return { + {"Modest", {Modest}, modest, MODEST_ROWS}, + {"Adamant", {Adamant}, adamant, ADAMANT_ROWS}, + {"Neutral", {Hardy, Docile, Serious, Bashful, Quirky}, neutral, NEUTRAL_ROWS}, + }; +} + +std::vector parse_rows(const std::string& text){ + std::vector rows; + std::istringstream lines(text); + std::string line; + while (std::getline(lines, line)){ + std::vector cells; + std::istringstream fields(line); + std::string cell; + while (std::getline(fields, cell, ',')){ + cells.push_back(cell); + } + rows.push_back({ + uint32_t(std::stoul(cells[0], nullptr, 16)), + uint32_t(std::stoul(cells[1], nullptr, 16)), + cells[2], + std::stoi(cells[3]), + cells[4], + cells[5], + uint16_t(std::stoul(cells[6], nullptr, 16)), + std::stoull(cells[7]), + std::stoull(cells[8]), + cells[9], + }); + } + return rows; +} + +std::string hex(uint32_t value){ + std::ostringstream out; + out << std::hex << std::uppercase << value; + return out.str(); +} + +std::string ivs_text(const AdvIVs& ivs){ + return std::to_string(ivs.hp) + "/" + std::to_string(ivs.attack) + "/" + std::to_string(ivs.defense) + + "/" + std::to_string(ivs.spatk) + "/" + std::to_string(ivs.spdef) + "/" + std::to_string(ivs.speed); +} + +std::string shiny_text(AdvShinyType type){ + switch (type){ + case AdvShinyType::Square: return "Square"; + case AdvShinyType::Star: return "Star"; + default: return "No"; + } +} + +// Ten Lines writes "Blackout R"; its Switch offsets for R and L are the same, and the +// RNG programs hold L. +std::string buttons_text(const InitialSeedEntry& entry){ + std::string seed_button = entry.seed_button == SeedButton::Start ? "Start" + : entry.seed_button == SeedButton::L ? "L" : "A"; + return seed_button + (entry.blackout_button == BlackoutButton::None ? "/None" : "/Blackout R"); +} + +std::string row_name(const TenLinesRow& row){ + return "Target " + hex(row.state) + ": "; +} + +uint32_t advance(uint32_t state, uint64_t advances){ + for (uint64_t c = 0; c < advances; c++){ + state = lcrng_next(state); + } + return state; +} + + +std::string check_pokemon(const TenLinesRow& row, const TenLinesGroup& group){ + AdvPokemonResult pokemon = method1_pokemon(row.state); + HiddenPower power = hidden_power(pokemon.ivs); + std::string actual = hex(pokemon.pid) + " " + shiny_text(shiny_type(pokemon.pid, TID, SID)) + + " " + std::to_string(int(pokemon.ability)) + " " + ivs_text(pokemon.ivs) + + " " + power.type + " " + std::to_string(power.power); + std::string expected = hex(row.pid) + " " + row.shiny + " " + std::to_string(row.ability) + + " " + row.ivs + " " + row.hidden_power; + if (actual != expected){ + return row_name(row) + "expected " + expected + ", got " + actual; + } + const std::vector& natures = group.natures; + if (std::find(natures.begin(), natures.end(), pokemon.nature) == natures.end()){ + return row_name(row) + "nature " + nature_to_string(pokemon.nature) + " is not in the group"; + } + return ""; +} + +std::string check_advances(const TenLinesRow& row){ + if (advance(row.seed, row.advances) != row.state){ + return row_name(row) + "seed " + hex(row.seed) + " + " + std::to_string(row.advances) + + " advances does not reach it"; + } + if (lcrng_distance(row.seed, row.state) != row.advances){ + return row_name(row) + "wrong distance from seed " + hex(row.seed); + } + // The RNG programs count advances the same way. + AdvRngSearcher program(row.seed, row.advances, AdvRngMethod::Method1); + if (program.generate_pokemon().pid != row.pid){ + return row_name(row) + "AdvRngSearcher gives PID " + hex(program.generate_pokemon().pid); + } + return ""; +} + +UnitTestResult run_method1(const TenLinesGroup& group){ + for (const TenLinesRow& row : parse_rows(group.rows)){ + std::string error = check_pokemon(row, group); + if (error.empty()){ + error = check_advances(row); + } + if (!error.empty()){ + return error; + } + } + return true; +} + +RngTargetFilters ten_lines_filters(const TenLinesGroup& group){ + RngTargetFilters filters; + filters.natures = group.natures; + filters.min_ivs = group.min_ivs; + filters.min_advances = 3000; + filters.avoided_seed_time_ms = 30500; + filters.avoided_seed_time_radius_ms = 3000; + return filters; +} + +std::vector leafgreen_mono_help_seeds(){ + SeedsDatabase database(seeds_json_path(false, Language::English)); + return initial_seed_entries(database, SoundSetting::Mono, "Help", true); +} + +std::string compare_seed_entry(const TenLinesRow& row, const InitialSeedEntry& entry){ + std::string expected = std::to_string(row.seed_time_ms) + " " + row.buttons; + std::string actual = std::to_string(entry.seed_time_ms) + " " + buttons_text(entry); + // Ten Lines lists every way to reach a seed, and the RNG programs use the earliest + // (SeedsDatabase::find_seed()): 3136 by Start at 58991 ms, not by A at 63359 ms. + if (buttons_text(entry) != row.buttons){ + return entry.seed_time_ms < row.seed_time_ms ? "" : "Expected " + expected + ", got " + actual; + } + // Ten Lines rounds the seed time down from 1/16 frames; the seed table here is 1 ms + // lower on about 1 row in 17 (61023 instead of 61024 for row 1833). + if (entry.seed_time_ms > row.seed_time_ms || entry.seed_time_ms + 1 < row.seed_time_ms){ + return "Expected " + expected + ", got " + actual; + } + return ""; +} + +std::string compare_target(const TenLinesRow& row, const RngTarget& target){ + std::string expected = hex(row.state) + " " + hex(row.seed) + " " + std::to_string(row.advances); + std::string actual = hex(target.state) + " " + hex(target.seed.seed) + " " + std::to_string(target.advances); + if (actual != expected){ + return "Expected " + expected + ", got " + actual; + } + std::string error = compare_seed_entry(row, target.seed); + if (!error.empty()){ + return row_name(row) + error; + } + if (target.shiny_for.size() != 1 || shiny_text(target.shiny_for[0].type) != row.shiny || target.shiny_probability != 1){ + return row_name(row) + "expected shiny (" + row.shiny + ") for the one SID"; + } + return ""; +} + +UnitTestResult run_search(const TenLinesGroup& group){ + std::vector targets = search_rng_targets( + leafgreen_mono_help_seeds(), TID, {{SID, 1}}, ten_lines_filters(group) + ); + std::vector rows = parse_rows(group.rows); + if (targets.size() < rows.size()){ + return "Expected at least " + std::to_string(rows.size()) + " targets, got " + std::to_string(targets.size()); + } + for (size_t c = 0; c < rows.size(); c++){ + std::string error = compare_target(rows[c], targets[c]); + if (!error.empty()){ + return "Target #" + std::to_string(c + 1) + ": " + error; + } + } + return true; +} + +UnitTestResult run_iv_search(){ + const TenLinesGroup group = groups()[2]; + std::vector seeds = leafgreen_mono_help_seeds(); + RngTargetFilters filters = ten_lines_filters(group); + std::vector shiny = search_rng_targets(seeds, TID, {{SID, 1}}, filters); + + filters.shiny_required = false; + std::vector any = search_rng_targets(seeds, TID, {{SID, 1}}, filters); + std::vector any_shiny; + for (const RngTarget& target : any){ + if (!target.shiny_for.empty()){ + any_shiny.push_back(target); + } + } + if (any.size() <= any_shiny.size()){ + return "Expected targets that are not shiny"; + } + if (any_shiny.size() != shiny.size()){ + return "Expected " + std::to_string(shiny.size()) + " shiny targets, got " + std::to_string(any_shiny.size()); + } + for (size_t c = 0; c < shiny.size(); c++){ + if (any_shiny[c].state != shiny[c].state || any_shiny[c].advances != shiny[c].advances){ + return "Shiny target #" + std::to_string(c + 1) + " differs: " + hex(any_shiny[c].state); + } + } + return true; +} + +UnitTestResult run_candidates(){ + const TenLinesGroup group = groups()[0]; + const uint16_t other_sid = SID ^ 0x0100; + std::vector targets = search_rng_targets( + leafgreen_mono_help_seeds(), TID, {{SID, 3}, {other_sid, 1}}, ten_lines_filters(group) + ); + size_t found = 0; + for (const RngTarget& target : targets){ + if (target.shiny_for.size() != 1){ + return "Target " + hex(target.state) + " is shiny for " + std::to_string(target.shiny_for.size()) + " SIDs"; + } + double expected = target.shiny_for[0].candidate == 0 ? 0.75 : 0.25; + if (target.shiny_probability != expected){ + return "Target " + hex(target.state) + " has shiny probability " + std::to_string(target.shiny_probability); + } + found += target.shiny_for[0].candidate == 0 && target.advances <= 171172; + } + if (found != 20){ + return "Expected the 20 Ten Lines targets for SID " + std::to_string(SID) + ", got " + std::to_string(found); + } + return true; +} + +UnitTestResult run_ranking(){ + auto target = [](uint32_t state, uint64_t advances, double probability){ + RngTarget ret{state, {0, 40000, SeedButton::A, BlackoutButton::None}, advances, {}, {}, probability}; + return ret; + }; + std::vector targets{ + target(0xA, 10000, 0.5), + target(0xB, 12500, 1), + target(0xC, 100, 0), + target(0xD, 1000, 0.1), + }; + rank_rng_targets(targets); + std::string order; + for (const RngTarget& item : targets){ + order += hex(item.state); + } + if (order != "BADC"){ + return "Expected order BADC, got " + order; + } + return true; +} + +enum class RngTargetSearchKind{ + Method1, + Search, + IvSearch, + Candidates, + Ranking, +}; + +struct RngTargetSearchInput{ + std::string name; + RngTargetSearchKind kind = RngTargetSearchKind::Method1; + size_t group_index = 0; +}; + +struct RngTargetSearchExpectation{ + std::string description = ""; +}; + +struct RngTargetSearchCase{ + RngTargetSearchInput input; + RngTargetSearchExpectation expectation; +}; + +const RngTargetSearchCase RNG_TARGET_SEARCH_CASES[] = { + { + .input = {.name = "Method 1 - Modest", .kind = RngTargetSearchKind::Method1, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "Method 1 - Adamant", .kind = RngTargetSearchKind::Method1, .group_index = 1}, + .expectation = {}, + }, + { + .input = {.name = "Method 1 - Neutral", .kind = RngTargetSearchKind::Method1, .group_index = 2}, + .expectation = {}, + }, + { + .input = {.name = "Search - Modest", .kind = RngTargetSearchKind::Search, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "Search - Adamant", .kind = RngTargetSearchKind::Search, .group_index = 1}, + .expectation = {}, + }, + { + .input = {.name = "Search - Neutral", .kind = RngTargetSearchKind::Search, .group_index = 2}, + .expectation = {}, + }, + { + .input = {.name = "IV search", .kind = RngTargetSearchKind::IvSearch, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "SID candidates", .kind = RngTargetSearchKind::Candidates, .group_index = 0}, + .expectation = {}, + }, + { + .input = {.name = "Ranking", .kind = RngTargetSearchKind::Ranking, .group_index = 0}, + .expectation = {}, + }, +}; + +class Test_RngTargetSearch : public UnitTest{ +public: + explicit Test_RngTargetSearch(const RngTargetSearchCase& test_case) + : UnitTest("PokemonFRLG::RngTargetSearch - " + test_case.input.name) + , m_case(test_case) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + switch (m_case.input.kind){ + case RngTargetSearchKind::Method1: + return run_method1(groups()[m_case.input.group_index]); + case RngTargetSearchKind::Search: + return run_search(groups()[m_case.input.group_index]); + case RngTargetSearchKind::IvSearch: + return run_iv_search(); + case RngTargetSearchKind::Candidates: + return run_candidates(); + case RngTargetSearchKind::Ranking: + return run_ranking(); + } + return "Unknown test kind"; + } + +private: + const RngTargetSearchCase m_case; +}; + +} // namespace + +void add_tests_RngTargetSearch(UnitTestDatabase& database){ + for (const RngTargetSearchCase& test_case : RNG_TARGET_SEARCH_CASES){ + database.add(test_case); + } +} + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h new file mode 100644 index 0000000000..1e79216cc4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h @@ -0,0 +1,24 @@ +/* RNG Target Search Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_RngTargetSearch_Tests_H +#define PokemonAutomation_PokemonFRLG_RngTargetSearch_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers RNG target search unit tests. +void add_tests_RngTargetSearch(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp index fe284e8a2c..ca6ea548e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp @@ -226,11 +226,10 @@ void RoamingLegendaryRng::program(SingleSwitchProgramEnvironment& env, ProContro /* * Settings: Text Speed fast */ + run_precheck(env, context); RoamingLegendaryRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h index f53f60a6ce..2b331ac54d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h @@ -12,10 +12,10 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -29,9 +29,11 @@ class RoamingLegendaryRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class RoamingLegendaryRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a roaming legendary. +class RoamingLegendaryRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = RoamingLegendaryRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~RoamingLegendaryRng(); RoamingLegendaryRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h index 12c1b2a77e..a619054ca0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h @@ -44,10 +44,6 @@ struct SeedMatch{ class SeedsDatabase{ public: - SeedsDatabase(const std::string& json_path); - SeedMatch find_seed(uint16_t target_seed, SoundSetting sound, int radius) const; - -private: struct SeedColumn{ std::string name; SoundSetting sound; @@ -56,6 +52,15 @@ class SeedsDatabase{ std::vector seeds; }; +public: + SeedsDatabase(const std::string& json_path); + SeedMatch find_seed(uint16_t target_seed, SoundSetting sound, int radius) const; + + // The delay in milliseconds before each row of the columns. + const std::vector& delays() const{ return m_delays; } + const std::vector& columns() const{ return m_columns; } + +private: std::vector m_delays; std::vector m_columns; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp index 0c3ac9bd67..c3b2e0f680 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp @@ -9,8 +9,6 @@ #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/ProgramStats/StatsTracking.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "Pokemon/Pokemon_Strings.h" #include "Pokemon/Pokemon_AdvRng.h" @@ -18,7 +16,8 @@ #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_TrainerIdReader.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" -#include "PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h" +#include "PokemonFRLG_SidSteps.h" #include "PokemonFRLG_SidHelper.h" namespace PokemonAutomation{ @@ -100,133 +99,6 @@ SidHelper::SidHelper() namespace{ -void set_sid_from_name_screen( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const uint64_t& SID_DELAY, - bool extra_press_at_end -){ - // this is performed blind to try to maximize consistency of timing - // ensure the OK button is selected - pbf_press_button(context, BUTTON_PLUS, 200ms, 300ms); - // confirm name (SID delay starts now) - pbf_press_button(context, BUTTON_A, 200ms, 1800ms); - // advance to "...about to unfold!", picking the default rival name - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - pbf_press_button(context, BUTTON_A, 200ms, 1050ms); - pbf_press_button(context, BUTTON_A, 200ms, 1550ms); - pbf_move_left_joystick(context, {0,-1}, 200ms, 300ms); - pbf_press_button(context, BUTTON_A, 200ms, 1050ms); - pbf_press_button(context, BUTTON_A, 200ms, 1550ms); - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - - // 2000 + 2500 + 1250 + 1750 + 500 + 1250 + 1750 + 2500 + 200 ms - Milliseconds delay(SID_DELAY > 13700 - ? SID_DELAY - 13700 - : 0 - ); - - if (extra_press_at_end){ - pbf_press_button(context, BUTTON_A, 200ms, 1300ms); - delay = delay > 1500ms ? delay - 1500ms : 0ms; - } - - pbf_press_button(context, BUTTON_A, 200ms, delay); - - // finish dialogue and lock in SID - pbf_press_button(context, BUTTON_A, 200ms, 0ms); - context.wait_for_all_requests(); -} - -void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - BlackScreenWatcher black_screen; - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, 10s, - { black_screen } - ); - - if (ret < 0){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, "SidHelper(): black screen not detected within 10 seconds of setting SID", env.console - ); - } - - BlackScreenOverWatcher black_screen_over; - context.wait_for_all_requests(); - int ret2 = wait_until( - env.console, context, 10s, - { black_screen_over } - ); - - if (ret2 < 0){ - env.log("finish_intro_animations(): end of black screen not detected within 10 seconds. Continuing anyway..."); - // if there's a problem, an error will be thrown when trying to navigate to the trainer card - } - - pbf_wait(context, 2000ms); - context.wait_for_all_requests(); -} - -void navigate_to_trainer_card(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - int errors = 0; - while (true){ - if (errors >= 5){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, "SidHelper(): failed 5 times to navigate to the Trainer Card", env.console - ); - } - - open_start_menu(env.console, context); - - // the positions are different before recieving a Pokemon and Pokedex - bool cursor = move_cursor_to_position( - env.console, context, SelectionArrowPositionStartMenu(1) - ); - if (!cursor){ - errors++; - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - } - - TrainerCardWatcher trainer_card(COLOR_RED); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - pbf_press_button(context, BUTTON_A, 200ms, 2300ms); - }, - { trainer_card } - ); - - if (ret < 0){ - env.log("SidHelper(): failed to detect Trainer Card"); - errors++; - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - } - - break; - } -} - -uint16_t read_tid(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language lang){ - TrainerIdReader reader; - VideoOverlaySet overlays(env.console.overlay()); - reader.make_overlays(overlays); - - VideoSnapshot screen = env.console.video().snapshot(); - env.log("Trainer Card detected."); - env.log("Reading TID..."); - uint16_t tid = reader.read_tid(env.logger(), lang, screen); - env.log("TID: " + std::to_string(tid)); - - context.wait_for_all_requests(); - - return tid; -} - std::vector> get_sid_messages( SingleSwitchProgramEnvironment& env, ProControllerContext& context, @@ -271,48 +143,15 @@ void SidHelper::program(SingleSwitchProgramEnvironment& env, ProControllerContex // SidHelper_Descriptor::Stats& stats = env.current_stats(); - uint64_t FINAL_TEXT_FRAMES; Language lang = LANGUAGE; - switch (lang){ - case Language::English: - FINAL_TEXT_FRAMES = 249; - break; - case Language::Japanese: - FINAL_TEXT_FRAMES = 194; - break; - case Language::Italian: - FINAL_TEXT_FRAMES = 236; - break; - case Language::French: - FINAL_TEXT_FRAMES = 205; - break; - case Language::German: - FINAL_TEXT_FRAMES = 208; - break; - case Language::Spanish: - FINAL_TEXT_FRAMES = 202; - break; - default: - FINAL_TEXT_FRAMES = 249; - } - - static const int64_t FIXED_ADVANCES_OFFSET = 7; // determined empirically. Probably not console/setup dependent - - bool extra_press_at_end = ( - LANGUAGE == Language::German || - LANGUAGE == Language::Japanese || - LANGUAGE == Language::Spanish || - LANGUAGE == Language::French - ); - - const uint64_t SID_DELAY = uint64_t((TARGET_ADVANCES - 2*FINAL_TEXT_FRAMES + FIXED_ADVANCES_OFFSET) * FRLG_FRAME_DURATION / 2); // advances pass 2 by 2 - env.log("Delay: " + std::to_string(SID_DELAY) + "ms"); + const SidTiming timing = sid_timing(lang, TARGET_ADVANCES); + env.log("Delay: " + std::to_string(timing.delay_ms) + "ms"); - set_sid_from_name_screen(env, context, SID_DELAY, extra_press_at_end); + set_sid_from_name_screen(context, timing); finish_intro_animations(env, context); - navigate_to_trainer_card(env, context); + navigate_to_trainer_card(env.console, context); - uint16_t tid = read_tid(env, context, lang); + uint16_t tid = read_trainer_card_tid(env.console, context, lang); std::vector> sid_messages = get_sid_messages( env, context, tid, TARGET_ADVANCES, NUM_CANDIDATES diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp new file mode 100644 index 0000000000..63438dbdb9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp @@ -0,0 +1,124 @@ +/* SID Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_SidSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +SidTiming sid_timing(Language language, uint32_t target_advances){ + uint64_t FINAL_TEXT_FRAMES; + switch (language){ + case Language::English: + FINAL_TEXT_FRAMES = 249; + break; + case Language::Japanese: + FINAL_TEXT_FRAMES = 194; + break; + case Language::Italian: + FINAL_TEXT_FRAMES = 236; + break; + case Language::French: + FINAL_TEXT_FRAMES = 205; + break; + case Language::German: + FINAL_TEXT_FRAMES = 208; + break; + case Language::Spanish: + FINAL_TEXT_FRAMES = 202; + break; + default: + FINAL_TEXT_FRAMES = 249; + } + + static const int64_t FIXED_ADVANCES_OFFSET = 7; // determined empirically. Probably not console/setup dependent + + bool extra_press_at_end = ( + language == Language::German || + language == Language::Japanese || + language == Language::Spanish || + language == Language::French + ); + + const uint64_t SID_DELAY = uint64_t((target_advances - 2*FINAL_TEXT_FRAMES + FIXED_ADVANCES_OFFSET) * FRLG_FRAME_DURATION / 2); // advances pass 2 by 2 + return SidTiming{.delay_ms = SID_DELAY, .extra_press_at_end = extra_press_at_end}; +} + +void set_sid_from_name_screen(ProControllerContext& context, const SidTiming& timing){ + // this is performed blind to try to maximize consistency of timing + // ensure the OK button is selected + pbf_press_button(context, BUTTON_PLUS, 200ms, 300ms); + // confirm name (SID delay starts now) + pbf_press_button(context, BUTTON_A, 200ms, 1800ms); + // advance to "...about to unfold!", picking the default rival name + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + pbf_press_button(context, BUTTON_A, 200ms, 1050ms); + pbf_press_button(context, BUTTON_A, 200ms, 1550ms); + pbf_move_left_joystick(context, {0,-1}, 200ms, 300ms); + pbf_press_button(context, BUTTON_A, 200ms, 1050ms); + pbf_press_button(context, BUTTON_A, 200ms, 1550ms); + pbf_press_button(context, BUTTON_A, 200ms, 2300ms); + + // 2000 + 2500 + 1250 + 1750 + 500 + 1250 + 1750 + 2500 + 200 ms + Milliseconds delay(timing.delay_ms > 13700 + ? timing.delay_ms - 13700 + : 0 + ); + + if (timing.extra_press_at_end){ + pbf_press_button(context, BUTTON_A, 200ms, 1300ms); + delay = delay > 1500ms ? delay - 1500ms : 0ms; + } + + pbf_press_button(context, BUTTON_A, 200ms, delay); + + // finish dialogue and lock in SID + pbf_press_button(context, BUTTON_A, 200ms, 0ms); + context.wait_for_all_requests(); +} + +void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BlackScreenWatcher black_screen; + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, 10s, + { black_screen } + ); + + if (ret < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "SidHelper(): black screen not detected within 10 seconds of setting SID", env.console + ); + } + + BlackScreenOverWatcher black_screen_over; + context.wait_for_all_requests(); + int ret2 = wait_until( + env.console, context, 10s, + { black_screen_over } + ); + + if (ret2 < 0){ + env.log("finish_intro_animations(): end of black screen not detected within 10 seconds. Continuing anyway..."); + // if there's a problem, an error will be thrown when trying to navigate to the trainer card + } + + pbf_wait(context, 2000ms); + context.wait_for_all_requests(); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h new file mode 100644 index 0000000000..033a4a8d7f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h @@ -0,0 +1,50 @@ +/* SID Steps + * + * From: https://github.com/PokemonAutomation/ + * + * SID Helper's steps from the naming screen to the overworld, which set the + * SID by timing the last press of the intro. Shared with AutoStory. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_SidSteps_H +#define PokemonAutomation_PokemonFRLG_SidSteps_H + +#include +#include "CommonFramework/Language.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// When to press the last A of the intro to land on an advance. +struct SidTiming{ + // From confirming the player's name to the last press. + uint64_t delay_ms = 0; + // The language's intro has one more text box before the last press. + bool extra_press_at_end = false; +}; + +// The timing that sets the SID at "target_advances" (odd) in a game in +// "language". +SidTiming sid_timing(Language language, uint32_t target_advances); + +// From the player's naming screen, confirms the name, picks the default +// rival name and presses through the intro at "timing", which sets the SID. +// Runs blind; ends on the last press of the intro. +void set_sid_from_name_screen(ProControllerContext& context, const SidTiming& timing); + +// After set_sid_from_name_screen(): waits out the black screen into the +// overworld. Throws OperationFailedException if no black screen comes +// within 10 seconds. +void finish_intro_animations(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp index 5b22bee42f..efaac7de01 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp @@ -6,22 +6,15 @@ #include "Common/Cpp/Strings/StringTools.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" #include "Pokemon/Pokemon_Strings.h" -#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" -#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" -#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattlePokemonDetector.h" -#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "PokemonFRLG_RngNavigation.h" -#include "PokemonFRLG_HardReset.h" +#include "PokemonFRLG_RngCalibration.h" #include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngAttempts.h" #include "PokemonFRLG_StarterRng.h" namespace PokemonAutomation{ @@ -42,26 +35,6 @@ StarterRng_Descriptor::StarterRng_Descriptor() ) {} -struct StarterRng_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , nonshiny(m_stats["Non-Shiny Hits"]) - , wildshinies(m_stats["Wild Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Non-Shiny Hits", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Wild Shinies", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& nonshiny; - std::atomic& wildshinies; - std::atomic& errors; -}; std::unique_ptr StarterRng_Descriptor::make_stats() const{ return std::unique_ptr(new Stats()); } @@ -115,12 +88,12 @@ StarterRng::StarterRng() , STARTER( "Starter Species:", { - {Starter::bulbasaur, "bulbasaur", "Bulbasaur"}, - {Starter::squirtle, "squirtle", "Squirtle"}, - {Starter::charmander, "charmander", "Charmander"}, + {StarterSpecies::bulbasaur, "bulbasaur", "Bulbasaur"}, + {StarterSpecies::squirtle, "squirtle", "Squirtle"}, + {StarterSpecies::charmander, "charmander", "Charmander"}, }, LockMode::LOCK_WHILE_RUNNING, - Starter::bulbasaur + StarterSpecies::bulbasaur ) , SEED( false, @@ -214,354 +187,13 @@ void StarterRng::on_config_value_changed(void* object){ -bool StarterRng::walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // return to the overworld - pbf_mash_button(context, BUTTON_B, 5000ms); - int num_steps_to_the_left; - switch(STARTER){ - case Starter::bulbasaur: - num_steps_to_the_left = 2; - break; - case Starter::squirtle: - num_steps_to_the_left = 3; - break; - case Starter::charmander: - num_steps_to_the_left = 4; - break; - default: - num_steps_to_the_left = 2; - } - - // dodge rival - pbf_move_left_joystick(context, {0, -1}, 40ms, 460ms); - pbf_move_left_joystick(context, {0, -1}, 100ms, 400ms); - - // line up with the doorway - pbf_move_left_joystick(context, {-1, 0}, 40ms, 460ms); // pivot left - for (int i=0; i( - env.console, context, - [](ProControllerContext& context){ - for (int i=0; i<5; i++){ - ssf_press_left_joystick(context, {0, -1}, 0ms, 20000ms, 0ms); - ssf_mash1_button(context, BUTTON_B, 20000ms); - } - }, - { black_screen } - ); - - bool failed = ret < 0; - if (failed){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "walk_to_rival_battle(): failed to initiate battle." - ); - } - return failed; -} - -bool StarterRng::auto_battle_rival( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS -){ - Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; - switch(STARTER){ - case Starter::bulbasaur: - evyield.speed = 1; // from charmander - break; - case Starter::squirtle: - evyield.spatk = 1; // from bulbasaur - break; - case Starter::charmander: - evyield.defense = 1; // from squirtle - } - - // detect the battle menu - BattleMenuWatcher battle_ready(COLOR_RED); - context.wait_for_all_requests(); - int ret1 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 30s); - }, - { battle_ready } - ); - if (ret1 < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "auto_battle_rival(): failed to detect the battle menu." - ); - return true; - } - env.log("Battle started. Using first move..."); - - // perform the first move and get through Oak's dialogue, - // which messes up most detectors when it dims the screen - pbf_mash_button(context, BUTTON_A, 1000ms); // execute first move - context.wait_for_all_requests(); - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 30s); - }, - { battle_ready } - ); - if (ret2 < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "auto_battle_rival(): failed to detect the battle menu." - ); - return true; - } - env.log("Oak tutorial dialogue finished. Mashing A..."); - - // mash A until somebody faints - BattleOpponentFaintWatcher player_won(COLOR_RED); - BattleFaintWatcher player_lost(COLOR_RED); - context.wait_for_all_requests(); - int ret3 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 300s); - }, - { player_won, player_lost } - ); - - switch(ret3){ - case 0: - env.log("Won battle against rival. Watching for level-up stats..."); - break; - case 1: - env.log("Lost battle against rival."); - pbf_mash_button(context, BUTTON_B, 20s); // exit battle and dialogue - return false; - default: - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "auto_battle_rival(): no fainting detected with 5 minutes." - ); - return true; - } - - // slowly advance dialog until level-up stats are visible - BattleLevelUpWatcher level_up_stats(COLOR_RED, BattleLevelUpDialog::stats, LANGUAGE); - BlackScreenWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret4 = run_until( - env.console, context, - [](ProControllerContext& context){ - for(int i=0; i<60; i++){ - pbf_press_button(context, BUTTON_A, 200ms, 1800ms); - } - }, - { level_up_stats, black_screen } - ); - - switch(ret4){ - case 0: - env.log("Level-up stats detected."); - break; - case 1: - env.log("Battle exited without detecting level-up stats"); - return true; // will cause issues with keeping track of level and EVs - default: - env.log("auto_battle_rival(): no recognized state within 2 minutes of winning battle."); - return true; - } - - // read stats - BattleLevelUpReader reader(COLOR_RED); - VideoOverlaySet overlays(env.console.overlay()); - reader.make_overlays(overlays); - - env.log("Reading stats..."); - VideoSnapshot screen = env.console.video().snapshot(); - StatReads stats = reader.read_stats(env.logger(), screen); - - update_filters(filters, pokemon, stats, evyield, BASE_STATS); - RNG_FILTERS.set(filters); - - // exit battle - pbf_mash_button(context, BUTTON_B, 20s); - context.wait_for_all_requests(); - - return false; -} - - - -bool StarterRng::walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // exit the lab - env.log("Exiting the lab..."); - BlackScreenWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, {0, -1}, 10s, 0ms); - }, - { black_screen } - ); - - if (ret < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "walk_to_route1_from_lab(): failed to exit lab." - ); - return true; - } - - env.log("Lab exited. Walking to Route 1..."); - pbf_wait(context, 5000ms); - pbf_move_left_joystick(context, {-1, 0}, 1280ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 3150ms, 300ms); - pbf_move_left_joystick(context, {+1, 0}, 330ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 720ms, 300ms); - context.wait_for_all_requests(); - return false; -} - -bool StarterRng::walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // exit the house - env.log("Exiting the house..."); - BlackScreenWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); - pbf_move_left_joystick(context, {-1, 0}, 900ms, 300ms); - pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); - }, - { black_screen } - ); - - if (ret < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "walk_to_route1_from_home(): failed to exit the house." - ); - return true; - } - - env.log("House exited. Walking to Route 1..."); - pbf_wait(context, 5s); - pbf_move_left_joystick(context, {+1, 0}, 1370ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 1450ms, 300ms); - pbf_move_left_joystick(context, {+1, 0}, 300ms, 300ms); - pbf_move_left_joystick(context, {0, +1}, 1250ms, 300ms); - - return false; -} - -int StarterRng::autolevel_on_route1( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS -){ - Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; - Pokemon::StatReads stats; - - env.log("Arrived at Route 1."); - bool leftright = true; - context.wait_for_all_requests(); - - while (true){ - // trigger encounter - env.log("Triggering wild encounters..."); - int ret = grass_spin(env.console, context, leftright); - if (ret < 0){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "autolevel_on_route1(): failed to trigger encounter." - ); - return -1; - } - - if (ret == 1){ // shiny - return 1; - } - - // auto battle - BattleResult ret2 = spam_first_move(env.console, context); - - BattleLevelUpWatcher level_up(COLOR_RED, BattleLevelUpDialog::stats, LANGUAGE); - BlackScreenWatcher black_screen(COLOR_RED); - VideoSnapshot screen; - int ret3; - bool failed; - BattleLevelUpReader reader; - - switch (ret2){ - case BattleResult::opponentfainted: - env.log("Opponent fainted."); - evyield.speed++; // always rattata or pidgey - leftright = !leftright; - - context.wait_for_all_requests(); - ret3 = run_until( - env.console, context, - [](ProControllerContext& context){ - for (int i=0; i<5; i++){ - pbf_press_button(context, BUTTON_B, 200ms, 1800ms); - } - }, - { level_up, black_screen } - ); - - switch (ret3){ - case 0: - env.log("Level-up stats detected. Reading stats..."); - screen = env.console.video().snapshot(); - stats = reader.read_stats(env.logger(), screen); - update_filters(filters, pokemon, stats, evyield, BASE_STATS); - RNG_FILTERS.set(filters); - exit_wild_battle(env.console, context, false, true); - return 0; - case -1: - exit_wild_battle(env.console, context, false, true); - default: - pbf_wait(context, 1000ms); - context.wait_for_all_requests(); - continue; - } - case BattleResult::playerfainted: - env.log("Pokemon fainted. Mashing B through dialogues..."); - pbf_mash_button(context, BUTTON_B, 30s); // skip through a few transitions and lots of dialogue - failed = walk_to_route1_from_home(env, context); - if (failed){ - return -1; - } - context.wait_for_all_requests(); - leftright = true; - continue; - case BattleResult::outofpp: - case BattleResult::unknown: - default: - return -1; - } - } -} - void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ /* * Settings: Text Speed fast */ + run_precheck(env, context); - StarterRng_Descriptor::Stats& stats = env.current_stats(); - - home_black_border_check(env.console, context); + StarterRngStats& stats = env.current_stats(); RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); @@ -572,279 +204,41 @@ void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerConte if (!seed_match.found){ throw UserSetupError(env.console, "The target Seed was not found in the seed database for this game version, language, and sound setting."); } - const std::vector SEED_VALUES = seed_match.seed_values; - const int16_t SEED_POSITION = seed_match.seed_position; - const uint64_t SEED_DELAY = seed_match.seed_delay; - const SeedButton SEED_BUTTON = seed_match.seed_button; - const BlackoutButton EXTRA_BUTTON = seed_match.extra_button; - env.log("Seed delay: " + std::to_string(SEED_DELAY) + "ms, button mode: " + seed_match.button_mode + env.log("Seed delay: " + std::to_string(seed_match.seed_delay) + "ms, button mode: " + seed_match.button_mode + ", column: " + seed_match.column_name); - BaseStats BASE_STATS; - switch (STARTER){ - case Starter::bulbasaur: - BASE_STATS = { 45, 49, 49, 65, 65, 45 }; - break; - case Starter::squirtle: - BASE_STATS = { 44, 48, 65, 50, 64, 43 }; - break; - case Starter::charmander: - BASE_STATS = { 39, 52, 43, 60, 50, 65 }; - break; - default: - break; - } - - static const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate - - static const uint64_t CONTINUE_SCREEN_FRAMES = 200; - - static const uint64_t INITIAL_ADVANCES_RADIUS = 1024; - - static const uint8_t MAX_HISTORY_LENGTH = 10; - - static const int16_t GENDER_THRESHOLD = 30; - - static const std::set SPECIES_LIST = { "bulbasaur", "squirtle", "charmander" }; - - env.log("RNG Target: " + std::to_string(STARTER.current_value())); - env.log("Target Seed: " + to_hex_string(TARGET_SEED)); - env.log("Target Advances: " + std::to_string(ADVANCES)); - - AdvRngSearcher searcher(TARGET_SEED, ADVANCES, AdvRngMethod::Method1); - AdvPokemonResult target_result = searcher.generate_pokemon(); - RNG_TARGET.set_target(target_result, GENDER_THRESHOLD); - log_target_pokemon(env.console, target_result); - - RngCalibrations calibrations = { - RNG_CALIBRATION.seed_calibration / FRLG_FRAME_DURATION, - RNG_CALIBRATION.csf_calibration, - RNG_CALIBRATION.advances_calibration - }; - log_calibrations(env.console, calibrations, true); - - Milliseconds launch_delay = INITIAL_LAUNCH_DELAY; - - RngUncertainHistory uncertain_history; - RngCalibrationHistory calibration_history; - - bool wildshiny_found = false; - - uint16_t failed_searches = 0; - - while (true){ - if (calibration_history.results.size() > 0){ - env.log("Checking for nonshiny target hit..."); - if (have_hit_target(TARGET_SEED, ADVANCES, calibration_history.results.back())){ - env.log("Target Hit!"); - stats.nonshiny++; - break; - } - env.log("Missed target."); - } - - if (failed_searches >= 5){ - env.log("Failed to find any matches 5 times in a row"); - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::NO_ERROR_REPORT, - "Failed to find any matches 5 times in a row. Check your seed and advances settings.", - env.console - ); - break; - } - - if (stats.resets > MAX_RESETS){ - env.log("Max resets reached."); - break; - } - - if (wildshiny_found){ - break; - } - - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Calibrating." - ); - env.update_stats(); - - - uint64_t advances_radius = get_advances_radius(env.console, calibration_history, INITIAL_ADVANCES_RADIUS); - - if (calibration_history.results.size() > 0){ - calibrations = get_calibrations(env.console, calibration_history, SEED_VALUES, SEED_POSITION, ADVANCES); - } - - // if previous resets had uncertain advances, slightly modify the seed delay to try to hit a different target - apply_seed_bump(calibrations, uncertain_history); - - uint64_t ingame_advances = ADVANCES - CONTINUE_SCREEN_FRAMES; - - RngTimings timings = prepare_timings( - env.console, PokemonFRLG_RngTarget::starters, - SEED_DELAY, CONTINUE_SCREEN_FRAMES, ingame_advances, - false, calibrations, - FIXED_SEED_OFFSET - ); - - env.log("Resetting Game..."); - reset_and_perform_blind_sequence( - env.console, context, - LANGUAGE, PokemonFRLG_RngTarget::starters, - SEED_BUTTON, EXTRA_BUTTON, timings, - launch_delay, false, PROFILE - ); - stats.resets++; - - RNG_FILTERS.reset(); - RNG_CALIBRATION.set_calibrations(calibrations); - RNG_CALIBRATION.reset_hits(); - - bool shiny_found = check_for_shiny(env.console, context, PokemonFRLG_RngTarget::starters); - - if (shiny_found){ - env.log("Shiny found!"); - stats.shinies++; - RNG_CALIBRATION.hits.set("Shiny!"); - send_program_notification( - env, - NOTIFICATION_SHINY, - COLOR_YELLOW, - "Shiny found!", - {}, "", - env.console.video().snapshot(), - true - ); - if (TAKE_VIDEO){ - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); - } - break; - } - - // Stage 1: initial search -- starter received - AdvObservedPokemon pokemon = read_summary(env.console, context, LANGUAGE, SPECIES_LIST); - pokemon.level[0] = 5; - AdvRngFilters filters = observation_to_filters(pokemon, BASE_STATS); - RNG_FILTERS.set(filters); - - std::vector search_hits = get_search_results(env.console, searcher, filters, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - RNG_CALIBRATION.set_hits(search_hits); - bool finished = update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1 - ); - if (finished){ - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - continue; - } - - // Stage 2: first search update -- post-rival-battle - bool failed = walk_to_rival_battle(env, context); - if (failed){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - continue; // reset game - } - - failed = auto_battle_rival(env, context, pokemon, filters, BASE_STATS); - if (failed){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - continue; // reset game - } - if (pokemon.level.size() > 1){ - search_hits = get_search_results(env.console, searcher, filters, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - RNG_CALIBRATION.set_hits(search_hits); - env.log("Number of search hits: " + std::to_string(search_hits.size())); - finished = update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 5 - ); - if (finished){ - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - continue; - } - } - - // Stage 3: subsequent search updates -- leveling up from wild encounters - failed = walk_to_route1_from_lab(env, context); - if (failed){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - continue; // reset game - } - - auto num_levels = pokemon.level.size(); - uint16_t MAX_LEVELS = 3; - while(true){ - if (num_levels > MAX_LEVELS){ - env.log("RNG search not complete after 3 level-ups."); - finished = update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 5, 2, true - ); - break; - } - - env.log("Level: " + std::to_string(4 + pokemon.level.size())); - env.log("Speed EVs: " + std::to_string(pokemon.evs.back().speed)); - - int ret2 = autolevel_on_route1(env, context, pokemon, filters, BASE_STATS); - if (ret2 < 0){ - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 1, 2, true - ); - stats.errors++; - break; - }else if(ret2 == 1){ - env.log("Wild shiny found!"); - stats.wildshinies++; - send_program_notification( - env, - NOTIFICATION_SHINY, - COLOR_YELLOW, - "Wild Shiny found!", - {}, "", - env.console.video().snapshot(), - true - ); - if (TAKE_VIDEO){ - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); - } - if (!IGNORE_WILD_SHINIES){ - wildshiny_found = true; - break; - } - } - - // force the search to finish after enough level-ups - if (pokemon.level.size() > num_levels){ - num_levels = pokemon.level.size(); - search_hits = get_search_results(env.console, searcher, filters, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - RNG_CALIBRATION.set_hits(search_hits); - env.log("Number of search hits: " + std::to_string(search_hits.size())); - update_history( - env.console, uncertain_history, calibration_history, - MAX_HISTORY_LENGTH, calibrations, search_hits, 5, 2, true - ); - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - break; - } - } - + StarterRngAttempts attempts( + StarterRngTarget{ + .starter = STARTER, + .seed = TARGET_SEED, + .advances = ADVANCES, + .seed_match = seed_match, + }, + StarterRngSettings{ + .language = LANGUAGE, + .profile = PROFILE, + .ignore_wild_shinies = IGNORE_WILD_SHINIES, + .take_video = TAKE_VIDEO, + .identify_shiny = false, + .max_resets = [this]{ return uint64_t(MAX_RESETS); }, + .on_reset = nullptr, + .on_read = nullptr, + }, + StarterRngDisplays{.target = RNG_TARGET, .filters = RNG_FILTERS, .calibration = RNG_CALIBRATION}, + StarterRngNotifications{ + .shiny = NOTIFICATION_SHINY, + .status_update = NOTIFICATION_STATUS_UPDATE, + .error_recoverable = NOTIFICATION_ERROR_RECOVERABLE, + }, + stats + ); + StarterRngResult result = attempts.run(env, context); + if (result.outcome == StarterRngOutcome::no_matches){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "Failed to find any matches 5 times in a row. Check your seed and advances settings.", + env.console + ); } if (GO_HOME_WHEN_DONE){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h index 4e99f55bda..80eb28aed6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h @@ -12,12 +12,13 @@ #include "Common/Cpp/Options/StaticTextOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Pokemon_StatsCalculation.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngAttempts.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -26,13 +27,16 @@ namespace PokemonFRLG{ class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ public: StarterRng_Descriptor(); - struct Stats; + using Stats = StarterRngStats; virtual std::unique_ptr make_stats() const override; }; -class StarterRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a starter. +class StarterRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = StarterRng_Descriptor; + // The party is empty before the starter, so there is nothing to check. + virtual size_t free_party_slots_needed() const override{ return 0; } ~StarterRng(); StarterRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; @@ -44,36 +48,11 @@ class StarterRng : public SingleSwitchProgramInstance, private ConfigOption::Lis private: virtual void on_config_value_changed(void* object) override; - enum class Starter{ - bulbasaur, - squirtle, - charmander - }; - enum class GameVersion{ firered, leafgreen }; - bool walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool auto_battle_rival( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS - ); - - bool walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - int autolevel_on_route1( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AdvObservedPokemon& pokemon, - AdvRngFilters& filters, - const BaseStats& BASE_STATS - ); - SectionDividerOption m_calibration_displays; RngTargetDisplay RNG_TARGET; RngFilterDisplay RNG_FILTERS; @@ -85,7 +64,7 @@ class StarterRng : public SingleSwitchProgramInstance, private ConfigOption::Lis EnumDropdownOption SOUND; SectionDividerOption m_target_settings; - EnumDropdownOption STARTER; + EnumDropdownOption STARTER; StringOption SEED; SimpleIntegerOptionADVANCES; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp new file mode 100644 index 0000000000..a42d25e781 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp @@ -0,0 +1,845 @@ +/* Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattlePokemonDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleLevelUpReader.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_HardReset.h" +#include "PokemonFRLG_RngNavigation.h" +#include "PokemonFRLG_StarterRngAttempts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate + +const uint64_t CONTINUE_SCREEN_FRAMES = 200; + +const uint64_t INITIAL_ADVANCES_RADIUS = 1024; + +const uint8_t MAX_HISTORY_LENGTH = 10; + +const int16_t GENDER_THRESHOLD = 30; + +const std::set& starter_species(){ + static const std::set SPECIES_LIST = { "bulbasaur", "squirtle", "charmander" }; + return SPECIES_LIST; +} + +} // namespace + + +BaseStats starter_base_stats(StarterSpecies starter){ + switch (starter){ + case StarterSpecies::bulbasaur: + return { 45, 49, 49, 65, 65, 45 }; + case StarterSpecies::squirtle: + return { 44, 48, 65, 50, 64, 43 }; + case StarterSpecies::charmander: + return { 39, 52, 43, 60, 50, 65 }; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + +EVs rival_ev_yield(StarterSpecies starter){ + Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; + switch(starter){ + case StarterSpecies::bulbasaur: + evyield.speed = 1; // from charmander + break; + case StarterSpecies::squirtle: + evyield.spatk = 1; // from bulbasaur + break; + case StarterSpecies::charmander: + evyield.defense = 1; // from squirtle + } + return evyield; +} + +int steps_left_to_lab_door(StarterSpecies starter){ + switch(starter){ + case StarterSpecies::bulbasaur: + return 2; + case StarterSpecies::squirtle: + return 3; + case StarterSpecies::charmander: + return 4; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + + +StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits){ + if (hits.empty()){ + return StarterRngOutcome::shiny; + } + const bool on_target = std::any_of(hits.begin(), hits.end(), [&](const AdvRngState& hit){ + return have_hit_target(seed, advances, hit); + }); + return on_target ? StarterRngOutcome::shiny_on_target : StarterRngOutcome::shiny_off_target; +} + +std::optional reset_hit( + const RngUncertainHistory& uncertain, const RngCalibrationHistory& calibration, const std::vector& hits +){ + // update_history() clears `uncertain` only when it takes a hit, and adds + // the reset's last after the earlier ones it settles. + if (hits.empty() || !uncertain.results.empty() || calibration.results.empty()){ + return std::nullopt; + } + return calibration.results.back(); +} + + +StarterRngStats::StarterRngStats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , nonshiny(m_stats["Non-Shiny Hits"]) + , wildshinies(m_stats["Wild Shinies"]) + , errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Non-Shiny Hits", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Wild Shinies", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); +} + + +StarterRngAttempts::StarterRngAttempts( + StarterRngTarget target, + StarterRngSettings settings, + const StarterRngDisplays& displays, + const StarterRngNotifications& notifications, + StarterRngStats& stats +) + : m_target(std::move(target)) + , m_settings(std::move(settings)) + , m_displays(displays) + , m_notifications(notifications) + , m_stats(stats) + , m_base_stats(starter_base_stats(m_target.starter)) + , m_searcher(m_target.seed, m_target.advances, AdvRngMethod::Method1) + , m_launch_delay(INITIAL_LAUNCH_DELAY) +{} + + +StarterRngResult StarterRngAttempts::run(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("RNG Target: " + std::to_string(static_cast(m_target.starter))); + env.log("Target Seed: " + to_hex_string(m_target.seed)); + env.log("Target Advances: " + std::to_string(m_target.advances)); + + AdvPokemonResult target_result = m_searcher.generate_pokemon(); + m_displays.target.set_target(target_result, GENDER_THRESHOLD); + log_target_pokemon(env.console, target_result); + + m_calibrations = { + m_displays.calibration.seed_calibration / FRLG_FRAME_DURATION, + m_displays.calibration.csf_calibration, + m_displays.calibration.advances_calibration + }; + log_calibrations(env.console, m_calibrations, true); + + while (true){ + std::optional outcome = finished(env); + if (outcome){ + StarterRngResult result{.outcome = *outcome, .pokemon = std::nullopt}; + if (*outcome == StarterRngOutcome::target_hit){ + result.pokemon = target_result; + } + return result; + } + + reset_game(env, context); + + if (check_shiny_starter(env, context)){ + const StarterRngOutcome shiny = m_settings.identify_shiny ? identify_shiny_starter(env, context) : StarterRngOutcome::shiny; + const bool on_target = shiny == StarterRngOutcome::shiny_on_target; + report_read(true); + return StarterRngResult{.outcome = shiny, .pokemon = on_target ? std::optional(target_result) : std::nullopt}; + } + + run_attempt(env, context); + report_read(false); + } +} + +void StarterRngAttempts::report_read(bool shiny){ + if (m_settings.on_read){ + m_settings.on_read(RngResetRead{ + .resets = m_stats.resets.load(), + .hits = m_search_hits, + .hit = shiny ? std::nullopt : reset_hit(m_uncertain_history, m_calibration_history, m_search_hits), + .shiny = shiny, + }); + } +} + +std::optional StarterRngAttempts::finished(SingleSwitchProgramEnvironment& env){ + if (m_calibration_history.results.size() > 0){ + env.log("Checking for nonshiny target hit..."); + if (have_hit_target(m_target.seed, m_target.advances, m_calibration_history.results.back())){ + env.log("Target Hit!"); + m_stats.nonshiny++; + return StarterRngOutcome::target_hit; + } + env.log("Missed target."); + } + + if (m_failed_searches >= 5){ + env.log("Failed to find any matches 5 times in a row"); + return StarterRngOutcome::no_matches; + } + + if (m_stats.resets > m_settings.max_resets()){ + env.log("Max resets reached."); + return StarterRngOutcome::out_of_resets; + } + + if (m_wildshiny_found){ + return StarterRngOutcome::wild_shiny; + } + + return std::nullopt; +} + +void StarterRngAttempts::reset_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + send_program_status_notification( + env, m_notifications.status_update, + "Calibrating." + ); + env.update_stats(); + + + m_advances_radius = get_advances_radius(env.console, m_calibration_history, INITIAL_ADVANCES_RADIUS); + + const SeedMatch& seed_match = m_target.seed_match; + if (m_calibration_history.results.size() > 0){ + m_calibrations = get_calibrations(env.console, m_calibration_history, seed_match.seed_values, seed_match.seed_position, m_target.advances); + } + + // if previous resets had uncertain advances, slightly modify the seed delay to try to hit a different target + apply_seed_bump(m_calibrations, m_uncertain_history); + + uint64_t ingame_advances = m_target.advances - CONTINUE_SCREEN_FRAMES; + + RngTimings timings = prepare_timings( + env.console, PokemonFRLG_RngTarget::starters, + seed_match.seed_delay, CONTINUE_SCREEN_FRAMES, ingame_advances, + false, m_calibrations, + FIXED_SEED_OFFSET + ); + + env.log("Resetting Game..."); + reset_and_perform_blind_sequence( + env.console, context, + m_settings.language, PokemonFRLG_RngTarget::starters, + seed_match.seed_button, seed_match.extra_button, timings, + m_launch_delay, false, m_settings.profile + ); + m_stats.resets++; + m_search_hits.clear(); + if (m_settings.on_reset){ + m_settings.on_reset(StarterRngProgress{.resets = m_stats.resets.load(), .calibrations = m_calibrations}); + } + + m_displays.filters.reset(); + m_displays.calibration.set_calibrations(m_calibrations); + m_displays.calibration.reset_hits(); +} + +bool StarterRngAttempts::check_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + bool shiny_found = check_for_shiny(env.console, context, PokemonFRLG_RngTarget::starters); + + if (shiny_found){ + env.log("Shiny found!"); + m_stats.shinies++; + m_displays.calibration.hits.set("Shiny!"); + send_shiny_notification(env, context, "Shiny found!"); + } + return shiny_found; +} + +// On the shiny's summary, as check_for_shiny() leaves it: reads it as +// stage 1 of an attempt does and searches near the target. +StarterRngOutcome StarterRngAttempts::identify_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvObservedPokemon pokemon = read_summary(env.console, context, m_settings.language, starter_species()); + pokemon.level[0] = 5; + AdvRngFilters filters = observation_to_filters(pokemon, m_base_stats); + m_displays.filters.set(filters); + const std::vector hits = search(env, filters); + m_displays.calibration.set_hits(hits); + const StarterRngOutcome outcome = identify_shiny(m_target.seed, m_target.advances, hits); + env.log(std::format( + "Shiny starter: {} states near the target match it; {}.", hits.size(), + outcome == StarterRngOutcome::shiny_on_target ? "the target is one of them" + : outcome == StarterRngOutcome::shiny_off_target ? "the target isn't" : "not known if it is the target" + )); + return outcome; +} + +void StarterRngAttempts::send_shiny_notification( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, const std::string& title +){ + VideoSnapshot screen = env.console.video().snapshot(); + send_program_notification( + env, + m_notifications.shiny, + COLOR_YELLOW, + title, + {}, "", + screen, + true + ); + if (m_settings.take_video){ + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); + } +} + +std::vector StarterRngAttempts::search(SingleSwitchProgramEnvironment& env, AdvRngFilters& filters){ + m_search_hits = get_search_results( + env.console, m_searcher, filters, m_target.seed_match.seed_values, + m_target.advances, m_advances_radius, GENDER_THRESHOLD + ); + return m_search_hits; +} + +void StarterRngAttempts::record_error(SingleSwitchProgramEnvironment& env, const std::vector& search_hits){ + update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 1, 2, true + ); + m_stats.errors++; +} + + +void StarterRngAttempts::run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Stage 1: initial search -- starter received + AdvObservedPokemon pokemon = read_summary(env.console, context, m_settings.language, starter_species()); + pokemon.level[0] = 5; + AdvRngFilters filters = observation_to_filters(pokemon, m_base_stats); + m_displays.filters.set(filters); + + std::vector search_hits = search(env, filters); + m_displays.calibration.set_hits(search_hits); + bool finished = update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 1 + ); + if (finished){ + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); + return; + } + + if (!run_rival_stage(env, context, pokemon, filters, search_hits)){ + return; + } + run_route1_stage(env, context, pokemon, filters, search_hits); +} + +// Returns false when the attempt ends here. +bool StarterRngAttempts::run_rival_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits +){ + // Stage 2: first search update -- post-rival-battle + bool failed = walk_to_rival_battle(env, context); + if (failed){ + record_error(env, search_hits); + return false; // reset game + } + + failed = auto_battle_rival(env, context, pokemon, filters); + if (failed){ + record_error(env, search_hits); + return false; // reset game + } + if (pokemon.level.size() > 1){ + search_hits = search(env, filters); + m_displays.calibration.set_hits(search_hits); + env.log("Number of search hits: " + std::to_string(search_hits.size())); + bool finished = update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 5 + ); + if (finished){ + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); + return false; + } + } + return true; +} + +void StarterRngAttempts::run_route1_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits +){ + // Stage 3: subsequent search updates -- leveling up from wild encounters + bool failed = walk_to_route1_from_lab(env, context); + if (failed){ + record_error(env, search_hits); + return; // reset game + } + + auto num_levels = pokemon.level.size(); + uint16_t MAX_LEVELS = 3; + while(true){ + if (num_levels > MAX_LEVELS){ + env.log("RNG search not complete after 3 level-ups."); + update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 5, 2, true + ); + return; + } + + env.log("Level: " + std::to_string(4 + pokemon.level.size())); + env.log("Speed EVs: " + std::to_string(pokemon.evs.back().speed)); + + int ret2 = autolevel_on_route1(env, context, pokemon, filters); + if (ret2 < 0){ + record_error(env, search_hits); + return; + }else if(ret2 == 1){ + if (stop_on_wild_shiny(env, context)){ + return; + } + } + + // force the search to finish after enough level-ups + if (pokemon.level.size() > num_levels){ + finish_search(env, filters, search_hits); + return; + } + } +} + +// Returns whether the attempts stop for the wild shiny. +bool StarterRngAttempts::stop_on_wild_shiny(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Wild shiny found!"); + m_stats.wildshinies++; + send_shiny_notification(env, context, "Wild Shiny found!"); + if (!m_settings.ignore_wild_shinies){ + m_wildshiny_found = true; + return true; + } + return false; +} + +void StarterRngAttempts::finish_search( + SingleSwitchProgramEnvironment& env, AdvRngFilters& filters, std::vector& search_hits +){ + search_hits = search(env, filters); + m_displays.calibration.set_hits(search_hits); + env.log("Number of search hits: " + std::to_string(search_hits.size())); + update_history( + env.console, m_uncertain_history, m_calibration_history, + MAX_HISTORY_LENGTH, m_calibrations, search_hits, 5, 2, true + ); + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); +} + + +bool StarterRngAttempts::walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // return to the overworld + pbf_mash_button(context, BUTTON_B, 5000ms); + int num_steps_to_the_left = steps_left_to_lab_door(m_target.starter); + + // dodge rival + pbf_move_left_joystick(context, {0, -1}, 40ms, 460ms); + pbf_move_left_joystick(context, {0, -1}, 100ms, 400ms); + + // line up with the doorway + pbf_move_left_joystick(context, {-1, 0}, 40ms, 460ms); // pivot left + for (int i=0; i( + env.console, context, + [](ProControllerContext& context){ + for (int i=0; i<5; i++){ + ssf_press_left_joystick(context, {0, -1}, 0ms, 20000ms, 0ms); + ssf_mash1_button(context, BUTTON_B, 20000ms); + } + }, + { black_screen } + ); + + bool failed = ret < 0; + if (failed){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "walk_to_rival_battle(): failed to initiate battle." + ); + } + return failed; +} + +// From the start of the rival battle: waits for the battle menu, uses the +// first move and waits out Oak's tutorial. Returns true on failure. +bool StarterRngAttempts::start_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // detect the battle menu + BattleMenuWatcher battle_ready(COLOR_RED); + context.wait_for_all_requests(); + int ret1 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 30s); + }, + { battle_ready } + ); + if (ret1 < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "auto_battle_rival(): failed to detect the battle menu." + ); + return true; + } + env.log("Battle started. Using first move..."); + + // perform the first move and get through Oak's dialogue, + // which messes up most detectors when it dims the screen + pbf_mash_button(context, BUTTON_A, 1000ms); // execute first move + context.wait_for_all_requests(); + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 30s); + }, + { battle_ready } + ); + if (ret2 < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "auto_battle_rival(): failed to detect the battle menu." + ); + return true; + } + env.log("Oak tutorial dialogue finished. Mashing A..."); + return false; +} + +bool StarterRngAttempts::auto_battle_rival( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters +){ + Pokemon::EVs evyield = rival_ev_yield(m_target.starter); + + if (start_rival_battle(env, context)){ + return true; + } + + // mash A until somebody faints + BattleOpponentFaintWatcher player_won(COLOR_RED); + BattleFaintWatcher player_lost(COLOR_RED); + context.wait_for_all_requests(); + int ret3 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 300s); + }, + { player_won, player_lost } + ); + + switch(ret3){ + case 0: + env.log("Won battle against rival. Watching for level-up stats..."); + break; + case 1: + env.log("Lost battle against rival."); + pbf_mash_button(context, BUTTON_B, 20s); // exit battle and dialogue + return false; + default: + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "auto_battle_rival(): no fainting detected with 5 minutes." + ); + return true; + } + + return read_rival_level_up(env, context, pokemon, filters, evyield); +} + +// After winning the rival battle: reads the level-up stats and leaves the +// battle. Returns true on failure. +bool StarterRngAttempts::read_rival_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield +){ + // slowly advance dialog until level-up stats are visible + BattleLevelUpWatcher level_up_stats(COLOR_RED, BattleLevelUpDialog::stats, m_settings.language); + BlackScreenWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret4 = run_until( + env.console, context, + [](ProControllerContext& context){ + for(int i=0; i<60; i++){ + pbf_press_button(context, BUTTON_A, 200ms, 1800ms); + } + }, + { level_up_stats, black_screen } + ); + + switch(ret4){ + case 0: + env.log("Level-up stats detected."); + break; + case 1: + env.log("Battle exited without detecting level-up stats"); + return true; // will cause issues with keeping track of level and EVs + default: + env.log("auto_battle_rival(): no recognized state within 2 minutes of winning battle."); + return true; + } + + read_rival_level_up_stats(env, pokemon, filters, evyield); + + // exit battle + pbf_mash_button(context, BUTTON_B, 20s); + context.wait_for_all_requests(); + + return false; +} + +void StarterRngAttempts::read_rival_level_up_stats( + SingleSwitchProgramEnvironment& env, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield +){ + // read stats + BattleLevelUpReader reader(COLOR_RED); + VideoOverlaySet overlays(env.console.overlay()); + reader.make_overlays(overlays); + + env.log("Reading stats..."); + VideoSnapshot screen = env.console.video().snapshot(); + StatReads stats = reader.read_stats(env.logger(), screen); + + update_filters(filters, pokemon, stats, evyield, m_base_stats); + m_displays.filters.set(filters); +} + + + +bool StarterRngAttempts::walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // exit the lab + env.log("Exiting the lab..."); + BlackScreenWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, {0, -1}, 10s, 0ms); + }, + { black_screen } + ); + + if (ret < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "walk_to_route1_from_lab(): failed to exit lab." + ); + return true; + } + + env.log("Lab exited. Walking to Route 1..."); + pbf_wait(context, 5000ms); + pbf_move_left_joystick(context, {-1, 0}, 1280ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 3150ms, 300ms); + pbf_move_left_joystick(context, {+1, 0}, 330ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 720ms, 300ms); + context.wait_for_all_requests(); + return false; +} + +bool StarterRngAttempts::walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // exit the house + env.log("Exiting the house..."); + BlackScreenWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); + pbf_move_left_joystick(context, {-1, 0}, 900ms, 300ms); + pbf_move_left_joystick(context, {0, -1}, 1000ms, 300ms); + }, + { black_screen } + ); + + if (ret < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "walk_to_route1_from_home(): failed to exit the house." + ); + return true; + } + + env.log("House exited. Walking to Route 1..."); + pbf_wait(context, 5s); + pbf_move_left_joystick(context, {+1, 0}, 1370ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 1450ms, 300ms); + pbf_move_left_joystick(context, {+1, 0}, 300ms, 300ms); + pbf_move_left_joystick(context, {0, +1}, 1250ms, 300ms); + + return false; +} + +int StarterRngAttempts::autolevel_on_route1( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters +){ + Pokemon::EVs evyield = {0, 0, 0, 0, 0, 0}; + + env.log("Arrived at Route 1."); + bool leftright = true; + context.wait_for_all_requests(); + + while (true){ + int ret = trigger_route1_encounter(env, context, leftright); + if (ret < 0){ + return -1; + } + + if (ret == 1){ // shiny + return 1; + } + + // auto battle + BattleResult ret2 = spam_first_move(env.console, context); + + switch (ret2){ + case BattleResult::opponentfainted: + env.log("Opponent fainted."); + evyield.speed++; // always rattata or pidgey + leftright = !leftright; + if (read_wild_level_up(env, context, pokemon, filters, evyield)){ + return 0; + } + continue; + case BattleResult::playerfainted: + if (return_to_route1_after_faint(env, context)){ + return -1; + } + leftright = true; + continue; + case BattleResult::outofpp: + case BattleResult::unknown: + default: + return -1; + } + } +} + +// Spins in the grass until a wild encounter. Returns grass_spin()'s result. +int StarterRngAttempts::trigger_route1_encounter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool leftright +){ + // trigger encounter + env.log("Triggering wild encounters..."); + int ret = grass_spin(env.console, context, leftright); + if (ret < 0){ + send_program_recoverable_error_notification( + env, m_notifications.error_recoverable, + "autolevel_on_route1(): failed to trigger encounter." + ); + } + return ret; +} + +// After the player's Pokemon fainted: walks from home back to Route 1. +// Returns true on failure. +bool StarterRngAttempts::return_to_route1_after_faint(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Pokemon fainted. Mashing B through dialogues..."); + pbf_mash_button(context, BUTTON_B, 30s); // skip through a few transitions and lots of dialogue + if (walk_to_route1_from_home(env, context)){ + return true; + } + context.wait_for_all_requests(); + return false; +} + +// After a wild Pokemon fainted: reads the level-up stats if they show and +// leaves the battle. Returns whether the stats were read. +bool StarterRngAttempts::read_wild_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield +){ + BattleLevelUpWatcher level_up(COLOR_RED, BattleLevelUpDialog::stats, m_settings.language); + BlackScreenWatcher black_screen(COLOR_RED); + BattleLevelUpReader reader; + + context.wait_for_all_requests(); + int ret3 = run_until( + env.console, context, + [](ProControllerContext& context){ + for (int i=0; i<5; i++){ + pbf_press_button(context, BUTTON_B, 200ms, 1800ms); + } + }, + { level_up, black_screen } + ); + + switch (ret3){ + case 0:{ + env.log("Level-up stats detected. Reading stats..."); + VideoSnapshot screen = env.console.video().snapshot(); + Pokemon::StatReads stats = reader.read_stats(env.logger(), screen); + update_filters(filters, pokemon, stats, evyield, m_base_stats); + m_displays.filters.set(filters); + exit_wild_battle(env.console, context, false, true); + return true; + } + case -1: + exit_wild_battle(env.console, context, false, true); + [[fallthrough]]; + default: + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + return false; + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h new file mode 100644 index 0000000000..c9a2d47116 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h @@ -0,0 +1,213 @@ +/* Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + * Starter RNG's reset, calibrate and attempt loop, for one target. The + * Starter RNG program runs it with its options, stats and displays; another + * program (AutoStory) can run it with its own. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngAttempts_H +#define PokemonAutomation_PokemonFRLG_StarterRngAttempts_H + +#include +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_AdvRng.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_SeedsDatabase.h" +#include "PokemonFRLG_StarterRngOutcome.h" +#include "PokemonFRLG_StarterRngTarget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What a reset's reads came to, once its search is done. Gift RNG's +// attempts report theirs this way too. +struct RngResetRead{ + uint64_t resets = 0; + // The states near the target that the Pokemon read matches. + std::vector hits; + // The one the calibration took as hit; none when it couldn't tell. + std::optional hit; + // Shiny right after the reset; `hits` are then its summary's. + bool shiny = false; +}; + +// The state update_history() took as hit for a reset whose last search +// found `hits`: the newest in `calibration`. It takes none for no hits, and +// none for a tie between advances, which it leaves in `uncertain`. +std::optional reset_hit( + const RngUncertainHistory& uncertain, const RngCalibrationHistory& calibration, const std::vector& hits +); + +// Console and game environment settings for starter RNG. +struct StarterRngSettings{ + Language language = Language::None; + // The Switch profile's position on the user selection screen; 0 for + // the default. + uint8_t profile = 0; + bool ignore_wild_shinies = false; + // Record a video when a shiny is found. + bool take_video = false; + // After a shiny, read its summary and search for the state hit, to + // tell whether it was the target (shiny_on_target or + // shiny_off_target). Off, the attempts end on the shiny at once. + bool identify_shiny = false; + // Read before each reset, since Starter RNG lets the user change it + // while running. + std::function max_resets; + // Called after each reset, if set, for a caller that logs the attempts. + std::function on_reset; + // Called after each reset's reads, if set, as on_reset is. + std::function on_read; +}; + +// Where the attempts show the target, the filters read so far and the +// calibration. The calibration display also holds the starting +// calibration. +struct StarterRngDisplays{ + RngTargetDisplay& target; + RngFilterDisplay& filters; + RngCalibrationDisplay& calibration; +}; + +// Notification event options for starter RNG outcomes. +struct StarterRngNotifications{ + EventNotificationOption& shiny; + EventNotificationOption& status_update; + EventNotificationOption& error_recoverable; +}; + + +// Complete result report from starter RNG execution. +struct StarterRngResult{ + StarterRngOutcome outcome = StarterRngOutcome::out_of_resets; + // The target's PID, nature and IVs, on target_hit and shiny_on_target. + std::optional pokemon; +}; + + +// Manages execution loop and tracking for starter resets. +class StarterRngAttempts{ +public: + StarterRngAttempts( + StarterRngTarget target, + StarterRngSettings settings, + const StarterRngDisplays& displays, + const StarterRngNotifications& notifications, + StarterRngStats& stats + ); + StarterRngAttempts(const StarterRngAttempts&) = delete; + StarterRngAttempts& operator=(const StarterRngAttempts&) = delete; + + // From the HOME menu with the game closed: resets the game and takes + // the starter at the target's timing until the outcome is known. Each + // non-shiny starter is read, battled against the rival and leveled on + // Route 1 to find the state hit and recalibrate. Ends in the game on + // the last screen the attempts reached. Call once per object. + StarterRngResult run(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + std::optional finished(SingleSwitchProgramEnvironment& env); + void reset_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool check_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + StarterRngOutcome identify_shiny_starter(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void send_shiny_notification(SingleSwitchProgramEnvironment& env, ProControllerContext& context, const std::string& title); + std::vector search(SingleSwitchProgramEnvironment& env, AdvRngFilters& filters); + void record_error(SingleSwitchProgramEnvironment& env, const std::vector& search_hits); + void report_read(bool shiny); + + void run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool run_rival_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits + ); + void run_route1_stage( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + AdvObservedPokemon& pokemon, AdvRngFilters& filters, std::vector& search_hits + ); + bool stop_on_wild_shiny(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void finish_search( + SingleSwitchProgramEnvironment& env, AdvRngFilters& filters, std::vector& search_hits + ); + + bool walk_to_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool start_rival_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool auto_battle_rival( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters + ); + bool read_rival_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield + ); + void read_rival_level_up_stats( + SingleSwitchProgramEnvironment& env, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield + ); + + bool walk_to_route1_from_lab(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool walk_to_route1_from_home(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + int trigger_route1_encounter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool leftright + ); + bool return_to_route1_after_faint(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + int autolevel_on_route1( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters + ); + bool read_wild_level_up( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AdvObservedPokemon& pokemon, + AdvRngFilters& filters, + const EVs& evyield + ); + + const StarterRngTarget m_target; + const StarterRngSettings m_settings; + StarterRngDisplays m_displays; + StarterRngNotifications m_notifications; + StarterRngStats& m_stats; + const BaseStats m_base_stats; + + AdvRngSearcher m_searcher; + RngCalibrations m_calibrations{}; + Milliseconds m_launch_delay; + RngUncertainHistory m_uncertain_history; + RngCalibrationHistory m_calibration_history; + uint64_t m_advances_radius = 0; + bool m_wildshiny_found = false; + uint16_t m_failed_searches = 0; + // The last search's hits, for on_read. + std::vector m_search_hits; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp new file mode 100644 index 0000000000..3a914823e7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp @@ -0,0 +1,117 @@ +/* Starter RNG Console Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonFRLG_StarterRngConsoleSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngPlanLogger::RngPlanLogger(ConsoleHandle& console) + : m_console(console) +{} + +void RngPlanLogger::log(const std::string& msg, Color color){ + m_console.log(msg, color); + if (msg.starts_with("RngPlan: result")){ + m_console.overlay().add_log(msg); + } +} + + +std::function reset_line_logger( + ConsoleHandle& console, std::string_view program, const RngAttempt& attempt, const SeedMatch& seed_match, uint64_t max_resets +){ + RngResetLine line{ + .program = program, .max_resets = max_resets, + .target_seed = attempt.target.seed.seed, .target_advances = attempt.target.advances, + .seed_values = seed_match.seed_values, .seed_position = seed_match.seed_position, + .read = {}, + }; + return [&console, line](const RngResetRead& read){ + RngResetLine reset = line; + reset.read = read; + const std::string text = rng_reset_line(reset); + console.log(text); + console.overlay().add_log(text); + }; +} + + +ConsoleStarterRngSteps::ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications +) + : m_env(env) + , m_context(context) + , m_settings(settings) + , m_notifications(notifications) + // TODO: LeafGreen, once AutoStory plays it. + , m_seeds(seeds_json_path(true, settings.language)) +{ + m_calibration_display.set_calibrations(settings.calibration); +} + +WallClock ConsoleStarterRngSteps::now(){ + return current_time(); +} + +StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ + // Starter RNG's default Nearby Seed Radius. + const int SEED_RADIUS = 5; + const SeedMatch seed_match = m_seeds.find_seed(attempt.target.seed.seed, m_settings.sound, SEED_RADIUS); + if (!seed_match.found){ + throw InternalProgramError(&m_env.logger(), PA_CURRENT_FUNCTION, "The plan's seed isn't in the seed list it came from."); + } + + StarterRngStats stats; + StarterRngAttempts attempts( + StarterRngTarget{ + .starter = StarterSpecies::squirtle, + .seed = attempt.target.seed.seed, + .advances = attempt.target.advances, + .seed_match = seed_match, + }, + StarterRngSettings{ + .language = m_settings.language, + .profile = 0, + .ignore_wild_shinies = true, + .take_video = false, + .identify_shiny = true, + .max_resets = [deadline = call.deadline, max_resets = call.max_resets]{ + return current_time() >= deadline ? uint64_t(0) : max_resets; + }, + .on_reset = call.on_reset, + .on_read = reset_line_logger(m_env.console, "Starter RNG", attempt, seed_match, call.max_resets), + }, + StarterRngDisplays{ + .target = m_target_display, + .filters = m_filter_display, + .calibration = m_calibration_display, + }, + m_notifications, + stats + ); + try{ + return attempts.run(m_env, m_context); + }catch (OperationFailedException& e){ + // Starter RNG refuses timings it can't press (check_timings()) this + // way; a failure in the game sends an error report. + if (e.error_report_mode() != ErrorReportMode::NO_ERROR_REPORT){ + throw; + } + throw StarterRngTimingsRefused(e.message()); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h new file mode 100644 index 0000000000..5baafa8774 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h @@ -0,0 +1,94 @@ +/* Starter RNG Console Steps + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's steps (PokemonFRLG_StarterRngLoop.h) on the + * console, and the log it writes to. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H +#define PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H + +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngDisplays.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The console's log, with the loop's result lines also on the stream's +// overlay log. Its state lines, too long for it, stay in the log. +class RngPlanLogger : public Logger{ +public: + explicit RngPlanLogger(ConsoleHandle& console); + virtual void log(const std::string& msg, Color color = Color()) override; + +private: + ConsoleHandle& m_console; +}; + + +// An on_read for `program`'s tries at `attempt`, which puts each reset's +// line (rng_reset_line()) on the console's log and its stream's overlay +// log. `program` is a literal, as "Starter RNG". +std::function reset_line_logger( + ConsoleHandle& console, std::string_view program, const RngAttempt& attempt, const SeedMatch& seed_match, uint64_t max_resets +); + + +// Console hardware and audio setup for starter manipulation. +struct StarterRngConsoleSettings{ + Language language = Language::English; + SoundSetting sound = SoundSetting::Mono; + // The calibration the first try starts from. + RngCalibrations calibration = {}; +}; + +// The loop's steps on the console, with Starter RNG's displays, stats and +// calibration kept here (AutoStory doesn't show them). Each try after the +// first starts from the calibration the last one ended with, and each +// reset puts one line (rng_reset_line()) on the log and the stream's +// overlay log. Squirtle, FireRed, the Switch's default profile. +class ConsoleStarterRngSteps : public StarterRngLoopSteps{ +public: + ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications + ); + + virtual WallClock now() override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; + +private: + SingleSwitchProgramEnvironment& m_env; + ProControllerContext& m_context; + StarterRngConsoleSettings m_settings; + StarterRngNotifications m_notifications; + SeedsDatabase m_seeds; + RngTargetDisplay m_target_display; + RngFilterDisplay m_filter_display; + RngCalibrationDisplay m_calibration_display; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp new file mode 100644 index 0000000000..63e17835ab --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp @@ -0,0 +1,337 @@ +/* Starter RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_StarterRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny_on_target: + return RngAttemptOutcome::SHINY; + case StarterRngOutcome::shiny: + case StarterRngOutcome::shiny_off_target: + return RngAttemptOutcome::SHINY_OFF_TARGET; + case StarterRngOutcome::target_hit: + return RngAttemptOutcome::HIT_NOT_SHINY; + case StarterRngOutcome::wild_shiny: + case StarterRngOutcome::out_of_resets: + case StarterRngOutcome::no_matches: + return RngAttemptOutcome::MISSED; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + +std::string starter_rng_outcome_name(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: + return "shiny"; + case StarterRngOutcome::shiny_on_target: + return "shiny_on_target"; + case StarterRngOutcome::shiny_off_target: + return "shiny_off_target"; + case StarterRngOutcome::target_hit: + return "target_hit"; + case StarterRngOutcome::wild_shiny: + return "wild_shiny"; + case StarterRngOutcome::out_of_resets: + return "out_of_resets"; + case StarterRngOutcome::no_matches: + return "no_matches"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + + +namespace{ + +// "-" for none. +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text.empty() ? "-" : text; +} + +std::string clock_text(Milliseconds time){ + const int64_t seconds = std::chrono::duration_cast(time).count(); + return std::format("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60); +} + +std::string calibration_text(const std::optional& calibration){ + if (!calibration){ + return "-"; + } + return std::format("{:.2f}/{:.2f}/{:.2f}", calibration->seed_offset, calibration->csf_offset, calibration->ingame_offset); +} + +} // namespace + +std::string rng_log_state(const RngLoopState& state){ + return std::format( + "RngPlan: state attempt={}/{} try={}/{} reset={}/{} seed={:04X} advances={} sids={} ruled_out={} " + "attempt_time={}/{} total_time={}/{} calibration={}", + state.attempt, state.attempts, state.try_number, state.tries, state.resets, state.max_resets, + state.seed, state.advances, join_sids(state.sids), join_sids(state.ruled_out), + clock_text(state.attempt_time), clock_text(state.attempt_cap), + clock_text(state.total_time), clock_text(state.total_cap), + calibration_text(state.calibration) + ); +} + + +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed){ + const auto found = std::find(seed_values.begin(), seed_values.end(), seed); + if (target_position < 0 || found == seed_values.end()){ + return std::nullopt; + } + return int(found - seed_values.begin()) - target_position; +} + +namespace{ + +std::string seed_text(const RngResetLine& line, uint16_t seed){ + if (seed == line.target_seed){ + return std::format("seed {:04x} = target", seed); + } + const std::optional frames = seed_frame_offset(line.seed_values, line.seed_position, seed); + if (!frames){ + return std::format("seed {:04x} (not near the target)", seed); + } + return std::format( + "seed {:04x} ({:+} frame{} {})", seed, *frames, std::abs(*frames) == 1 ? "" : "s", *frames > 0 ? "late" : "early" + ); +} + +std::string advance_text(uint64_t target, uint64_t advance){ + if (advance == target){ + return std::format("advance {}", advance); + } + return std::format("advance {} (target {}, {:+})", advance, target, int64_t(advance) - int64_t(target)); +} + +size_t distinct_states(const std::vector& hits){ + std::set> states; + for (const AdvRngState& hit : hits){ + states.emplace(hit.seed, hit.advance); + } + return states.size(); +} + +std::string shiny_text(const RngResetLine& line){ + const std::vector& hits = line.read.hits; + const bool on_target = std::any_of(hits.begin(), hits.end(), [&](const AdvRngState& hit){ + return have_hit_target(line.target_seed, line.target_advances, hit); + }); + if (on_target){ + return seed_text(line, line.target_seed) + ", " + advance_text(line.target_advances, line.target_advances) + ". HIT, shiny!"; + } + return hits.empty() ? "shiny, not known if on the target." : "shiny, not on the target."; +} + +} // namespace + +std::string rng_reset_line(const RngResetLine& line){ + const RngResetRead& read = line.read; + const std::string head = std::format("{} try {}/{}: ", line.program, read.resets, line.max_resets); + if (read.shiny){ + return head + shiny_text(line); + } + const size_t states = distinct_states(read.hits); + std::optional hit = read.hit; + if (!hit && states == 1){ + hit = read.hits.front(); + } + if (!hit){ + return head + (states == 0 + ? std::string("no match read (stats fit no seed/advance).") + : std::format("{} possible matches, can't tell which.", states)); + } + const bool on_target = have_hit_target(line.target_seed, line.target_advances, *hit); + return head + seed_text(line, hit->seed) + ", " + advance_text(line.target_advances, hit->advance) + + (on_target ? ". HIT, not shiny." : ". Missed."); +} + + +namespace{ + +std::optional loop_end(RngPlanStep step){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return std::nullopt; + case RngPlanStep::GOT_SHINY: + return StarterRngLoopEnd::SHINY; + case RngPlanStep::GOT_SHINY_OFF_TARGET: + return StarterRngLoopEnd::SHINY_OFF_TARGET; + case RngPlanStep::GOT_TARGET: + return StarterRngLoopEnd::TARGET; + case RngPlanStep::OUT_OF_ATTEMPTS: + return StarterRngLoopEnd::OUT_OF_ATTEMPTS; + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: + return StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); +} + +// The loop's state lines and tries, across the attempts. +class LoopLog{ +public: + LoopLog(Logger& logger, const RngPlanTracker& tracker, const StarterRngLoopLimits& limits, WallClock start) + : m_logger(logger) + , m_tracker(tracker) + , m_limits(limits) + , m_start(start) + , m_start_sids(tracker.remaining_sids()) + {} + + // A new try of the tracker's current attempt, starting at `now`. + void begin_try(WallClock now){ + const size_t index = m_tracker.attempt_index(); + m_try = (m_tries_of && *m_tries_of == index) ? m_try + 1 : 1; + m_tries_of = index; + m_try_start = now; + } + size_t try_number() const{ + return m_try; + } + + void log_state(WallClock now, uint64_t resets, const std::optional& calibration){ + const RngAttempt& attempt = m_tracker.current_attempt(); + std::vector ruled_out; + for (uint16_t sid : m_start_sids){ + const std::vector& left = m_tracker.remaining_sids(); + if (std::find(left.begin(), left.end(), sid) == left.end()){ + ruled_out.push_back(sid); + } + } + m_logger.log(rng_log_state(RngLoopState{ + .attempt = m_tracker.attempt_index() + 1, .attempts = m_tracker.attempt_count(), + .try_number = m_try, .tries = m_limits.max_retries + 1, + .resets = resets, .max_resets = m_limits.max_resets, + .seed = attempt.target.seed.seed, .advances = attempt.target.advances, + .sids = attempt.sids, .ruled_out = std::move(ruled_out), + .attempt_time = std::chrono::duration_cast(now - m_try_start), .attempt_cap = m_limits.attempt_time, + .total_time = std::chrono::duration_cast(now - m_start), .total_cap = m_limits.total_time, + .calibration = calibration, + })); + } + +private: + Logger& m_logger; + const RngPlanTracker& m_tracker; + const StarterRngLoopLimits& m_limits; + const WallClock m_start; + const std::vector m_start_sids; + std::optional m_tries_of; + size_t m_try = 0; + WallClock m_try_start; +}; + +// What one try came to, for the tracker and the result line. +struct TryOutcome{ + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + std::string detail; + std::optional pokemon; +}; + +// Runs one try of the tracker's current attempt, logging its state lines. +StarterRngResult run_try( + LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + log.begin_try(start); + log.log_state(start, 0, std::nullopt); + StarterRngAttemptCall call{ + .index = tracker.attempt_index(), + .deadline = deadline, + .max_resets = limits.max_resets, + .on_reset = [&](const StarterRngProgress& progress){ + log.log_state(steps.now(), progress.resets, progress.calibrations); + }, + }; + return steps.run_attempt(tracker.current_attempt(), call); +} + +// run_try(), with Starter RNG refusing the attempt's timings as an attempt +// that can't run. Other errors, a setup error such as no sound included, +// would fail every attempt the same way, so they end the loop. +TryOutcome run_try_outcome( + Logger& logger, LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + try{ + const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); + // The deadline ends a try as out of resets. + const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; + return TryOutcome{ + .outcome = plan_outcome(attempt.outcome), + .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), + .pokemon = attempt.pokemon, + }; + }catch (StarterRngTimingsRefused& e){ + logger.log(std::format("RngPlan: attempt {} can't run: {}", tracker.attempt_index() + 1, e.message()), COLOR_RED); + return TryOutcome{.outcome = RngAttemptOutcome::UNUSABLE, .detail = "setup_error", .pokemon = std::nullopt}; + } +} + +} // namespace + + +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +){ + StarterRngLoopResult result; + const WallClock loop_start = steps.now(); + const WallClock total_deadline = loop_start + limits.total_time; + LoopLog log(logger, tracker, limits, loop_start); + while (true){ + std::optional end = loop_end(tracker.step()); + if (end){ + result.end = *end; + break; + } + const WallClock start = steps.now(); + if (start >= total_deadline){ + logger.log("RngPlan: out of time before attempt " + std::to_string(tracker.attempt_index() + 1)); + result.end = StarterRngLoopEnd::OUT_OF_TIME; + break; + } + const size_t index = tracker.attempt_index(); + const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); + const TryOutcome attempt = run_try_outcome(logger, log, tracker, steps, limits, start, deadline); + result.attempts_run++; + const RngPlanStep step = tracker.record(attempt.outcome); + logger.log(rng_log_result(RngResultLog{ + .index = index, .try_number = log.try_number(), .outcome = attempt.outcome, + .detail = attempt.detail, .pokemon = attempt.pokemon, + .next = rng_plan_next(step, index, tracker.attempt_index()), + })); + } + result.remaining_sids = tracker.remaining_sids(); + result.sid = tracker.confirmed_sid(); + if (result.end == StarterRngLoopEnd::SHINY && result.sid){ + logger.log(rng_log_confirmed(tid, *result.sid, sid_helper_candidates)); + } + return result; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h new file mode 100644 index 0000000000..3960b6fff0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h @@ -0,0 +1,131 @@ +/* Starter RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + * An RNG plan's attempts (PokemonFRLG_RngPlan.h), each run with Starter + * RNG's attempt loop (StarterRngAttempts), until one comes out shiny or + * the plan, its retries or the time run out. Its "RngPlan: state" and + * "RngPlan: result" lines are listed with the plan's in + * PokemonFRLG_RngPlanLog.h. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoop_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoop_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "PokemonFRLG_StarterRngLoopLog.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Timeout and iteration constraints on starter RNG loop. +struct StarterRngLoopLimits{ + // An attempt makes no more resets after this long, and counts as missed. + Milliseconds attempt_time = Milliseconds(0); + // No attempt starts after this long. + Milliseconds total_time = Milliseconds(0); + // Resets per try of an attempt. + uint64_t max_resets = 0; + // The tracker's retries of a missed attempt, for the state lines. + size_t max_retries = 0; +}; + +// Starter RNG refused an attempt's timings (check_timings()). The loop +// records the attempt as unusable and moves on; any other error, a +// UserSetupError included, stops the loop. +class StarterRngTimingsRefused : public Exception{ +public: + explicit StarterRngTimingsRefused(std::string message) : m_message(std::move(message)) {} + // code-health: allow char_pointer -- Exception::name() is the fixed base-class interface it overrides + virtual const char* name() const override{ return "StarterRngTimingsRefused"; } + virtual std::string message() const override{ return m_message; } + +private: + std::string m_message; +}; + +// One try of an attempt, as the loop asks the steps for it. +struct StarterRngAttemptCall{ + // From 0. + size_t index = 0; + // No reset after this. + WallClock deadline; + uint64_t max_resets = 0; + // To call after each reset. + std::function on_reset; +}; + +// The game steps of the loop, injected so that its decisions run in tests +// without a Switch. +class StarterRngLoopSteps{ +public: + virtual ~StarterRngLoopSteps() = default; + virtual WallClock now() = 0; + // Runs Starter RNG's attempts at `attempt`'s target from the save under + // the ball, as `call` says. Throws StarterRngTimingsRefused when + // Starter RNG refuses the attempt's timings; the loop logs it and moves on. + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; +}; + +// Termination condition of the starter RNG loop. +enum class StarterRngLoopEnd{ + // The starter is shiny and the target; the game is on its summary, not saved. + SHINY, + // The starter is shiny but not the target (or not known to be), so it + // doesn't tell the SID; the game is on its summary, not saved. + SHINY_OFF_TARGET, + // Shiny not required, and the target was hit. The game is where + // Starter RNG's calibration left it, not saved. + TARGET, + // Every attempt was hit and none was shiny. + OUT_OF_ATTEMPTS, + // The last attempt still shiny for a SID left missed more often than + // the retries allow, or couldn't run. + MISSED_EVERY_ATTEMPT_LEFT, + // The total time ran out with attempts left. + OUT_OF_TIME, +}; + +// Aggregated outcome of the starter RNG loop. +struct StarterRngLoopResult{ + StarterRngLoopEnd end = StarterRngLoopEnd::OUT_OF_TIME; + // Attempts run, retries included. + size_t attempts_run = 0; + // The SID candidates not ruled out. + std::vector remaining_sids; + // The SID, once a shiny leaves one candidate. + std::optional sid; +}; + +// Runs `tracker`'s attempts through `steps` until the plan ends or +// `limits.total_time` has passed. Logs an "RngPlan: state" line at the +// start of each try and after each reset, an "RngPlan: result" line after +// it and, when a shiny leaves one SID, an "RngPlan: confirmed" line placing +// it among SID Helper's candidates for `tid`. +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h new file mode 100644 index 0000000000..31ab38ef8f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h @@ -0,0 +1,86 @@ +/* Starter RNG Loop Log + * + * From: https://github.com/PokemonAutomation/ + * + * How the Starter RNG loop reports: an attempt's outcome as the plan counts + * it, the loop's state line and each reset's line. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoopLog_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoopLog_H + +#include +#include +#include +#include +#include "PokemonFRLG_RngPlan.h" +#include "PokemonFRLG_StarterRngOutcome.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the +// target is SHINY; one off it, or not known to be on it, is +// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, +// which the plan runs again. +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); +// As the result line names it: "shiny_on_target", "target_hit", +// "out_of_resets"... (The loop says "attempt_deadline" instead of +// "out_of_resets" once the try's deadline has passed.) +std::string starter_rng_outcome_name(StarterRngOutcome outcome); + + +// Where the loop is, for an "RngPlan: state" line. +struct RngLoopState{ + // From 1, of `attempts`. + size_t attempt = 1; + size_t attempts = 0; + // From 1, of `tries`. + size_t try_number = 1; + size_t tries = 0; + uint64_t resets = 0; + uint64_t max_resets = 0; + uint16_t seed = 0; + uint64_t advances = 0; + // The SIDs the attempt is shiny for, and those ruled out so far. + std::vector sids; + std::vector ruled_out; + Milliseconds attempt_time = Milliseconds(0); + Milliseconds attempt_cap = Milliseconds(0); + Milliseconds total_time = Milliseconds(0); + Milliseconds total_cap = Milliseconds(0); + // The calibration of the last reset, in frames; none before the first. + std::optional calibration; +}; +// Formats loop state summary line for logging. +std::string rng_log_state(const RngLoopState& state); + + +// A reset's reads, for its one line on the stream's log. +struct RngResetLine{ + // "Starter RNG" or "Gift RNG". + std::string_view program; + uint64_t max_resets = 0; + uint16_t target_seed = 0; + uint64_t target_advances = 0; + // The seeds near the target, in the order of their delays, and the + // target's place among them (SeedMatch). + std::vector seed_values; + int16_t seed_position = -1; + RngResetRead read; +}; +// The frames from the target seed to `seed` among `seed_values`: +1 for +// the seed a frame later. None when either isn't among them. +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed); +// As "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed." +std::string rng_reset_line(const RngResetLine& line); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp new file mode 100644 index 0000000000..03765216f1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp @@ -0,0 +1,567 @@ +/* Starter RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's decisions and log lines on scripted attempt + * outcomes and a fake clock. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_StarterRngLoop.h" +#include "PokemonFRLG_StarterRngLoop_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct StarterRngLoopInput{ + std::string name; + std::function body; +}; + +struct StarterRngLoopExpectation{ + std::string_view description; +}; + +struct StarterRngLoopTestCase{ + StarterRngLoopInput input; + StarterRngLoopExpectation expectation; +}; + +class Test_StarterRngLoop : public UnitTest{ +public: + explicit Test_StarterRngLoop(StarterRngLoopTestCase scenario) + : UnitTest("PokemonFRLG::StarterRngLoop - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StarterRngLoopTestCase m_scenario; +}; + + +class LineLogger : public Logger{ +public: + virtual void log(const std::string& msg, Color) override{ + lines.push_back(msg); + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + + std::vector lines; +}; + +// Each try takes `minutes_per_attempt` on the clock, makes one reset at +// its end with calibration 1.5/-2/0.25 frames, and comes out as the next +// of `outcomes`. An empty one is Starter RNG refusing the timings: a +// StarterRngTimingsRefused at once. +class ScriptedSteps : public StarterRngLoopSteps{ +public: + ScriptedSteps(std::vector> outcomes, int minutes_per_attempt) + : m_outcomes(std::move(outcomes)) + , m_minutes(minutes_per_attempt) + {} + + virtual WallClock now() override{ + return m_now; + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ + if (m_next >= m_outcomes.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "More attempts than scripted."); + } + indices.push_back(call.index); + deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); + const std::optional outcome = m_outcomes[m_next++]; + if (!outcome){ + throw StarterRngTimingsRefused("Refused timings."); + } + m_now += std::chrono::minutes(m_minutes); + call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); + return StarterRngResult{.outcome = *outcome, .pokemon = std::nullopt}; + } + + std::vector indices; + // Each attempt's deadline, in minutes from the start. + std::vector deadlines_min; + +private: + static inline const WallClock START = WallClock{} + std::chrono::hours(1000); + std::vector> m_outcomes; + int m_minutes; + LineLogger m_logger; + WallClock m_now = START; + size_t m_next = 0; +}; + +// A setup problem Starter RNG hits on every attempt alike, such as no +// audio input. +class SetupErrorSteps : public StarterRngLoopSteps{ +public: + virtual WallClock now() override{ + return WallClock{} + std::chrono::hours(1000); + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall&) override{ + calls++; + throw UserSetupError(m_logger, "No sound detected."); + } + + size_t calls = 0; + +private: + LineLogger m_logger; +}; + +// SID Helper's candidates 100, 200, 300; attempt 1 is shiny for 100 and +// 200, attempt 2 for 300. +const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; + +std::vector attempts(){ + RngAttempt first{}; + first.target.seed.seed = 0xceff; + first.target.advances = 983; + first.sids = {100, 200}; + RngAttempt second{}; + second.target.seed.seed = 0x2ef6; + second.target.advances = 29364; + second.sids = {300}; + return {first, second}; +} + +// 60-minute tries, 12 hours in all, 50 resets a try, 2 retries. +const StarterRngLoopLimits LIMITS{ + .attempt_time = std::chrono::minutes(60), + .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, +}; + +std::string end_name(StarterRngLoopEnd end){ + switch (end){ + case StarterRngLoopEnd::SHINY: + return "SHINY"; + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return "SHINY_OFF_TARGET"; + case StarterRngLoopEnd::TARGET: + return "TARGET"; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return "OUT_OF_ATTEMPTS"; + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "MISSED_EVERY_ATTEMPT_LEFT"; + case StarterRngLoopEnd::OUT_OF_TIME: + return "OUT_OF_TIME"; + } + return "?"; +} + +std::string join(const std::vector& values){ + std::string text; + for (size_t value : values){ + text += (text.empty() ? "" : ",") + std::to_string(value + 1); + } + return text; +} + + +struct LoopRow{ + std::string name; + // Empty: Starter RNG refuses the attempt's timings. + std::vector> outcomes; + int minutes_per_attempt; + bool shiny_required; + StarterRngLoopEnd end; + // The attempts run, from 1, as "1,1,2". + std::string attempts_run; + // The SID confirmed, or 0 for none; with it, an "RngPlan: confirmed" line. + uint16_t sid; + // Log lines the loop must write. + std::vector lines; +}; + +using enum StarterRngOutcome; +const std::optional REFUSED = std::nullopt; + +const std::vector LOOP_ROWS = { + { + .name = "hit, then shiny confirms the SID", + .outcomes = {target_hit, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: state attempt=1/2 try=1/3 reset=0/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:00:00/01:00:00 total_time=00:00:00/12:00:00 calibration=-", + "RngPlan: state attempt=1/2 try=1/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:30:00/01:00:00 total_time=00:30:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: result attempt=1 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: state attempt=2/2 try=1/3 reset=0/50 seed=2EF6 advances=29364 sids=300 ruled_out=100,200 " + "attempt_time=00:00:00/01:00:00 total_time=00:30:00/12:00:00 calibration=-", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "shiny on the target for two SIDs confirms none", + .outcomes = {shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm"}, + }, + { + .name = "shiny off the target confirms nothing", + .outcomes = {target_hit, shiny_off_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a shiny not known to be the target confirms nothing", + .outcomes = {shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny_off_target starter_rng=shiny nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "misses retry the same attempt", + .outcomes = {out_of_resets, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, + .lines = { + "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=2 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, + }, + { + .name = "an attempt past its deadline", + .outcomes = {out_of_resets, shiny_on_target}, + .minutes_per_attempt = 90, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=missed starter_rng=attempt_deadline nature=- ivs=- pid=- next=retry"}, + }, + { + .name = "retries used up, then the next attempt", + .outcomes = {out_of_resets, no_matches, wild_shiny, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "every attempt left missed too often", + .outcomes = {out_of_resets, out_of_resets, out_of_resets, no_matches, no_matches, no_matches}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,1,1,2,2,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=3 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "miss, hit, miss, then shiny", + .outcomes = {out_of_resets, target_hit, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,2,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=2 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=2 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, + }, + { + .name = "an attempt whose timings Starter RNG refuses is skipped", + .outcomes = {REFUSED, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: attempt 1 can't run: Refused timings.", + "RngPlan: result attempt=1 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=next_attempt", + }, + }, + { + .name = "no attempt Starter RNG will run", + .outcomes = {REFUSED, REFUSED}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "every attempt hit, none shiny", + .outcomes = {target_hit, target_hit}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a hit ends the plan with shiny not required", + .outcomes = {target_hit}, + .minutes_per_attempt = 30, .shiny_required = false, + .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, + .lines = {}, + }, + { + .name = "no attempt starts after the total time", + .outcomes = {out_of_resets, out_of_resets}, + .minutes_per_attempt = 400, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, + .lines = { + "RngPlan: state attempt=1/2 try=2/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=06:40:00/01:00:00 total_time=13:20:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: out of time before attempt 1", + }, + }, +}; + +UnitTestResult run_loop_row(const LoopRow& row){ + RngPlanTracker tracker(attempts(), CANDIDATES, row.shiny_required, 2); + ScriptedSteps steps(row.outcomes, row.minutes_per_attempt); + LineLogger logger; + StarterRngLoopResult result = run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + + const std::string expected = std::format("end {}, attempts {}, sid {}", end_name(row.end), row.attempts_run, row.sid); + const std::string got = std::format( + "end {}, attempts {}, sid {}", end_name(result.end), join(steps.indices), result.sid.value_or(0) + ); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + for (const std::string& line : row.lines){ + if (!logger.has(line)){ + return "Expected the log line \"" + line + "\""; + } + } + const bool confirmed = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: confirmed"); + }); + if (confirmed != (row.sid != 0)){ + return std::format("Expected {} \"RngPlan: confirmed\" line", row.sid != 0 ? "a" : "no"); + } + if (result.attempts_run != steps.indices.size()){ + return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); + } + return true; +} + + +// An attempt's deadline is an hour after it starts, or the end of the +// total time if sooner: attempts of 400 minutes start at 0 and 400, and +// none at 800, past the total of 430. +UnitTestResult test_deadlines(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 5); + ScriptedSteps steps({StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, 400); + LineLogger logger; + const StarterRngLoopLimits limits{ + .attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430), .max_resets = 50, .max_retries = 5, + }; + run_starter_rng_plan(logger, tracker, steps, limits, 12345, CANDIDATES); + std::string got; + for (int deadline : steps.deadlines_min){ + got += (got.empty() ? "" : ",") + std::to_string(deadline); + } + if (got != "60,430"){ + return "Expected deadlines 60,430 minutes; got " + got; + } + return true; +} + + +// A setup error other than refused timings stops the loop at once: it +// reaches the program, and the attempt is neither recorded nor skipped. +UnitTestResult test_setup_error_stops(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 2); + SetupErrorSteps steps; + LineLogger logger; + const size_t sids = tracker.remaining_sids().size(); + bool thrown = false; + try{ + run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + }catch (UserSetupError&){ + thrown = true; + } + const bool result_line = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: result") || line.starts_with("RngPlan: attempt"); + }); + const std::string expected = std::format("thrown 1, calls 1, attempt 1, sids {}, result line 0", sids); + const std::string got = std::format( + "thrown {}, calls {}, attempt {}, sids {}, result line {}", + int(thrown), steps.calls, tracker.attempt_index() + 1, tracker.remaining_sids().size(), int(result_line) + ); + if (got != expected){ + return "Expected " + expected + "; got " + got; + } + return true; +} + + +// The state line on its own: hours, empty lists and a negative offset. +UnitTestResult test_state_line(){ + const std::string got = rng_log_state(RngLoopState{ + .attempt = 3, .attempts = 5, .try_number = 2, .tries = 3, .resets = 41, .max_resets = 50, + .seed = 0x70fe, .advances = 1200, .sids = {}, .ruled_out = {7, 8}, + .attempt_time = std::chrono::seconds(3 * 3600 + 61), .attempt_cap = std::chrono::hours(3), + .total_time = std::chrono::minutes(605), .total_cap = std::chrono::hours(12), + .calibration = RngCalibrations{-0.5, 12, -3.125}, + }); + const std::string expected = + "RngPlan: state attempt=3/5 try=2/3 reset=41/50 seed=70FE advances=1200 sids=- ruled_out=7,8 " + "attempt_time=03:01:01/03:00:00 total_time=10:05:00/12:00:00 calibration=-0.50/12.00/-3.12"; + if (got != expected){ + return "Expected \"" + expected + "\", got \"" + got + "\"."; + } + return true; +} + + + +AdvRngState state(uint16_t seed, uint64_t advance){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + return hit; +} + +// Target: seed 9cf3 at advance 1670, between 7425 a frame earlier and +// e66e a frame later. +struct ResetLineRow{ + std::string name; + std::string program; + RngResetRead read; + std::string expected; +}; + +const std::vector RESET_LINE_ROWS = { + { + .name = "seed on the target", .program = "Gift RNG", + .read = {.resets = 28, .hits = {state(0x9cf3, 1669)}, .hit = state(0x9cf3, 1669), .shiny = false}, + .expected = "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed.", + }, + { + .name = "seed a frame late", .program = "Starter RNG", + .read = {.resets = 27, .hits = {state(0xe66e, 1677), state(0x7425, 1690)}, .hit = state(0xe66e, 1677), .shiny = false}, + .expected = "Starter RNG try 27/50: seed e66e (+1 frame late), advance 1677 (target 1670, +7). Missed.", + }, + { + .name = "seed a frame early", .program = "Gift RNG", + .read = {.resets = 4, .hits = {state(0x7425, 1670)}, .hit = std::nullopt, .shiny = false}, + .expected = "Gift RNG try 4/50: seed 7425 (-1 frame early), advance 1670. Missed.", + }, + { + .name = "seed not near the target", .program = "Gift RNG", + .read = {.resets = 5, .hits = {state(0x1234, 1670)}, .hit = state(0x1234, 1670), .shiny = false}, + .expected = "Gift RNG try 5/50: seed 1234 (not near the target), advance 1670. Missed.", + }, + { + .name = "no match", .program = "Gift RNG", + .read = {.resets = 19, .hits = {}, .hit = std::nullopt, .shiny = false}, + .expected = "Gift RNG try 19/50: no match read (stats fit no seed/advance).", + }, + { + .name = "several matches", .program = "Gift RNG", + .read = { + .resets = 3, .hits = {state(0x9cf3, 1668), state(0x9cf3, 1668), state(0xe66e, 1671), state(0x7425, 1675)}, + .hit = std::nullopt, .shiny = false, + }, + .expected = "Gift RNG try 3/50: 3 possible matches, can't tell which.", + }, + { + .name = "target hit", .program = "Starter RNG", + .read = {.resets = 12, .hits = {state(0x9cf3, 1670)}, .hit = state(0x9cf3, 1670), .shiny = false}, + .expected = "Starter RNG try 12/50: seed 9cf3 = target, advance 1670. HIT, not shiny.", + }, + { + .name = "shiny on the target", .program = "Gift RNG", + .read = {.resets = 31, .hits = {state(0xe66e, 1671), state(0x9cf3, 1670)}, .hit = std::nullopt, .shiny = true}, + .expected = "Gift RNG try 31/50: seed 9cf3 = target, advance 1670. HIT, shiny!", + }, + { + .name = "shiny off the target", .program = "Gift RNG", + .read = {.resets = 9, .hits = {state(0xe66e, 1671)}, .hit = std::nullopt, .shiny = true}, + .expected = "Gift RNG try 9/50: shiny, not on the target.", + }, +}; + +UnitTestResult test_reset_line(const ResetLineRow& row){ + const std::string got = rng_reset_line(RngResetLine{ + .program = row.program, .max_resets = 50, .target_seed = 0x9cf3, .target_advances = 1670, + .seed_values = {0x1111, 0x7425, 0x9cf3, 0xe66e, 0x2222}, .seed_position = 2, + .read = row.read, + }); + if (got != row.expected){ + return "Expected \"" + row.expected + "\", got \"" + got + "\"."; + } + return true; +} + +UnitTestResult test_loop_rows(){ + for (const LoopRow& row : LOOP_ROWS){ + UnitTestResult res = run_loop_row(row); + if (res.result != UnitTestResult::PASSED){ + return row.name + ": " + res.message; + } + } + return true; +} + +UnitTestResult test_reset_line_rows(){ + for (const ResetLineRow& row : RESET_LINE_ROWS){ + UnitTestResult res = test_reset_line(row); + if (res.result != UnitTestResult::PASSED){ + return row.name + ": " + res.message; + } + } + return true; +} + +const StarterRngLoopTestCase STARTER_RNG_LOOP_CASES[] = { + { + .input = {.name = "attempt deadlines", .body = test_deadlines}, + .expectation = {.description = "verifies attempt timeout and deadline handling"}, + }, + { + .input = {.name = "a setup error stops the loop", .body = test_setup_error_stops}, + .expectation = {.description = "aborts loop when setup verification fails"}, + }, + { + .input = {.name = "state line", .body = test_state_line}, + .expectation = {.description = "formats loop state line output correctly"}, + }, + { + .input = {.name = "loop row scenarios", .body = test_loop_rows}, + .expectation = {.description = "evaluates simulated starter RNG loop rows"}, + }, + { + .input = {.name = "reset line scenarios", .body = test_reset_line_rows}, + .expectation = {.description = "evaluates RNG reset summary lines"}, + }, +}; + +} // namespace + + +void add_tests_StarterRngLoop(UnitTestDatabase& database){ + for (const auto& scenario : STARTER_RNG_LOOP_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h new file mode 100644 index 0000000000..378eee8684 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h @@ -0,0 +1,24 @@ +/* Starter RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoop_Tests_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoop_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers starter RNG loop unit tests. +void add_tests_StarterRngLoop(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h new file mode 100644 index 0000000000..44a93b0977 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h @@ -0,0 +1,43 @@ +/* Starter RNG Outcome + * + * From: https://github.com/PokemonAutomation/ + * + * What one Starter RNG attempt ended with, and how a shiny is identified + * from the seed and advances it hit. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngOutcome_H +#define PokemonAutomation_PokemonFRLG_StarterRngOutcome_H + +#include +#include +#include "Pokemon/Pokemon_AdvRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Result outcome of an individual starter attempt. +enum class StarterRngOutcome{ + shiny, // The starter was shiny after a reset; not known if on the target. + shiny_on_target, // Shiny, and the target is among the states its stats match. + shiny_off_target, // Shiny, and the states its stats match aren't the target. + target_hit, // The calibration shows the target was hit; not shiny. + wild_shiny, // A wild shiny on Route 1, with ignore_wild_shinies off. + out_of_resets, // More resets than max_resets. + no_matches, // 5 searches in a row matched no state near the target. +}; + +// A shiny's outcome from the states its stats match near the target +// ("hits"): on the target if it is among them, off it if not, and just +// shiny if none match. +StarterRngOutcome identify_shiny(uint16_t seed, uint64_t advances, const std::vector& hits); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h new file mode 100644 index 0000000000..035afc19e6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h @@ -0,0 +1,72 @@ +/* Starter RNG Target + * + * From: https://github.com/PokemonAutomation/ + * + * The starter Starter RNG aims for: its species and their stats, the target + * advances and the program's stats. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngTarget_H +#define PokemonAutomation_PokemonFRLG_StarterRngTarget_H + +#include +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "Pokemon/Pokemon_AdvRng.h" +#include "Pokemon/Pokemon_StatsCalculation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Selectable Kanto starter species. +enum class StarterSpecies{ + bulbasaur, + squirtle, + charmander +}; + +// The species' base stats. +BaseStats starter_base_stats(StarterSpecies starter); +// The EVs the rival's starter gives when the player's "starter" beats it. +EVs rival_ev_yield(StarterSpecies starter); +// After taking "starter" from its ball and dodging the rival, the steps +// left that line the player up with the lab's door. +int steps_left_to_lab_door(StarterSpecies starter); + + +// Statistical counters for Starter RNG attempts. +struct StarterRngStats : public StatsTracker{ + StarterRngStats(); + + std::atomic& resets; + std::atomic& shinies; + std::atomic& nonshiny; + std::atomic& wildshinies; + std::atomic& errors; +}; + + +// Target criteria for starter manipulation. +struct StarterRngTarget{ + StarterSpecies starter = StarterSpecies::bulbasaur; + uint16_t seed = 0; + uint64_t advances = 0; + // The seed's entry in the seeds database (found). + SeedMatch seed_match; +}; + +// Where an attempt is after a reset: the resets so far, and the +// calibration that reset was timed with. +struct StarterRngProgress{ + uint64_t resets = 0; + RngCalibrations calibrations{}; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h new file mode 100644 index 0000000000..9d6f5c4716 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h @@ -0,0 +1,61 @@ +/* Starter RNG Timings + * + * From: https://github.com/PokemonAutomation/ + * + * Starter RNG's waits as the RNG plan computes them: its smallest Advances + * setting, its title screen and in-game waits before calibration, and the + * margins the plan keeps from Starter RNG's limits. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngTimings_H +#define PokemonAutomation_PokemonFRLG_StarterRngTimings_H + +#include +#include "PokemonFRLG_RngTargetSearch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Starter RNG's smallest Advances setting. +inline constexpr uint64_t STARTER_RNG_MIN_ADVANCES = 940; + +// Starter RNG's title screen wait, before calibration: the seed list's +// delay plus this (FIXED_SEED_OFFSET in StarterRng's attempts). +inline constexpr int64_t STARTER_RNG_FIXED_SEED_OFFSET_MS = -845; +// The shortest title screen wait the plan uses. Starter RNG refuses waits +// under 29,650 ms, and its docs (pokemonautomation.github.io, +// docs/Programs/PokemonFRLG/StarterRng.md, "Avoid low seed delays when +// possible") warn that waits near 30,500 ms can miss the title screen +// press. 31,500 ms keeps a second clear of that for the seed calibration. +inline constexpr int64_t STARTER_RNG_MIN_SEED_WAIT_MS = 31500; +// Starter RNG's title screen wait for `seed`, as prepare_timings() makes it +// before calibration. +int64_t starter_rng_seed_wait_ms(const InitialSeedEntry& seed); +// Whether the wait is at least STARTER_RNG_MIN_SEED_WAIT_MS. (Console B, +// 2026-11-02, FireRed English: seeds 11A3 and 405C, at 30,473 and +// 30,488 ms in the table, are 29,628 and 29,643 ms waits, which Starter +// RNG refuses.) +bool starter_rng_can_wait_for(const InitialSeedEntry& seed); + +// Starter RNG's Continue Screen frames, taken off the advances before the +// in-game wait (CONTINUE_SCREEN_FRAMES in StarterRng's attempts). +inline constexpr uint64_t STARTER_RNG_CONTINUE_SCREEN_FRAMES = 200; +// Starter RNG's in-game wait for `advances`, before calibration. It +// refuses one under 7,500 ms, which STARTER_RNG_MIN_ADVANCES just makes. +int64_t starter_rng_ingame_ms(uint64_t advances); +// Room for the in-game calibration, in advances (2 per frame of wait): the +// calibration moves the wait, and it went to -720 after one miss on console +// B (2026-11-02, seed B579 at 967 advances: an 8 s wait cut to 1.7 s). The +// plan's targets are at least this many advances past Starter RNG's +// minimum. To tune from the logs' calibrations. +inline constexpr uint64_t STARTER_RNG_INGAME_MARGIN_ADVANCES = 720; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp index 30bdaaea7a..d4cde6017c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp @@ -232,11 +232,10 @@ void StaticRng::program(SingleSwitchProgramEnvironment& env, ProControllerContex /* * Settings: Text Speed fast */ + run_precheck(env, context); StaticRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h index 29e117f7fa..3a274e79e8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h @@ -14,13 +14,13 @@ #include "Common/Cpp/Options/TextEditOption.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Pokemon_StatsCalculation.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngCalibration.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -34,9 +34,11 @@ class StaticRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class StaticRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a static encounter. +class StaticRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = StaticRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~StaticRng(); StaticRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp index 9aeb97fb45..96a98f5084 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp @@ -277,11 +277,10 @@ void WildRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& /* * Settings: Text Speed fast */ + run_precheck(env, context); WildRng_Descriptor::Stats& stats = env.current_stats(); - home_black_border_check(env.console, context); - RNG_FILTERS.reset(); RNG_CALIBRATION.reset_hits(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h index 1fa342063a..25daee4b08 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.h @@ -13,11 +13,11 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "CommonTools/Options/LanguageOCROption.h" #include "CommonTools/Options/StringSelectOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "Pokemon/Pokemon_AdvRng.h" #include "PokemonFRLG_BlindNavigation.h" #include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_RngProgram.h" #include "PokemonFRLG_SeedsDatabase.h" namespace PokemonAutomation{ @@ -31,9 +31,11 @@ class WildRng_Descriptor : public SingleSwitchProgramDescriptor{ virtual std::unique_ptr make_stats() const override; }; -class WildRng : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +// Calibrates timings to hit an RNG target for a random wild encounter. +class WildRng : public RngProgramInstance, private ConfigOption::Listener{ public: using Descriptor = WildRng_Descriptor; + virtual size_t free_party_slots_needed() const override{ return 1; } ~WildRng(); WildRng(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 41849b07a5..8f737a3202 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2063,6 +2063,11 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPartyMember.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPoses.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPresses.h @@ -2118,10 +2123,20 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenCursor.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard_Tests.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeys.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.cpp + Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_BlindNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_BlindNavigation.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -2142,18 +2157,59 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngHelper.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngLoopRoutines.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngLoopRoutines.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngMethod1.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngNavigation.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTestTargets.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngProgram.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngStatsDatabase.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngStatsDatabase.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RoamingLegendaryRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidHelper.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoopLog.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngOutcome.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTarget.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngTimings.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp