diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 49d9b56265..601ffcbf7a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -29,6 +29,7 @@ #include "Inference/PokemonFRLG_WildEncounterReader.h" #include "Programs/BoxOrganization/PokemonFRLG_BoxSorter_Tests.h" #include "PokemonFRLG_Navigation.h" +#include "Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -290,6 +291,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_ShinySymbolDetector(database); add_tests_TrainerIdReader(database); add_tests_WildEncounterReader(database); + add_tests_GiftRngAttempts(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp index 3341d8cef2..2abd7ef2e9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp @@ -38,23 +38,6 @@ GiftRng_Descriptor::GiftRng_Descriptor() ) {} -struct GiftRng_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , nonshiny(m_stats["Non-Shiny Hits"]) - , 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("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& nonshiny; - std::atomic& errors; -}; std::unique_ptr GiftRng_Descriptor::make_stats() const{ return std::unique_ptr(new Stats()); } @@ -232,7 +215,7 @@ void GiftRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& * Settings: Text Speed fast */ - GiftRng_Descriptor::Stats& stats = env.current_stats(); + GiftRngStats& stats = env.current_stats(); home_black_border_check(env.console, context); @@ -245,242 +228,41 @@ void GiftRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& 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; - int16_t GENDER_THRESHOLD = -1; - uint8_t LEVEL = 0; - switch (TARGET){ - case PokemonFRLG_RngTarget::magikarp: - BASE_STATS = { 20, 10, 55, 15, 20, 80 }; - GENDER_THRESHOLD = 126; - LEVEL = 5; - break; - case PokemonFRLG_RngTarget::hitmonchan: - BASE_STATS = { 50, 105, 79, 35, 110, 76 }; - GENDER_THRESHOLD = -1; - LEVEL = 25; - break; - case PokemonFRLG_RngTarget::hitmonlee: - BASE_STATS = { 50, 120, 53, 35, 110, 87 }; - GENDER_THRESHOLD = -1; - LEVEL = 25; - break; - case PokemonFRLG_RngTarget::eevee: - BASE_STATS = { 55, 55, 50, 45, 65, 55 }; - GENDER_THRESHOLD = 30; - LEVEL = 25; - break; - case PokemonFRLG_RngTarget::lapras: - BASE_STATS = { 130, 85, 80, 85, 95, 60 }; - GENDER_THRESHOLD = 126; - LEVEL = 25; - break; - case PokemonFRLG_RngTarget::omanyte: - BASE_STATS = { 35, 40, 100, 90, 55, 35 }; - GENDER_THRESHOLD = 30; - LEVEL = 5; - break; - case PokemonFRLG_RngTarget::kabuto: - BASE_STATS = { 30, 80, 90, 55, 45, 55 }; - GENDER_THRESHOLD = 30; - LEVEL = 5; - break; - case PokemonFRLG_RngTarget::aerodactyl: - BASE_STATS = { 80, 105, 65, 60, 75, 130 }; - GENDER_THRESHOLD = 30; - LEVEL = 5; - break; - case PokemonFRLG_RngTarget::gamecornerabra: - BASE_STATS = { 25, 20, 15, 105, 55, 90 }; - GENDER_THRESHOLD = 63; - break; - case PokemonFRLG_RngTarget::gamecornerclefairy: - BASE_STATS = { 70, 45, 48, 60, 65, 35 }; - GENDER_THRESHOLD = 190; - break; - case PokemonFRLG_RngTarget::gamecornerdratinifr: - case PokemonFRLG_RngTarget::gamecornerdratinilg: - BASE_STATS = { 41, 64, 45, 50, 50, 50 }; - GENDER_THRESHOLD = 126; - break; - case PokemonFRLG_RngTarget::gamecornerscyther: - BASE_STATS = { 70, 110, 80, 55, 80, 105 }; - GENDER_THRESHOLD = 126; - LEVEL = 25; - break; - case PokemonFRLG_RngTarget::gamecornerpinsir: - BASE_STATS = { 65, 125, 100, 55, 70, 85 }; - GENDER_THRESHOLD = 126; - LEVEL = 18; - break; - case PokemonFRLG_RngTarget::gamecornerporygon: - BASE_STATS = { 65, 60, 70, 85, 75, 40 }; - GENDER_THRESHOLD = -1; - break; - case PokemonFRLG_RngTarget::togepi: - case PokemonFRLG_RngTarget::togepifast: - BASE_STATS = { 35, 20, 65, 40, 65, 20 }; - GENDER_THRESHOLD = 30; - LEVEL = 5; - break; - default: - break; - } - - static const int64_t FIXED_SEED_OFFSET = -845; // milliseconds, approximate - - static const uint64_t CONTINUE_SCREEN_FRAMES = 200; - - const uint64_t INITIAL_ADVANCES_RADIUS = USE_TEACHY_TV ? 4096 : 1024; - - const uint8_t MAX_HISTORY_LENGTH = USE_TEACHY_TV ? 2 : 10; - - static const std::set SPECIES_LIST = { - "magikarp", "hitmonchan", "hitmonlee", "eevee", "lapras", - "omanyte", "kabuto", "aerodactyl", - "abra", "clefairy", "dratini", "scyther", "pinsir", "porygon", - "togepi" - }; - - env.log("RNG Target: " + std::to_string(TARGET.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; - - 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; - } - - 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, TARGET, - SEED_DELAY, CONTINUE_SCREEN_FRAMES, ingame_advances, - USE_TEACHY_TV, calibrations, - FIXED_SEED_OFFSET, LANGUAGE - ); - - env.log("Resetting Game..."); - reset_and_perform_blind_sequence( - env.console, context, LANGUAGE, TARGET, - 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, TARGET); - - 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; - } - - AdvObservedPokemon pokemon = read_summary(env.console, context, LANGUAGE, SPECIES_LIST); - if (LEVEL > 0){ - pokemon.level[0] = LEVEL; - } - AdvRngFilters filters = observation_to_filters(pokemon, BASE_STATS); - RNG_FILTERS.set(filters); - - std::vector search_hits = refine_calibration_with_rare_candy( - env, context, LANGUAGE, pokemon, filters, BASE_STATS, - uncertain_history, calibration_history, calibrations, - MAX_HISTORY_LENGTH, MAX_RARE_CANDIES, AdvRngMethod::Method1, false, - stats.errors, NOTIFICATION_ERROR_RECOVERABLE, - [&](AdvRngFilters& f){ - return get_search_results(env.console, searcher, f, SEED_VALUES, ADVANCES, advances_radius, GENDER_THRESHOLD); - }, - [&](const std::vector& h){ RNG_CALIBRATION.set_hits(h); }, - [&](const AdvRngFilters& f){ RNG_FILTERS.set(f); }, - [&](const std::vector& h){ - return all_equal(h) || all_indistinguishable(h, searcher, GENDER_THRESHOLD); - } - ); - - env.log("RNG search finished."); - update_failed_searches(failed_searches, search_hits); - + GiftRngAttempts attempts( + GiftRngTarget{ + .target = TARGET, + .seed = TARGET_SEED, + .advances = ADVANCES, + .seed_match = seed_match, + }, + GiftRngSettings{ + .language = LANGUAGE, + .profile = PROFILE, + .use_teachy_tv = USE_TEACHY_TV, + .take_video = TAKE_VIDEO, + .identify_shiny = false, + .max_resets = [this]{ return uint64_t(MAX_RESETS); }, + .max_rare_candies = [this]{ return uint64_t(MAX_RARE_CANDIES); }, + .on_reset = nullptr, + }, + GiftRngDisplays{.target = RNG_TARGET, .filters = RNG_FILTERS, .calibration = RNG_CALIBRATION}, + GiftRngNotifications{ + .shiny = NOTIFICATION_SHINY, + .status_update = NOTIFICATION_STATUS_UPDATE, + .error_recoverable = NOTIFICATION_ERROR_RECOVERABLE, + }, + stats + ); + GiftRngResult result = attempts.run(env, context); + if (result.outcome == GiftRngOutcome::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_GiftRng.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h index 3df8e600ac..1f7d8463e5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h @@ -15,6 +15,7 @@ #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" #include "PokemonFRLG_BlindNavigation.h" +#include "PokemonFRLG_GiftRngAttempts.h" #include "PokemonFRLG_RngDisplays.h" #include "PokemonFRLG_SeedsDatabase.h" @@ -25,7 +26,7 @@ namespace PokemonFRLG{ class GiftRng_Descriptor : public SingleSwitchProgramDescriptor{ public: GiftRng_Descriptor(); - struct Stats; + using Stats = GiftRngStats; virtual std::unique_ptr make_stats() const override; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.cpp new file mode 100644 index 0000000000..fd6c3c050a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.cpp @@ -0,0 +1,316 @@ +/* Gift RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonFRLG_RngNavigation.h" +#include "PokemonFRLG_HardReset.h" +#include "PokemonFRLG_RngLoopRoutines.h" +#include "PokemonFRLG_GiftRngAttempts.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 std::set& gift_species_names(){ + static const std::set SPECIES_LIST = { + "magikarp", "hitmonchan", "hitmonlee", "eevee", "lapras", + "omanyte", "kabuto", "aerodactyl", + "abra", "clefairy", "dratini", "scyther", "pinsir", "porygon", + "togepi" + }; + return SPECIES_LIST; +} + +} + + +GiftRngSpecies gift_rng_species(PokemonFRLG_RngTarget target){ + switch (target){ + case PokemonFRLG_RngTarget::magikarp: + return {.base_stats = { 20, 10, 55, 15, 20, 80 }, .gender_threshold = 126, .level = 5}; + case PokemonFRLG_RngTarget::hitmonchan: + return {.base_stats = { 50, 105, 79, 35, 110, 76 }, .gender_threshold = -1, .level = 25}; + case PokemonFRLG_RngTarget::hitmonlee: + return {.base_stats = { 50, 120, 53, 35, 110, 87 }, .gender_threshold = -1, .level = 25}; + case PokemonFRLG_RngTarget::eevee: + return {.base_stats = { 55, 55, 50, 45, 65, 55 }, .gender_threshold = 30, .level = 25}; + case PokemonFRLG_RngTarget::lapras: + return {.base_stats = { 130, 85, 80, 85, 95, 60 }, .gender_threshold = 126, .level = 25}; + case PokemonFRLG_RngTarget::omanyte: + return {.base_stats = { 35, 40, 100, 90, 55, 35 }, .gender_threshold = 30, .level = 5}; + case PokemonFRLG_RngTarget::kabuto: + return {.base_stats = { 30, 80, 90, 55, 45, 55 }, .gender_threshold = 30, .level = 5}; + case PokemonFRLG_RngTarget::aerodactyl: + return {.base_stats = { 80, 105, 65, 60, 75, 130 }, .gender_threshold = 30, .level = 5}; + case PokemonFRLG_RngTarget::gamecornerabra: + return {.base_stats = { 25, 20, 15, 105, 55, 90 }, .gender_threshold = 63, .level = 0}; + case PokemonFRLG_RngTarget::gamecornerclefairy: + return {.base_stats = { 70, 45, 48, 60, 65, 35 }, .gender_threshold = 190, .level = 0}; + case PokemonFRLG_RngTarget::gamecornerdratinifr: + case PokemonFRLG_RngTarget::gamecornerdratinilg: + return {.base_stats = { 41, 64, 45, 50, 50, 50 }, .gender_threshold = 126, .level = 0}; + case PokemonFRLG_RngTarget::gamecornerscyther: + return {.base_stats = { 70, 110, 80, 55, 80, 105 }, .gender_threshold = 126, .level = 25}; + case PokemonFRLG_RngTarget::gamecornerpinsir: + return {.base_stats = { 65, 125, 100, 55, 70, 85 }, .gender_threshold = 126, .level = 18}; + case PokemonFRLG_RngTarget::gamecornerporygon: + return {.base_stats = { 65, 60, 70, 85, 75, 40 }, .gender_threshold = -1, .level = 0}; + case PokemonFRLG_RngTarget::togepi: + case PokemonFRLG_RngTarget::togepifast: + return {.base_stats = { 35, 20, 65, 40, 65, 20 }, .gender_threshold = 30, .level = 5}; + default: + return {}; + } +} + + +GiftRngOutcome gift_shiny_outcome(uint16_t seed, uint64_t advances, const std::vector& hits){ + if (hits.empty()){ + return GiftRngOutcome::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 ? GiftRngOutcome::shiny_on_target : GiftRngOutcome::shiny_off_target; +} + + +GiftRngStats::GiftRngStats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , nonshiny(m_stats["Non-Shiny Hits"]) + , 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("Errors", HIDDEN_IF_ZERO); +} + + +GiftRngAttempts::GiftRngAttempts( + GiftRngTarget target, + GiftRngSettings settings, + const GiftRngDisplays& displays, + const GiftRngNotifications& notifications, + GiftRngStats& stats +) + : m_target(std::move(target)) + , m_settings(std::move(settings)) + , m_displays(displays) + , m_notifications(notifications) + , m_stats(stats) + , m_species(gift_rng_species(m_target.target)) + , m_initial_advances_radius(m_settings.use_teachy_tv ? 4096 : 1024) + , m_max_history_length(m_settings.use_teachy_tv ? 2 : 10) + , m_searcher(m_target.seed, m_target.advances, AdvRngMethod::Method1) + , m_launch_delay(INITIAL_LAUNCH_DELAY) +{} + + +GiftRngResult GiftRngAttempts::run(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("RNG Target: " + std::to_string(static_cast(m_target.target))); + 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, m_species.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){ + GiftRngResult result{.outcome = *outcome, .pokemon = std::nullopt}; + if (*outcome == GiftRngOutcome::target_hit){ + result.pokemon = target_result; + } + return result; + } + + reset_game(env, context); + + if (check_shiny_gift(env, context)){ + const GiftRngOutcome shiny = m_settings.identify_shiny ? identify_shiny_gift(env, context) : GiftRngOutcome::shiny; + const bool on_target = shiny == GiftRngOutcome::shiny_on_target; + return GiftRngResult{.outcome = shiny, .pokemon = on_target ? std::optional(target_result) : std::nullopt}; + } + + run_attempt(env, context); + } +} + +std::optional GiftRngAttempts::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 GiftRngOutcome::target_hit; + } + env.log("Missed target."); + } + + if (m_failed_searches >= 5){ + env.log("Failed to find any matches 5 times in a row"); + return GiftRngOutcome::no_matches; + } + + if (m_stats.resets > m_settings.max_resets()){ + env.log("Max resets reached."); + return GiftRngOutcome::out_of_resets; + } + + return std::nullopt; +} + +void GiftRngAttempts::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, m_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, m_target.target, + seed_match.seed_delay, CONTINUE_SCREEN_FRAMES, ingame_advances, + m_settings.use_teachy_tv, m_calibrations, + FIXED_SEED_OFFSET, m_settings.language + ); + + env.log("Resetting Game..."); + reset_and_perform_blind_sequence( + env.console, context, m_settings.language, m_target.target, + seed_match.seed_button, seed_match.extra_button, timings, + m_launch_delay, false, m_settings.profile + ); + m_stats.resets++; + if (m_settings.on_reset){ + m_settings.on_reset(GiftRngProgress{.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 GiftRngAttempts::check_shiny_gift(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + bool shiny_found = check_for_shiny(env.console, context, m_target.target); + + if (shiny_found){ + env.log("Shiny found!"); + m_stats.shinies++; + m_displays.calibration.hits.set("Shiny!"); + send_program_notification( + env, + m_notifications.shiny, + COLOR_YELLOW, + "Shiny found!", + {}, "", + env.console.video().snapshot(), + true + ); + if (m_settings.take_video){ + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 0ms); + } + } + return shiny_found; +} + +// On the shiny's summary, as check_for_shiny() leaves it: reads it as an +// attempt does and searches near the target, without Rare Candies. +GiftRngOutcome GiftRngAttempts::identify_shiny_gift(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvObservedPokemon pokemon = read_gift(env, context); + AdvRngFilters filters = observation_to_filters(pokemon, m_species.base_stats); + m_displays.filters.set(filters); + const std::vector hits = search(env, filters); + m_displays.calibration.set_hits(hits); + const GiftRngOutcome outcome = gift_shiny_outcome(m_target.seed, m_target.advances, hits); + env.log(std::format( + "Shiny gift: {} states near the target match it; {}.", hits.size(), + outcome == GiftRngOutcome::shiny_on_target ? "the target is one of them" + : outcome == GiftRngOutcome::shiny_off_target ? "the target isn't" : "not known if it is the target" + )); + return outcome; +} + +AdvObservedPokemon GiftRngAttempts::read_gift(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvObservedPokemon pokemon = read_summary(env.console, context, m_settings.language, gift_species_names()); + if (m_species.level > 0){ + pokemon.level[0] = m_species.level; + } + return pokemon; +} + +std::vector GiftRngAttempts::search(SingleSwitchProgramEnvironment& env, AdvRngFilters& filters){ + return get_search_results( + env.console, m_searcher, filters, m_target.seed_match.seed_values, + m_target.advances, m_advances_radius, m_species.gender_threshold + ); +} + + +void GiftRngAttempts::run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvObservedPokemon pokemon = read_gift(env, context); + AdvRngFilters filters = observation_to_filters(pokemon, m_species.base_stats); + m_displays.filters.set(filters); + + std::vector search_hits = refine_calibration_with_rare_candy( + env, context, m_settings.language, pokemon, filters, m_species.base_stats, + m_uncertain_history, m_calibration_history, m_calibrations, + m_max_history_length, m_settings.max_rare_candies(), AdvRngMethod::Method1, false, + m_stats.errors, m_notifications.error_recoverable, + [&](AdvRngFilters& f){ + return search(env, f); + }, + [&](const std::vector& h){ m_displays.calibration.set_hits(h); }, + [&](const AdvRngFilters& f){ m_displays.filters.set(f); }, + [&](const std::vector& h){ + return all_equal(h) || all_indistinguishable(h, m_searcher, m_species.gender_threshold); + } + ); + + env.log("RNG search finished."); + update_failed_searches(m_failed_searches, search_hits); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.h new file mode 100644 index 0000000000..335ebef350 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.h @@ -0,0 +1,185 @@ +/* Gift RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + * Gift RNG's reset, calibrate and attempt loop, for one target. The Gift + * RNG program runs it with its options, stats and displays; another + * program (AutoStory) can run it with its own. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_GiftRngAttempts_H +#define PokemonAutomation_PokemonFRLG_GiftRngAttempts_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_BlindNavigation.h" +#include "PokemonFRLG_RngCalibration.h" +#include "PokemonFRLG_RngDisplays.h" +#include "PokemonFRLG_SeedsDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What the search needs to know about a gift: its base stats, its gender +// threshold (-1 if genderless) and the level it is received at (0 to keep +// the level read from its summary). +struct GiftRngSpecies{ + BaseStats base_stats{}; + int16_t gender_threshold = -1; + uint8_t level = 0; +}; + +// The gift that "target" gives. Targets that aren't gifts get the defaults. +GiftRngSpecies gift_rng_species(PokemonFRLG_RngTarget target); + + +struct GiftRngStats : public StatsTracker{ + GiftRngStats(); + + std::atomic& resets; + std::atomic& shinies; + std::atomic& nonshiny; + std::atomic& errors; +}; + + +struct GiftRngTarget{ + PokemonFRLG_RngTarget target = PokemonFRLG_RngTarget::magikarp; + 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 GiftRngProgress{ + uint64_t resets = 0; + RngCalibrations calibrations{}; +}; + +struct GiftRngSettings{ + Language language = Language::None; + // The Switch profile's position on the user selection screen; 0 for + // the default. + uint8_t profile = 0; + // Advance the RNG in the Teachy TV. + bool use_teachy_tv = 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 Gift RNG lets the user change it + // while running. + std::function max_resets; + // The Rare Candies at the top of the bag. Read before each search, as + // max_resets is. + std::function max_rare_candies; + // Called after each reset, if set, for a caller that logs the attempts. + std::function on_reset; +}; + +// Where the attempts show the target, the filters read so far and the +// calibration. The calibration display also holds the starting +// calibration. +struct GiftRngDisplays{ + RngTargetDisplay& target; + RngFilterDisplay& filters; + RngCalibrationDisplay& calibration; +}; + +struct GiftRngNotifications{ + EventNotificationOption& shiny; + EventNotificationOption& status_update; + EventNotificationOption& error_recoverable; +}; + + +enum class GiftRngOutcome{ + shiny, // The gift 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. + out_of_resets, // More resets than max_resets. + no_matches, // 5 searches in a row matched no state near the target. +}; + +// A shiny gift'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. +GiftRngOutcome gift_shiny_outcome(uint16_t seed, uint64_t advances, const std::vector& hits); + +struct GiftRngResult{ + GiftRngOutcome outcome = GiftRngOutcome::out_of_resets; + // The target's PID, nature and IVs, on target_hit and shiny_on_target. + std::optional pokemon; +}; + + +class GiftRngAttempts{ +public: + GiftRngAttempts( + GiftRngTarget target, + GiftRngSettings settings, + const GiftRngDisplays& displays, + const GiftRngNotifications& notifications, + GiftRngStats& stats + ); + GiftRngAttempts(const GiftRngAttempts&) = delete; + GiftRngAttempts& operator=(const GiftRngAttempts&) = delete; + + // From the HOME menu with the game closed: resets the game and + // receives the gift at the target's timing until the outcome is known. + // Each non-shiny gift is read, leveled with Rare Candies if needed, to + // find the state hit and recalibrate. Ends in the game on the last + // screen the attempts reached. Call once per object. + GiftRngResult run(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + std::optional finished(SingleSwitchProgramEnvironment& env); + void reset_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool check_shiny_gift(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + GiftRngOutcome identify_shiny_gift(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + AdvObservedPokemon read_gift(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + std::vector search(SingleSwitchProgramEnvironment& env, AdvRngFilters& filters); + void run_attempt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + const GiftRngTarget m_target; + const GiftRngSettings m_settings; + GiftRngDisplays m_displays; + GiftRngNotifications m_notifications; + GiftRngStats& m_stats; + const GiftRngSpecies m_species; + const uint64_t m_initial_advances_radius; + const uint8_t m_max_history_length; + + AdvRngSearcher m_searcher; + RngCalibrations m_calibrations{}; + Milliseconds m_launch_delay; + RngUncertainHistory m_uncertain_history; + RngCalibrationHistory m_calibration_history; + uint64_t m_advances_radius = 0; + uint16_t m_failed_searches = 0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.cpp new file mode 100644 index 0000000000..c76a7e90f9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.cpp @@ -0,0 +1,159 @@ +/* Gift RNG Attempts Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Gift RNG's per-target base stats, gender thresholds and levels, as Gift + * RNG set them before its attempts moved out of the program; and whether + * a shiny gift was the target. + * + */ + +#include +#include +#include +#include +#include "PokemonFRLG_GiftRngAttempts.h" +#include "PokemonFRLG_GiftRngAttempts_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + + +namespace{ + +struct GiftRow{ + PokemonFRLG_RngTarget target = PokemonFRLG_RngTarget::magikarp; + std::string name = ""; + BaseStats base_stats{}; + int16_t gender_threshold = -1; + uint8_t level = 0; +}; + +const std::vector GIFT_ROWS = { + {.target = PokemonFRLG_RngTarget::magikarp, .name = "Magikarp", .base_stats = {20, 10, 55, 15, 20, 80}, .gender_threshold = 126, .level = 5}, + {.target = PokemonFRLG_RngTarget::hitmonchan, .name = "Hitmonchan", .base_stats = {50, 105, 79, 35, 110, 76}, .gender_threshold = -1, .level = 25}, + {.target = PokemonFRLG_RngTarget::hitmonlee, .name = "Hitmonlee", .base_stats = {50, 120, 53, 35, 110, 87}, .gender_threshold = -1, .level = 25}, + {.target = PokemonFRLG_RngTarget::eevee, .name = "Eevee", .base_stats = {55, 55, 50, 45, 65, 55}, .gender_threshold = 30, .level = 25}, + {.target = PokemonFRLG_RngTarget::lapras, .name = "Lapras", .base_stats = {130, 85, 80, 85, 95, 60}, .gender_threshold = 126, .level = 25}, + {.target = PokemonFRLG_RngTarget::omanyte, .name = "Omanyte", .base_stats = {35, 40, 100, 90, 55, 35}, .gender_threshold = 30, .level = 5}, + {.target = PokemonFRLG_RngTarget::kabuto, .name = "Kabuto", .base_stats = {30, 80, 90, 55, 45, 55}, .gender_threshold = 30, .level = 5}, + {.target = PokemonFRLG_RngTarget::aerodactyl, .name = "Aerodactyl", .base_stats = {80, 105, 65, 60, 75, 130}, .gender_threshold = 30, .level = 5}, + {.target = PokemonFRLG_RngTarget::gamecornerabra, .name = "Game Corner Abra", .base_stats = {25, 20, 15, 105, 55, 90}, .gender_threshold = 63, .level = 0}, + {.target = PokemonFRLG_RngTarget::gamecornerclefairy, .name = "Game Corner Clefairy", .base_stats = {70, 45, 48, 60, 65, 35}, .gender_threshold = 190, .level = 0}, + {.target = PokemonFRLG_RngTarget::gamecornerdratinifr, .name = "Game Corner Dratini FR", .base_stats = {41, 64, 45, 50, 50, 50}, .gender_threshold = 126, .level = 0}, + {.target = PokemonFRLG_RngTarget::gamecornerdratinilg, .name = "Game Corner Dratini LG", .base_stats = {41, 64, 45, 50, 50, 50}, .gender_threshold = 126, .level = 0}, + {.target = PokemonFRLG_RngTarget::gamecornerscyther, .name = "Game Corner Scyther", .base_stats = {70, 110, 80, 55, 80, 105}, .gender_threshold = 126, .level = 25}, + {.target = PokemonFRLG_RngTarget::gamecornerpinsir, .name = "Game Corner Pinsir", .base_stats = {65, 125, 100, 55, 70, 85}, .gender_threshold = 126, .level = 18}, + {.target = PokemonFRLG_RngTarget::gamecornerporygon, .name = "Game Corner Porygon", .base_stats = {65, 60, 70, 85, 75, 40}, .gender_threshold = -1, .level = 0}, + {.target = PokemonFRLG_RngTarget::togepi, .name = "Togepi", .base_stats = {35, 20, 65, 40, 65, 20}, .gender_threshold = 30, .level = 5}, + {.target = PokemonFRLG_RngTarget::togepifast, .name = "Togepi pre-approved", .base_stats = {35, 20, 65, 40, 65, 20}, .gender_threshold = 30, .level = 5}, +}; + +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 GiftRngSpecies& species){ + return std::format( + "base stats {}, gender threshold {}, level {}", + to_string(species.base_stats), species.gender_threshold, species.level + ); +} + +class Test_GiftSpecies : public UnitTest{ +public: + explicit Test_GiftSpecies(const GiftRow& row) + : UnitTest("PokemonFRLG::GiftRngAttempts - Gift species " + row.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string expected = to_string(GiftRngSpecies{ + .base_stats = m_row.base_stats, + .gender_threshold = m_row.gender_threshold, + .level = m_row.level, + }); + const std::string got = to_string(gift_rng_species(m_row.target)); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + return true; + } + +private: + GiftRow m_row; +}; + + +// Target: seed 0x70FE, advance 1000. +struct ShinyRow{ + std::string name = ""; + // The (seed, advance) of each state the shiny's stats match. + std::vector> hits = {}; + GiftRngOutcome expected = GiftRngOutcome::shiny; +}; + +const std::vector SHINY_ROWS = { + {.name = "the target alone", .hits = {{0x70fe, 1000}}, .expected = GiftRngOutcome::shiny_on_target}, + {.name = "the target among others", .hits = {{0x70fe, 998}, {0x70fe, 1000}, {0x70ff, 1000}}, .expected = GiftRngOutcome::shiny_on_target}, + {.name = "another advance", .hits = {{0x70fe, 1002}}, .expected = GiftRngOutcome::shiny_off_target}, + {.name = "another seed", .hits = {{0x70fd, 1000}}, .expected = GiftRngOutcome::shiny_off_target}, + {.name = "no match", .hits = {}, .expected = GiftRngOutcome::shiny}, +}; + +const char* outcome_name(GiftRngOutcome outcome){ + switch (outcome){ + case GiftRngOutcome::shiny: return "shiny"; + case GiftRngOutcome::shiny_on_target: return "shiny_on_target"; + case GiftRngOutcome::shiny_off_target: return "shiny_off_target"; + case GiftRngOutcome::target_hit: return "target_hit"; + case GiftRngOutcome::out_of_resets: return "out_of_resets"; + case GiftRngOutcome::no_matches: return "no_matches"; + } + return "?"; +} + +class Test_GiftShinyOutcome : public UnitTest{ +public: + explicit Test_GiftShinyOutcome(const ShinyRow& row) + : UnitTest("PokemonFRLG::GiftRngAttempts - Shiny " + row.name) + , m_row(row) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::vector hits; + for (const auto& [seed, advance] : m_row.hits){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + hits.push_back(hit); + } + const GiftRngOutcome got = gift_shiny_outcome(0x70fe, 1000, hits); + if (got != m_row.expected){ + return std::string("Expected ") + outcome_name(m_row.expected) + ", got " + outcome_name(got); + } + return true; + } + +private: + ShinyRow m_row; +}; + +} + + +void add_tests_GiftRngAttempts(UnitTestDatabase& database){ + for (const GiftRow& row : GIFT_ROWS){ + database.add(row); + } + for (const ShinyRow& row : SHINY_ROWS){ + database.add(row); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.h new file mode 100644 index 0000000000..e9795466f5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.h @@ -0,0 +1,24 @@ +/* Gift RNG Attempts Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_GiftRngAttempts_Tests_H +#define PokemonAutomation_PokemonFRLG_GiftRngAttempts_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The pure parts of the Gift RNG attempts. +void add_tests_GiftRngAttempts(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 247470c0db..d2b5cb00fb 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1809,6 +1809,10 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EncountersDatabase.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRng.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_GiftRngAttempts_Tests.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_HardReset.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_HardReset.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_LocationsDatabase.cpp