diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index d7fc0c3e76..0e703eff26 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -229,6 +229,12 @@ add_library(SerialProgramsLib STATIC ${CORE_LIBRARY_SOURCES} ${LIBRARY_SOURCES}) # Create binary target if (APPLE) + set(PA_MACOS_BUNDLE_IDENTIFIER "PokemonAutomation.SerialPrograms" CACHE STRING "Bundle identifier for this macOS build") + set(PA_MACOS_BUNDLE_NAME "SerialPrograms" CACHE STRING "Display name for this macOS build") + set(PA_MACOS_SIGNING_IDENTITY "" CACHE STRING "Optional persistent certificate for local macOS code signing") + if (PA_MACOS_SIGNING_IDENTITY AND PA_MACOS_BUNDLE_IDENTIFIER STREQUAL "PokemonAutomation.SerialPrograms") + message(FATAL_ERROR "Set PA_MACOS_BUNDLE_IDENTIFIER to a dedicated local identifier before enabling local signing.") + endif() set(SerialPrograms_ICON ${CMAKE_CURRENT_SOURCE_DIR}/../IconResource/icon.icns) # set_source_files_properties(SerialPrograms_ICON PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") @@ -238,8 +244,8 @@ if (APPLE) add_executable(SerialPrograms MACOSX_BUNDLE ${SerialPrograms_ICON} ${EXECUTABLE_SOURCES}) set_target_properties(SerialPrograms PROPERTIES BUNDLE True - MACOSX_BUNDLE_GUI_IDENTIFIER PokemonAutomation.SerialPrograms - MACOSX_BUNDLE_BUNDLE_NAME SerialPrograms + MACOSX_BUNDLE_GUI_IDENTIFIER ${PA_MACOS_BUNDLE_IDENTIFIER} + MACOSX_BUNDLE_BUNDLE_NAME ${PA_MACOS_BUNDLE_NAME} MACOSX_BUNDLE_BUNDLE_VERSION "0.1" MACOSX_BUNDLE_SHORT_VERSION_STRING "0.1" MACOSX_BUNDLE_ICON_FILE "icon.icns" @@ -944,6 +950,11 @@ if(COMMAND_LINE_EXE) include(Source/CommandLine/CommandLineExecutable.cmake) endif() +if (APPLE AND PA_MACOS_SIGNING_IDENTITY) + include(cmake/LocalMacSigning.cmake) + pa_sign_local_macos_app(SerialPrograms) +endif() + if(PA_PYTHON_BINDINGS) # Python bindings (GUI-free) from subdirectory include(Source/PythonBindings/PythonBindings.cmake) diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.cpp new file mode 100644 index 0000000000..c003d62526 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.cpp @@ -0,0 +1,51 @@ +#include "Common/Cpp/Json/JsonArray.h" +#include "PokemonSV_IsolatedHuntSandwichOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +IsolatedHuntSandwichOption::IsolatedHuntSandwichOption(OCR::LanguageOCROption* language) + : SandwichMakerOption("Sandwich: Encounter Power from ordinary ingredients by default. " + "Fire: 6 Rice + 2 Curry Powder + 2 Wasabi (expected Lv. 2; inspect active powers). Grass: Great Klawf Claw (Lv. 2). " + "Herba Mystica settings apply only when explicitly enabled below.", + language, BaseRecipe::shiny, false, GroupOption::EnableMode::ALWAYS_ENABLED) + , USE_HERBA("Use Herba Mystica:
Add Sparkling Power using two selected herbs.", + LockMode::LOCK_WHILE_RUNNING, false) +{ + PA_ADD_OPTION(USE_HERBA); + configure_for(IsolatedEncounterType::FIRE); +} + +void IsolatedHuntSandwichOption::load_json(const JsonValue& json){ + SandwichMakerOption::load_json(json); + configure_for(TYPE == PokemonType::grass ? IsolatedEncounterType::GRASS : IsolatedEncounterType::FIRE); +} + +void IsolatedHuntSandwichOption::configure_for(IsolatedEncounterType type){ + TYPE.set(type == IsolatedEncounterType::GRASS ? PokemonType::grass : PokemonType::fire); + if (USE_HERBA){ + BASE_RECIPE.set(BaseRecipe::shiny); + }else{ + // Ordinary Fire Lv2 custom recipe and Grass Lv2 recipe #105; no rare herbs. + // https://www.reddit.com/r/PokemonScarletViolet/comments/zhff1k/ + // https://bulbapedia.bulbagarden.net/wiki/Sandwich_recipe + JsonArray ingredients; + const std::vector recipe = type == IsolatedEncounterType::FIRE + ? std::vector{"rice", "rice", "rice", "rice", "rice", "rice", + "curry-powder", "curry-powder", "wasabi", "wasabi"} + : std::vector{"klawf-stick", "tomato", "lettuce", "salt", "olive-oil", "wasabi"}; + for (const auto& item : recipe){ ingredients.push_back(item); } + BASE_RECIPE.set(BaseRecipe::custom); + SANDWICH_INGREDIENTS.load_json(JsonValue(std::move(ingredients))); + } + HERBA_ONE.set_visibility(ConfigOptionState::ENABLED); + HERBA_TWO.set_visibility(ConfigOptionState::ENABLED); + TYPE.set_visibility(ConfigOptionState::HIDDEN); + BASE_RECIPE.set_visibility(ConfigOptionState::HIDDEN); + SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.h b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.h new file mode 100644 index 0000000000..75f9b23652 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.h @@ -0,0 +1,23 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntSandwichOption_H +#define PokemonAutomation_PokemonSV_IsolatedHuntSandwichOption_H + +#include "PokemonSV_SandwichMakerOption.h" +#include "VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class IsolatedHuntSandwichOption : public SandwichMakerOption{ +public: + IsolatedHuntSandwichOption(OCR::LanguageOCROption* language); + virtual void load_json(const JsonValue& json) override; + void configure_for(IsolatedEncounterType type); + + BooleanCheckBoxOption USE_HERBA; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.cpp new file mode 100644 index 0000000000..955f524e49 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.cpp @@ -0,0 +1,102 @@ +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonSV_IsolatedHuntTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +const StringSelectDatabase& targets(){ + static const StringSelectDatabase database([]{ + StringSelectDatabase entries; + entries.add_entry(StringSelectEntry("charcadet", "Charcadet")); + entries.add_entry(StringSelectEntry("chespin", "Chespin")); + return entries; + }()); + return database; +} + +const EnumDropdownDatabase& types(){ + static const EnumDropdownDatabase database{ + {IsolatedEncounterType::FIRE, "fire", "Fire"}, + {IsolatedEncounterType::GRASS, "grass", "Grass"}, + }; + return database; +} + +const EnumDropdownDatabase& locations(){ + static const EnumDropdownDatabase database{ + {IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL, "west-province-one-central", "West Province One Central"}, + {IsolatedHuntLocation::CHARGESTONE_CAVE, "chargestone-cave", "Chargestone Cavern"}, + }; + return database; +} + +const EnumDropdownDatabase& actions(){ + static const EnumDropdownDatabase database{ + {IsolatedShinyAction::STOP, "stop", "Stop"}, + {IsolatedShinyAction::CATCH, "catch", "Catch"}, + {IsolatedShinyAction::CATCH_AND_SAVE, "catch-and-save", "Catch and save"}, + }; + return database; +} + +} + +IsolatedHuntRow::IsolatedHuntRow(EditableTableOption& parent) + : EditableTableRow(parent) + , enabled(LockMode::LOCK_WHILE_RUNNING, true) + , pokemon(targets(), LockMode::LOCK_WHILE_RUNNING, "charcadet") + , type(types(), LockMode::LOCK_WHILE_RUNNING, IsolatedEncounterType::FIRE) + , location(locations(), LockMode::LOCK_WHILE_RUNNING, IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL) + , shiny_action(actions(), LockMode::LOCK_WHILE_RUNNING, IsolatedShinyAction::STOP) + , ball(LockMode::LOCK_WHILE_RUNNING, "poke-ball") + , ball_limit(LockMode::LOCK_WHILE_RUNNING, 40, 1, 999) +{ + PA_ADD_OPTION(enabled); + PA_ADD_OPTION(pokemon); + PA_ADD_OPTION(type); + PA_ADD_OPTION(location); + PA_ADD_OPTION(shiny_action); + PA_ADD_OPTION(ball); + PA_ADD_OPTION(ball_limit); +} + +std::unique_ptr IsolatedHuntRow::clone() const{ + auto row = std::make_unique(parent()); + row->load_json(to_json()); + return row; +} + +IsolatedHuntRequest IsolatedHuntRow::snapshot() const{ + return { + .pokemon = pokemon.slug(), .type = type, .location = location, + .ball = ball.slug(), .ball_limit = ball_limit, .enabled = enabled, + .shiny_action = shiny_action, + }; +} + +IsolatedHuntTable::IsolatedHuntTable() + : EditableTableOption_t( + "Hunts:
Choose a compatible target/type/location. Routes are experimental; verify the actual spawn patch.", + LockMode::LOCK_WHILE_RUNNING, make_defaults() + ) +{} + +std::vector IsolatedHuntTable::make_header() const{ + return {"Enabled", "Pokemon", "Encounter Type", "Location", "Shiny Action", "Ball", "Ball Limit"}; +} + +std::vector IsolatedHuntTable::snapshot() const{ + return EditableTableOption_t::snapshot(); +} + +std::vector> IsolatedHuntTable::make_defaults(){ + std::vector> rows; + rows.push_back(std::make_unique(*this)); + return rows; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.h b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.h new file mode 100644 index 0000000000..b8d634f38b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.h @@ -0,0 +1,43 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntTable_H +#define PokemonAutomation_PokemonSV_IsolatedHuntTable_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "VideoGames/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class IsolatedHuntRow : public EditableTableRow{ +public: + IsolatedHuntRow(EditableTableOption& parent); + virtual std::unique_ptr clone() const override; + IsolatedHuntRequest snapshot() const; +private: + BooleanCheckBoxCell enabled; + StringSelectCell pokemon; + EnumDropdownCell type; + EnumDropdownCell location; + EnumDropdownCell shiny_action; + PokemonSwSh::PokemonBallSelectCell ball; + SimpleIntegerCell ball_limit; +}; + +class IsolatedHuntTable : public EditableTableOption_t{ +public: + IsolatedHuntTable(); + virtual std::vector make_header() const override; + std::vector snapshot() const; +private: + std::vector> make_defaults(); +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.cpp new file mode 100644 index 0000000000..656a3d518e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.cpp @@ -0,0 +1,175 @@ +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.h" +#include "PokemonSV_IsolatedHuntCorridor_Tests.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +struct CorridorCase{ + std::string name; + IsolatedHuntLimits limits{.max_rounds = 2, .ascent = {.enabled = true, .segments_per_ascent = 1}}; + std::vector markers; + std::vector rounds; + bool aligned = true; + bool landed = true; + bool acquired = false; + bool pending_refusal = false; + bool pending_battle = false; + IsolatedHuntBattleResult battle = IsolatedHuntBattleResult::STOP; + uint64_t initial_time = 0; + uint64_t segment_time = 0; + uint64_t align_time = 0; + uint64_t flight_time = 0; + IsolatedHuntStop expected; + std::string steps; +}; +class CorridorActions : public IsolatedHuntActions{ +public: + CorridorCase test; + size_t marker_next = 0; + size_t round_next = 0; + uint64_t clock = 0; + std::string steps; + virtual bool reset_start(const IsolatedHuntRequest&) override{ return true; } + virtual bool prepare_sandwich(const IsolatedHuntRequest&) override{ return true; } + virtual bool verify_meal_power(const IsolatedHuntRequest&) override{ return true; } + virtual bool travel_to_anchor(const IsolatedHuntRequest&) override{ steps += "flight "; clock += test.flight_time; return test.landed; } + virtual IsolatedHuntRound clear_round(const IsolatedHuntRequest&) override{ return {}; } + virtual bool refresh_spawns(const IsolatedHuntRequest&) override{ steps += "refresh "; return false; } + virtual bool acquire_refused_target(const IsolatedHuntRequest&) override{ steps += "acquire "; return test.acquired; } + virtual IsolatedHuntBattleResult handle_battle(const IsolatedHuntRequest&) override{ + steps += "battle "; return test.battle; + } + virtual bool refusal_pending() const override{ return test.pending_refusal; } + virtual bool battle_pending() const override{ return test.pending_battle; } + virtual uint64_t now_ms() const override{ return clock; } + virtual IsolatedMarkerState marker_state() override{ + steps += "marker "; + return marker_next < test.markers.size() ? test.markers[marker_next++] : IsolatedMarkerState::PRESENT; + } + virtual bool realign_marker() override{ steps += "align "; clock += test.align_time; return test.aligned; } + virtual IsolatedHuntRound advance_ascent(const IsolatedHuntRequest&, const IsolatedAscentLimits& limits) override{ + steps += "advance:" + std::to_string(limits.segment_ms) + ":" + std::to_string(limits.clearing_wait_ms) + " "; + clock += test.segment_time; + return round_next < test.rounds.size() ? test.rounds[round_next++] : IsolatedHuntRound{.kills = 1}; + } +}; +std::vector navigation_cases(){ + return { + {.name = "Missing marker forbids movement and flight", .markers = {IsolatedMarkerState::MISSING}, + .expected = IsolatedHuntStop::MARKER_MISSING, .steps = "marker "}, + {.name = "Arrival flies and verifies a fresh marker before advancing", .markers = {IsolatedMarkerState::ARRIVED}, + .expected = IsolatedHuntStop::ROUND_LIMIT, + .steps = "marker flight marker align advance:600:5000 flight marker align advance:600:5000 "}, + {.name = "Marker loss between segments stops without resetting", + .limits = {.max_rounds = 2, .ascent = {.enabled = true, .segments_per_ascent = 6}}, + .markers = {IsolatedMarkerState::PRESENT, IsolatedMarkerState::MISSING}, + .expected = IsolatedHuntStop::MARKER_MISSING, .steps = "marker align advance:600:5000 marker "}, + {.name = "Failed heading correction stops", .aligned = false, + .expected = IsolatedHuntStop::REANCHOR_FAILED, .steps = "marker align "}, + {.name = "Wrong, absent center or failed landing cannot reanchor", .landed = false, + .expected = IsolatedHuntStop::TRAVEL_FAILED, .steps = "marker align advance:600:5000 flight "}, + {.name = "Missing marker after flight stops before heading correction", + .markers = {IsolatedMarkerState::PRESENT, IsolatedMarkerState::MISSING}, + .expected = IsolatedHuntStop::REANCHOR_FAILED, .steps = "marker align advance:600:5000 flight marker "}, + }; +} +std::vector event_cases(){ + return { + {.name = "Pending refusal takes priority over exhausted hunt budget", + .limits = {.max_rounds = 2, .duration_ms = 500, .ascent = {.enabled = true}}, + .pending_refusal = true, .initial_time = 1000, + .expected = IsolatedHuntStop::UNRESOLVED_REFUSAL, .steps = "acquire "}, + {.name = "Unresolved refusal at cap forbids reset", .rounds = {{.event = IsolatedHuntEvent::REFUSAL}}, + .expected = IsolatedHuntStop::UNRESOLVED_REFUSAL, .steps = "marker align advance:600:5000 acquire "}, + {.name = "Acquired refusal uses shared shiny stop before reset", .rounds = {{.event = IsolatedHuntEvent::REFUSAL}}, + .acquired = true, .expected = IsolatedHuntStop::BATTLE_POLICY, + .steps = "marker align advance:600:5000 acquire battle "}, + {.name = "Battle policy stops at cap", .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, + .expected = IsolatedHuntStop::BATTLE_POLICY, .steps = "marker align advance:600:5000 battle "}, + {.name = "Battle failure never resets", .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, + .battle = IsolatedHuntBattleResult::FAILED, .expected = IsolatedHuntStop::BATTLE_FAILED, + .steps = "marker align advance:600:5000 battle "}, + {.name = "Handled battle restores anchor before next segment", .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, + .battle = IsolatedHuntBattleResult::CONTINUE, .expected = IsolatedHuntStop::ROUND_LIMIT, + .steps = "marker align advance:600:5000 battle flight marker align advance:600:5000 "}, + {.name = "Refusal during navigation forbids departure", .pending_refusal = true, + .expected = IsolatedHuntStop::UNRESOLVED_REFUSAL, .steps = "acquire "}, + {.name = "Handled navigation battle leaves a failure for inspection", .pending_battle = true, + .battle = IsolatedHuntBattleResult::CONTINUE, .expected = IsolatedHuntStop::TRAVEL_FAILED, + .steps = "battle "}, + }; +} +std::vector budget_cases(){ + return { + {.name = "Lead still clearing at observation cap forbids flight", .rounds = {{.kills = 1, .clearing_busy = true}}, + .expected = IsolatedHuntStop::CLEARING_TIMEOUT, .steps = "marker align advance:600:5000 "}, + {.name = "Insufficient movement budget stops before reset", .rounds = {{.budget_exhausted = true}}, + .expected = IsolatedHuntStop::TIME_LIMIT, .steps = "marker align advance:600:5000 "}, + {.name = "No progress stops before cap reset", .limits = {.max_rounds = 2, .max_empty_rounds = 1, + .ascent = {.enabled = true, .segments_per_ascent = 1}}, .rounds = {{.kills = 0}}, + .expected = IsolatedHuntStop::NO_PROGRESS, .steps = "marker align advance:600:5000 "}, + {.name = "Hunt time expiry forbids flight", .limits = {.max_rounds = 2, .duration_ms = 500, + .ascent = {.enabled = true, .segments_per_ascent = 1}}, .segment_time = 1000, + .expected = IsolatedHuntStop::TIME_LIMIT, .steps = "marker align advance:600:5000 "}, + {.name = "Meal expiry forbids flight", .limits = {.max_rounds = 2, .power_duration_ms = 500, + .ascent = {.enabled = true, .segments_per_ascent = 1}}, .segment_time = 1000, + .expected = IsolatedHuntStop::POWER_EXPIRED, .steps = "marker align advance:600:5000 "}, + {.name = "Meal expiry during alignment forbids movement", .limits = {.max_rounds = 2, .power_duration_ms = 500, + .ascent = {.enabled = true}}, .align_time = 1000, + .expected = IsolatedHuntStop::POWER_EXPIRED, .steps = "marker align "}, + {.name = "Flight consumes hunt budget before reanchor", .limits = {.max_rounds = 2, .duration_ms = 500, + .ascent = {.enabled = true, .segments_per_ascent = 1}}, .flight_time = 1000, + .expected = IsolatedHuntStop::TIME_LIMIT, .steps = "marker align advance:600:5000 flight marker "}, + }; +} +UnitTestResult check_cases(const std::vector& cases){ + for (const auto& test : cases){ + CorridorActions actions; + actions.test = test; + actions.clock = test.initial_time; + const auto result = run_isolated_corridor({}, test.limits, actions, 0, 0); + if (result.stop != test.expected || actions.steps != test.steps){ + return test.name + ": expected stop=" + std::to_string((int)test.expected) + " [" + test.steps + + "]; read stop=" + std::to_string((int)result.stop) + " [" + actions.steps + "]"; + } + if (test.expected != IsolatedHuntStop::ROUND_LIMIT && test.expected != IsolatedHuntStop::TIME_LIMIT && + test.expected != IsolatedHuntStop::POWER_EXPIRED && can_leave_isolated_hunt(result.stop)){ + return test.name + ": expected no departure after failure; read departure allowed"; + } + } + return true; +} + +} +UnitTestResult test_isolated_hunt_corridor(){ + if (isolated_stage_timeout_ms(1000, UINT64_MAX, 90000) != 90000){ + return "Expected an unlimited hunt deadline to preserve the bounded startup stage; read overflowed timeout"; + } + if (isolated_stage_timeout_ms(1000, 900, 90000) != 0 || + isolated_stage_timeout_ms(1000, 1250, 90000) != 250){ + return "Expected expired deadline=0ms and remaining deadline=250ms; read incorrect bounded timeout"; + } + CorridorActions actions; + IsolatedHuntRequest request; + const IsolatedHuntLimits limits{.max_rounds = 3, .ascent = {.enabled = true, .segments_per_ascent = 2}}; + const auto result = run_isolated_corridor(request, limits, actions, 0, 0); + const std::string expected = "marker align advance:600:5000 marker align advance:600:5000 flight marker align advance:600:5000 "; + if (result.rounds != 3 || result.kills != 3 || result.refreshes != 1 || actions.steps != expected){ + return "Expected three bounded segments and one flight/reanchor [" + expected + "]; read [" + actions.steps + "]"; + } + CorridorActions invalid_actions; + auto invalid = limits; + invalid.ascent.segment_ms = 0; + const auto rejected = run_isolated_corridor(request, invalid, invalid_actions, 0, 0); + if (rejected.stop != IsolatedHuntStop::INVALID_PLAN || !invalid_actions.steps.empty()){ + return "Expected invalid zero-length segment rejected before actions; read stop=" + std::to_string((int)rejected.stop); + } + for (const auto& cases : {navigation_cases(), event_cases(), budget_cases()}){ + const auto result = check_cases(cases); + if (result.result != UnitTestResult::PASSED){ return result; } + } + return true; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.h new file mode 100644 index 0000000000..3f42008cbf --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.h @@ -0,0 +1,16 @@ +/* Isolated Uphill Corridor + * + * From: https://github.com/PokemonAutomation/ + * + */ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntCorridor_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHuntCorridor_Tests_H +#include "Common/Cpp/TestRunners/UnitTest.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +UnitTestResult test_isolated_hunt_corridor(); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.cpp new file mode 100644 index 0000000000..a167cfd1aa --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.cpp @@ -0,0 +1,43 @@ +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.h" +#include "PokemonSV_IsolatedHuntEncounter_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +UnitTestResult test_isolated_hunt_encounter_options(){ + struct Case{ + IsolatedShinyAction policy; + EncounterActionsAction expected; + }; + const std::vector cases{ + {.policy = IsolatedShinyAction::STOP, .expected = EncounterActionsAction::STOP_PROGRAM}, + {.policy = IsolatedShinyAction::CATCH, .expected = EncounterActionsAction::THROW_BALLS}, + {.policy = IsolatedShinyAction::CATCH_AND_SAVE, .expected = EncounterActionsAction::THROW_BALLS_AND_SAVE}, + }; + EncounterBotCommonOptions base; + base.VIDEO_ON_SHINY = false; + for (const auto& test : cases){ + const IsolatedHuntRequest request{ + .pokemon = "charcadet", .type = IsolatedEncounterType::FIRE, + .location = IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL, + .ball = "luxury-ball", .ball_limit = 15, .shiny_action = test.policy, + }; + const auto options = make_isolated_encounter_options(base, request); + const auto entries = options->ACTIONS_TABLE.snapshot(); + if (entries.size() != 1){ + return "Expected one per-target shared encounter rule; read " + std::to_string(entries.size()); + } + const auto& entry = entries.front(); + if (entry.pokemon != request.pokemon || entry.shininess != EncounterActionsShininess::SHINY || + entry.action != test.expected || entry.ball != request.ball || entry.ball_limit != request.ball_limit || + options->VIDEO_ON_SHINY || !base.ACTIONS_TABLE.snapshot().empty()){ + return "Expected isolated shiny action/luxury-ball/15 with base settings preserved; read " + entry.ball; + } + } + return true; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.h new file mode 100644 index 0000000000..23a701de5b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.h @@ -0,0 +1,11 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntEncounter_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHuntEncounter_Tests_H +#include "Common/Cpp/TestRunners/UnitTest.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +UnitTestResult test_isolated_hunt_encounter_options(); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.cpp new file mode 100644 index 0000000000..5cbc8a7544 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.cpp @@ -0,0 +1,82 @@ +/* Isolated Hunt Flight Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ +#include +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.h" +#include "PokemonSV_IsolatedHuntFlight_Tests.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +struct FlightCase{ + std::string name; + Language language = Language::ChineseTraditional; + bool selected = true; + std::vector reads = {}; + bool prompt = true; + bool landed = true; + bool expected = false; + std::string steps; +}; +class ScriptedFlight : public IsolatedFlightActions{ +public: + ScriptedFlight(const FlightCase& test) : m_test(test){} + std::string steps; + virtual bool open_confirmation() override{ steps += "select "; return m_test.selected; } + virtual std::string read_destination() override{ + steps += "read "; + return m_next < m_test.reads.size() ? m_test.reads[m_next++] : ""; + } + virtual bool confirmation_visible() override{ steps += "prompt "; return m_test.prompt; } + virtual bool confirm_and_wait() override{ steps += "confirm "; return m_test.landed; } +private: + const FlightCase& m_test; + size_t m_next = 0; +}; +std::vector rejection_cases(){ + return { + {.name = "Observed North pilot must never confirm", .reads = {"西第1區:北"}, .steps = "select read "}, + {.name = "Missing name", .reads = {""}, .steps = "select read "}, + {.name = "Partial name", .reads = {"西第1區"}, .steps = "select read "}, + {.name = "Other area", .reads = {"西第2區:中央"}, .steps = "select read "}, + {.name = "Conflicting second read", .reads = {"西第1區:中央", "西第1區:北"}, .steps = "select read read "}, + {.name = "Unreadable second read", .reads = {"西第1區:中央", ""}, .steps = "select read read "}, + {.name = "English North", .language = Language::English, + .reads = {"West Province (Area One) - North"}, .steps = "select read "}, + {.name = "Unsupported language spends no input", .language = Language::Japanese, .steps = ""}, + {.name = "No confirmation found", .selected = false, .steps = "select "}, + }; +} +std::vector confirmation_cases(){ + return { + {.name = "Central name twice before confirmation", .reads = {"西第1區:中央", "西第 1 區 : 中央"}, + .expected = true, .steps = "select read read prompt confirm "}, + {.name = "English Central", .language = Language::English, + .reads = {"West Province (Area One) - Central", "West Province (Area One) - Central\n"}, + .expected = true, .steps = "select read read prompt confirm "}, + {.name = "Prompt disappeared after reads", .reads = {"西第1區:中央", "西第1區:中央"}, + .prompt = false, .steps = "select read read prompt "}, + {.name = "Verified name without landing is failure", .reads = {"西第1區:中央", "西第1區:中央"}, + .landed = false, .steps = "select read read prompt confirm "}, + }; +} +} +UnitTestResult test_isolated_hunt_flight(){ + auto cases = rejection_cases(); + const auto confirmations = confirmation_cases(); + cases.insert(cases.end(), confirmations.begin(), confirmations.end()); + for (const auto& test : cases){ + ScriptedFlight actions(test); + const bool actual = fly_to_isolated_central(actions, test.language); + if (actual != test.expected || actions.steps != test.steps){ + return test.name + ": expected success=" + std::to_string(test.expected) + " [" + test.steps + + "]; read success=" + std::to_string(actual) + " [" + actions.steps + "]"; + } + } + return true; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.h new file mode 100644 index 0000000000..8356c43458 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.h @@ -0,0 +1,16 @@ +/* Isolated Hunt Flight Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntFlight_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHuntFlight_Tests_H +#include "Common/Cpp/TestRunners/UnitTest.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +UnitTestResult test_isolated_hunt_flight(); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.cpp new file mode 100644 index 0000000000..25385567a2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.cpp @@ -0,0 +1,358 @@ +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.h" +#include "PokemonSV_IsolatedHuntLoop_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +struct LoopCase{ + std::string name; + std::vector rounds = {}; + IsolatedHuntLimits limits{.max_rounds = 2}; + bool start_ok = true; + bool prepare_ok = true; + bool power_ok = true; + bool travel_ok = true; + bool refresh_ok = true; + bool reanchor_ok = true; + bool acquired = false; + bool pending_battle = false; + bool pending_refusal = false; + uint64_t reset_ms = 0; + uint64_t verify_ms = 0; + uint64_t travel_ms = 0; + IsolatedHuntBattleResult battle = IsolatedHuntBattleResult::STOP; + IsolatedHuntResult expected; + std::string steps; +}; + +class ScriptedHunt : public IsolatedHuntActions{ +public: + ScriptedHunt(const LoopCase& test) : m_test(test){} + std::string steps; + virtual bool reset_start(const IsolatedHuntRequest&) override{ steps += "start "; m_clock += m_test.reset_ms; return m_test.start_ok; } + virtual bool prepare_sandwich(const IsolatedHuntRequest&) override{ steps += "sandwich "; return m_test.prepare_ok; } + virtual bool verify_meal_power(const IsolatedHuntRequest&) override{ + steps += "verify "; m_clock += m_test.verify_ms; return m_test.power_ok; + } + virtual bool travel_to_anchor(const IsolatedHuntRequest&) override{ + steps += "travel "; + m_clock += m_test.travel_ms; + return m_travel++ == 0 ? m_test.travel_ok : m_test.reanchor_ok; + } + virtual IsolatedHuntRound clear_round(const IsolatedHuntRequest&) override{ + steps += "clear "; + m_clock += 1000; + return m_next < m_test.rounds.size() ? m_test.rounds[m_next++] : IsolatedHuntRound{.kills = 2}; + } + virtual bool refresh_spawns(const IsolatedHuntRequest&) override{ steps += "refresh "; return m_test.refresh_ok; } + virtual bool acquire_refused_target(const IsolatedHuntRequest&) override{ steps += "acquire "; return m_test.acquired; } + virtual IsolatedHuntBattleResult handle_battle(const IsolatedHuntRequest& request) override{ + steps += "battle:" + request.ball + ":" + std::to_string(request.ball_limit) + " "; + return m_test.battle; + } + virtual bool battle_pending() const override{ return m_test.pending_battle; } + virtual bool refusal_pending() const override{ return m_test.pending_refusal; } + virtual uint64_t now_ms() const override{ return m_clock; } +private: + const LoopCase& m_test; + size_t m_next = 0; + size_t m_travel = 0; + uint64_t m_clock = 0; +}; + +std::string describe(const IsolatedHuntResult& result){ + return "stop=" + std::to_string((int)result.stop) + ", kills=" + std::to_string(result.kills) + + ", rounds=" + std::to_string(result.rounds) + ", encounters=" + std::to_string(result.encounters) + + ", refusals=" + std::to_string(result.refusals) + ", refreshes=" + std::to_string(result.refreshes); +} + +std::vector clearing_cases(){ + return { + { + .name = "Sandwich before travel and bounded clearing", + .expected = {.stop = IsolatedHuntStop::ROUND_LIMIT, .kills = 4, .rounds = 2}, + .steps = "start sandwich verify travel clear clear ", + }, + { + .name = "Unresolved refusal never despawns target", + .rounds = {{.event = IsolatedHuntEvent::REFUSAL}}, + .expected = {.stop = IsolatedHuntStop::UNRESOLVED_REFUSAL, .rounds = 1, .refusals = 1}, + .steps = "start sandwich verify travel clear acquire ", + }, + }; +} + +std::vector battle_cases(){ + return { + { + .name = "Battle policy stops with configured ball", + .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, + .expected = {.stop = IsolatedHuntStop::BATTLE_POLICY, .rounds = 1, .encounters = 1}, + .steps = "start sandwich verify travel clear battle:luxury-ball:15 ", + }, + { + .name = "Refusal acquisition delegates battle handling", + .rounds = {{.event = IsolatedHuntEvent::REFUSAL}}, .acquired = true, + .expected = {.stop = IsolatedHuntStop::BATTLE_POLICY, .rounds = 1, .encounters = 1, .refusals = 1}, + .steps = "start sandwich verify travel clear acquire battle:luxury-ball:15 ", + }, + { + .name = "Reanchor failure prevents more clearing", + .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, .reanchor_ok = false, + .battle = IsolatedHuntBattleResult::CONTINUE, + .expected = {.stop = IsolatedHuntStop::TRAVEL_FAILED, .rounds = 1, .encounters = 1}, + .steps = "start sandwich verify travel clear battle:luxury-ball:15 travel ", + }, + { + .name = "Handled battle requires reanchor before more clearing", + .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, .battle = IsolatedHuntBattleResult::CONTINUE, + .expected = {.stop = IsolatedHuntStop::ROUND_LIMIT, .kills = 2, .rounds = 2, .encounters = 1}, + .steps = "start sandwich verify travel clear battle:luxury-ball:15 travel clear ", + }, + }; +} + +std::vector limit_cases(){ + return { + { + .name = "Time limit checked between rounds", .limits = {.max_rounds = 2, .duration_ms = 500}, + .expected = {.stop = IsolatedHuntStop::TIME_LIMIT, .kills = 2, .rounds = 1}, + .steps = "start sandwich verify travel clear ", + }, + { + .name = "Empty rounds refresh once then stop at bound", + .rounds = {{.kills = 0}, {.kills = 0}}, .limits = {.max_rounds = 5, .max_empty_rounds = 2}, + .expected = {.stop = IsolatedHuntStop::NO_PROGRESS, .rounds = 2, .refreshes = 1}, + .steps = "start sandwich verify travel clear refresh clear ", + }, + { + .name = "Refresh failure does not resume", .rounds = {{.kills = 0}}, .refresh_ok = false, + .expected = {.stop = IsolatedHuntStop::REFRESH_FAILED, .rounds = 1}, + .steps = "start sandwich verify travel clear refresh ", + }, + { + .name = "Final round does not waste a refresh", .rounds = {{.kills = 0}}, .limits = {.max_rounds = 1}, + .expected = {.stop = IsolatedHuntStop::ROUND_LIMIT, .rounds = 1}, + .steps = "start sandwich verify travel clear ", + }, + { + .name = "Expired time budget prevents refresh", .rounds = {{.kills = 0}}, + .limits = {.max_rounds = 2, .duration_ms = 500}, + .expected = {.stop = IsolatedHuntStop::TIME_LIMIT, .rounds = 1}, + .steps = "start sandwich verify travel clear ", + }, + { + .name = "Kills reset consecutive empty rounds", .rounds = {{.kills = 0}, {.kills = 2}, {.kills = 0}}, + .limits = {.max_rounds = 3, .max_empty_rounds = 2}, + .expected = {.stop = IsolatedHuntStop::ROUND_LIMIT, .kills = 2, .rounds = 3, .refreshes = 1}, + .steps = "start sandwich verify travel clear refresh clear clear ", + }, + { + .name = "Zero round budget rejected before ingredients", .limits = {.max_rounds = 0}, + .expected = {.stop = IsolatedHuntStop::INVALID_PLAN}, .steps = "", + }, + }; +} + +std::vector setup_cases(){ + return { + { + .name = "Maker completion without verified power cannot travel or roam", .power_ok = false, + .expected = {.stop = IsolatedHuntStop::POWER_UNVERIFIED}, .steps = "start sandwich verify ", + }, + { + .name = "Sandwich failure prevents travel", .prepare_ok = false, + .expected = {.stop = IsolatedHuntStop::SETUP_FAILED}, .steps = "start sandwich ", + }, + { + .name = "Travel failure prevents clearing", .travel_ok = false, + .expected = {.stop = IsolatedHuntStop::TRAVEL_FAILED}, .steps = "start sandwich verify travel ", + }, + { + .name = "Battle failure prevents travel or clearing", .rounds = {{.event = IsolatedHuntEvent::BATTLE}}, + .battle = IsolatedHuntBattleResult::FAILED, + .expected = {.stop = IsolatedHuntStop::BATTLE_FAILED, .rounds = 1, .encounters = 1}, + .steps = "start sandwich verify travel clear battle:luxury-ball:15 ", + }, + }; +} + +std::vector interruption_cases(){ + return { + {.name = "Setup refusal cannot reset or depart", .prepare_ok = false, .pending_refusal = true, + .expected = {.stop = IsolatedHuntStop::UNRESOLVED_REFUSAL, .refusals = 1}, + .steps = "start sandwich acquire "}, + {.name = "Central corridor dispatch checks marker before movement", + .limits = {.max_rounds = 2, .ascent = {.enabled = true}}, + .expected = {.stop = IsolatedHuntStop::MARKER_MISSING}, .steps = "start sandwich verify travel "}, + {.name = "Invalid corridor stops before ingredients", + .limits = {.max_rounds = 2, .ascent = {.enabled = true, .segment_ms = 0}}, + .expected = {.stop = IsolatedHuntStop::INVALID_PLAN}, .steps = ""}, + { + .name = "Verification battle stops before flight selection", .power_ok = false, .pending_battle = true, + .expected = {.stop = IsolatedHuntStop::BATTLE_POLICY, .encounters = 1}, + .steps = "start sandwich verify battle:luxury-ball:15 ", + }, + { + .name = "Setup battle uses shared policy and stops before travel", + .prepare_ok = false, .pending_battle = true, .battle = IsolatedHuntBattleResult::CONTINUE, + .expected = {.stop = IsolatedHuntStop::SETUP_FAILED, .encounters = 1}, + .steps = "start sandwich battle:luxury-ball:15 ", + }, + { + .name = "Travel battle uses shared policy and stops without blind continuation", + .travel_ok = false, .pending_battle = true, .battle = IsolatedHuntBattleResult::CONTINUE, + .expected = {.stop = IsolatedHuntStop::TRAVEL_FAILED, .encounters = 1}, + .steps = "start sandwich verify travel battle:luxury-ball:15 ", + }, + { + .name = "Shiny during travel obeys stop policy", .travel_ok = false, .pending_battle = true, + .expected = {.stop = IsolatedHuntStop::BATTLE_POLICY, .encounters = 1}, + .steps = "start sandwich verify travel battle:luxury-ball:15 ", + }, + { + .name = "Refresh battle is handled without more movement", .rounds = {{.kills = 0}}, + .refresh_ok = false, .pending_battle = true, + .expected = {.stop = IsolatedHuntStop::BATTLE_POLICY, .rounds = 1, .encounters = 1}, + .steps = "start sandwich verify travel clear refresh battle:luxury-ball:15 ", + }, + }; +} + +std::vector power_cases(){ + return { + { + .name = "Supervision time counts against active power", + .limits = {.max_rounds = 2, .power_duration_ms = 500}, .verify_ms = 1000, + .expected = {.stop = IsolatedHuntStop::POWER_EXPIRED}, .steps = "start sandwich verify travel ", + }, + { + .name = "Travel cannot silently exhaust sandwich power", + .limits = {.max_rounds = 2, .power_duration_ms = 500}, .travel_ms = 1000, + .expected = {.stop = IsolatedHuntStop::POWER_EXPIRED}, .steps = "start sandwich verify travel ", + }, + { + .name = "Clearing stops when power expires", + .limits = {.max_rounds = 2, .power_duration_ms = 500}, + .expected = {.stop = IsolatedHuntStop::POWER_EXPIRED, .kills = 2, .rounds = 1}, + .steps = "start sandwich verify travel clear ", + }, + { + .name = "Zero power budget rejected before ingredients", + .limits = {.max_rounds = 2, .power_duration_ms = 0}, + .expected = {.stop = IsolatedHuntStop::INVALID_PLAN}, .steps = "", + }, + }; +} + +std::vector resume_cases(){ + return { + {.name = "Anchor resume cannot silently make a fresh meal", + .limits = {.max_rounds = 2, .resume_at_anchor = true}, + .expected = {.stop = IsolatedHuntStop::INVALID_PLAN}, .steps = ""}, + {.name = "Existing meal at Central bypasses Zero Gate but retains power and local anchor checks", + .limits = {.max_rounds = 2, .use_existing_power = true, .resume_at_anchor = true}, .start_ok = false, + .expected = {.stop = IsolatedHuntStop::ROUND_LIMIT, .kills = 4, .rounds = 2}, + .steps = "verify travel clear clear "}, + {.name = "Existing power resumes clearing without making another sandwich", + .limits = {.max_rounds = 2, .use_existing_power = true}, .prepare_ok = false, + .expected = {.stop = IsolatedHuntStop::ROUND_LIMIT, .kills = 4, .rounds = 2}, + .steps = "start verify travel clear clear "}, + {.name = "Resume rejects missing or wrong active power without remaking", + .limits = {.max_rounds = 2, .use_existing_power = true}, .power_ok = false, + .expected = {.stop = IsolatedHuntStop::POWER_UNVERIFIED}, .steps = "start verify "}, + {.name = "Resume uses remaining power budget including verification and travel", + .limits = {.max_rounds = 2, .power_duration_ms = 500, .use_existing_power = true}, .travel_ms = 1000, + .expected = {.stop = IsolatedHuntStop::POWER_EXPIRED}, .steps = "start verify travel "}, + {.name = "Resume still dispatches the Central corridor", + .limits = {.max_rounds = 2, .ascent = {.enabled = true}, .use_existing_power = true}, + .expected = {.stop = IsolatedHuntStop::MARKER_MISSING}, .steps = "start verify travel "}, + {.name = "Resume counts Zero Gate realignment against remaining power", + .limits = {.max_rounds = 2, .power_duration_ms = 500, .use_existing_power = true}, .reset_ms = 1000, + .expected = {.stop = IsolatedHuntStop::POWER_EXPIRED}, .steps = "start verify travel "}, + }; +} + +std::vector loop_cases(){ + auto tests = clearing_cases(); + const auto resume = resume_cases(); + tests.insert(tests.end(), resume.begin(), resume.end()); + const auto battles = battle_cases(); + tests.insert(tests.end(), battles.begin(), battles.end()); + const auto limits = limit_cases(); + tests.insert(tests.end(), limits.begin(), limits.end()); + const auto interruptions = interruption_cases(); + tests.insert(tests.end(), interruptions.begin(), interruptions.end()); + const auto power = power_cases(); + tests.insert(tests.end(), power.begin(), power.end()); + const std::vector starts{ + { + .name = "Failed starting flight spends no ingredients", .start_ok = false, + .expected = {.stop = IsolatedHuntStop::START_FAILED}, .steps = "start ", + }, + { + .name = "Battle during starting flight stops before ingredients", .start_ok = false, .pending_battle = true, + .expected = {.stop = IsolatedHuntStop::BATTLE_POLICY, .encounters = 1}, + .steps = "start battle:luxury-ball:15 ", + }, + }; + tests.insert(tests.end(), starts.begin(), starts.end()); + const auto setup = setup_cases(); + tests.insert(tests.end(), setup.begin(), setup.end()); + return tests; +} + +} + +UnitTestResult test_isolated_hunt_loop(){ + const IsolatedHuntRequest request{ + .pokemon = "charcadet", .type = IsolatedEncounterType::FIRE, + .location = IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL, + .ball = "luxury-ball", .ball_limit = 15, + }; + for (const auto& test : loop_cases()){ + ScriptedHunt actions(test); + const auto result = run_isolated_hunt(request, test.limits, actions); + if (describe(result) != describe(test.expected) || actions.steps != test.steps){ + return test.name + ": expected " + describe(test.expected) + " [" + test.steps + + "]; read " + describe(result) + " [" + actions.steps + "]"; + } + } + return true; +} + +UnitTestResult test_isolated_hunt_exit_policy(){ + struct Case{ IsolatedHuntStop stop; bool expected; }; + const std::vector cases{ + {.stop = IsolatedHuntStop::ROUND_LIMIT, .expected = true}, + {.stop = IsolatedHuntStop::TIME_LIMIT, .expected = true}, + {.stop = IsolatedHuntStop::POWER_EXPIRED, .expected = true}, + {.stop = IsolatedHuntStop::UNRESOLVED_REFUSAL, .expected = false}, + {.stop = IsolatedHuntStop::BATTLE_POLICY, .expected = false}, + {.stop = IsolatedHuntStop::BATTLE_FAILED, .expected = false}, + {.stop = IsolatedHuntStop::NO_PROGRESS, .expected = false}, + {.stop = IsolatedHuntStop::REFRESH_FAILED, .expected = false}, + {.stop = IsolatedHuntStop::TRAVEL_FAILED, .expected = false}, + {.stop = IsolatedHuntStop::SETUP_FAILED, .expected = false}, + {.stop = IsolatedHuntStop::POWER_UNVERIFIED, .expected = false}, + {.stop = IsolatedHuntStop::INVALID_PLAN, .expected = false}, + {.stop = IsolatedHuntStop::START_FAILED, .expected = false}, + {.stop = IsolatedHuntStop::MARKER_MISSING, .expected = false}, + {.stop = IsolatedHuntStop::REANCHOR_FAILED, .expected = false}, + {.stop = IsolatedHuntStop::CLEARING_TIMEOUT, .expected = false}, + }; + for (const auto& test : cases){ + const bool actual = can_leave_isolated_hunt(test.stop); + if (actual != test.expected){ + return "Expected departure=" + std::to_string(test.expected) + " for stop=" + + std::to_string((int)test.stop) + "; read " + std::to_string(actual); + } + } + return true; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.h new file mode 100644 index 0000000000..0519ae9476 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.h @@ -0,0 +1,16 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntLoop_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHuntLoop_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +UnitTestResult test_isolated_hunt_loop(); +UnitTestResult test_isolated_hunt_exit_policy(); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.cpp new file mode 100644 index 0000000000..4dcae531dd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.cpp @@ -0,0 +1,91 @@ +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Options/PokemonSV_IsolatedHuntTable.h" +#include "Options/PokemonSV_IsolatedHuntSandwichOption.h" +#include "PokemonSV_IsolatedHuntOptions_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +UnitTestResult test_isolated_hunt_options(){ + IsolatedHuntTable table; + auto defaults = table.snapshot(); + if (defaults.size() != 1 || defaults[0].pokemon != "charcadet" || defaults[0].shiny_action != IsolatedShinyAction::STOP){ + return "Expected one default Charcadet row with stop-on-shiny policy."; + } + JsonObject row; + row["enabled"] = true; + row["pokemon"] = "chespin"; + row["type"] = "grass"; + row["location"] = "chargestone-cave"; + row["shiny_action"] = "catch-and-save"; + row["ball"] = "friend-ball"; + row["ball_limit"] = 20; + JsonArray rows; + rows.push_back(std::move(row)); + table.load_json(JsonValue(std::move(rows))); + const auto request = table.snapshot().front(); + if (request.pokemon != "chespin" || request.type != IsolatedEncounterType::GRASS || + request.location != IsolatedHuntLocation::CHARGESTONE_CAVE || + request.shiny_action != IsolatedShinyAction::CATCH_AND_SAVE || + request.ball != "friend-ball" || request.ball_limit != 20){ + return "Expected saved Chespin/Grass/Cave/catch-save/friend-ball/20 options; read " + table.to_json().dump(); + } + IsolatedHuntTable restored; + restored.load_json(table.to_json()); + const auto plan = make_isolated_hunt_plan(restored.snapshot()); + if (!plan.error.empty() || plan.hunts.size() != 1){ + return "Expected valid round-tripped hunt options; read " + plan.error; + } + return true; +} + +UnitTestResult test_isolated_hunt_sandwich(){ + IsolatedHuntSandwichOption option(nullptr); + if (option.USE_HERBA || option.BASE_RECIPE != BaseRecipe::custom){ + return "Expected ordinary ingredients and Herba Mystica disabled by default; read " + option.to_json().dump(); + } + struct Case{ + IsolatedEncounterType type; + std::string ingredients; + }; + const Case cases[]{ + {.type = IsolatedEncounterType::FIRE, .ingredients = "[\"rice\",\"rice\",\"rice\",\"rice\",\"rice\",\"rice\",\"curry-powder\",\"curry-powder\",\"wasabi\",\"wasabi\"]"}, + {.type = IsolatedEncounterType::GRASS, .ingredients = "[\"klawf-stick\",\"tomato\",\"lettuce\",\"salt\",\"olive-oil\",\"wasabi\"]"}, + }; + for (const auto& test : cases){ + option.configure_for(test.type); + std::vector actual; + for (const auto& row : option.SANDWICH_INGREDIENTS.copy_snapshot()){ + actual.push_back(row->item.slug()); + } + JsonArray actual_json; + for (const auto& item : actual){ actual_json.push_back(item); } + if (actual_json.dump(-1) != test.ingredients){ + return "Expected ordinary recipe " + test.ingredients + "; read " + actual_json.dump(); + } + } + JsonObject legacy; + legacy["BASE_RECIPE"] = "shiny"; + IsolatedHuntSandwichOption restored(nullptr); + restored.load_json(JsonValue(std::move(legacy))); + if (restored.USE_HERBA || restored.BASE_RECIPE != BaseRecipe::custom){ + return "Expected legacy shiny settings to require explicit herb opt-in; read " + restored.to_json().dump(); + } + restored.USE_HERBA = true; + restored.configure_for(IsolatedEncounterType::GRASS); + if (restored.BASE_RECIPE != BaseRecipe::shiny || restored.TYPE != PokemonType::grass){ + return "Expected opted-in Grass Sparkling recipe; read " + restored.to_json().dump(); + } + restored.USE_HERBA = false; + restored.configure_for(IsolatedEncounterType::FIRE); + if (restored.BASE_RECIPE != BaseRecipe::custom){ + return "Expected disabling herb opt-in to restore ordinary recipe; read " + restored.to_json().dump(); + } + return true; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.h new file mode 100644 index 0000000000..76d852abf2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.h @@ -0,0 +1,12 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntOptions_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHuntOptions_Tests_H +#include "Common/Cpp/TestRunners/UnitTest.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +UnitTestResult test_isolated_hunt_options(); +UnitTestResult test_isolated_hunt_sandwich(); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.cpp new file mode 100644 index 0000000000..66ac752f73 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.cpp @@ -0,0 +1,76 @@ +#include +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.h" +#include "PokemonSV_IsolatedHuntPower_Tests.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +struct PowerCase{ + std::string name; + Language language = Language::ChineseTraditional; + IsolatedEncounterType type = IsolatedEncounterType::FIRE; + uint8_t level = 2; + std::vector reads; + bool opened = true; + bool closed = true; + bool expected = false; + size_t expected_reads = 0; + bool expected_close = false; +}; +class ScriptedPower : public IsolatedPowerActions{ +public: + ScriptedPower(const PowerCase& test) : m_test(test){} + size_t reads = 0; + bool closed = false; + virtual bool open_panel() override{ return m_test.opened; } + virtual std::string read_encounter_power() override{ + return reads < m_test.reads.size() ? m_test.reads[reads++] : ""; + } + virtual bool close_panel() override{ closed = true; return m_test.closed; } +private: + const PowerCase& m_test; +}; +std::vector power_cases(){ + return { + {.name = "Actual ordinary Fire level two panel", .reads = {"遭遇力:火 Lv. 2", "遭遇力:火 Lv. 2"}, + .expected = true, .expected_reads = 2, .expected_close = true}, + {.name = "English ordinary Fire level two", .language = Language::English, + .reads = {"Encounter Power: Fire Lv. 2", "Encounter Power: Fire Lv. 2"}, + .expected = true, .expected_reads = 2, .expected_close = true}, + {.name = "Earlier Fire level one pilot is rejected", .reads = {"遭遇力:火 Lv. 1"}, .expected_reads = 1}, + {.name = "Wrong type", .reads = {"遭遇力:草 Lv. 2"}, .expected_reads = 1}, + {.name = "Other power cannot substitute", .reads = {"團戰力:火 Lv. 2"}, .expected_reads = 1}, + {.name = "Unreadable panel", .reads = {""}, .expected_reads = 1}, + {.name = "Conflicting second read", .reads = {"遭遇力:火 Lv. 2", "遭遇力:火 Lv. 1"}, .expected_reads = 2}, + {.name = "Missing second read", .reads = {"遭遇力:火 Lv. 2", ""}, .expected_reads = 2}, + {.name = "Panel opening failed", .opened = false}, + {.name = "Panel closure failed", .reads = {"遭遇力:火 Lv. 2", "遭遇力:火 Lv. 2"}, + .closed = false, .expected_reads = 2, .expected_close = true}, + {.name = "Unsupported language", .language = Language::Japanese}, + {.name = "Unsupported requested level", .level = 1}, + {.name = "Grass ordinary recipe", .type = IsolatedEncounterType::GRASS, + .reads = {"遭遇力:草 Lv. 2", "遭遇力:草 Lv. 2"}, .expected = true, .expected_reads = 2, .expected_close = true}, + {.name = "Explicit herb power", .level = 3, .reads = {"遭遇力:火 Lv. 3", "遭遇力:火 Lv. 3"}, + .expected = true, .expected_reads = 2, .expected_close = true}, + {.name = "Full width digit", .reads = {"遭遇力:火 Lv. 2", "遭遇力:火 Lv. 2"}, + .expected = true, .expected_reads = 2, .expected_close = true}, + }; +} +} +UnitTestResult test_isolated_hunt_power(){ + const auto cases = power_cases(); + for (const auto& test : cases){ + ScriptedPower actions(test); + const bool accepted = verify_isolated_power(actions, test.language, test.type, test.level); + if (accepted != test.expected || actions.reads != test.expected_reads || actions.closed != test.expected_close){ + return test.name + ": expected accepted=" + std::to_string(test.expected) + + ", reads=" + std::to_string(test.expected_reads) + ", close=" + std::to_string(test.expected_close) + + "; read accepted=" + std::to_string(accepted) + ", reads=" + std::to_string(actions.reads) + + ", close=" + std::to_string(actions.closed); + } + } + return true; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.h new file mode 100644 index 0000000000..0e9389a5a0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.h @@ -0,0 +1,11 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntPower_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHuntPower_Tests_H +#include "Common/Cpp/TestRunners/UnitTest.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +UnitTestResult test_isolated_hunt_power(); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.cpp new file mode 100644 index 0000000000..8a8c11166e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.cpp @@ -0,0 +1,103 @@ +/* Isolated Hunt Tests + * + * From: https://github.com/PokemonAutomation/ + */ + +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h" +#include "PokemonSV_IsolatedHunt_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +struct PlanCase{ + std::string name; + std::vector requests; + std::vector expected; +}; + +std::vector plan_cases(){ + const IsolatedHuntRequest chespin{ + .pokemon = "chespin", .type = IsolatedEncounterType::GRASS, + .location = IsolatedHuntLocation::CHARGESTONE_CAVE, + .ball = "friend-ball", .ball_limit = 20, + }; + const IsolatedHuntRequest charcadet{ + .pokemon = "charcadet", .type = IsolatedEncounterType::FIRE, + .location = IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL, + .ball = "luxury-ball", .ball_limit = 15, + }; + auto wrong_type = chespin; + wrong_type.type = IsolatedEncounterType::FIRE; + auto wrong_location = chespin; + wrong_location.location = IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL; + auto no_ball = chespin; + no_ball.ball.clear(); + auto zero_balls = chespin; + zero_balls.ball_limit = 0; + auto disabled = wrong_type; + disabled.enabled = false; + return { + {.name = "Grass Chespin", .requests = {chespin}, .expected = {chespin}}, + {.name = "Fire Charcadet", .requests = {charcadet}, .expected = {charcadet}}, + {.name = "Mixed queue preserves order and catch settings", .requests = {chespin, charcadet}, .expected = {chespin, charcadet}}, + {.name = "Fire Chespin rejected", .requests = {wrong_type}, .expected = {}}, + {.name = "Wrong habitat rejected", .requests = {wrong_location}, .expected = {}}, + {.name = "Invalid later row rejects whole plan", .requests = {chespin, wrong_type}, .expected = {}}, + {.name = "Disabled invalid row ignored", .requests = {disabled, chespin}, .expected = {chespin}}, + {.name = "Empty ball rejected", .requests = {no_ball}, .expected = {}}, + {.name = "Zero ball limit rejected", .requests = {zero_balls}, .expected = {}}, + {.name = "Empty queue rejected", .requests = {}, .expected = {}}, + {.name = "Disabled-only queue rejected", .requests = {disabled}, .expected = {}}, + }; +} + +} + +UnitTestResult test_isolated_hunt_plan(){ + for (const auto& test : plan_cases()){ + const auto plan = make_isolated_hunt_plan(test.requests); + if (plan.error.empty() != !test.expected.empty() || plan.hunts.size() != test.expected.size()){ + return test.name + ": expected hunts=" + std::to_string(test.expected.size()) + + "; read hunts=" + std::to_string(plan.hunts.size()) + ", error=" + plan.error; + } + for (size_t c = 0; c < plan.hunts.size(); c++){ + const auto& hunt = plan.hunts[c]; + const auto& expected = test.expected[c]; + if (hunt.pokemon != expected.pokemon || hunt.ball != expected.ball || hunt.ball_limit != expected.ball_limit){ + return test.name + ": expected " + expected.pokemon + "/" + expected.ball + + "/" + std::to_string(expected.ball_limit) + "; read " + hunt.pokemon + + "/" + hunt.ball + "/" + std::to_string(hunt.ball_limit); + } + } + } + return true; +} + +UnitTestResult test_isolated_hunt_locations(){ + struct Case{ + IsolatedEncounterType type; + std::string expected_pokemon; + IsolatedHuntLocation expected_location; + }; + const std::vector cases{ + {.type = IsolatedEncounterType::GRASS, .expected_pokemon = "chespin", .expected_location = IsolatedHuntLocation::CHARGESTONE_CAVE}, + {.type = IsolatedEncounterType::FIRE, .expected_pokemon = "charcadet", .expected_location = IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL}, + }; + for (const auto& test : cases){ + const auto locations = isolated_locations_for_type(test.type); + if (locations.size() != 1){ + return "Expected one location for " + test.expected_pokemon + "; read " + std::to_string(locations.size()); + } + const auto& location = locations.front(); + if (location.type != test.type || location.pokemon != test.expected_pokemon || location.location != test.expected_location){ + return "Expected compatible location for " + test.expected_pokemon + "; read " + location.pokemon + "/" + location.label; + } + } + return true; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.h new file mode 100644 index 0000000000..06aa80b1bd --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.h @@ -0,0 +1,16 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHunt_Tests_H +#define PokemonAutomation_PokemonSV_IsolatedHunt_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +UnitTestResult test_isolated_hunt_plan(); +UnitTestResult test_isolated_hunt_locations(); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Panels.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Panels.cpp index 62706f9f83..9df3475179 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Panels.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Panels.cpp @@ -50,6 +50,7 @@ #include "Programs/General/PokemonSV_StatsResetEventBattle.h" #include "Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h" +#include "Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.h" #include "Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h" #include "Programs/AutoStory/PokemonSV_AutoStory.h" @@ -82,6 +83,15 @@ PanelListFactory::PanelListFactory() ) {} +namespace{ +void add_shiny_hunting_panels(std::vector& ret){ + ret.emplace_back("---- Shiny Hunting ----"); + ret.emplace_back(make_SingleSwitchProgram()); + ret.emplace_back(make_SingleSwitchProgram()); + ret.emplace_back(make_SingleSwitchProgram< ShinyHuntScatterbug>()); +} +} + std::vector PanelListFactory::make_panels() const{ std::vector ret; @@ -137,9 +147,7 @@ std::vector PanelListFactory::make_panels() const{ ret.emplace_back(make_SingleSwitchProgram()); ret.emplace_back(make_SingleSwitchProgram()); - ret.emplace_back("---- Shiny Hunting ----"); - ret.emplace_back(make_SingleSwitchProgram()); - ret.emplace_back(make_SingleSwitchProgram< ShinyHuntScatterbug>()); + add_shiny_hunting_panels(ret); ret.emplace_back("---- Story Automation ----"); ret.emplace_back(make_SingleSwitchProgram()); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.cpp new file mode 100644 index 0000000000..7d23359819 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.cpp @@ -0,0 +1,58 @@ +#include +#include +#include "Programs/Sandwiches/PokemonSV_SandwichEating.h" +#include "PokemonSV_SandwichEating_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +struct EatingCase{ + const char* name; + uint64_t command_ms; + uint64_t picnic_at_ms; + bool expected; + uint64_t expected_ms; +}; +class ScriptedEating : public SandwichEatingActions{ +public: + ScriptedEating(const EatingCase& test) : m_test(test){} + virtual uint64_t now_ms() const override{ return m_clock; } + virtual bool confirm_and_observe(uint64_t observation_ms) override{ + m_clock += std::max(m_test.command_ms, observation_ms); + const bool detected = m_clock >= m_test.picnic_at_ms; + if (detected){ m_clock = m_test.picnic_at_ms; } + return detected; + } +private: + const EatingCase& m_test; + uint64_t m_clock = 0; +}; +} +UnitTestResult test_sandwich_eating(){ + const std::vector cases{ + {.name = "Early command completion must not truncate eating observation", + .command_ms = 1240, .picnic_at_ms = 28000, .expected = true, .expected_ms = 28000}, + {.name = "Normal confirmation observes picnic immediately", + .command_ms = 160, .picnic_at_ms = 2000, .expected = true, .expected_ms = 2000}, + {.name = "Long result transition still reaches picnic", + .command_ms = 1240, .picnic_at_ms = 60000, .expected = true, .expected_ms = 60000}, + {.name = "Missing picnic stops at real time bound despite fast commands", + .command_ms = 160, .picnic_at_ms = UINT64_MAX, .expected = false, .expected_ms = 80000}, + {.name = "Slow commands do not multiply the observation timeout", + .command_ms = 5000, .picnic_at_ms = UINT64_MAX, .expected = false, .expected_ms = 80000}, + }; + for (const auto& test : cases){ + ScriptedEating actions(test); + const bool actual = wait_for_sandwich_picnic(actions); + if (actual != test.expected || actions.now_ms() != test.expected_ms){ + return std::string(test.name) + ": expected picnic=" + std::to_string(test.expected) + + " at ms=" + std::to_string(test.expected_ms) + "; read picnic=" + std::to_string(actual) + + " at ms=" + std::to_string(actions.now_ms()); + } + } + return true; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.h new file mode 100644 index 0000000000..4a1cf8031e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.h @@ -0,0 +1,11 @@ +#ifndef PokemonAutomation_PokemonSV_SandwichEating_Tests_H +#define PokemonAutomation_PokemonSV_SandwichEating_Tests_H +#include "Common/Cpp/TestRunners/UnitTest.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +UnitTestResult test_sandwich_eating(); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Tests.cpp index ef37700f13..7afef85df7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/PokemonSV_Tests.cpp @@ -29,12 +29,46 @@ #include "Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h" #include "Programs/Farming/PokemonSV_BBQTests.h" #include "PokemonSV_Tests.h" +#include "PokemonSV_IsolatedHunt_Tests.h" +#include "PokemonSV_IsolatedHuntFlight_Tests.h" +#include "PokemonSV_IsolatedHuntPower_Tests.h" +#include "PokemonSV_SandwichEating_Tests.h" +#include "PokemonSV_IsolatedHuntLoop_Tests.h" +#include "PokemonSV_IsolatedHuntCorridor_Tests.h" +#include "PokemonSV_IsolatedHuntOptions_Tests.h" +#include "PokemonSV_IsolatedHuntEncounter_Tests.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSV{ +namespace{ +class Test_IsolatedHunt : public UnitTest{ +public: + Test_IsolatedHunt(std::string name, UnitTestResult (*test)()) + : UnitTest(std::move(name)), m_test(test) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_test(); + } +private: + UnitTestResult (*m_test)(); +}; +} + void add_tests(UnitTestDatabase& database){ + database.add("PokemonSV/IsolatedHunt/Flight", test_isolated_hunt_flight); + database.add("PokemonSV/IsolatedHunt/Power", test_isolated_hunt_power); + database.add("PokemonSV/IsolatedHunt/Plan", test_isolated_hunt_plan); + database.add("PokemonSV/IsolatedHunt/Locations", test_isolated_hunt_locations); + database.add("PokemonSV/IsolatedHunt/Loop", test_isolated_hunt_loop); + database.add("PokemonSV/IsolatedHunt/Corridor", test_isolated_hunt_corridor); + database.add("PokemonSV/IsolatedHunt/ExitPolicy", test_isolated_hunt_exit_policy); + database.add("PokemonSV/IsolatedHunt/Options", test_isolated_hunt_options); + database.add("PokemonSV/IsolatedHunt/Sandwich", test_isolated_hunt_sandwich); + database.add("PokemonSV/IsolatedHunt/EncounterOptions", test_isolated_hunt_encounter_options); + database.add("PokemonSV/Sandwich/Eating", test_sandwich_eating); + add_tests_WhiteButtonDetector(database); add_tests_BoxInfoDetector(database); add_tests_BoxEggDetector(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index c2d61152df..02e1c50f2e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -4,6 +4,7 @@ * */ +#include "VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.h" #include "Common/Cpp/PrettyPrint.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Exceptions/UnexpectedBattleException.h" @@ -299,15 +300,8 @@ void realign_player(const ProgramInfo& info, VideoStream& stream, ProControllerC case PlayerRealignMode::REALIGN_OLD_MARKER: handle_unexpected_battles(info, stream, context, [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - open_map_from_overworld(info, stream, context, false); - }); - - handle_unexpected_battles(info, stream, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - leave_phone_to_overworld(info, stream, context); + realign_to_existing_destination(info, stream, context); }); - - pbf_press_button(context, BUTTON_L, 160ms, 840ms); return; case PlayerRealignMode::REALIGN_NO_MARKER: pbf_move_left_joystick(context, {move_x, move_y}, move_duration, 1000ms); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp index 426e85f38e..7d7eaa4ddd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp @@ -28,6 +28,7 @@ #include "VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" #include "VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h" #include "PokemonSV_MaterialFarmerTools.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.h" // #include // using std::cout; @@ -706,55 +707,6 @@ void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoSt move_from_league_club_entrance_to_item_printer(info, stream, context); } -void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - int numAttempts = 0; - const int maxAttempts = 11; - bool isFlySuccessful = false; - - // in order to land on the target fly point semi-consistently, - // the push magnitude can range from 69 to 85 (range of 16). - // On each failure, try increasing/decreasing the push by 1/4 of the max range, - // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment - const std::array adjustment_table = { - 0ms, 0ms, 0ms, 32ms, -32ms, 64ms, -64ms, 128ms, -128ms, 0ms, 0ms, 0ms - }; - while (!isFlySuccessful && numAttempts < maxAttempts){ - // close all menus - pbf_mash_button(context, BUTTON_B, 800ms); - - numAttempts++; - - open_map_from_overworld(info, stream, context); - - // change from Paldea map to Blueberry map - pbf_press_button(context, BUTTON_L, 400ms, 2400ms); - - // move cursor to bottom right corner - pbf_move_left_joystick(context, {+1, -1}, 5000ms, 400ms); - - // move cursor to Blueberry academy fast travel point (up-left) - // try different magnitudes of cursor push with each failure. -// int push_magnitude_ticks = 105 + adjustment_table[numAttempts]; -// Milliseconds push_magnitude = push_magnitude_ticks * 8ms; - Milliseconds push_magnitude = 840ms + adjustment_table[numAttempts]; - pbf_move_left_joystick(context, {-0.5, +0.5}, push_magnitude, 400ms); - - // press A to fly to Blueberry academy - isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); - if (!isFlySuccessful){ - stream.log("Failed to fly to Blueberry academy."); - // dump_snapshot(stream); - } - } - - if (!isFlySuccessful){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "Failed to fly to Blueberry academy, five times in a row.", - stream - ); - } -} void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h index e6921661cc..51c055dcdb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h @@ -169,8 +169,6 @@ void run_from_battles_and_back_to_pokecenter( void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); -void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.cpp new file mode 100644 index 0000000000..b5de7979b1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.cpp @@ -0,0 +1,43 @@ +/* Destination Marker Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ +#include +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" +#include "PokemonSV_MenuNavigation.h" +#include "PokemonSV_MarkerNavigation.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +DestinationMarkerState read_destination_marker(const ImageViewRGB32& screen){ + DestinationMarkerDetector arrival(COLOR_CYAN, {0.717, 0.165, 0.03, 0.061}, false); + if (arrival.detect(screen)){ return DestinationMarkerState::ARRIVED; } + DestinationMarkerDetector minimap(COLOR_BLUE, {0.815, 0.645, 0.180, 0.320}, true); + return minimap.detect(screen) ? DestinationMarkerState::PRESENT : DestinationMarkerState::MISSING; +} +bool destination_marker_ahead(const ImageViewRGB32& screen){ + DestinationMarkerDetector minimap(COLOR_BLUE, {0.815, 0.645, 0.180, 0.320}, true); + auto hits = minimap.detect_all(screen); + const auto yellow = minimap.detect_all_yellow(screen); + hits.insert(hits.end(), yellow.begin(), yellow.end()); + for (const auto& box : hits){ + const double x = box.x + box.width / 2; + const double y = box.y + box.height / 2; + // Player is at the minimap center. Require a marker in the forward cone before a pulse. + if (std::abs(x - 0.906) <= 0.025 && y < 0.815){ return true; } + } + return false; +} +void realign_to_existing_destination(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + // Existing AutoStory old-marker behavior. Its heading effect still needs route-specific field validation. + open_map_from_overworld(info, stream, context, false); + leave_phone_to_overworld(info, stream, context); + pbf_press_button(context, BUTTON_L, 160ms, 840ms); + context.wait_for_all_requests(); +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.h new file mode 100644 index 0000000000..778c373e99 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.h @@ -0,0 +1,24 @@ +/* Destination Marker Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ +#ifndef PokemonAutomation_PokemonSV_MarkerNavigation_H +#define PokemonAutomation_PokemonSV_MarkerNavigation_H +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +enum class DestinationMarkerState{ MISSING, PRESENT, ARRIVED }; +DestinationMarkerState read_destination_marker(const ImageViewRGB32& screen); +// Conservative minimap bearing gate, not a terrain-clearance test. +bool destination_marker_ahead(const ImageViewRGB32& screen); +// Caller owns battle/refusal watchers and deadlines. This routine never flees a battle. +void realign_to_existing_destination(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.cpp new file mode 100644 index 0000000000..1da2e248a8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.cpp @@ -0,0 +1,44 @@ +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_MenuNavigation.h" +#include "PokemonSV_WorldNavigation.h" +#include "PokemonSV_RegionTravel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +bool blueberry_entrance_attempt(const ProgramInfo& info, VideoStream& stream, + ProControllerContext& context, Milliseconds adjustment +){ + pbf_mash_button(context, BUTTON_B, 800ms); + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_L, 400ms, 2400ms); + pbf_move_left_joystick(context, {+1, -1}, 5000ms, 400ms); + pbf_move_left_joystick(context, {-0.5, +0.5}, 840ms + adjustment, 400ms); + return fly_to_overworld_from_map(info, stream, context, true); +} + +} + +void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + // Preserve the material farmer's search range and attempt order. + const std::array adjustments{ + 0ms, 0ms, 32ms, -32ms, 64ms, -64ms, 128ms, -128ms, 0ms, 0ms, 0ms + }; + for (const auto adjustment : adjustments){ + if (blueberry_entrance_attempt(info, stream, context, adjustment)){ + return; + } + stream.log("Failed to fly to Blueberry academy."); + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "Failed to fly to Blueberry academy after 11 attempts.", stream + ); +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.h new file mode 100644 index 0000000000..3b334a241d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.h @@ -0,0 +1,13 @@ +#ifndef PokemonAutomation_PokemonSV_RegionTravel_H +#define PokemonAutomation_PokemonSV_RegionTravel_H +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.cpp new file mode 100644 index 0000000000..e9e295f9b9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.cpp @@ -0,0 +1,20 @@ +#include +#include "PokemonSV_SandwichEating.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +bool wait_for_sandwich_picnic(SandwichEatingActions& actions){ + const uint64_t deadline = actions.now_ms() + 80000; + while (true){ + const uint64_t now = actions.now_ms(); + if (now >= deadline){ return false; } + const uint64_t remaining = deadline - now; + if (actions.confirm_and_observe(std::min(4000, remaining))){ return true; } + } +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.h new file mode 100644 index 0000000000..b47adb7c1c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.h @@ -0,0 +1,23 @@ +#ifndef PokemonAutomation_PokemonSV_SandwichEating_H +#define PokemonAutomation_PokemonSV_SandwichEating_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class SandwichEatingActions{ +public: + virtual ~SandwichEatingActions() = default; + virtual uint64_t now_ms() const = 0; + // Confirm once and observe for picnic, allowing at least this much real time. + virtual bool confirm_and_observe(uint64_t observation_ms) = 0; +}; + +bool wait_for_sandwich_picnic(SandwichEatingActions& actions); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.cpp new file mode 100644 index 0000000000..5b155c85d0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.cpp @@ -0,0 +1,44 @@ +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h" +#include "PokemonSV_SandwichEating.h" +#include "PokemonSV_SandwichEatingConsole.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +class ConsoleSandwichEating : public SandwichEatingActions{ +public: + ConsoleSandwichEating(VideoStream& stream, ProControllerContext& context) + : m_stream(stream), m_context(context){} + virtual uint64_t now_ms() const override{ + return (uint64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + } + virtual bool confirm_and_observe(uint64_t observation_ms) override{ + const WallClock deadline = current_time() + Milliseconds(observation_ms); + const int ret = run_until(m_stream, m_context, + [&](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 160ms, 0ms); + context.wait_for_all_requests(); + // Command completion alone does not establish elapsed game transition time. + context.wait_until(deadline); + }, {m_picnic}); + return ret == 0; + } +private: + VideoStream& m_stream; + ProControllerContext& m_context; + PicnicWatcher m_picnic; +}; +} + +bool wait_for_sandwich_picnic(VideoStream& stream, ProControllerContext& context){ + ConsoleSandwichEating actions(stream, context); + return wait_for_sandwich_picnic(actions); +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.h new file mode 100644 index 0000000000..23f560c771 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.h @@ -0,0 +1,16 @@ +#ifndef PokemonAutomation_PokemonSV_SandwichEatingConsole_H +#define PokemonAutomation_PokemonSV_SandwichEatingConsole_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +bool wait_for_sandwich_picnic(VideoStream& stream, ProControllerContext& context); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp index e5b806bf79..b96b911df9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp @@ -29,6 +29,7 @@ #include "VideoGames/PokemonSV/Resources/PokemonSV_Ingredients.h" #include "VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h" #include "VideoGames/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h" +#include "PokemonSV_SandwichEatingConsole.h" #include "PokemonSV_SandwichRoutines.h" // #include @@ -588,20 +589,10 @@ void finish_sandwich_eating( VideoStream& stream, ProControllerContext& context ){ stream.overlay().add_log("Eating", COLOR_WHITE); - PicnicWatcher picnic_watcher; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (int i = 0; i < 20; i++){ - pbf_press_button(context, BUTTON_A, 160ms, 3840ms); - } - }, - {picnic_watcher} - ); - if (ret < 0){ + if (!wait_for_sandwich_picnic(stream, context)){ dump_image_and_throw_recoverable_exception( info, stream, "PicnicNotDetected", - "finish_sandwich_eating(): cannot detect picnic after 60 seconds." + "finish_sandwich_eating(): cannot detect picnic after 80 seconds." ); } stream.overlay().add_log("Finish eating", COLOR_WHITE); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntAscentConsole.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntAscentConsole.cpp new file mode 100644 index 0000000000..03c679b6ec --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntAscentConsole.cpp @@ -0,0 +1,93 @@ +/* Isolated Uphill Console Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ +#include +#include "CommonTools/Async/InferenceRoutines.h" +#include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "VideoGames/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" +#include "VideoGames/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_IsolatedHuntConsoleActions.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +bool ConsoleIsolatedHuntActions::reset_ascent(const IsolatedHuntRequest& request, const char* reason){ + m_env.console.log("Isolated ascent: stage=flight-reset, reason=" + std::string(reason) + + ", leg=" + std::to_string(m_ascent_leg) + ", reset=" + std::to_string(m_ascent_reset)); + return travel_to_anchor(request); +} +bool ConsoleIsolatedHuntActions::clearing_active() const{ + const auto last = m_sensors.lets_go_kill.last_kill(); + return last != WallClock::min() && current_time() - last < Milliseconds(2000); +} +void ConsoleIsolatedHuntActions::set_deadlines(uint64_t power, uint64_t hunt){ + m_deadline = std::min(power, hunt); +} +IsolatedMarkerState ConsoleIsolatedHuntActions::marker_state(){ + if (m_marker_arrived){ return IsolatedMarkerState::ARRIVED; } + const auto marker = read_destination_marker(m_env.console.video().snapshot()); + m_env.console.log("Isolated ascent: stage=marker, state=" + std::to_string((int)marker) + + ", leg=" + std::to_string(m_ascent_leg) + ", reset=" + std::to_string(m_ascent_reset)); + switch (marker){ + case DestinationMarkerState::PRESENT: return IsolatedMarkerState::PRESENT; + case DestinationMarkerState::ARRIVED: return IsolatedMarkerState::ARRIVED; + case DestinationMarkerState::MISSING: return IsolatedMarkerState::MISSING; + } + return IsolatedMarkerState::MISSING; +} +bool ConsoleIsolatedHuntActions::realign_marker(){ + bool present = false; + const bool success = guard("ascent reanchor: old-marker heading correction", Milliseconds(20000), + [&](ProControllerContext& context){ + realign_to_existing_destination(m_env.program_info(), m_env.console, context); + present = marker_state() == IsolatedMarkerState::PRESENT && + destination_marker_ahead(m_env.console.video().snapshot()); + m_env.console.log("Isolated ascent: stage=reanchor, marker ahead=" + std::to_string(present)); + }); + return success && present; +} +IsolatedHuntRound ConsoleIsolatedHuntActions::advance_ascent(const IsolatedHuntRequest& request, + const IsolatedAscentLimits& limits +){ + const auto before = m_stats.m_kills.load(); + const auto started = now_ms(); + NormalBattleMenuWatcher battle(COLOR_RED); + SweatBubbleWatcher refusal(COLOR_GREEN); + DestinationMarkerWatcher arrival(COLOR_CYAN, {0.717, 0.165, 0.03, 0.061}); + // The deadline is also checked by policy between stages. Shorten this movement before queuing it. + const auto remaining = m_deadline > started ? m_deadline - started : 0; + if (remaining < (uint64_t)limits.segment_ms + limits.clearing_wait_ms + 4000){ return {.budget_exhausted = true}; } + const int ret = run_until(m_env.console, m_context, + [&](ProControllerContext& context){ + walk_forward_while_clear_front_path(m_env.program_info(), m_env.console, context, + Milliseconds(limits.segment_ms), +1, Milliseconds(limits.segment_ms + 1), Milliseconds(limits.clearing_wait_ms)); + // Observe recent defeats before another map operation or movement. Never wait without a bound. + const auto quiet_deadline = std::min(m_deadline, now_ms() + 10000); + do{ + context.wait_for(Milliseconds(250)); + }while (now_ms() < quiet_deadline && clearing_active()); + + }, {battle, refusal, arrival}); + m_pending_battle = ret == 0; + m_pending_refusal = ret == 1; + m_marker_arrived = ret == 2; + m_stats.passes++; + if (m_pending_refusal){ m_stats.refusals++; } + m_sensors.throw_if_no_sound(); + update_elapsed(); + const auto kills = m_stats.m_kills.load() - before; + m_empty_rounds = kills == 0 ? m_empty_rounds + 1 : 0; + m_env.console.log("Isolated ascent: stage=advance, target=" + request.pokemon + ", leg=" + + std::to_string(++m_ascent_leg) + ", movement cap ms=" + std::to_string(limits.segment_ms) + + ", elapsed ms=" + std::to_string(now_ms() - started) + ", detected defeats=" + std::to_string(kills) + + ", no-progress=" + std::to_string(m_empty_rounds) + ", event=" + std::to_string(ret)); + return {.kills = kills, .event = m_pending_battle ? IsolatedHuntEvent::BATTLE : + m_pending_refusal ? IsolatedHuntEvent::REFUSAL : IsolatedHuntEvent::CLEAR, + .clearing_busy = ret < 0 && clearing_active()}; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.cpp new file mode 100644 index 0000000000..b5f6dc83ff --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.cpp @@ -0,0 +1,327 @@ +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/UnexpectedBattleException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "VideoGames/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" +#include "VideoGames/PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "VideoGames/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_IsolatedHuntTravel.h" +#include "PokemonSV_IsolatedHuntCorridor.h" +#include "PokemonSV_IsolatedHuntConsoleActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +class StageDeadline : public VisualInferenceCallback{ +public: + StageDeadline(Milliseconds timeout) + : VisualInferenceCallback("IsolatedStageDeadline"), m_deadline(current_time() + timeout) + {} + virtual void make_overlays(VideoOverlaySet&) const override{} + virtual bool process_frame(const ImageViewRGB32&, WallClock) override{ + return current_time() >= m_deadline; + } +private: + WallClock m_deadline; +}; + +const char* stop_name(IsolatedHuntStop stop){ + switch (stop){ + case IsolatedHuntStop::ROUND_LIMIT: return "round limit"; + case IsolatedHuntStop::START_FAILED: return "start flight failed"; + case IsolatedHuntStop::INVALID_PLAN: return "invalid plan"; + case IsolatedHuntStop::POWER_UNVERIFIED: return "Meal Power not verified"; + case IsolatedHuntStop::SETUP_FAILED: return "setup failed"; + case IsolatedHuntStop::TRAVEL_FAILED: return "travel failed"; + case IsolatedHuntStop::UNRESOLVED_REFUSAL: return "unresolved refusal"; + case IsolatedHuntStop::BATTLE_POLICY: return "battle policy stop"; + case IsolatedHuntStop::BATTLE_FAILED: return "battle failed"; + case IsolatedHuntStop::TIME_LIMIT: return "time limit"; + case IsolatedHuntStop::NO_PROGRESS: return "no progress"; + case IsolatedHuntStop::REFRESH_FAILED: return "refresh failed"; + case IsolatedHuntStop::POWER_EXPIRED: return "sandwich power expired"; + case IsolatedHuntStop::MARKER_MISSING: return "destination marker missing"; + case IsolatedHuntStop::REANCHOR_FAILED: return "marker reanchor failed"; + case IsolatedHuntStop::CLEARING_TIMEOUT: return "lead still clearing at observation cap"; + } + return "unknown"; +} + +} + +ConsoleIsolatedHuntActions::ConsoleIsolatedHuntActions(SingleSwitchProgramEnvironment& env, + ProControllerContext& context, IsolatedHuntStats& stats, Language language, + IsolatedHuntSandwichOption& sandwich, const EncounterBotCommonOptions& encounter_options, + const IsolatedHuntRequest& request +) + : m_env(env), m_context(context), m_stats(stats), m_language(language), m_sandwich(sandwich) + , m_options(make_isolated_encounter_options(encounter_options, request)) + , m_sensors(env.logger(), env.console, context) + , m_battle_tracker(env.logger(), m_sensors) + , m_hunt_seconds_before(stats.hunt_seconds.load()) +{ + m_encounters = std::make_unique(env, env.console, stats, m_sensors.lets_go_kill); +} + +uint64_t ConsoleIsolatedHuntActions::now_ms() const{ + return (uint64_t)std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +void ConsoleIsolatedHuntActions::phase(const std::string& stage){ + m_env.console.log("Isolated hunt state: " + stage); + m_env.console.overlay().add_log(stage, COLOR_BLUE); +} + +void ConsoleIsolatedHuntActions::update_elapsed(){ + if (m_hunt_started != 0){ + m_stats.hunt_seconds.store(m_hunt_seconds_before + (now_ms() - m_hunt_started) / 1000); + } + m_env.update_stats(); +} + +bool ConsoleIsolatedHuntActions::guard(const std::string& stage, Milliseconds timeout, + const std::function& command +){ + phase(stage); + const auto started = now_ms(); + m_env.console.log("Isolated stage begin: stage=" + stage + ", timeout ms=" + std::to_string(timeout.count())); + if (m_pending_battle || m_pending_refusal){ return false; } + timeout = Milliseconds(isolated_stage_timeout_ms(started, m_deadline, (uint64_t)timeout.count())); + if (timeout <= 0ms){ return false; } + NormalBattleMenuWatcher battle(COLOR_RED); + SweatBubbleWatcher refusal(COLOR_GREEN); + StageDeadline deadline(timeout); + try{ + const int result = run_until( + m_env.console, m_context, + [&](ProControllerContext& context){ command(context); }, {battle, refusal, deadline} + ); + m_pending_battle = result == 0; + m_pending_refusal = result == 1; + if (result == 2){ + m_env.console.log("Isolated stage timed out: " + stage, COLOR_RED); + } + const std::string outcome = result < 0 ? "completed" : result == 0 ? "battle" : result == 1 ? "refusal" : "timeout"; + m_env.console.log("Isolated stage end: stage=" + stage + ", outcome=" + outcome + + ", elapsed ms=" + std::to_string(now_ms() - started)); + return result < 0; + }catch (UnexpectedBattleException&){ + m_pending_battle = true; + }catch (ProgramFinishedException&){ + m_pending_battle = true; + }catch (OperationFailedException& error){ + m_env.console.log(stage + ": " + error.message(), COLOR_RED); + } + m_env.console.log("Isolated stage end: stage=" + stage + ", outcome=exception, battle=" + + std::to_string(m_pending_battle) + ", elapsed ms=" + std::to_string(now_ms() - started)); + return false; +} + +bool ConsoleIsolatedHuntActions::reset_start(const IsolatedHuntRequest&){ + bool arrived = false; + const bool success = guard("re-fly Zero Gate starting anchor", 90000ms, + [&](ProControllerContext& context){ + // The full-hunt start contract is outdoors at Zero Gate, including after a picnic retry. + // Select only the overlapping anchor; never substitute a nearby unrelated fly point. + open_map_from_overworld(m_env.program_info(), m_env.console, context); + arrived = fly_to_overworld_from_map(m_env.program_info(), m_env.console, context, true); + } + ); + return success && arrived; +} + +bool ConsoleIsolatedHuntActions::prepare_sandwich(const IsolatedHuntRequest& request){ + m_sandwich.configure_for(request.type); + m_env.console.log("Isolated recipe: target=" + request.pokemon + ", type=" + + (request.type == IsolatedEncounterType::FIRE ? "fire" : "grass") + + ", herbs=" + std::to_string((bool)m_sandwich.USE_HERBA)); + // Six rice servings need more placement and OCR steps than the previous single-filling pilot. + const bool success = guard("save and make " + request.pokemon + " sandwich", 600000ms, + [&](ProControllerContext& context){ + save_game_from_overworld(m_env.program_info(), m_env.console, context); + picnic_at_zero_gate(m_env.program_info(), m_env.console, context); + pbf_move_left_joystick(context, {0, +1}, 560ms, 0ms); + if (!enter_sandwich_recipe_list(m_env.program_info(), m_env.console, context)){ + throw UserSetupError(m_env.logger(), "Could not open sandwich recipes. Inspect ingredients and picnic setup."); + } + make_sandwich_option(m_env, m_env.console, context, m_sandwich); + m_stats.sandwiches++; + leave_picnic(m_env.program_info(), m_env.console, context); + } + ); + m_env.update_stats(); + return success; +} + +bool ConsoleIsolatedHuntActions::verify_meal_power(const IsolatedHuntRequest& request){ + bool verified = false; + const bool success = guard("automatic Meal Power verification", 120000ms, + [&](ProControllerContext& context){ + verified = m_verifier && m_verifier(context, request, IsolatedHuntVerification::MEAL_POWER); + } + ); + return success && verified; +} + +bool ConsoleIsolatedHuntActions::travel_to_anchor(const IsolatedHuntRequest& request){ + bool arrived = false; + const bool success = guard("travel to " + request.pokemon + " patch", 420000ms, + [&](ProControllerContext& context){ + if (m_initial_travel && m_resume_at_anchor){ + m_env.console.log("Anchor resume: supervised current patch; skipping initial flight."); + arrived = true; + }else{ + arrived = travel_to_isolated_hunt(m_env.program_info(), m_env.console, context, + request.location, m_initial_travel, m_language); + } + if (arrived){ + if (request.location == IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL){ + if (m_initial_travel){ + arrived = m_verifier && m_verifier(context, request, IsolatedHuntVerification::CENTRAL_PATH); + } + m_marker_arrived = false; + }else{ + approach_isolated_patch(m_env.console, context, request.location); + } + } + } + ); + if (success && arrived && !m_initial_travel){ + m_stats.refreshes++; + m_ascent_reset++; + m_ascent_leg = 0; + m_env.console.log("Isolated ascent: stage=flight-reset, reset=" + std::to_string(m_ascent_reset) + ", landed=1"); + } + if (success && arrived && m_initial_travel){ + m_hunt_started = now_ms(); + m_initial_travel = false; + } + return success && arrived; +} + +void ConsoleIsolatedHuntActions::roam(ProControllerContext& context, IsolatedHuntLocation location){ + const auto duration = location == IsolatedHuntLocation::CHARGESTONE_CAVE ? 700ms : 1400ms; + const std::array, 4> directions{{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}}; + for (const auto& direction : directions){ + pbf_press_button(context, BUTTON_R, 160ms, 1500ms); + pbf_move_left_joystick(context, {direction[0], direction[1]}, duration, 200ms); + } + pbf_wait(context, 2000ms); + context.wait_for_all_requests(); +} + +IsolatedHuntRound ConsoleIsolatedHuntActions::clear_round(const IsolatedHuntRequest& request){ + phase("clearing " + request.pokemon); + const auto started = now_ms(); + const auto before = m_stats.m_kills.load(); + NormalBattleMenuWatcher battle(COLOR_RED); + SweatBubbleWatcher refusal(COLOR_GREEN); + const int result = run_until( + m_env.console, m_context, + [&](ProControllerContext& context){ roam(context, request.location); }, + {battle, refusal} + ); + m_pending_battle = result == 0; + m_stats.passes++; + if (result == 1){ + m_stats.refusals++; + } + m_sensors.throw_if_no_sound(); + update_elapsed(); + const auto event = result == 0 ? IsolatedHuntEvent::BATTLE : + result == 1 ? IsolatedHuntEvent::REFUSAL : IsolatedHuntEvent::CLEAR; + const auto kills = m_stats.m_kills.load() - before; + m_empty_rounds = event == IsolatedHuntEvent::CLEAR && kills == 0 ? m_empty_rounds + 1 : 0; + m_env.console.log("Isolated round: target=" + request.pokemon + ", elapsed ms=" + + std::to_string(now_ms() - started) + ", detected kills=" + std::to_string(kills) + + ", empty rounds=" + std::to_string(m_empty_rounds) + ", event=" + + (event == IsolatedHuntEvent::CLEAR ? "clear" : event == IsolatedHuntEvent::REFUSAL ? "refusal" : "battle")); + return {.kills = kills, .event = event}; +} + +bool ConsoleIsolatedHuntActions::refresh_spawns(const IsolatedHuntRequest& request){ + m_env.console.log("Isolated refresh: reason=empty round, count=" + std::to_string(m_empty_rounds)); + return travel_to_anchor(request); +} + +bool ConsoleIsolatedHuntActions::acquire_refused_target(const IsolatedHuntRequest&){ + phase("refusal: attempt battle entry; do not reset spawns"); + NormalBattleMenuWatcher battle(COLOR_RED); + const int result = run_until( + m_env.console, m_context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_ZR, 5000ms); + pbf_wait(context, 10000ms); + }, + {battle} + ); + m_pending_battle = result == 0; + m_pending_refusal = !m_pending_battle; + return m_pending_battle; +} + +IsolatedHuntBattleResult ConsoleIsolatedHuntActions::handle_battle(const IsolatedHuntRequest& request){ + phase("shared encounter handling: " + request.pokemon); + m_pending_battle = false; + m_pending_refusal = false; + m_sensors.throw_if_no_sound(); + m_stats.m_encounters++; + m_encounters->encounter_rate_tracker().report_encounter(); + bool caught = false, should_save = false; + try{ + process_battle(caught, should_save, m_env, *m_options, m_env.console, m_context, + m_battle_tracker, m_encounters->encounter_frequencies(), m_stats.m_shinies, m_language); + }catch (ProgramFinishedException&){ + update_elapsed(); + return IsolatedHuntBattleResult::STOP; + } + if (should_save){ + save_game_from_overworld(m_env.program_info(), m_env.console, m_context); + } + update_elapsed(); + return IsolatedHuntBattleResult::CONTINUE; +} + +bool ConsoleIsolatedHuntActions::return_to_zero_gate(const IsolatedHuntRequest& request){ + // The caller has accepted the stop policy. Hunt deadlines must not disable the bounded departure stage. + // Pending battle/refusal latches remain enforced by guard(). + set_deadlines(UINT64_MAX, UINT64_MAX); + bool arrived = false; + const bool success = guard("return to Zero Gate", 180000ms, + [&](ProControllerContext& context){ + arrived = return_from_isolated_hunt(m_env.program_info(), m_env.console, context, request.location); + if (arrived){ + save_game_from_overworld(m_env.program_info(), m_env.console, context); + } + } + ); + return success && arrived; +} + +void ConsoleIsolatedHuntActions::report(const IsolatedHuntRequest& request, const IsolatedHuntResult& result){ + update_elapsed(); + const auto seconds = m_hunt_started == 0 ? 0 : (now_ms() - m_hunt_started) / 1000; + const auto rate = seconds == 0 ? 0.0 : 60.0 * (double)result.kills / (double)seconds; + m_env.console.log("Isolated result: target=" + request.pokemon + ", stop=" + + stop_name(result.stop) + ", detected kills=" + std::to_string(result.kills) + + ", rounds=" + std::to_string(result.rounds) + ", encounters=" + std::to_string(result.encounters) + ", refusals=" + std::to_string(result.refusals) + + ", refreshes=" + std::to_string(result.refreshes) + ", hunt seconds=" + std::to_string(seconds) + + ", kills/min=" + std::to_string(rate)); +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.h new file mode 100644 index 0000000000..ba592d03b6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.h @@ -0,0 +1,78 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntConsoleActions_H +#define PokemonAutomation_PokemonSV_IsolatedHuntConsoleActions_H + +#include +#include +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" +#include "VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.h" +#include "PokemonSV_IsolatedHuntLoop.h" +#include "PokemonSV_IsolatedHuntStats.h" +#include "PokemonSV_IsolatedHuntEncounter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class ConsoleIsolatedHuntActions : public IsolatedHuntActions{ +public: + ConsoleIsolatedHuntActions(SingleSwitchProgramEnvironment& env, ProControllerContext& context, + IsolatedHuntStats& stats, Language language, IsolatedHuntSandwichOption& sandwich, + const EncounterBotCommonOptions& encounter_options, const IsolatedHuntRequest& request); + virtual bool reset_start(const IsolatedHuntRequest& request) override; + virtual bool prepare_sandwich(const IsolatedHuntRequest& request) override; + using Verifier = std::function; + void set_verifier(Verifier verifier){ m_verifier = std::move(verifier); } + void resume_at_anchor(){ m_resume_at_anchor = true; } + virtual bool verify_meal_power(const IsolatedHuntRequest& request) override; + virtual bool travel_to_anchor(const IsolatedHuntRequest& request) override; + virtual IsolatedHuntRound clear_round(const IsolatedHuntRequest& request) override; + virtual bool refresh_spawns(const IsolatedHuntRequest& request) override; + virtual bool acquire_refused_target(const IsolatedHuntRequest& request) override; + virtual IsolatedHuntBattleResult handle_battle(const IsolatedHuntRequest& request) override; + virtual bool battle_pending() const override{ return m_pending_battle; } + virtual uint64_t now_ms() const override; + virtual bool refusal_pending() const override{ return m_pending_refusal; } + virtual IsolatedMarkerState marker_state() override; + virtual bool realign_marker() override; + virtual bool reset_ascent(const IsolatedHuntRequest& request, const char* reason) override; + virtual IsolatedHuntRound advance_ascent(const IsolatedHuntRequest& request, const IsolatedAscentLimits& limits) override; + virtual void set_deadlines(uint64_t power, uint64_t hunt) override; + bool return_to_zero_gate(const IsolatedHuntRequest& request); + void report(const IsolatedHuntRequest& request, const IsolatedHuntResult& result); +private: + bool guard(const std::string& stage, Milliseconds timeout, + const std::function& command); + void roam(ProControllerContext& context, IsolatedHuntLocation location); + void phase(const std::string& stage); + void update_elapsed(); + bool clearing_active() const; + + Verifier m_verifier; + SingleSwitchProgramEnvironment& m_env; + ProControllerContext& m_context; + IsolatedHuntStats& m_stats; + Language m_language; + IsolatedHuntSandwichOption& m_sandwich; + std::unique_ptr m_options; + // Audio inference must stop before destroying the tracker captured in its callback. + std::unique_ptr m_encounters; + OverworldSensors m_sensors; + OverworldBattleTracker m_battle_tracker; + uint16_t m_empty_rounds = 0; + bool m_initial_travel = true; + bool m_resume_at_anchor = false; + bool m_pending_battle = false; + bool m_pending_refusal = false; + bool m_marker_arrived = false; + uint64_t m_deadline = UINT64_MAX; + uint16_t m_ascent_leg = 0; + uint16_t m_ascent_reset = 0; + uint64_t m_hunt_started = 0; + uint64_t m_hunt_seconds_before; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.cpp new file mode 100644 index 0000000000..b70f861563 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.cpp @@ -0,0 +1,154 @@ +/* Isolated Uphill Corridor + * + * From: https://github.com/PokemonAutomation/ + * + */ +#include "PokemonSV_IsolatedHuntCorridor.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +bool budget_expired(IsolatedHuntResult& result, const IsolatedHuntLimits& limits, + IsolatedHuntActions& actions, uint64_t power_started, uint64_t hunt_started +){ + const uint64_t now = actions.now_ms(); + if (now - power_started >= limits.power_duration_ms){ + result.stop = IsolatedHuntStop::POWER_EXPIRED; + return true; + } + if (now - hunt_started >= limits.duration_ms){ + result.stop = IsolatedHuntStop::TIME_LIMIT; + return true; + } + return false; +} +bool encounter(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, + IsolatedHuntResult& result, IsolatedHuntEvent event +){ + if (event == IsolatedHuntEvent::REFUSAL){ + result.refusals++; + if (!actions.acquire_refused_target(request)){ + result.stop = IsolatedHuntStop::UNRESOLVED_REFUSAL; + return true; + } + } + result.encounters++; + const auto battle = actions.handle_battle(request); + if (battle == IsolatedHuntBattleResult::CONTINUE){ return false; } + result.stop = battle == IsolatedHuntBattleResult::STOP ? + IsolatedHuntStop::BATTLE_POLICY : IsolatedHuntStop::BATTLE_FAILED; + return true; +} +bool interrupted(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, + IsolatedHuntResult& result +){ + if (actions.refusal_pending() || actions.battle_pending()){ + if (result.stop == IsolatedHuntStop::ROUND_LIMIT){ result.stop = IsolatedHuntStop::TRAVEL_FAILED; } + } + if (actions.refusal_pending()){ + encounter(request, actions, result, IsolatedHuntEvent::REFUSAL); + return true; + } + if (actions.battle_pending()){ + encounter(request, actions, result, IsolatedHuntEvent::BATTLE); + return true; + } + return false; +} +bool reset_ascent(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, + IsolatedHuntResult& result, const char* reason +){ + if (!actions.reset_ascent(request, reason)){ + result.stop = IsolatedHuntStop::TRAVEL_FAILED; + interrupted(request, actions, result); + return false; + } + result.refreshes++; + return true; +} +struct AscentState{ + uint16_t leg = 0; + uint8_t empty = 0; + bool reset = false; + const char* reason = "segment cap"; +}; +bool prepare_segment(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, + IsolatedHuntResult& result, AscentState& state +){ + const auto marker = state.reset ? IsolatedMarkerState::ARRIVED : actions.marker_state(); + if (interrupted(request, actions, result)){ return false; } + if (marker == IsolatedMarkerState::ARRIVED){ + if (!reset_ascent(request, actions, result, state.reset ? state.reason : "marker arrival")){ return false; } + state.leg = 0; + state.reset = false; + if (actions.marker_state() != IsolatedMarkerState::PRESENT){ + result.stop = IsolatedHuntStop::REANCHOR_FAILED; + interrupted(request, actions, result); + return false; + } + }else if (marker == IsolatedMarkerState::MISSING){ + result.stop = IsolatedHuntStop::MARKER_MISSING; + return false; + } + return true; +} +bool align_ascent(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, IsolatedHuntResult& result){ + if (!actions.realign_marker()){ + result.stop = IsolatedHuntStop::REANCHOR_FAILED; + interrupted(request, actions, result); + return false; + } + return true; +} +} +uint64_t isolated_stage_timeout_ms(uint64_t started, uint64_t deadline, uint64_t requested){ + const uint64_t remaining = deadline > started ? deadline - started : 0; + return remaining < requested ? remaining : requested; +} +bool valid_isolated_ascent(const IsolatedAscentLimits& limits){ + return limits.segments_per_ascent > 0 && limits.segments_per_ascent <= 30 && + limits.segment_ms >= 100 && limits.segment_ms <= 2000 && + limits.clearing_wait_ms >= 2000 && limits.clearing_wait_ms <= 15000; +} +IsolatedHuntResult run_isolated_corridor(const IsolatedHuntRequest& request, + const IsolatedHuntLimits& limits, IsolatedHuntActions& actions, + uint64_t power_started, uint64_t hunt_started +){ + if (!valid_isolated_ascent(limits.ascent) || limits.max_rounds == 0 || limits.max_empty_rounds == 0){ + return {.stop = IsolatedHuntStop::INVALID_PLAN}; + } + IsolatedHuntResult result{.stop = IsolatedHuntStop::ROUND_LIMIT}; + AscentState state; + while (result.rounds < limits.max_rounds){ + if (interrupted(request, actions, result)){ return result; } + if (budget_expired(result, limits, actions, power_started, hunt_started)){ return result; } + if (!prepare_segment(request, actions, result, state)){ return result; } + if (budget_expired(result, limits, actions, power_started, hunt_started)){ return result; } + if (!align_ascent(request, actions, result)){ return result; } + if (budget_expired(result, limits, actions, power_started, hunt_started)){ return result; } + const auto round = actions.advance_ascent(request, limits.ascent); + if (round.budget_exhausted){ + result.stop = power_started + limits.power_duration_ms < hunt_started + limits.duration_ms ? + IsolatedHuntStop::POWER_EXPIRED : IsolatedHuntStop::TIME_LIMIT; + return result; + } + result.rounds++; + result.kills += round.kills; + state.reset = ++state.leg >= limits.ascent.segments_per_ascent; + state.reason = "segment cap"; + if (round.event != IsolatedHuntEvent::CLEAR){ + if (encounter(request, actions, result, round.event)){ return result; } + state.reset = true; + state.reason = "handled encounter"; + state.empty = 0; + continue; + } + if (round.clearing_busy){ result.stop = IsolatedHuntStop::CLEARING_TIMEOUT; return result; } + state.empty = round.kills == 0 ? state.empty + 1 : 0; + if (state.empty >= limits.max_empty_rounds){ result.stop = IsolatedHuntStop::NO_PROGRESS; return result; } + } + return result; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.h new file mode 100644 index 0000000000..efce0b795d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.h @@ -0,0 +1,20 @@ +/* Isolated Uphill Corridor + * + * From: https://github.com/PokemonAutomation/ + * + */ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntCorridor_H +#define PokemonAutomation_PokemonSV_IsolatedHuntCorridor_H +#include "PokemonSV_IsolatedHuntLoop.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +uint64_t isolated_stage_timeout_ms(uint64_t started, uint64_t deadline, uint64_t requested); +bool valid_isolated_ascent(const IsolatedAscentLimits& limits); +IsolatedHuntResult run_isolated_corridor(const IsolatedHuntRequest& request, + const IsolatedHuntLimits& limits, IsolatedHuntActions& actions, + uint64_t power_started, uint64_t hunt_started); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.cpp new file mode 100644 index 0000000000..6ad626d324 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.cpp @@ -0,0 +1,44 @@ +#include "Common/Cpp/Json/JsonObject.h" +#include "PokemonSV_IsolatedHuntEncounter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +const char* action_slug(IsolatedShinyAction action){ + switch (action){ + case IsolatedShinyAction::STOP: return "stop-program"; + case IsolatedShinyAction::CATCH: return "throw-balls"; + case IsolatedShinyAction::CATCH_AND_SAVE: return "throw-balls-and-save"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid isolated hunt shiny action."); +} + +} + +std::unique_ptr make_isolated_encounter_options( + const EncounterBotCommonOptions& base, const IsolatedHuntRequest& request +){ + auto options = std::make_unique(); + options->load_json(base.to_json()); + options->NOTIFICATION_NONSHINY.load_json(base.NOTIFICATION_NONSHINY.to_json()); + options->NOTIFICATION_SHINY.load_json(base.NOTIFICATION_SHINY.to_json()); + options->NOTIFICATION_CATCH_SUCCESS.load_json(base.NOTIFICATION_CATCH_SUCCESS.to_json()); + options->NOTIFICATION_CATCH_FAILED.load_json(base.NOTIFICATION_CATCH_FAILED.to_json()); + JsonObject rule; + rule["pokemon"] = request.pokemon; + rule["shininess"] = "shiny"; + rule["action"] = action_slug(request.shiny_action); + rule["pokeball"] = request.ball; + rule["ball_limit"] = request.ball_limit; + auto row = std::make_unique(options->ACTIONS_TABLE); + row->load_json(JsonValue(std::move(rule))); + // The shared handler applies the last matching rule; this row owns the selected target. + options->ACTIONS_TABLE.append_row(std::move(row)); + return options; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.h new file mode 100644 index 0000000000..d75bf2eb6a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.h @@ -0,0 +1,14 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntEncounter_H +#define PokemonAutomation_PokemonSV_IsolatedHuntEncounter_H +#include "VideoGames/PokemonSV/Options/PokemonSV_EncounterBotCommon.h" +#include "PokemonSV_IsolatedHuntPlan.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +std::unique_ptr make_isolated_encounter_options( + const EncounterBotCommonOptions& base, const IsolatedHuntRequest& request +); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.cpp new file mode 100644 index 0000000000..5779cdbcf1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.cpp @@ -0,0 +1,35 @@ +/* Isolated Hunt Flight Policy + * + * From: https://github.com/PokemonAutomation/ + * + */ +#include "PokemonSV_IsolatedHuntText.h" +#include "PokemonSV_IsolatedHuntFlight.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +std::u32string central_name(Language language){ + switch (language){ + case Language::English: return U"westprovinceareaonecentral"; + case Language::ChineseTraditional: return U"西第1區中央"; + default: return {}; + } +} +} +bool fly_to_isolated_central(IsolatedFlightActions& actions, Language language){ + const auto expected = central_name(language); + if (expected.empty() || !actions.open_confirmation()){ + return false; + } + // Both reads must contain the complete name; never fuzzy-match North to Central. + for (size_t read = 0; read < 2; read++){ + if (normalize_isolated_text(actions.read_destination()) != expected){ + return false; + } + } + return actions.confirmation_visible() && actions.confirm_and_wait(); +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.h new file mode 100644 index 0000000000..560c9c7eae --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.h @@ -0,0 +1,27 @@ +/* Isolated Hunt Flight Policy + * + * From: https://github.com/PokemonAutomation/ + * + */ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntFlight_H +#define PokemonAutomation_PokemonSV_IsolatedHuntFlight_H +#include +#include "CommonFramework/Language.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +class IsolatedFlightActions{ +public: + virtual ~IsolatedFlightActions() = default; + // Select a candidate and stop at the Yes/No flight confirmation, without accepting it. + virtual bool open_confirmation() = 0; + virtual std::string read_destination() = 0; + virtual bool confirmation_visible() = 0; + virtual bool confirm_and_wait() = 0; +}; +// A generic fly icon or successful landing is not evidence of destination identity. +bool fly_to_isolated_central(IsolatedFlightActions& actions, Language language); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.cpp new file mode 100644 index 0000000000..d0a6c59e7d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.cpp @@ -0,0 +1,183 @@ +#include "PokemonSV_IsolatedHuntLoop.h" +#include "PokemonSV_IsolatedHuntCorridor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +bool handle_battle_policy(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, IsolatedHuntResult& result){ + result.encounters++; + switch (actions.handle_battle(request)){ + case IsolatedHuntBattleResult::STOP: + result.stop = IsolatedHuntStop::BATTLE_POLICY; + return true; + case IsolatedHuntBattleResult::FAILED: + result.stop = IsolatedHuntStop::BATTLE_FAILED; + return true; + case IsolatedHuntBattleResult::CONTINUE: + return false; + } + result.stop = IsolatedHuntStop::BATTLE_FAILED; + return true; +} + +IsolatedHuntResult failed_stage(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, IsolatedHuntStop reason){ + IsolatedHuntResult result{.stop = reason}; + if (actions.refusal_pending()){ + result.refusals++; + if (!actions.acquire_refused_target(request)){ + result.stop = IsolatedHuntStop::UNRESOLVED_REFUSAL; + return result; + } + handle_battle_policy(request, actions, result); + }else if (actions.battle_pending()){ + handle_battle_policy(request, actions, result); + } + return result; +} + +bool handle_encounter(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, IsolatedHuntResult& result){ + if (handle_battle_policy(request, actions, result)){ + return true; + } + if (!actions.travel_to_anchor(request)){ + result.stop = IsolatedHuntStop::TRAVEL_FAILED; + if (actions.battle_pending()){ + handle_battle_policy(request, actions, result); + } + return true; + } + return false; +} + +bool handle_event(const IsolatedHuntRequest& request, IsolatedHuntActions& actions, + IsolatedHuntResult& result, IsolatedHuntEvent event +){ + if (event == IsolatedHuntEvent::REFUSAL){ + result.refusals++; + if (!actions.acquire_refused_target(request)){ + result.stop = IsolatedHuntStop::UNRESOLVED_REFUSAL; + return true; + } + } + return handle_encounter(request, actions, result); +} + +bool handle_empty_round(const IsolatedHuntRequest& request, const IsolatedHuntLimits& limits, + IsolatedHuntActions& actions, IsolatedHuntResult& result, uint8_t empty, bool allow_refresh +){ + if (empty >= limits.max_empty_rounds){ + result.stop = IsolatedHuntStop::NO_PROGRESS; + return true; + } + if (empty > 0 && allow_refresh){ + if (!actions.refresh_spawns(request)){ + result.stop = IsolatedHuntStop::REFRESH_FAILED; + if (actions.battle_pending()){ + handle_battle_policy(request, actions, result); + } + return true; + } + result.refreshes++; + } + return false; +} + +bool expired(IsolatedHuntResult& result, const IsolatedHuntLimits& limits, + uint64_t now, uint64_t hunt_started, uint64_t power_started +){ + if (now - power_started >= limits.power_duration_ms){ + result.stop = IsolatedHuntStop::POWER_EXPIRED; + return true; + } + if (now - hunt_started >= limits.duration_ms){ + result.stop = IsolatedHuntStop::TIME_LIMIT; + return true; + } + return false; +} + +} + +namespace{ +struct HuntSetup{ + IsolatedHuntResult result; + uint64_t power_started = 0; +}; +HuntSetup setup_hunt(const IsolatedHuntRequest& request, const IsolatedHuntLimits& limits, IsolatedHuntActions& actions){ + if (!make_isolated_hunt_plan({request}).error.empty() || + (limits.ascent.enabled && !valid_isolated_ascent(limits.ascent)) || + (limits.resume_at_anchor && (!limits.use_existing_power || request.location != IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL)) || + limits.max_rounds == 0 || limits.max_empty_rounds == 0 || limits.duration_ms == 0 || limits.power_duration_ms == 0){ + return {{.stop = IsolatedHuntStop::INVALID_PLAN}}; + } + const uint64_t setup_started = actions.now_ms(); + if (limits.use_existing_power){ + actions.set_deadlines(setup_started + limits.power_duration_ms, UINT64_MAX); + } + if (!limits.resume_at_anchor && !actions.reset_start(request)){ + return {failed_stage(request, actions, IsolatedHuntStop::START_FAILED)}; + } + if (!limits.use_existing_power && !actions.prepare_sandwich(request)){ + return {failed_stage(request, actions, IsolatedHuntStop::SETUP_FAILED)}; + } + const uint64_t power_started = limits.use_existing_power ? setup_started : actions.now_ms(); + actions.set_deadlines(power_started + limits.power_duration_ms, UINT64_MAX); + if (!actions.verify_meal_power(request)){ + return {failed_stage(request, actions, IsolatedHuntStop::POWER_UNVERIFIED)}; + } + if (!actions.travel_to_anchor(request)){ + return {failed_stage(request, actions, IsolatedHuntStop::TRAVEL_FAILED)}; + } + return {{.stop = IsolatedHuntStop::ROUND_LIMIT}, power_started}; +} +} + +bool can_leave_isolated_hunt(IsolatedHuntStop stop){ + return stop == IsolatedHuntStop::ROUND_LIMIT || stop == IsolatedHuntStop::TIME_LIMIT || + stop == IsolatedHuntStop::POWER_EXPIRED; +} + +IsolatedHuntResult run_isolated_hunt( + const IsolatedHuntRequest& request, const IsolatedHuntLimits& limits, + IsolatedHuntActions& actions +){ + const auto setup = setup_hunt(request, limits, actions); + if (setup.result.stop != IsolatedHuntStop::ROUND_LIMIT){ return setup.result; } + const uint64_t power_started = setup.power_started; + IsolatedHuntResult result{.stop = IsolatedHuntStop::ROUND_LIMIT}; + const uint64_t started = actions.now_ms(); + actions.set_deadlines(power_started + limits.power_duration_ms, started + limits.duration_ms); + if (limits.ascent.enabled){ + return run_isolated_corridor(request, limits, actions, power_started, started); + } + uint8_t empty = 0; + while (result.rounds < limits.max_rounds){ + if (expired(result, limits, actions.now_ms(), started, power_started)){ + return result; + } + const auto round = actions.clear_round(request); + result.kills += round.kills; + result.rounds++; + if (round.event != IsolatedHuntEvent::CLEAR){ + if (handle_event(request, actions, result, round.event)){ + return result; + } + empty = 0; + continue; + } + empty = round.kills == 0 ? empty + 1 : 0; + const auto now = actions.now_ms(); + const bool allow_refresh = result.rounds < limits.max_rounds && now - started < limits.duration_ms && + now - power_started < limits.power_duration_ms; + if (handle_empty_round(request, limits, actions, result, empty, allow_refresh)){ + return result; + } + } + return result; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.h new file mode 100644 index 0000000000..6e77f6e8f7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.h @@ -0,0 +1,87 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntLoop_H +#define PokemonAutomation_PokemonSV_IsolatedHuntLoop_H + +#include "PokemonSV_IsolatedHuntPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class IsolatedMarkerState{ MISSING, PRESENT, ARRIVED }; + +enum class IsolatedHuntVerification{ MEAL_POWER, CENTRAL_PATH }; +enum class IsolatedHuntEvent{ CLEAR, REFUSAL, BATTLE }; +enum class IsolatedHuntBattleResult{ CONTINUE, STOP, FAILED }; +enum class IsolatedHuntStop{ ROUND_LIMIT, INVALID_PLAN, START_FAILED, SETUP_FAILED, POWER_UNVERIFIED, TRAVEL_FAILED, UNRESOLVED_REFUSAL, BATTLE_POLICY, BATTLE_FAILED, TIME_LIMIT, NO_PROGRESS, REFRESH_FAILED, POWER_EXPIRED, MARKER_MISSING, REANCHOR_FAILED, CLEARING_TIMEOUT }; + +struct IsolatedHuntRound{ + uint64_t kills = 0; + IsolatedHuntEvent event = IsolatedHuntEvent::CLEAR; + bool budget_exhausted = false; + bool clearing_busy = false; +}; + +struct IsolatedAscentLimits{ + bool enabled = false; + uint16_t segments_per_ascent = 6; + uint16_t segment_ms = 600; + uint16_t clearing_wait_ms = 5000; +}; + +struct IsolatedHuntLimits{ + uint16_t max_rounds = 30; + uint8_t max_empty_rounds = 3; + uint64_t duration_ms = 120000; + uint64_t power_duration_ms = 29 * 60 * 1000; + IsolatedAscentLimits ascent; + bool use_existing_power = false; + bool resume_at_anchor = false; +}; + +struct IsolatedHuntResult{ + IsolatedHuntStop stop; + uint64_t kills = 0; + uint16_t rounds = 0; + uint16_t encounters = 0; + uint16_t refusals = 0; + uint16_t refreshes = 0; +}; + +class IsolatedHuntActions{ +public: + virtual ~IsolatedHuntActions() = default; + virtual bool reset_start(const IsolatedHuntRequest& request) = 0; + virtual bool prepare_sandwich(const IsolatedHuntRequest& request) = 0; + virtual bool verify_meal_power(const IsolatedHuntRequest& request) = 0; + // Also called after a handled battle; success must mean the route anchor is restored. + virtual bool travel_to_anchor(const IsolatedHuntRequest& request) = 0; + // Watch for battles and refusals throughout the bounded movement/observation window. + virtual IsolatedHuntRound clear_round(const IsolatedHuntRequest& request) = 0; + virtual bool refresh_spawns(const IsolatedHuntRequest& request) = 0; + // True only after battle entry is confirmed, not merely after throwing the lead. + virtual bool acquire_refused_target(const IsolatedHuntRequest& request) = 0; + virtual IsolatedHuntBattleResult handle_battle(const IsolatedHuntRequest& request) = 0; + virtual bool battle_pending() const{ return false; } + virtual bool refusal_pending() const{ return false; } + virtual IsolatedMarkerState marker_state(){ return IsolatedMarkerState::MISSING; } + virtual bool realign_marker(){ return false; } + virtual bool reset_ascent(const IsolatedHuntRequest& request, const char*){ return travel_to_anchor(request); } + virtual IsolatedHuntRound advance_ascent(const IsolatedHuntRequest& request, const IsolatedAscentLimits&){ + return clear_round(request); + } + virtual void set_deadlines(uint64_t, uint64_t){} + // Monotonic time; setup and initial travel are excluded from the hunt budget. + virtual uint64_t now_ms() const = 0; +}; + +bool can_leave_isolated_hunt(IsolatedHuntStop stop); + +IsolatedHuntResult run_isolated_hunt( + const IsolatedHuntRequest& request, const IsolatedHuntLimits& limits, + IsolatedHuntActions& actions +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.cpp new file mode 100644 index 0000000000..9faa2080e1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.cpp @@ -0,0 +1,63 @@ +#include "PokemonSV_IsolatedHuntPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +std::vector isolated_locations_for_type(IsolatedEncounterType type){ + const std::vector locations{ + { + .location = IsolatedHuntLocation::CHARGESTONE_CAVE, + .type = IsolatedEncounterType::GRASS, + .pokemon = "chespin", + .label = "Chargestone Cavern - Cave habitat", + .start_anchor = "Central Plaza", + .prerequisites = "Canyon diversity upgrade; Chargestone fly unlock; verify Cave spawn patch", + }, + { + .location = IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL, + .type = IsolatedEncounterType::FIRE, + .pokemon = "charcadet", + .label = "West Province Area One Central - Rocky habitat", + .start_anchor = "West Province Area One Central fly spot", + .prerequisites = "Fly unlock; verify demonstrated Rocky spawn patch", + }, + }; + std::vector matches; + for (const auto& location : locations){ + if (location.type == type){ + matches.push_back(location); + } + } + return matches; +} + +IsolatedHuntPlan make_isolated_hunt_plan(const std::vector& requests){ + IsolatedHuntPlan plan; + for (const auto& request : requests){ + if (!request.enabled){ + continue; + } + if (request.ball.empty() || request.ball_limit == 0){ + return {.hunts = {}, .error = "Select a ball and a positive ball limit for " + request.pokemon}; + } + bool found = false; + for (const auto& profile : isolated_locations_for_type(request.type)){ + if (profile.location == request.location && profile.pokemon == request.pokemon){ + found = true; + } + } + if (!found){ + return {.hunts = {}, .error = "Unsupported Pokemon/type/location combination: " + request.pokemon}; + } + plan.hunts.push_back(request); + } + if (plan.hunts.empty()){ + return {.hunts = {}, .error = "Enable at least one hunt."}; + } + return plan; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h new file mode 100644 index 0000000000..5cd418b76b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h @@ -0,0 +1,48 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntPlan_H +#define PokemonAutomation_PokemonSV_IsolatedHuntPlan_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class IsolatedShinyAction{ STOP, CATCH, CATCH_AND_SAVE }; + +enum class IsolatedEncounterType{ GRASS, FIRE }; +enum class IsolatedHuntLocation{ CHARGESTONE_CAVE, WEST_PROVINCE_ONE_CENTRAL }; + +struct IsolatedHuntRequest{ + std::string pokemon; + IsolatedEncounterType type; + IsolatedHuntLocation location; + std::string ball; + uint16_t ball_limit = 40; + bool enabled = true; + IsolatedShinyAction shiny_action = IsolatedShinyAction::STOP; +}; + +struct IsolatedHuntLocationProfile{ + IsolatedHuntLocation location; + IsolatedEncounterType type; + std::string pokemon; + std::string label; + std::string start_anchor; + std::string prerequisites; +}; + +std::vector isolated_locations_for_type(IsolatedEncounterType type); + +struct IsolatedHuntPlan{ + std::vector hunts; + std::string error; +}; + +IsolatedHuntPlan make_isolated_hunt_plan(const std::vector& requests); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.cpp new file mode 100644 index 0000000000..cc6e169dbc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.cpp @@ -0,0 +1,31 @@ +#include "PokemonSV_IsolatedHuntText.h" +#include "PokemonSV_IsolatedHuntPower.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +std::u32string expected_power(Language language, IsolatedEncounterType type, uint8_t level){ + if ((type != IsolatedEncounterType::FIRE && type != IsolatedEncounterType::GRASS) || (level != 2 && level != 3)){ + return {}; + } + const bool fire = type == IsolatedEncounterType::FIRE; + std::u32string name; + switch (language){ + case Language::English: name = fire ? U"encounterpowerfirelv" : U"encounterpowergrasslv"; break; + case Language::ChineseTraditional: name = fire ? U"遭遇力火lv" : U"遭遇力草lv"; break; + default: return {}; + } + return name + utf8_to_utf32(std::to_string(level)); +} +} +bool verify_isolated_power(IsolatedPowerActions& actions, Language language, IsolatedEncounterType type, uint8_t level){ + const auto expected = expected_power(language, type, level); + if (expected.empty() || !actions.open_panel()){ return false; } + for (size_t read = 0; read < 2; read++){ + if (normalize_isolated_text(actions.read_encounter_power()) != expected){ return false; } + } + return actions.close_panel(); +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.h new file mode 100644 index 0000000000..1e991655b4 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.h @@ -0,0 +1,20 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntPower_H +#define PokemonAutomation_PokemonSV_IsolatedHuntPower_H +#include +#include "CommonFramework/Language.h" +#include "PokemonSV_IsolatedHuntPlan.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +class IsolatedPowerActions{ +public: + virtual ~IsolatedPowerActions() = default; + virtual bool open_panel() = 0; + virtual std::string read_encounter_power() = 0; + virtual bool close_panel() = 0; +}; +bool verify_isolated_power(IsolatedPowerActions& actions, Language language, IsolatedEncounterType type, uint8_t level); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.cpp new file mode 100644 index 0000000000..c6cdf40607 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.cpp @@ -0,0 +1,71 @@ +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_IsolatedHuntText.h" +#include "PokemonSV_IsolatedHuntPower.h" +#include "PokemonSV_IsolatedHuntPowerConsole.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ +class ConsolePower : public IsolatedPowerActions{ +public: + ConsolePower(VideoStream& stream, ProControllerContext& context, Language language) + : m_stream(stream), m_context(context), m_language(language){} + virtual bool open_panel() override{ + for (size_t attempt = 0; attempt < 3; attempt++){ + pbf_press_dpad(m_context, DPAD_RIGHT, 160ms, 1040ms); + m_context.wait_for_all_requests(); + if (!read_encounter_power().empty()){ return true; } + } + return false; + } + virtual std::string read_encounter_power() override{ + m_context.wait_for(250ms); + const auto screen = m_stream.video().snapshot(); + const auto text = read_isolated_encounter_power(screen, m_language); + m_stream.log("Isolated power OCR: " + text); + return text; + } + virtual bool close_panel() override{ + pbf_press_button(m_context, BUTTON_B, 160ms, 1040ms); + OverworldWatcher overworld(m_stream.logger(), COLOR_BLUE); + return wait_until(m_stream, m_context, 5000ms, {overworld}) == 0; + } +private: + VideoStream& m_stream; + ProControllerContext& m_context; + Language m_language; +}; +} +std::string read_isolated_encounter_power(const ImageViewRGB32& screen, Language language){ + const double width = language == Language::English ? 0.340 : 0.200; + for (double y : std::array{0.160, 0.216, 0.272}){ + // Separate the widely spaced columns so OCR does not merge the type into the level. + const auto label = OCR::ocr_read(language, + extract_box_reference(screen, ImageFloatBox{0.530, y, width, 0.050})); + const auto normalized = normalize_isolated_text(label); + if (normalized.find(U"encounterpower") == std::u32string::npos && + normalized.find(U"遭遇力") == std::u32string::npos){ continue; } + const auto level = OCR::ocr_read(Language::English, + extract_box_reference(screen, ImageFloatBox{0.885, y, 0.050, 0.050})); + return label + " " + level; + } + return ""; +} +bool check_isolated_meal_power(VideoStream& stream, ProControllerContext& context, + Language language, IsolatedEncounterType type, uint8_t level +){ + ConsolePower actions(stream, context, language); + const bool verified = verify_isolated_power(actions, language, type, level); + stream.log("Isolated verification: stage=meal power, method=OCR, type=" + + std::string(type == IsolatedEncounterType::FIRE ? "fire" : "grass") + ", level=" + + std::to_string(level) + ", accepted=" + std::to_string(verified)); + return verified; +} +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.h new file mode 100644 index 0000000000..8432b72560 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.h @@ -0,0 +1,17 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntPowerConsole_H +#define PokemonAutomation_PokemonSV_IsolatedHuntPowerConsole_H +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonSV_IsolatedHuntPlan.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +std::string read_isolated_encounter_power(const ImageViewRGB32& screen, Language language); +bool check_isolated_meal_power(VideoStream& stream, ProControllerContext& context, + Language language, IsolatedEncounterType type, uint8_t level); +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.cpp new file mode 100644 index 0000000000..5573fce921 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.cpp @@ -0,0 +1,396 @@ +/* Isolated Hunt Prototype + * + * From: https://github.com/PokemonAutomation/ + * + * Field question: can stationary Let's Go clearing acquire a refused target + * with ZR? Start at a prepared anchor, or scout the existing Chargestone court. + * Stop after a battle, an unresolved refusal, or bounded empty passes so the + * operator can inspect positioning before trying any spawn-reset movement. + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/ScopeExit.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "VideoGames/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" +#include "VideoGames/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" +#include "VideoGames/PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_Terarium.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_AreaZero.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_LetsGoTools.h" +#include "PokemonSV_IsolatedHuntPrototype.h" +#include "PokemonSV_IsolatedHuntStats.h" +#include "PokemonSV_IsolatedHuntPowerConsole.h" +#include "PokemonSV_IsolatedHuntConsoleActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +IsolatedHuntPrototype_Descriptor::IsolatedHuntPrototype_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:IsolatedHuntPrototype", + STRING_POKEMON + " SV", "Isolated Hunt Prototype", + "", "Supervised target-specific sandwich and bounded hunting. Start at Zero Gate with a healthy lead. Checks Meal Powers and Central before clearing. Set an uphill destination marker and match the lower corridor at its prompt. Bounded ascents fly back to name-verified Central. Route geometry needs field calibration.", + ProgramControllerClass::StandardController_NoRestrictions, + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::ENABLE_COMMANDS + ) +{} + +struct IsolatedHuntPrototype_Descriptor::Stats : public IsolatedHuntStats{}; + +std::unique_ptr IsolatedHuntPrototype_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +namespace{ +const char* hunt_start_description(){ + return + "Start:
Full hunt: start at Zero Gate as if just flown there, on foot. " + "Anchor resume: stand at the verified Central uphill patch in the overworld. Skips initial flight; confirm location, marker and heading at the path checkpoint. " + "Existing sandwich: finish the result screen, pack up the picnic and return to the Zero Gate overworld first. Set the conservative remaining power budget below. " + "Meal Power and flight selection are automatic. Use manual controls only at the Central path prompt. Other modes are controls. Prepared spot: stand on foot, facing the target patch. " + "Central Plaza: start as if just flown there; uses the existing Chargestone court approach. " + "Chespin requires the Canyon diversity upgrade and a verified Grass spawn patch."; +} +} + +IsolatedHuntPrototype::IsolatedHuntPrototype() + : LANGUAGE("Game Language:", IV_READER().languages(), LockMode::LOCK_WHILE_RUNNING, true) + , START( + hunt_start_description(), + { + {Start::HUNT_FROM_ZERO_GATE, "hunt-from-zero-gate", "Supervised hunt from Zero Gate"}, + {Start::EXISTING_POWER_FROM_ZERO_GATE, "existing-power-zero-gate", "Resume from Zero Gate with existing sandwich"}, + {Start::EXISTING_POWER_AT_ANCHOR, "existing-power-anchor", "Resume near hunting anchor with existing sandwich"}, + {Start::PREPARED_SPOT, "prepared", "Prepared hunting spot (Chespin or Charcadet)"}, + {Start::CENTRAL_PLAZA, "central-plaza", "Central Plaza to Chargestone court"}, + {Start::RETURN_TO_ZERO_GATE, "return-zerogate", "Return from Area Zero to Zero Gate (travel only)"}, + }, + LockMode::LOCK_WHILE_RUNNING, Start::HUNT_FROM_ZERO_GATE + ) + , SANDWICH_OPTIONS(&LANGUAGE) + , EXISTING_POWER_SECONDS("Existing sandwich: remaining power budget (seconds):
Resume only. " + "Set below the in-game remaining time, allowing for recovery and leaving a safety margin. " + "Includes verification, flight and path setup. Power type and level are checked automatically; the timer is not read.", + LockMode::LOCK_WHILE_RUNNING, 300, 30, 1740) + , PATCH_VERIFIED("Central path inspected:
At the path pause, position the player on the demonstrated " + "lower uphill corridor by Central, on foot. Set a destination marker below the river bank. Check only after matching terrain, heading and safe clearing bounds.", + LockMode::UNLOCK_WHILE_RUNNING, false) + , RUN_SECONDS( + "Clearing time limit (seconds):
Starts after the approach. Stops between passes; each pass takes at most about 17 seconds.", + LockMode::LOCK_WHILE_RUNNING, 120, 15, 600 + ) + , MAX_ROUNDS("Maximum clearing rounds per target:", LockMode::LOCK_WHILE_RUNNING, 100, 1, 1000) + , EMPTY_PASSES( + "Stop after consecutive passes without a kill:
Stops for inspection without resetting nearby spawns.", + LockMode::LOCK_WHILE_RUNNING, 3, 1, 10 + ) + , ASCENT_SEGMENTS("Central ascent: maximum segments before flight reset:
Conservative cap; does not prove arrival or safe geometry.", + LockMode::LOCK_WHILE_RUNNING, 6, 1, 30) + , ASCENT_SEGMENT_MS("Central ascent: forward segment (ms):", LockMode::LOCK_WHILE_RUNNING, 600, 100, 2000) + , ASCENT_CLEAR_MS("Central ascent: clearing wait (ms):", LockMode::LOCK_WHILE_RUNNING, 5000, 2000, 15000) + , NOTIFICATIONS({ + &ENCOUNTER_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + add_options(); +} + +bool IsolatedHuntPrototype::existing_power() const{ + return START == Start::EXISTING_POWER_FROM_ZERO_GATE || START == Start::EXISTING_POWER_AT_ANCHOR; +} + +void IsolatedHuntPrototype::add_options(){ + SANDWICH_OPTIONS.TYPE.set_visibility(ConfigOptionState::HIDDEN); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(START); + PA_ADD_OPTION(HUNTS); + PA_ADD_OPTION(SANDWICH_OPTIONS); + PA_ADD_OPTION(EXISTING_POWER_SECONDS); + PA_ADD_OPTION(PATCH_VERIFIED); + PA_ADD_OPTION(MAX_ROUNDS); + PA_ADD_OPTION(RUN_SECONDS); + PA_ADD_OPTION(EMPTY_PASSES); + PA_ADD_OPTION(ASCENT_SEGMENTS); + PA_ADD_OPTION(ASCENT_SEGMENT_MS); + PA_ADD_OPTION(ASCENT_CLEAR_MS); + PA_ADD_OPTION(ENCOUNTER_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); +} + +bool IsolatedHuntPrototype::verify_setup(VideoStream& stream, ProControllerContext& context, + const IsolatedHuntRequest& request, IsolatedHuntVerification stage +){ + if (stage == IsolatedHuntVerification::MEAL_POWER){ + return check_isolated_meal_power(stream, context, LANGUAGE, request.type, SANDWICH_OPTIONS.USE_HERBA ? 3 : 2); + } + const auto started = current_time(); + PATCH_VERIFIED = false; + stream.log("SUPERVISED: stand on foot at the lower Central uphill corridor, set a marker with a river buffer, and match the safe heading. Then check Central path inspected.", COLOR_BLUE); + const WallClock deadline = current_time() + 110s; + while (!PATCH_VERIFIED && current_time() < deadline){ context.wait_for(250ms); } + const bool accepted = PATCH_VERIFIED; + PATCH_VERIFIED = false; + stream.log("Isolated verification: stage=Central path, method=supervised, accepted=" + std::to_string(accepted) + + ", elapsed ms=" + std::to_string(std::chrono::duration_cast(current_time() - started).count())); + if (!accepted){ return false; } + OverworldWatcher overworld(stream.logger(), COLOR_BLUE); + return wait_until(stream, context, 5000ms, {overworld}) == 0; +} + +bool IsolatedHuntPrototype::run_one_hunt(SingleSwitchProgramEnvironment& env, + ProControllerContext& context, const IsolatedHuntRequest& request +){ + auto& stats = env.current_stats(); + ConsoleIsolatedHuntActions actions(env, context, stats, LANGUAGE, SANDWICH_OPTIONS, ENCOUNTER_OPTIONS, request); + if (START == Start::EXISTING_POWER_AT_ANCHOR){ actions.resume_at_anchor(); } + actions.set_verifier([&](ProControllerContext& stage_context, const IsolatedHuntRequest& hunt, IsolatedHuntVerification stage){ + return verify_setup(env.console, stage_context, hunt, stage); + }); + const IsolatedHuntLimits limits{ + .max_rounds = MAX_ROUNDS, .max_empty_rounds = EMPTY_PASSES, + .duration_ms = (uint64_t)RUN_SECONDS * 1000, + .power_duration_ms = existing_power() ? (uint64_t)EXISTING_POWER_SECONDS * 1000 : 29 * 60 * 1000, + .ascent = {.enabled = request.location == IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL, + .segments_per_ascent = ASCENT_SEGMENTS, .segment_ms = ASCENT_SEGMENT_MS, .clearing_wait_ms = ASCENT_CLEAR_MS}, + .use_existing_power = existing_power(), + .resume_at_anchor = START == Start::EXISTING_POWER_AT_ANCHOR, + }; + env.console.log("Isolated setup: existing power=" + std::to_string(limits.use_existing_power) + + ", power budget ms=" + std::to_string(limits.power_duration_ms)); + const auto result = run_isolated_hunt(request, limits, actions); + actions.report(request, result); + if (!can_leave_isolated_hunt(result.stop)){ + env.console.log("Stopped at the current location for inspection; no departure after refusal, policy stop or failure.", COLOR_BLUE); + return false; + } + if (!actions.return_to_zero_gate(request)){ + if (actions.battle_pending()){ + actions.handle_battle(request); + } + env.console.log("Return flight failed or was interrupted. Inspect location before restarting AZP.", COLOR_RED); + return false; + } + env.console.log("Return flight completed and saved. Verify Zero Gate before handing back to AZP."); + return true; +} + +void IsolatedHuntPrototype::check_power_language(SingleSwitchProgramEnvironment& env) const{ + if (LANGUAGE != Language::English && LANGUAGE != Language::ChineseTraditional){ + throw UserSetupError(env.logger(), "Automatic Meal Power verification supports English and Traditional Chinese only."); + } +} + +void IsolatedHuntPrototype::run_hunts(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + const auto plan = make_isolated_hunt_plan(HUNTS.snapshot()); + if (!plan.error.empty()){ + throw UserSetupError(env.logger(), plan.error); + } + if (existing_power() && plan.hunts.size() != 1){ + throw UserSetupError(env.logger(), "Existing sandwich resume requires exactly one enabled hunt."); + } + if (START == Start::EXISTING_POWER_AT_ANCHOR && plan.hunts.front().location != IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL){ + throw UserSetupError(env.logger(), "Anchor resume currently supports the supervised Central corridor only."); + } + if (LANGUAGE == Language::None){ + throw UserSetupError(env.logger(), "Select the game language before starting."); + } + check_power_language(env); + assert_16_9_720p_min(env.logger(), env.console); + require_player(env.console, context, BUTTON_LCLICK); + OverworldWatcher overworld(env.logger(), COLOR_BLUE); + if (wait_until(env.console, context, 5000ms, {overworld}) < 0){ + throw UserSetupError(env.logger(), "Start at the Zero Gate fly spot in the overworld."); + } + for (const auto& request : plan.hunts){ + if (!run_one_hunt(env, context, request)){ + break; + } + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +bool IsolatedHuntPrototype::approach(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START == Start::RETURN_TO_ZERO_GATE){ + env.console.log("Prototype state: returning from Area Zero to Zero Gate."); + return_to_outside_zero_gate(env.program_info(), env.console, context); + return false; + } + if (START == Start::CENTRAL_PLAZA){ + env.console.log("Prototype state: approach Chargestone court."); + central_to_chargestone(env.program_info(), env.console, context); + pbf_wait(context, 3000ms); + // Match the existing BBQ court approach; its Chespin footprint still needs field verification. + pbf_press_button(context, BUTTON_L, 160ms, 400ms); + pbf_move_left_joystick(context, {0, +1}, 2000ms, 400ms); + pbf_move_left_joystick(context, {+1, 0}, 1440ms, 400ms); + pbf_press_button(context, BUTTON_L, 160ms, 400ms); + context.wait_for_all_requests(); + } + return true; +} + +bool IsolatedHuntPrototype::clear_pass(SingleSwitchProgramEnvironment& env, + ProControllerContext& context, OverworldSensors& sensors, uint8_t& empty +){ + auto& stats = env.current_stats(); + const uint64_t before = stats.m_kills.load(); + env.console.log("Prototype state: clearing pass " + std::to_string(stats.passes.load() + 1)); + SweatBubbleWatcher bubble(COLOR_GREEN); + int refused = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_R, 160ms, 1600ms); + }, + {bubble} + ); + if (refused == 0){ + stats.refusals++; + env.update_stats(); + env.console.log("Prototype state: refusal detected; trying ZR. Refusal does not confirm a shiny."); + pbf_mash_button(context, BUTTON_ZR, 5000ms); + pbf_wait(context, 10000ms); + context.wait_for_all_requests(); + return false; + } + // A fixed observation window keeps a long kill chain from extending a pass indefinitely. + pbf_wait(context, 12000ms); + context.wait_for_all_requests(); + sensors.throw_if_no_sound(); + stats.passes++; + uint64_t kills = stats.m_kills.load() - before; + empty = kills == 0 ? empty + 1 : 0; + env.update_stats(); + env.console.log("Prototype pass: kills=" + std::to_string(kills) + + ", consecutive empty passes=" + std::to_string(empty)); + return true; +} + +std::string IsolatedHuntPrototype::clear_spot(SingleSwitchProgramEnvironment& env, + ProControllerContext& context, OverworldSensors& sensors +){ + const auto started = current_time(); + auto& stats = env.current_stats(); + const auto seconds_before = stats.hunt_seconds.load(); + const auto kills_before = stats.m_kills.load(); + auto update_time = [&]{ + const auto elapsed = std::chrono::duration_cast(current_time() - started).count(); + stats.hunt_seconds.store(seconds_before + elapsed / 1000); + env.update_stats(); + return elapsed; + }; + ScopeExit report([&]{ + const auto elapsed = update_time(); + const auto kills = stats.m_kills.load() - kills_before; + env.console.log("Isolated clearing summary: mode=prepared, elapsed ms=" + std::to_string(elapsed) + + ", detected kills=" + std::to_string(kills) + ", kills/min=" + + std::to_string(elapsed == 0 ? 0.0 : 60000.0 * kills / elapsed)); + }); + WallClock deadline = started + std::chrono::seconds(RUN_SECONDS); + uint8_t empty = 0; + while (current_time() < deadline){ + update_time(); + if (!clear_pass(env, context, sensors, empty)){ + return "Refusal acquisition timed out without a battle. Inspect the target and positioning."; + } + if (empty >= EMPTY_PASSES){ + return "No clearing progress. Inspect spawn density, lead health and target reachability."; + } + } + return "Clearing time limit reached."; +} + +bool IsolatedHuntPrototype::process_encounter(SingleSwitchProgramEnvironment& env, + ProControllerContext& context, OverworldSensors& sensors, + OverworldBattleTracker& battle_tracker, LetsGoEncounterBotTracker& encounters +){ + auto& stats = env.current_stats(); + env.console.log("Prototype state: battle detected; using shared encounter/shiny handling."); + sensors.throw_if_no_sound(); + stats.m_encounters++; + env.update_stats(); + encounters.encounter_rate_tracker().report_encounter(); + bool caught = false, should_save = false; + try{ + process_battle(caught, should_save, env, ENCOUNTER_OPTIONS, env.console, context, + battle_tracker, encounters.encounter_frequencies(), stats.m_shinies, LANGUAGE); + }catch (ProgramFinishedException&){ + env.console.log("Prototype stopped by encounter policy. Leaving the battle for inspection.", COLOR_BLUE); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + return true; + } + if (should_save){ + save_game_from_overworld(env.program_info(), env.console, context); + } + return false; +} + +void IsolatedHuntPrototype::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START == Start::HUNT_FROM_ZERO_GATE || existing_power()){ + run_hunts(env, context); + return; + } + if (START != Start::RETURN_TO_ZERO_GATE){ check_power_language(env); } + auto& stats = env.current_stats(); + assert_16_9_720p_min(env.logger(), env.console); + require_player(env.console, context, BUTTON_LCLICK); + OverworldWatcher overworld(env.logger(), COLOR_BLUE); + if (wait_until(env.console, context, 5000ms, {overworld}) < 0){ + throw UserSetupError(env.logger(), "Start in the overworld at the selected anchor."); + } + // Stop audio inference before destroying the tracker captured by its kill callback. + std::unique_ptr encounters; + OverworldSensors sensors(env.logger(), env.console, context); + OverworldBattleTracker battle_tracker(env.logger(), sensors); + encounters = std::make_unique(env, env.console, stats, sensors.lets_go_kill); + std::string stop_reason; + NormalBattleMenuWatcher battle_menu(COLOR_RED); + int result = run_until( + env.console, context, + [&](ProControllerContext& context){ + if (!approach(env, context)){ + stop_reason = "Returned to Zero Gate. Ready for the release AZP program."; + return; + } + const auto plan = make_isolated_hunt_plan(HUNTS.snapshot()); + if (!plan.error.empty()){ + throw UserSetupError(env.logger(), plan.error); + } + if (!verify_setup(env.console, context, plan.hunts.front(), IsolatedHuntVerification::MEAL_POWER)){ + stop_reason = "Active Meal Power was not verified; no clearing."; + return; + } + stop_reason = clear_spot(env, context, sensors); + }, + {battle_menu} + ); + if (result == 0){ + if (process_encounter(env, context, sensors, battle_tracker, *encounters)){ + return; + } + // Do not resume a timed movement path after an encounter changes the anchor. + stop_reason = "Battle handled. Inspect positioning before another run."; + } + env.console.log("Prototype stopped: " + stop_reason, COLOR_BLUE); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.h new file mode 100644 index 0000000000..c592e4613a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.h @@ -0,0 +1,83 @@ +/* Isolated Hunt Prototype + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntPrototype_H +#define PokemonAutomation_PokemonSV_IsolatedHuntPrototype_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonSV/Options/PokemonSV_EncounterBotCommon.h" +#include "VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.h" +#include "VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldSensors.h" +#include "PokemonSV_LetsGoTools.h" +#include "PokemonSV_IsolatedHuntLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class IsolatedHuntPrototype_Descriptor : public SingleSwitchProgramDescriptor{ +public: + IsolatedHuntPrototype_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class IsolatedHuntPrototype : public SingleSwitchProgramInstance{ +public: + using Descriptor = IsolatedHuntPrototype_Descriptor; + IsolatedHuntPrototype(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void add_options(); + bool existing_power() const; + void check_power_language(SingleSwitchProgramEnvironment& env) const; + void run_hunts(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool run_one_hunt(SingleSwitchProgramEnvironment& env, ProControllerContext& context, const IsolatedHuntRequest& request); + bool verify_setup(VideoStream& stream, ProControllerContext& context, + const IsolatedHuntRequest& request, IsolatedHuntVerification stage); + bool approach(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool clear_pass(SingleSwitchProgramEnvironment& env, ProControllerContext& context, + OverworldSensors& sensors, uint8_t& empty); + std::string clear_spot(SingleSwitchProgramEnvironment& env, ProControllerContext& context, OverworldSensors& sensors); + bool process_encounter(SingleSwitchProgramEnvironment& env, ProControllerContext& context, + OverworldSensors& sensors, OverworldBattleTracker& battle_tracker, LetsGoEncounterBotTracker& encounters); + + enum class Start{ + HUNT_FROM_ZERO_GATE, + EXISTING_POWER_FROM_ZERO_GATE, + EXISTING_POWER_AT_ANCHOR, + PREPARED_SPOT, + CENTRAL_PLAZA, + RETURN_TO_ZERO_GATE, + }; + + OCR::LanguageOCROption LANGUAGE; + EnumDropdownOption START; + IsolatedHuntTable HUNTS; + IsolatedHuntSandwichOption SANDWICH_OPTIONS; + SimpleIntegerOption EXISTING_POWER_SECONDS; + BooleanCheckBoxOption PATCH_VERIFIED; + SimpleIntegerOption RUN_SECONDS; + SimpleIntegerOption MAX_ROUNDS; + SimpleIntegerOption EMPTY_PASSES; + SimpleIntegerOption ASCENT_SEGMENTS; + SimpleIntegerOption ASCENT_SEGMENT_MS; + SimpleIntegerOption ASCENT_CLEAR_MS; + EncounterBotCommonOptions ENCOUNTER_OPTIONS; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntStats.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntStats.h new file mode 100644 index 0000000000..1ae646af4c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntStats.h @@ -0,0 +1,31 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntStats_H +#define PokemonAutomation_PokemonSV_IsolatedHuntStats_H +#include "PokemonSV_LetsGoTools.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class IsolatedHuntStats : public LetsGoEncounterBotStats{ +public: + IsolatedHuntStats() + : passes(m_stats["Clearing Passes"]), refusals(m_stats["Refusals"]) + , refreshes(m_stats["Spawn Refreshes"]), sandwiches(m_stats["Sandwiches"]) + , hunt_seconds(m_stats["Hunt Seconds"]) + { + m_display_order.emplace_back("Clearing Passes"); + m_display_order.emplace_back("Refusals"); + m_display_order.emplace_back("Spawn Refreshes"); + m_display_order.emplace_back("Sandwiches"); + m_display_order.emplace_back("Hunt Seconds"); + } + std::atomic& passes; + std::atomic& refusals; + std::atomic& refreshes; + std::atomic& sandwiches; + std::atomic& hunt_seconds; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntText.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntText.h new file mode 100644 index 0000000000..7f528521f6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntText.h @@ -0,0 +1,22 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntText_H +#define PokemonAutomation_PokemonSV_IsolatedHuntText_H +#include "Common/Cpp/Strings/Unicode.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +inline std::u32string normalize_isolated_text(const std::string& text){ + std::u32string result; + for (char32_t ch : utf8_to_utf32(text)){ + if (ch >= U'0' && ch <= U'9'){ ch = ch - U'0' + U'0'; } + if (ch >= U'A' && ch <= U'Z'){ ch = ch - U'A' + U'a'; } + if ((ch >= U'a' && ch <= U'z') || (ch >= U'0' && ch <= U'9') || + (ch >= 0x4e00 && ch <= 0x9fff)){ + result += ch; + } + } + return result; +} +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.cpp new file mode 100644 index 0000000000..8f4ba263bb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.cpp @@ -0,0 +1,134 @@ +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "VideoGames/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h" +#include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "VideoGames/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_IsolatedHuntFlight.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.h" +#include "VideoGames/PokemonSV/Programs/PokemonSV_Terarium.h" +#include "PokemonSV_IsolatedHuntTravel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +class CentralFlight : public IsolatedFlightActions{ +public: + CentralFlight(VideoStream& stream, ProControllerContext& context, Language language) + : m_stream(stream), m_context(context), m_language(language) + {} + virtual bool open_confirmation() override{ + pbf_press_button(m_context, BUTTON_A, 160ms, 1040ms); + MapFlyMenuWatcher menu(COLOR_BLUE); + if (wait_until(m_stream, m_context, 5000ms, {menu}) < 0){ return false; } + pbf_press_button(m_context, BUTTON_A, 160ms, 1040ms); + PromptDialogWatcher prompt(COLOR_BLUE, {0.686, 0.494, 0.171, 0.163}); + return wait_until(m_stream, m_context, 5000ms, {prompt}) == 0; + } + virtual std::string read_destination() override{ + m_context.wait_for(250ms); + const auto screen = m_stream.video().snapshot(); + const auto text = OCR::ocr_read(m_language, + extract_box_reference(screen, ImageFloatBox{0.300, 0.335, 0.400, 0.068})); + m_stream.log("Flight destination read: " + text); + return text; + } + virtual bool confirmation_visible() override{ + PromptDialogDetector prompt(COLOR_BLUE, {0.686, 0.494, 0.171, 0.163}); + return prompt.detect(m_stream.video().snapshot()); + } + virtual bool confirm_and_wait() override{ + pbf_press_button(m_context, BUTTON_A, 160ms, 1040ms); + OverworldWatcher overworld(m_stream.logger(), COLOR_BLUE); + return wait_until(m_stream, m_context, 60000ms, {overworld}) == 0; + } +private: + VideoStream& m_stream; + ProControllerContext& m_context; + Language m_language; +}; + +bool refly_local_anchor(const ProgramInfo& info, VideoStream& stream, + ProControllerContext& context, IsolatedHuntLocation location +){ + open_map_from_overworld(info, stream, context); + context.wait_for_all_requests(); + const auto kind = location == IsolatedHuntLocation::CHARGESTONE_CAVE ? FlyPoint::FAST_TRAVEL : FlyPoint::POKECENTER; + return fly_to_visible_closest_flypoint_cur_zoom_level(info, stream, context, kind); +} + +} + +bool travel_to_isolated_hunt(const ProgramInfo& info, VideoStream& stream, + ProControllerContext& context, IsolatedHuntLocation location, bool from_zero_gate, Language language +){ + if (location == IsolatedHuntLocation::WEST_PROVINCE_ONE_CENTRAL){ + open_map_from_overworld(info, stream, context); + if (from_zero_gate){ + stream.log("Central candidate seek: one zoom out, west 950ms, south 650ms; name verification required."); + // Candidate derived from the Central-to-Zero-Gate map traversal; verify identity before flying. + pbf_press_button(context, BUTTON_ZL, 160ms, 840ms); + pbf_move_left_joystick(context, {-1, 0}, 950ms, 200ms); + pbf_move_left_joystick(context, {0, -1}, 650ms, 200ms); + } + if (!from_zero_gate){ + // The player cursor can cover the local center icon when re-flying from its landing spot. + pbf_move_left_joystick(context, {-1, 0}, 160ms, 200ms); + } + if (!detect_closest_flypoint_and_move_map_cursor_there(info, stream, context, FlyPoint::POKECENTER)){ + return false; + } + CentralFlight flight(stream, context, language); + const bool arrived = fly_to_isolated_central(flight, language); + if (!arrived){ stream.log("Central flight failed; stopping for inspection.", COLOR_RED); } + return arrived; + } + if (!from_zero_gate){ + return refly_local_anchor(info, stream, context, location); + } + if (location == IsolatedHuntLocation::CHARGESTONE_CAVE){ + fly_from_paldea_to_blueberry_entrance(info, stream, context); + return_to_plaza(info, stream, context); + central_to_chargestone(info, stream, context); + return true; + } + return false; +} + +void approach_isolated_patch(VideoStream& stream, ProControllerContext& context, IsolatedHuntLocation location){ + pbf_press_button(context, BUTTON_L, 160ms, 400ms); + if (location == IsolatedHuntLocation::CHARGESTONE_CAVE){ + stream.log("Approach: existing Chargestone court; verify this is the Chespin Cave habitat."); + pbf_move_left_joystick(context, {0, +1}, 2000ms, 400ms); + pbf_move_left_joystick(context, {+1, 0}, 1440ms, 400ms); + pbf_press_button(context, BUTTON_L, 160ms, 400ms); + }else{ + stream.log("Central approach requires supervised matching of the demonstrated path.", COLOR_BLUE); + } + context.wait_for_all_requests(); +} + +bool return_from_isolated_hunt(const ProgramInfo& info, VideoStream& stream, + ProControllerContext& context, IsolatedHuntLocation location +){ + if (location == IsolatedHuntLocation::CHARGESTONE_CAVE){ + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_R, 400ms, 2400ms); + pbf_press_button(context, BUTTON_ZL, 160ms, 840ms); + pbf_move_left_joystick(context, {-1, 0}, 200ms, 800ms); + pbf_press_button(context, BUTTON_ZR, 160ms, 840ms); + context.wait_for_all_requests(); + return fly_to_visible_closest_flypoint_cur_zoom_level(info, stream, context, FlyPoint::FAST_TRAVEL); + } + stream.log("Central return route is uncalibrated. Supervised return to Zero Gate required; no automatic departure.", COLOR_BLUE); + return false; +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.h new file mode 100644 index 0000000000..c57aee48b7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.h @@ -0,0 +1,19 @@ +#ifndef PokemonAutomation_PokemonSV_IsolatedHuntTravel_H +#define PokemonAutomation_PokemonSV_IsolatedHuntTravel_H +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonSV_IsolatedHuntPlan.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +bool travel_to_isolated_hunt(const ProgramInfo& info, VideoStream& stream, + ProControllerContext& context, IsolatedHuntLocation location, bool from_zero_gate, Language language); +void approach_isolated_patch(VideoStream& stream, ProControllerContext& context, IsolatedHuntLocation location); +bool return_from_isolated_hunt(const ProgramInfo& info, VideoStream& stream, + ProControllerContext& context, IsolatedHuntLocation location); +} +} +} +#endif diff --git a/SerialPrograms/cmake/LocalMacSigning.cmake b/SerialPrograms/cmake/LocalMacSigning.cmake new file mode 100644 index 0000000000..d800eeb6d8 --- /dev/null +++ b/SerialPrograms/cmake/LocalMacSigning.cmake @@ -0,0 +1,22 @@ +# Keep local privacy grants tied to a persistent certificate rather than a binary hash. +# All deployment commands must precede this signing step. +function(pa_sign_local_macos_app target) + if (PA_MACOS_SIGNING_IDENTITY STREQUAL "-") + message(FATAL_ERROR "Local signing requires a persistent certificate, not an ad-hoc signature.") + endif() + find_program(PA_CODESIGN_EXECUTABLE codesign REQUIRED) + set(sign_commands + COMMAND "${PA_CODESIGN_EXECUTABLE}" --force --timestamp=none + --sign "${PA_MACOS_SIGNING_IDENTITY}" + --identifier "${PA_MACOS_BUNDLE_IDENTIFIER}" + "$" + COMMAND "${PA_CODESIGN_EXECUTABLE}" --verify --strict --verbose=2 + "$" + ) + # Explicit target builds sign after relinking. Default builds also cover plist-only changes. + add_custom_command(TARGET ${target} POST_BUILD ${sign_commands} + COMMENT "Signing local macOS app with persistent identity" VERBATIM) + add_custom_target(${target}LocalSignature ALL ${sign_commands} + DEPENDS ${target} + COMMENT "Refreshing local macOS app signature" VERBATIM) +endfunction() diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 1603b71bc5..e98b4911a2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2551,6 +2551,41 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonSV/PokemonSV_Panels.h Source/VideoGames/PokemonSV/PokemonSV_Settings.cpp Source/VideoGames/PokemonSV/PokemonSV_Settings.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntLoop_Tests.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntCorridor_Tests.h + Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.cpp + Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntTable.h + Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.cpp + Source/VideoGames/PokemonSV/Options/PokemonSV_IsolatedHuntSandwichOption.h + Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.cpp + Source/VideoGames/PokemonSV/Programs/PokemonSV_RegionTravel.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntText.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPowerConsole.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPower.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntPower_Tests.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntFlight.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntTravel.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntStats.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntAscentConsole.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntConsoleActions.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntEncounter.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntEncounter_Tests.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntOptions_Tests.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHuntFlight_Tests.h + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_IsolatedHunt_Tests.h Source/VideoGames/PokemonSV/PokemonSV_Tests.cpp Source/VideoGames/PokemonSV/PokemonSV_Tests.h Source/VideoGames/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -2752,10 +2787,18 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonSV/Programs/PokemonSV_Terarium.h Source/VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp Source/VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h + Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.h + Source/VideoGames/PokemonSV/Programs/PokemonSV_MarkerNavigation.cpp Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h + Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.cpp + Source/VideoGames/PokemonSV/PokemonSV_SandwichEating_Tests.h + Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.cpp + Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEatingConsole.h + Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.cpp + Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichEating.h Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp Source/VideoGames/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp @@ -2764,6 +2807,14 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntLoop.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntCorridor.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPlan.h + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.cpp + Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_IsolatedHuntPrototype.h Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp Source/VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h Source/VideoGames/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp