From 16f1a19463caede60cc0abc55d2d19cb743e1fdc Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 15:03:01 -0800 Subject: [PATCH] FRLG: overworld walker, maps from Packages and recovery basics The FRLG overworld for AutoStory, copied from #213's tip: maps embedded from the pinned PokemonSimulation resource pack (prepared under Packages), route planning and the walker, the player-facing reader, and re-anchoring and recovery after an interrupted leg, with their unit tests. CI prepares the same pinned map pack before configuring. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../workflows/cpp-ci-serial-programs-base.yml | 15 + .gitignore | 3 + SerialPrograms/CMakeLists.txt | 4 + .../Overworld/PokemonFRLG_OverworldMap.cpp | 252 +++++ .../Overworld/PokemonFRLG_OverworldMap.h | 71 ++ .../Overworld/PokemonFRLG_OverworldMaps.cpp | 118 +++ .../Overworld/PokemonFRLG_OverworldMaps.h | 72 ++ .../PokemonFRLG_OverworldMaps_Tests.cpp | 306 ++++++ .../Overworld/PokemonFRLG_OverworldObjects.h | 43 + .../PokemonFRLG_OverworldReanchor.cpp | 374 +++++++ .../Overworld/PokemonFRLG_OverworldReanchor.h | 102 ++ .../PokemonFRLG_OverworldReanchor_Tests.cpp | 284 +++++ .../PokemonFRLG_OverworldRecovery.cpp | 358 +++++++ .../Overworld/PokemonFRLG_OverworldRecovery.h | 123 +++ .../PokemonFRLG_OverworldRecovery_Tests.cpp | 548 ++++++++++ .../Overworld/PokemonFRLG_OverworldRoute.cpp | 993 ++++++++++++++++++ .../Overworld/PokemonFRLG_OverworldRoute.h | 82 ++ .../PokemonFRLG_OverworldRouteCosts.h | 57 + .../PokemonFRLG_OverworldRouteSteps.h | 82 ++ .../PokemonFRLG_OverworldTileRules.h | 52 + .../Overworld/PokemonFRLG_OverworldTiles.h | 89 ++ .../PokemonFRLG_OverworldTrainerCrossing.h | 45 + .../Overworld/PokemonFRLG_OverworldWalk.cpp | 445 ++++++++ .../Overworld/PokemonFRLG_OverworldWalk.h | 92 ++ .../PokemonFRLG_OverworldWalkMoves.h | 65 ++ .../PokemonFRLG_OverworldWalkOptions.h | 73 ++ .../PokemonFRLG_OverworldWalkTimes.h | 57 + .../PokemonFRLG_OverworldWalkWatches.h | 55 + .../PokemonFRLG_OverworldWalk_Tests.cpp | 111 ++ .../PokemonFRLG_OverworldWalkedTiles.h | 49 + .../PokemonFRLG_PlayerFacingReader.cpp | 264 +++++ .../PokemonFRLG_PlayerFacingReader.h | 59 ++ .../PokemonFRLG/PokemonFRLG_Tests.cpp | 15 + .../cmake/PokesimMapResources.cmake | 15 + SerialPrograms/cmake/SourceFiles.cmake | 29 + devtools/maps/RESOURCE_MAPS.md | 43 + devtools/maps/map-resources.lock.json | 11 + 37 files changed, 5456 insertions(+) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldObjects.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTileRules.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTiles.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTrainerCrossing.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkWatches.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h create mode 100644 SerialPrograms/cmake/PokesimMapResources.cmake create mode 100644 devtools/maps/RESOURCE_MAPS.md create mode 100644 devtools/maps/map-resources.lock.json diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 58f1a9d890..743c68fdbb 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -88,6 +88,19 @@ jobs: ref: 'master' path: 'Arduino-Source/Packages' + - name: Install Python for pinned map preparation + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Prepare approved FRLG map resources + id: map-resources + uses: dayfine/PokemonSimulation/integrations/arduino-source/verify-map-packs@906956e94fc912ae9adb0e44845da780f3bc7e4c + with: + layout: resources + operation: prepare + consumer-directory: Arduino-Source + - name: Install Qt uses: jurplel/install-qt-action@v4 with: @@ -204,6 +217,8 @@ jobs: # every file missed, compiling took 10-40% longer than before on Linux and macOS, and # about twice as long on Windows. CCACHE_DEPEND: 1 + POKESIM_TOOLS_SOURCE: ${{ steps.map-resources.outputs.tools-source }} + POKESIM_SOURCE_CACHE: ${{ steps.map-resources.outputs.source-cache }} run: | cd Arduino-Source/SerialPrograms mkdir bin diff --git a/.gitignore b/.gitignore index ef6f409ae9..a6b04ddffd 100644 --- a/.gitignore +++ b/.gitignore @@ -81,3 +81,6 @@ Packages/* # Local agent/linter environments. .venv-code-health/ __pycache__/ + +# External PokemonSimulation tools/data cache; prepared maps live in ignored Packages. +.pokesim-map-source/ diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index b009fa0814..01d3bb2bca 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -227,6 +227,10 @@ add_library(SerialProgramsLib STATIC ${CORE_LIBRARY_SOURCES} ${LIBRARY_SOURCES}) include(cmake/EmbedTextFiles.cmake) pa_embed_text_files(SerialProgramsLib Source/Pokemon/Navigation/TestMaps Pokemon/Navigation/Pokemon_Navigation_Tests.h PokemonAutomation::Pokemon navigation_test_map_json) +include(cmake/PokesimMapResources.cmake) +pa_frlg_map_resources(FRLG_MAP_RESOURCES) +pa_embed_text_files(SerialProgramsLib "${FRLG_MAP_RESOURCES}" + VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h PokemonAutomation::NintendoSwitch::PokemonFRLG overworld_map_json) # Create binary target diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp new file mode 100644 index 0000000000..5171db55b0 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp @@ -0,0 +1,252 @@ +/* Overworld Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_OverworldMap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +bool in_bounds(const MapData& map, const TilePos& point){ + return map.tiles.contains(point); +} +TileKind tile_at(const MapData& map, const TilePos& point){ + return in_bounds(map, point) ? map.tiles.at(point) : TileKind::WALL; +} +uint8_t elevation_at(const MapData& map, const TilePos& point){ + if (!in_bounds(map, point)){ + return ELEVATION_IGNORED; + } + return map.elevation ? map.elevation->at(point) : ELEVATION_GROUND; +} + +bool is_wall(const MapData& map, const TilePos& point){ + const TileKind tile = tile_at(map, point); + return tile == TileKind::WALL || tile == TileKind::DOOR || tile == TileKind::SIGN || is_ledge(map, point); +} +bool is_ledge(const MapData& map, const TilePos& point){ + switch (tile_at(map, point)){ + case TileKind::LEDGE_NORTH: + case TileKind::LEDGE_SOUTH: + case TileKind::LEDGE_WEST: + case TileKind::LEDGE_EAST: + return true; + default: + return false; + } +} +bool is_water(const MapData& map, const TilePos& point){ + return tile_at(map, point) == TileKind::WATER; +} +bool is_tall_grass(const MapData& map, const TilePos& point){ + return tile_at(map, point) == TileKind::TALL_GRASS; +} + +namespace{ + +// The tile closed on its `side` edge. +TileKind closed_side(Direction side){ + switch (side){ + case Direction::NORTH: + return TileKind::CLOSED_NORTH; + case Direction::SOUTH: + return TileKind::CLOSED_SOUTH; + case Direction::EAST: + return TileKind::CLOSED_EAST; + case Direction::WEST: + return TileKind::CLOSED_WEST; + } + return TileKind::WALL; +} +Direction opposite(Direction direction){ + switch (direction){ + case Direction::NORTH: + return Direction::SOUTH; + case Direction::SOUTH: + return Direction::NORTH; + case Direction::EAST: + return Direction::WEST; + case Direction::WEST: + return Direction::EAST; + } + return direction; +} + +// How the warp on this tile is entered, if there is one. +std::optional warp_entry(const MapData& map, const TilePos& point){ + const MapWarp* warp = warp_at(map, point); + if (warp == nullptr){ + return std::nullopt; + } + return warp->enter; +} + +} // namespace + +bool blocks_entering(const MapData& map, const TilePos& point, Direction direction){ + // Moving south enters by the north edge. + return tile_at(map, point) == closed_side(opposite(direction)); +} +bool blocks_leaving(const MapData& map, const TilePos& point, Direction direction){ + return tile_at(map, point) == closed_side(direction); +} + +bool warps_on_step(const MapData& map, const TilePos& point){ + const std::optional entry = warp_entry(map, point); + return entry == WarpEntry::STEP_ON || entry == WarpEntry::CAVE_ENTRANCE; +} +bool is_door(const MapData& map, const TilePos& point){ + return tile_at(map, point) == TileKind::DOOR; +} +std::optional exit_mat(const MapData& map, const TilePos& point){ + const std::optional entry = warp_entry(map, point); + if (!entry){ + return std::nullopt; + } + switch (*entry){ + case WarpEntry::WALK_NORTH: + return Direction::NORTH; + case WarpEntry::WALK_SOUTH: + return Direction::SOUTH; + case WarpEntry::WALK_WEST: + return Direction::WEST; + case WarpEntry::WALK_EAST: + return Direction::EAST; + default: + return std::nullopt; + } +} +bool walks_out_on_arrival(const MapData& map, const TilePos& point){ + return is_door(map, point) || warp_entry(map, point) == WarpEntry::CAVE_ENTRANCE; +} + +void hide_objects(MapData& map, const std::set& flags){ + std::vector shown; + for (const MapObject& object : map.objects){ + if (!object.hide_flag || flags.count(*object.hide_flag) == 0){ + shown.push_back(object); + } + } + map.objects = std::move(shown); +} + +namespace{ + +// The tiles `object` may stand on: its wander box, or its own tile. +Pokemon::TileBox standing_box(const MapObject& object){ + return object.wander.value_or( + Pokemon::TileBox{.x0 = object.x, .y0 = object.y, .x1 = object.x, .y1 = object.y} + ); +} + +// Whether `trainer`, standing on `from`, sees `tile` any way it looks. +bool sees_from(const MapData& map, const Pokemon::MapTrainer& trainer, const TilePos& from, const TilePos& tile){ + for (Direction look : trainer.looks){ + TilePos seen = from; + for (int c = 0; c < trainer.sight && !is_wall(map, seen.next(look)); c++){ + seen = seen.next(look); + if (seen == tile){ + return true; + } + } + } + return false; +} + +} // namespace + +const MapObject* object_at(const MapData& map, const TilePos& point){ + for (const MapObject& object : map.objects){ + const Pokemon::TileBox box = standing_box(object); + if (box.x0 <= point.x && point.x <= box.x1 && box.y0 <= point.y && point.y <= box.y1){ + return &object; + } + } + return nullptr; +} + +bool trainer_may_see(const MapData& map, const MapObject& object, const TilePos& tile){ + if (!object.trainer){ + return false; + } + const Pokemon::TileBox box = standing_box(object); + for (int y = box.y0; y <= box.y1; y++){ + for (int x = box.x0; x <= box.x1; x++){ + if (sees_from(map, *object.trainer, TilePos{x, y}, tile)){ + return true; + } + } + } + return false; +} + + + +StepKind classify_step(const MapData& map, const PlayerState& state, Direction direction){ + return classify_step_onto(map, state, direction, map, state.position.next(direction)); +} + +StepKind classify_step_onto( + const MapData& from, const PlayerState& state, Direction direction, + const MapData& to, const TilePos& destination +){ + if (is_wall(to, destination) + || blocks_leaving(from, state.position, direction) + || blocks_entering(to, destination, direction) + ){ + return StepKind::BLOCKED; + } + + const uint8_t level = elevation_at(to, destination); + const bool mismatch = state.elevation != ELEVATION_ANY + && level != ELEVATION_ANY && level != ELEVATION_IGNORED + && level != state.elevation; + if (mismatch){ + // CanStopSurfing() and IsPlayerFacingSurfableFishableWater(). + if (state.surfing && level == ELEVATION_GROUND && object_at(to, destination) == nullptr){ + return StepKind::STOP_SURFING; + } + if (!state.surfing && state.elevation == ELEVATION_GROUND && is_water(to, destination)){ + return StepKind::START_SURF; + } + return StepKind::BLOCKED; + } + + if (object_at(to, destination) != nullptr){ + return StepKind::BLOCKED; + } + return StepKind::WALK; +} + +PlayerState after_step(const MapData& map, const PlayerState& state, Direction direction, StepKind kind){ + return after_step_onto(map, state, map, state.position.next(direction), kind); +} + +PlayerState after_step_onto( + const MapData& from, const PlayerState& state, + const MapData& to, const TilePos& destination, StepKind kind +){ + PlayerState next = state; + next.position = destination; + const uint8_t level = elevation_at(to, destination); + if (level != ELEVATION_IGNORED && elevation_at(from, state.position) != ELEVATION_IGNORED){ + next.elevation = level; + } + if (kind == StepKind::START_SURF){ + next.surfing = true; + }else if (kind == StepKind::STOP_SURFING){ + next.surfing = false; + } + return next; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h new file mode 100644 index 0000000000..bcbcc8ed79 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h @@ -0,0 +1,71 @@ +/* Overworld Map + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's walking rules on a map (a Pokemon::MapData): per tile collision, + * elevation and the behaviors that matter for walking (water, one-way + * edges), plus its warps and the objects standing on it. The map data is + * generated from the pret/pokefirered decompilation, and classify_step() + * follows the game's own collision checks (GetCollisionAtCoords() in + * src/event_object_movement.c), so a route planned on these maps is one the + * game allows. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldMap_H +#define PokemonAutomation_PokemonFRLG_OverworldMap_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonFRLG_OverworldObjects.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// What decides where the player's next step can go. +struct PlayerState{ + TilePos position; + uint8_t elevation = ELEVATION_GROUND; + bool surfing = false; +}; + +// Classification of movement result when taking a step. +enum class StepKind{ + BLOCKED, + WALK, // moves one tile (on land, or on water while surfing) + STOP_SURFING, // moves from water onto land and stops surfing + START_SURF, // blocked, but facing water the player can Surf onto +}; + +// What pressing `direction` once does to the player in `state`. +StepKind classify_step(const MapData& map, const PlayerState& state, Direction direction); + +// The same for a step that crosses into another map: from `state` on `from` +// onto `destination` on `to`. +StepKind classify_step_onto( + const MapData& from, const PlayerState& state, Direction direction, + const MapData& to, const TilePos& destination +); + +// The player after a step of kind WALK, STOP_SURFING or START_SURF (the +// Surf action moves the player onto the water). +PlayerState after_step(const MapData& map, const PlayerState& state, Direction direction, StepKind kind); +// The player state resulting from stepping across map boundaries. +PlayerState after_step_onto( + const MapData& from, const PlayerState& state, + const MapData& to, const TilePos& destination, StepKind kind +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp new file mode 100644 index 0000000000..a1a91e3b2d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -0,0 +1,118 @@ +/* Overworld Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonFRLG_OverworldMaps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr std::string_view MAP_NAMES[] = { + // From a new game to Brock. + "PalletTown", + "PalletTown_PlayersHouse_1F", + "PalletTown_PlayersHouse_2F", + "PalletTown_RivalsHouse", + "PalletTown_ProfessorOaksLab", + "Route1", + "ViridianCity", + "ViridianCity_Mart", + "ViridianCity_PokemonCenter_1F", + "Route22", + "Route2", + "Route2_ViridianForest_SouthEntrance", + "ViridianForest", + "Route2_ViridianForest_NorthEntrance", + "PewterCity", + "PewterCity_PokemonCenter_1F", + "PewterCity_Mart", + "PewterCity_Museum_1F", + "PewterCity_Gym", + // Cerulean Cave, for Mewtwo. + "CeruleanCity_PokemonCenter_1F", + "CeruleanCity", + "Route24", + "CeruleanCave_1F", + "CeruleanCave_2F", + "CeruleanCave_B1F", +}; + + +const std::vector& all_maps(){ + static const std::vector MAPS = []{ + std::vector maps; + for (std::string_view name : MAP_NAMES){ + maps.push_back(load_map(std::string(name))); + } + return maps; + }(); + return MAPS; +} + +} // namespace + + +MapData parse_map(const std::string& json, const std::string& source){ + return Pokemon::parse_map(parse_json(json), source); +} + +MapData load_map(const std::string& name){ + const std::string source = "Maps/" + name + ".json"; + const std::vector>& files = overworld_map_json(); + const auto file = std::find_if(files.begin(), files.end(), [&](const auto& item){ return item.first == name; }); + if (file == files.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, source + " is not built into the program."); + } + MapData map = parse_map(file->second, source); + if (map.name != name){ + throw ParseException(source + ": name is \"" + map.name + "\", not \"" + name + "\"."); + } + return map; +} + +std::vector overworld_maps(const std::set& set_flags){ + std::vector maps = all_maps(); + for (MapData& map : maps){ + hide_objects(map, set_flags); + } + return maps; +} + +TilePos map_point(const std::vector& maps, const std::string& map, const std::string& point){ + for (const MapData& data : maps){ + if (data.name != map){ + continue; + } + const auto iter = data.points.find(point); + if (iter != data.points.end()){ + return iter->second; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No point \"" + point + "\" on map " + map + "."); +} + +std::set map_flag_set(const std::vector& maps, const std::string& name){ + std::set flags; + for (const MapData& map : maps){ + const auto iter = map.flag_sets.find(name); + if (iter != map.flag_sets.end()){ + flags.insert(iter->second.begin(), iter->second.end()); + } + } + return flags; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h new file mode 100644 index 0000000000..f561970d25 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h @@ -0,0 +1,72 @@ +/* Overworld Maps + * + * From: https://github.com/PokemonAutomation/ + * + * The FRLG maps the overworld routes know about so far: every map from a + * new game in Pallet Town through Viridian City, Route 2 and Viridian + * Forest to Brock's gym in Pewter City; and Cerulean City, its Pokemon + * Center, Route 24 to its north, and the three floors of Cerulean Cave, + * where Mewtwo waits on B1F. + * + * Each map is a pinned PokemonSimulation JSON resource, prepared under + * Packages/Resources/Pokemon/Maps/frlg and built into the program by CMake + * (pa_embed_text_files() in cmake/EmbedTextFiles.cmake), so the program and + * its tests read the same copy. The schema is Pokemon::MapData's + * (Pokemon/Navigation/Pokemon_MapData.h). A warp leads to point + * "warp_" of its map, the tile of that map's warp n. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldMaps_H +#define PokemonAutomation_PokemonFRLG_OverworldMaps_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldMap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Reads a map from its JSON text (Pokemon::parse_map()). `source` names it +// in errors. Throws ParseException, naming the map and the field, if a field +// is missing or doesn't fit the schema. +MapData parse_map(const std::string& json, const std::string& source); + +// (name, JSON text) of each file in Maps/, sorted by name. Generated at +// build time. +// TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonFRLG/Maps) when ready. +const std::vector>& overworld_map_json(); + +// Reads map `name` from overworld_map_json(). Throws InternalProgramError if +// it isn't built in, and ParseException as parse_map(). +MapData load_map(const std::string& name); + +// Every map, by its decompilation name ("CeruleanCity", "CeruleanCave_B1F", ...), +// with the objects the given event flags hide removed. The maps are parsed +// once, on the first call. +std::vector overworld_maps(const std::set& set_flags = {}); + +// Point `point` of map `map` among `maps`, e.g. ("CeruleanCave_B1F", +// "mewtwo"). Throws InternalProgramError if there is none. +TilePos map_point(const std::vector& maps, const std::string& map, const std::string& point); + +// The flags in flag set `name` of every map among `maps`, e.g. +// "after_hall_of_fame": the flags the Hall of Fame sets, which clear the way +// to Cerulean Cave. +std::set map_flag_set(const std::vector& maps, const std::string& name); + + +// Registers overworld map unit tests. +void add_tests_OverworldMaps(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp new file mode 100644 index 0000000000..fca2836022 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp @@ -0,0 +1,306 @@ +/* Overworld Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct OverworldMapsInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct OverworldMapsExpectation{ + std::string_view description; +}; + +struct OverworldMapsTestCase{ + OverworldMapsInput input; + OverworldMapsExpectation expectation; +}; + +class Test_OverworldMaps : public UnitTest{ +public: + explicit Test_OverworldMaps(OverworldMapsTestCase scenario) + : UnitTest("PokemonFRLG::OverworldMaps - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + OverworldMapsTestCase m_scenario; +}; + + +const std::string VALID_MAP = R"({ + "name": "Test", + "source": {"decomp_file": "data/maps/Test/map.json", "revision": "test", "date": "2026-10-31"}, + "tiles": ["#.w", "~D."], + "elevation": ["031", "3f3"], + "points": {"door": [1, 1]}, + "warps": [ + {"x": 1, "y": 1, "enter": "walk_into", "to_map": "Other", "to_point": "warp_2"}, + {"x": 2, "y": 1, "enter": "walk_south"} + ], + "objects": [{"name": "nurse", "kind": "npc", "x": 0, "y": 1, "wander": {"x0": 0, "y0": 1, "x1": 1, "y1": 1}, "hide_flag": "FLAG_X"}], + "flag_sets": {"later": ["FLAG_X", "FLAG_Y"]}, + "connections": [{"side": "south", "to_map": "Other", "offset": -4}] +})"; + +// The ParseException that parsing `json` throws, or empty if it doesn't. +std::string parse_error(const std::string& json){ + try{ + parse_map(json, "Test.json"); + }catch (ParseException& e){ + return e.message(); + } + return ""; +} + +// Whether `text` contains every one of `parts`. +bool mentions(const std::string& text, std::initializer_list parts){ + for (std::string_view part : parts){ + if (text.find(part) == std::string::npos){ + return false; + } + } + return true; +} + +UnitTestResult test_valid_map(){ + const MapData map = parse_map(VALID_MAP, "Test.json"); + if (map.name != "Test" || map.tiles.width != 3 || map.tiles.height != 2 + || map.tiles.at({0, 1}) != TileKind::TALL_GRASS || exit_mat(map, {2, 1}) != Direction::SOUTH + ){ + return "Wrong name, size or tiles."; + } + if (elevation_at(map, {2, 0}) != 1 || elevation_at(map, {1, 1}) != 15){ + return "Wrong elevation."; + } + const MapWarp* door = warp_at(map, {1, 1}); + if (map.warps.size() != 2 || door == nullptr || !door->to || door->to->map != "Other" || door->to->point != "warp_2"){ + return "Wrong warps."; + } + const MapObject* nurse = object_at(map, {1, 1}); + if (map.objects.size() != 1 || nurse == nullptr || nurse->name != "nurse" || nurse->hide_flag != "FLAG_X"){ + return "Wrong objects."; + } + const MapConnection& connection = map.connections.at(0); + if (connection.side != Direction::SOUTH || connection.offset != -4 || connection.to_map != "Other"){ + return "Wrong connections."; + } + if (map.points.at("door") != TilePos{1, 1} || map.flag_sets.at("later") != std::set{"FLAG_X", "FLAG_Y"}){ + return "Wrong points or flag sets."; + } + return true; +} + +UnitTestResult test_missing_field(){ + std::string json = VALID_MAP; + json.replace(json.find("\"tiles\""), 7, "\"cells\""); + const std::string error = parse_error(json); + if (!mentions(error, {"Test.json", "tiles", "missing"})){ + return "Expected an error naming the missing tiles, got: \"" + error + "\""; + } + return true; +} + +UnitTestResult test_elevation_left_out(){ + std::string json = VALID_MAP; + json.erase(json.find("\"elevation\""), std::string("\"elevation\": [\"031\", \"3f3\"],").size()); + const MapData map = parse_map(json, "Test.json"); + for (int y = 0; y < 2; y++){ + for (int x = 0; x < 3; x++){ + if (elevation_at(map, {x, y}) != ELEVATION_GROUND){ + return "Expected ground everywhere without an elevation grid."; + } + } + } + return true; +} + +UnitTestResult test_bad_field_type(){ + std::string json = VALID_MAP; + json.replace(json.find("\"x\": 1"), 6, "\"x\": \"1\""); + const std::string error = parse_error(json); + if (!mentions(error, {"Test.json", "warps[0]", "x", "integer"})){ + return "Expected an error naming warps[0].x, got: \"" + error + "\""; + } + return true; +} + +UnitTestResult test_bad_row_length(){ + std::string json = VALID_MAP; + json.replace(json.find("\"~D.\""), 5, "\"~D\""); + const std::string error = parse_error(json); + if (!mentions(error, {"Test.json", "tiles[1]", "string of 3 glyphs"})){ + return "Expected an error naming the short row, got: \"" + error + "\""; + } + return true; +} + +UnitTestResult test_unknown_tile(){ + std::string json = VALID_MAP; + json.replace(json.find("\"#.w\""), 5, "\"#.?\""); + const std::string error = parse_error(json); + if (!mentions(error, {"Test.json", "tiles[0]", "unknown glyph '?'", "(2, 0)"})){ + return "Expected an error naming the unknown tile, got: \"" + error + "\""; + } + return true; +} + +// Route 3's Lass Robin, shrunk: she wanders x 2, y 2..4 looking north and +// south, sight 3, below a corridor (row 1) walled off at x 2 above it; a +// bug catcher at (5, 4) looks west, sight 2. +const std::string TRAINERS_MAP = R"({ + "name": "Trainers", + "source": {"decomp_file": "", "revision": "test", "date": "2026-11-02"}, + "tiles": ["##.####", ".......", ".......", ".......", ".......", "~~~~~~~"], + "objects": [ + {"name": "lass", "kind": "npc", "x": 2, "y": 3, "wander": {"x0": 2, "y0": 2, "x1": 2, "y1": 4}, "trainer": {"sight": 3, "looks": ["north", "south"]}}, + {"name": "bug_catcher", "kind": "npc", "x": 5, "y": 4, "facing": "west", "trainer": {"sight": 2}}, + {"name": "youngster", "kind": "npc", "x": 6, "y": 1} + ] +})"; + +// A wanderer sees from every tile she may stand on, short of a wall; a +// trainer standing still only along his facing; a non-trainer nothing. +UnitTestResult test_trainer_sight(){ + const MapData map = parse_map(TRAINERS_MAP, "Trainers.json"); + const MapObject& lass = map.objects[0]; + const MapObject& bug_catcher = map.objects[1]; + const MapObject& youngster = map.objects[2]; + struct Case{ + const MapObject* object; + TilePos tile; + bool sees; + }; + const Case cases[] = { + {&lass, {2, 1}, true}, // from (2, 2..4), north + {&lass, {2, 0}, true}, // the gap in the wall, 2 tiles up from (2, 2) + {&lass, {2, 5}, true}, // south, from (2, 4) + {&lass, {1, 1}, false}, + {&bug_catcher, {3, 4}, true}, + {&bug_catcher, {2, 4}, false}, // past his sight + {&bug_catcher, {5, 3}, false}, // not his way + {&youngster, {5, 1}, false}, + }; + for (const Case& c : cases){ + if (trainer_may_see(map, *c.object, c.tile) != c.sees){ + return c.object->name + (c.sees ? " should see " : " shouldn't see ") + Pokemon::to_string(c.tile) + "."; + } + } + return true; +} + +UnitTestResult test_not_json(){ + const std::string error = parse_error("{\"name\": "); + if (!mentions(error, {"Test.json", "not a JSON object"})){ + return "Expected an error for broken JSON, got: \"" + error + "\""; + } + return true; +} + +// A hall with an escalator at (1, 2) to a floor that isn't loaded, like +// Route 4's Pokemon Center. +const std::string ESCALATOR_HALL = R"({ + "name": "Hall", "source": {"decomp_file": "", "revision": "test", "date": "2026-11-02"}, + "tiles": ["######", "#....#", "#....#", "######"], + "warps": [{"x": 1, "y": 2, "enter": "step_on"}] +})"; + +// Holding west along the escalator's row rides it: a leg there ends by +// counting tiles, never by holding to the wall behind it (console B, +// 2026-11-02, Route 4's Pokemon Center). +UnitTestResult test_no_hold_onto_escalator(){ + const std::vector maps{parse_map(ESCALATOR_HALL, "Hall")}; + if (hold_to_wall(maps, {"Hall", {4, 2}}, false, Direction::WEST)){ + return "Expected no hold west along the escalator's row."; + } + const std::optional> route = plan_overworld_route(maps, {"Hall", {4, 2}}, {{"Hall", {2, 1}}, std::nullopt}); + if (!route || !(follow_overworld_route(maps, {"Hall", {4, 2}}, *route) == MapPosition{"Hall", {2, 1}})){ + return "Expected a route from (4, 2) to (2, 1)."; + } + for (const RouteStep& step : *route){ + if (step.to_wall && step.direction == Direction::WEST && step.end.point == TilePos{2, 2}){ + return "Expected no hold west next to the escalator: " + to_string(step); + } + } + return true; +} + + +const OverworldMapsTestCase OVERWORLD_MAPS_CASES[] = { + { + .input = {.name = "valid map", .body = test_valid_map}, + .expectation = {.description = "parses valid map json and properties"}, + }, + { + .input = {.name = "missing field", .body = test_missing_field}, + .expectation = {.description = "detects missing required fields in map json"}, + }, + { + .input = {.name = "elevation left out", .body = test_elevation_left_out}, + .expectation = {.description = "handles omitted elevation data cleanly"}, + }, + { + .input = {.name = "field of the wrong type", .body = test_bad_field_type}, + .expectation = {.description = "rejects invalid field types in map json"}, + }, + { + .input = {.name = "row of the wrong length", .body = test_bad_row_length}, + .expectation = {.description = "rejects rows not matching declared width"}, + }, + { + .input = {.name = "unknown tile", .body = test_unknown_tile}, + .expectation = {.description = "rejects unmapped character codes in tile map"}, + }, + { + .input = {.name = "not JSON", .body = test_not_json}, + .expectation = {.description = "rejects malformed json input string"}, + }, + { + .input = {.name = "trainer sight", .body = test_trainer_sight}, + .expectation = {.description = "evaluates line of sight for trainer objects"}, + }, + { + .input = {.name = "no hold onto an escalator", .body = test_no_hold_onto_escalator}, + .expectation = {.description = "prevents holding into an escalator"}, + }, +}; + +} // namespace + + +void add_tests_OverworldMaps(UnitTestDatabase& database){ + for (const auto& scenario : OVERWORLD_MAPS_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldObjects.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldObjects.h new file mode 100644 index 0000000000..70baec8852 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldObjects.h @@ -0,0 +1,43 @@ +/* Overworld Objects + * + * From: https://github.com/PokemonAutomation/ + * + * The objects standing on a map: which one is on a tile, what a + * trainer may see, and the ones the game hides by flag. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldObjects_H +#define PokemonAutomation_PokemonFRLG_OverworldObjects_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonFRLG_OverworldTileRules.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The object standing, or maybe wandering, on this tile. +const MapObject* object_at(const MapData& map, const TilePos& point); + +// Whether `object`, a trainer, may see the player on `tile`: up to its +// sight ahead, any way it looks, short of a wall, from its tile or, for +// one who wanders, from any tile it may wander to. False for an object +// that isn't a trainer. +bool trainer_may_see(const MapData& map, const MapObject& object, const TilePos& tile); + +// Removes the objects the game hides once one of `flags` is set. +void hide_objects(MapData& map, const std::set& flags); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp new file mode 100644 index 0000000000..b8fdbf7c43 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp @@ -0,0 +1,374 @@ +/* Overworld Re-anchor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonFRLG_OverworldReanchor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +constexpr size_t MAX_HOLDS = 3; + +Direction opposite(Direction direction){ + return (Direction)(((int)direction + 2) % 4); +} + +// The way from `from` to `to`, on the same row or column. +Direction towards(const TilePos& from, const TilePos& to){ + if (to.x == from.x){ + return to.y < from.y ? Direction::NORTH : Direction::SOUTH; + } + return to.x < from.x ? Direction::WEST : Direction::EAST; +} + +const MapData* map_named(const std::vector& maps, const std::string& name){ + for (const MapData& map : maps){ + if (map.name == name){ + return ↦ + } + } + return nullptr; +} + +// Whether the player could stand on `position`. +bool standable(const std::vector& maps, const MapPosition& position, bool surfing){ + const MapData* map = map_named(maps, position.map); + return map != nullptr && in_bounds(*map, position.point) + && !is_wall(*map, position.point) && object_at(*map, position.point) == nullptr + && is_water(*map, position.point) == surfing; +} + +template +void add_unique(std::vector& items, const Type& item){ + if (std::find(items.begin(), items.end(), item) == items.end()){ + items.push_back(item); + } +} + +// Where `step` started: `tiles` back from its end, on the same map. +std::optional walk_back(const std::vector& maps, const RouteStep& step){ + MapPosition position = step.end; + for (int c = 0; c < step.tiles; c++){ + position.point = position.point.next(opposite(step.direction)); + if (!standable(maps, position, step.surfing)){ + return std::nullopt; + } + } + return position; +} + +// Where trainer `object` of `map`, who may see the player on `tile`, +// stands once walked up: next to the player, on the side they came from. +// Each tile a wanderer may stand on is checked on its own, since the side +// depends on it. +void add_trainer_stops( + const MapData& map, size_t object, const MapPosition& tile, std::vector& stops +){ + const MapObject& trainer = map.objects[object]; + const Pokemon::TileBox box = trainer.wander.value_or( + Pokemon::TileBox{.x0 = trainer.x, .y0 = trainer.y, .x1 = trainer.x, .y1 = trainer.y} + ); + const int width = box.x1 - box.x0 + 1; + const int count = width * (box.y1 - box.y0 + 1); + for (int c = 0; c < count; c++){ + MapObject standing = trainer; + standing.wander.reset(); + standing.x = box.x0 + c % width; + standing.y = box.y0 + c / width; + if (trainer_may_see(map, standing, tile.point)){ + const TilePos beside = tile.point.next(towards(tile.point, TilePos{standing.x, standing.y})); + add_unique(stops, TrainerStop{.object = object, .at = MapPosition{tile.map, beside}}); + } + } +} + +// The trainers who may see the player on `tile`, and where each stands +// once walked up. +std::vector trainers_seeing(const std::vector& maps, const MapPosition& tile){ + std::vector stops; + const MapData* map = map_named(maps, tile.map); + for (size_t c = 0; map != nullptr && c < map->objects.size(); c++){ + if (trainer_may_see(*map, map->objects[c], tile.point)){ + add_trainer_stops(*map, c, tile, stops); + } + } + return stops; +} + +// `maps` with a trainer who walked up standing on each of `trainers`: they +// stay there after the battle, so the player can't walk through. +std::vector with_trainers(const std::vector& maps, const std::vector& trainers){ + std::vector ret = maps; + for (const MapPosition& at : trainers){ + for (MapData& map : ret){ + if (map.name == at.map && in_bounds(map, at.point)){ + map.tiles.cells[(size_t)at.point.y * map.tiles.width + at.point.x] = TileKind::WALL; + } + } + } + return ret; +} + +// Where the player may be, on which of the maps as they may stand (with +// or without a trainer next to them). +struct Hypothesis{ + size_t world = 0; + MapPosition at; + + bool operator==(const Hypothesis& other) const = default; +}; + +bool converged(const std::vector& positions){ + for (const Hypothesis& position : positions){ + if (!(position.at == positions[0].at)){ + return false; + } + } + return true; +} + +// Whether a person stands, or may wander, on a tile `wall` passes after +// `from`. The step rules don't have people, but one there stops the player +// short of the wall. +bool person_on_the_way( + const std::vector& world, const MapPosition& from, + bool surfing, Direction direction, const WallHold& wall +){ + RouteStep hold; + hold.direction = direction; + hold.tiles = wall.tiles; + hold.surfing = surfing; + const std::vector tiles = leg_tiles(world, from, hold); + for (size_t c = 1; c < tiles.size(); c++){ + const MapData* map = map_named(world, tiles[c].map); + if (map != nullptr && object_at(*map, tiles[c].point) != nullptr){ + return true; + } + } + return false; +} + +// Holding `direction` from each of `positions`: where they end up, as a leg +// to a wall as long as the longest of them. Nothing if any isn't stopped +// by a wall, or may be stopped short by a person. +std::optional, RouteStep>> hold_all( + const std::vector>& worlds, const std::vector& positions, + bool surfing, Direction direction +){ + std::vector ends; + RouteStep hold; + hold.direction = direction; + hold.surfing = surfing; + hold.to_wall = true; + hold.facing_after = direction; + for (const Hypothesis& position : positions){ + const std::optional wall = hold_to_wall(worlds[position.world], position.at, surfing, direction); + if (!wall || person_on_the_way(worlds[position.world], position.at, surfing, direction, *wall)){ + return std::nullopt; + } + add_unique(ends, Hypothesis{position.world, wall->end}); + hold.tiles = std::max(hold.tiles, wall->tiles); + hold.wild = hold.wild || wall->wild; + hold.end = wall->end; + } + return std::make_pair(std::move(ends), hold); +} + +int total_tiles(const std::vector& legs){ + int total = 0; + for (const RouteStep& leg : legs){ + total += leg.tiles; + } + return total; +} + +struct Found{ + std::vector holds; + MapPosition at; +}; + +// Every way of exactly `depth` holds that brings all of `positions` to one +// tile, in a fixed order. +void search( + const std::vector>& worlds, const std::vector& positions, bool surfing, + size_t depth, std::vector& holds, std::vector& found +){ + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + auto next = hold_all(worlds, positions, surfing, direction); + if (!next || next->first == positions || next->second.tiles == 0){ + continue; + } + holds.push_back(next->second); + if (converged(next->first)){ + if (depth == 1){ + found.push_back(Found{holds, next->first[0].at}); + } + }else if (depth > 1){ + search(worlds, next->first, surfing, depth - 1, holds, found); + } + holds.pop_back(); + } +} + +// Whether `route`, planned from `at` on other maps, walks the same on +// `world`: each leg to a wall stops at its end, each open leg gets there. +bool walks_same(const std::vector& world, MapPosition at, const std::vector& route){ + for (const RouteStep& step : route){ + if (step.action == RouteAction::WALK && step.to_wall){ + const std::optional hold = hold_to_wall(world, at, step.surfing, step.direction); + if (!hold || !(hold->end == step.end)){ + return false; + } + }else if (step.action == RouteAction::WALK){ + const std::vector tiles = leg_tiles(world, at, step); + const size_t expected = (size_t)(step.tiles - (step.warps ? 1 : 0)) + 1; + if (tiles.size() != expected || (!step.warps && !(tiles.back() == step.end))){ + return false; + } + } + at = step.end; + } + return true; +} + +bool walks_same_everywhere( + const std::vector>& worlds, const std::vector& positions, + const MapPosition& from, const std::vector& route +){ + for (const Hypothesis& position : positions){ + if (!walks_same(worlds[position.world], from, route)){ + return false; + } + } + return true; +} + +// The ways to find the player from all of `positions`: fewest holds first, +// then fewest tiles held. None needed if they are all on one tile. +std::vector find_player( + const std::vector>& worlds, const std::vector& positions, bool surfing +){ + std::vector found; + if (converged(positions)){ + found.push_back(Found{{}, positions[0].at}); + } + for (size_t depth = 1; found.empty() && depth <= MAX_HOLDS; depth++){ + std::vector holds; + search(worlds, positions, surfing, depth, holds, found); + std::stable_sort(found.begin(), found.end(), [](const Found& a, const Found& b){ + return total_tiles(a.holds) < total_tiles(b.holds); + }); + } + return found; +} + +} // namespace + + +WalkedTiles walked_near(const RouteStep& step, int estimate, Milliseconds tile_time){ + // The estimate is rounded to the nearest tile already. + const int spread = tile_time.count() > 0 + ? (int)((STOP_TIMING_SLACK + tile_time / 2) / tile_time) + : step.tiles; + return WalkedTiles{ + .min = std::clamp(estimate - spread, 0, step.tiles), + .max = std::clamp(estimate + spread, 0, step.tiles), + }; +} + +WalkedTiles whole_leg(const RouteStep& step){ + return WalkedTiles{.min = 0, .max = step.tiles}; +} + +std::string to_string(const StopCandidate& candidate){ + std::string text = to_string(candidate.player); + if (candidate.trainer){ + text += std::format(" (stopped by a trainer, now at {})", Pokemon::to_string(candidate.trainer->at.point)); + } + return text; +} + +std::vector stop_candidates( + const std::vector& maps, + const std::optional& start, + const RouteStep& step, + WalkedTiles walked +){ + std::vector candidates; + if (step.action != RouteAction::WALK){ + return candidates; + } + const std::optional from = start ? start : walk_back(maps, step); + if (!from){ + return candidates; + } + const std::vector tiles = leg_tiles(maps, *from, step); + const int last = std::min((int)tiles.size() - 1, walked.max); + for (int c = 1; c <= last; c++){ + for (const TrainerStop& trainer : trainers_seeing(maps, tiles[c])){ + candidates.push_back(StopCandidate{.player = tiles[c], .trainer = trainer}); + } + } + if (!candidates.empty() && !step.wild){ + return candidates; + } + for (int c = std::max(0, walked.min); c <= last; c++){ + add_unique(candidates, StopCandidate{.player = tiles[c], .trainer = std::nullopt}); + } + return candidates; +} + +std::optional plan_reanchor( + const std::vector& maps, + const std::vector& candidates, + const RouteStep& step, + const RouteCosts& costs +){ + if (candidates.empty() || step.action != RouteAction::WALK){ + return std::nullopt; + } + + // The maps as they may stand: as they are, and with each trainer who + // may have walked up. + std::vector> worlds{maps}; + std::vector trainers; + std::vector positions; + for (const StopCandidate& candidate : candidates){ + size_t world = 0; + if (candidate.trainer){ + worlds.push_back(with_trainers(maps, {candidate.trainer->at})); + world = worlds.size() - 1; + add_unique(trainers, candidate.trainer->at); + } + add_unique(positions, Hypothesis{world, candidate.player}); + } + + const std::vector clear_of_trainers = with_trainers(maps, trainers); + for (const Found& at : find_player(worlds, positions, step.surfing)){ + const Direction facing = at.holds.empty() ? step.direction : at.holds.back().direction; + // The way back keeps clear of every trainer who may stand in it if + // it can, and must walk the same whether they do or not. + std::optional> back = plan_overworld_route(clear_of_trainers, at.at, RouteGoal{step.end, std::nullopt}, costs, facing); + if (!back && !trainers.empty()){ + back = plan_overworld_route(maps, at.at, RouteGoal{step.end, std::nullopt}, costs, facing); + } + if (back && (trainers.empty() || walks_same_everywhere(worlds, positions, at.at, *back))){ + return Reanchor{.holds = at.holds, .found = at.at, .back = std::move(*back)}; + } + } + return std::nullopt; +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h new file mode 100644 index 0000000000..709712e783 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h @@ -0,0 +1,102 @@ +/* Overworld Re-anchor + * + * From: https://github.com/PokemonAutomation/ + * + * Finding the player again after a battle or a message stopped a leg + * part-way. The timing of the stop narrows where they are to a few tiles of + * the leg (and a trainer who saw them may have stopped them earlier, on a + * tile in their sight); this looks for holds to walls, none to three, that + * end on the same tile from every one of them, and a way back to the leg's + * end that walks the same from there whichever it was. If there are none, + * the caller stops: the player is never guessed to be on one of them. + * + * The player is taken to be on the leg's line. Wider sets were tried: + * with even one tile to either side, Route 1's people and ledges cut some + * hold for some tile, and nothing on its grass legs could be found. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldReanchor_H +#define PokemonAutomation_PokemonFRLG_OverworldReanchor_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldMap.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldWalkedTiles.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// A trainer who saw the player and walked up to them: which of `map`'s +// objects, and the tile next to the player they stand on afterwards. +struct TrainerStop{ + size_t object = 0; + MapPosition at; + + bool operator==(const TrainerStop& other) const = default; +}; + +// One way things may stand after a stop: the player's tile, and the +// trainer who stopped them there, if one did. +struct StopCandidate{ + MapPosition player; + std::optional trainer; + + bool operator==(const StopCandidate& other) const = default; +}; +// Formats a StopCandidate as a string. +std::string to_string(const StopCandidate& candidate); + +// Where `step`, an open WALK from `start`, may have been stopped: +// - on the tiles `walked` covers, by a wild battle or a message; +// - on any tile up to `walked.max` a trainer may see, by that trainer: +// the player stops as soon as they are seen, and the trainer speaks +// only after walking up, so later than the timing says. +// Off the grass a message is taken to be a trainer's wherever one may see +// the player, so there only the second kind are left, if there are any. +// `start` not known: worked back from the leg's end. Empty if it can't be. +std::vector stop_candidates( + const std::vector& maps, + const std::optional& start, + const RouteStep& step, + WalkedTiles walked +); + +// A candidate reanchor route step with its cost estimate. +struct Reanchor{ + // Legs to walls, in order, that bring the player to `found` from every + // candidate; none if there was only one. Each but the last ends on a + // tile that depends on the candidate; its `end` is one of them. + std::vector holds; + MapPosition found; + // From `found` back to the stopped leg's end, walking the same from + // there whichever candidate it was (a trainer who walked up stays). + std::vector back; +}; + +// After `step` stopped part-way, from `candidates`. Nothing if no holds +// bring them all to one tile, or no way back walks the same from there. +std::optional plan_reanchor( + const std::vector& maps, + const std::vector& candidates, + const RouteStep& step, + const RouteCosts& costs = default_route_costs() +); + + +// Registers overworld reanchor unit tests. +void add_tests_OverworldReanchor(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp new file mode 100644 index 0000000000..9eeaf20652 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp @@ -0,0 +1,284 @@ +/* Overworld Re-anchor Tests + * + * From: https://github.com/PokemonAutomation/ + * + * stop_candidates() and plan_reanchor(): finding the player again at a + * wall after an open leg stopped part-way. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldReanchor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct OverworldReanchorInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct OverworldReanchorExpectation{ + std::string_view description; +}; + +struct OverworldReanchorTestCase{ + OverworldReanchorInput input; + OverworldReanchorExpectation expectation; +}; + +class Test_OverworldReanchor : public UnitTest{ +public: + explicit Test_OverworldReanchor(OverworldReanchorTestCase scenario) + : UnitTest("PokemonFRLG::OverworldReanchor - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + OverworldReanchorTestCase m_scenario; +}; + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + +std::string describe(const std::optional& anchor){ + if (!anchor){ + return "none"; + } + std::string text = to_string(anchor->found) + " after"; + for (const RouteStep& hold : anchor->holds){ + text += " " + to_string(hold); + } + return text + ", then" + describe(anchor->back); +} + +// How a walking leg may have stopped: anywhere (seen after the hold), and +// at each estimate the timing can give. +std::vector stops_of(const RouteStep& step){ + std::vector stops{whole_leg(step)}; + for (int estimate = 0; estimate <= step.tiles; estimate++){ + stops.push_back(walked_near(step, estimate, std::chrono::milliseconds(267))); + } + return stops; +} + +// Plans from `start` to `goal`, then checks that the player can be found +// again however an open leg through tall grass is stopped, and that the +// way back reaches that leg's end. +UnitTestResult check_reanchors(const std::vector& maps, const MapPosition& start, const RouteGoal& goal){ + const std::optional> route = plan_overworld_route(maps, start, goal); + if (!route){ + return "No route from " + to_string(start) + "."; + } + std::optional at = start; + for (const RouteStep& step : *route){ + if (step.action != RouteAction::WALK || !step.wild || step.to_wall){ + at = step.end; + continue; + } + for (const WalkedTiles& walked : stops_of(step)){ + const std::vector candidates = stop_candidates(maps, at, step, walked); + const std::optional anchor = plan_reanchor(maps, candidates, step); + if (!anchor){ + return std::format( + "Can't find the player again on {}, stopped {} to {} tiles in ({} candidates):{}", + to_string(step), walked.min, walked.max, candidates.size(), describe(*route) + ); + } + if (!(follow_overworld_route(maps, anchor->found, anchor->back) == step.end)){ + return "The way back from " + to_string(anchor->found) + " misses the end of " + to_string(step) + "."; + } + } + at = step.end; + } + return true; +} + +// Console B, 2026-11-01: battles on Route 1 left the walker a tile or a +// whole leg off its count, four times. +UnitTestResult test_viridian_mart_to_oaks_lab(){ + const std::vector maps = overworld_maps(); + return check_reanchors( + maps, {"ViridianCity_Mart", map_point(maps, "ViridianCity_Mart", "clerk_front")}, + {{"PalletTown_ProfessorOaksLab", {6, 4}}, std::nullopt} + ); +} +UnitTestResult test_pallet_to_viridian_mart(){ + const std::vector maps = overworld_maps(); + return check_reanchors( + maps, {"PalletTown", map_point(maps, "PalletTown", "oaks_lab_front")}, + {{"ViridianCity_Mart", map_point(maps, "ViridianCity_Mart", "clerk_front")}, std::nullopt} + ); +} +// All grass, walled in by trees: where the walker was lost twice (console B, +// 2026-11-01, runs 16 and 17), and where the long dungeon walks start. +UnitTestResult test_viridian_forest(){ + const std::vector maps = overworld_maps(); + return check_reanchors( + maps, {"ViridianForest", {29, 61}}, + {{"Route2_ViridianForest_NorthEntrance", {7, 8}}, std::nullopt} + ); +} + +// A field with a wall at its east end and a row of ledges to the south. +const std::string TEST_FIELD_JSON = R"({ + "name": "Field", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["########", "#......#", "#......#", "#vvvvvv#", "#......#"], + "elevation": ["33333333", "33333333", "33333333", "33333333", "33333333"] +})"; + +// Stopped part-way east, the player holds back west to the wall, the +// shorter way, and walks back. Stopped part-way south above the ledges, +// which would be hopped, they hold back north. +UnitTestResult test_rules(){ + const std::vector maps{parse_map(TEST_FIELD_JSON, "Field")}; + RouteStep east; + east.direction = Direction::EAST; + east.tiles = 3; + east.end = {"Field", {4, 1}}; + std::optional anchor = plan_reanchor(maps, stop_candidates(maps, MapPosition{"Field", {1, 1}}, east, whole_leg(east)), east); + if (!anchor || anchor->holds.size() != 1 || anchor->holds[0].direction != Direction::WEST || !(anchor->found.point == TilePos{1, 1})){ + return "Expected a hold west to (1, 1), got " + describe(anchor); + } + if (anchor->back.size() != 1 || !(anchor->back[0].end == east.end)){ + return "Expected one leg back east to (4, 1), got " + describe(anchor); + } + RouteStep south; + south.direction = Direction::SOUTH; + south.tiles = 1; + south.end = {"Field", {3, 2}}; + anchor = plan_reanchor(maps, stop_candidates(maps, std::nullopt, south, whole_leg(south)), south); + if (!anchor || anchor->holds.size() != 1 || anchor->holds[0].direction != Direction::NORTH || !(anchor->found.point == TilePos{3, 1})){ + return "Expected a hold north back to (3, 1), got " + describe(anchor); + } + return true; +} + +// The timing narrows a stop to a tile either side of its estimate walking, +// two running, within the leg. +UnitTestResult test_timing(){ + RouteStep leg; + leg.direction = Direction::EAST; + leg.tiles = 10; + struct Case{ + int estimate; + int tile_ms; + int min; + int max; + }; + const Case cases[] = { + {.estimate = 5, .tile_ms = 267, .min = 4, .max = 6}, + {.estimate = 0, .tile_ms = 267, .min = 0, .max = 1}, + {.estimate = 10, .tile_ms = 267, .min = 9, .max = 10}, + {.estimate = 5, .tile_ms = 133, .min = 3, .max = 7}, + {.estimate = 1, .tile_ms = 133, .min = 0, .max = 3}, + }; + for (const Case& c : cases){ + const WalkedTiles walked = walked_near(leg, c.estimate, std::chrono::milliseconds(c.tile_ms)); + if (walked.min != c.min || walked.max != c.max){ + return std::format( + "{} tiles in at {}ms a tile: expected {} to {}, got {} to {}.", + c.estimate, c.tile_ms, c.min, c.max, walked.min, walked.max + ); + } + } + return true; +} + +// A field with someone standing in the middle of its north row. +const std::string TEST_PERSON_JSON = R"({ + "name": "Person", "source": {"decomp_file": "", "revision": "test", "date": "2026-11-02"}, + "tiles": ["#######", "#.....#", "#.....#", "#######"], + "objects": [{"name": "youngster", "kind": "npc", "x": 3, "y": 1}] +})"; + +// Stopped going east along the south row: holding north would meet the +// person from one of the tiles, so the player holds along the row. On the +// north row, past the person, they don't hold west into them. +UnitTestResult test_person_in_the_way(){ + const std::vector maps{parse_map(TEST_PERSON_JSON, "Person")}; + RouteStep east; + east.direction = Direction::EAST; + east.tiles = 4; + east.end = {"Person", {5, 2}}; + const std::optional anchor = plan_reanchor(maps, stop_candidates(maps, MapPosition{"Person", {1, 2}}, east, whole_leg(east)), east); + if (!anchor || anchor->holds.size() != 1 || anchor->holds[0].direction == Direction::NORTH){ + return "Expected one hold along the row, clear of the person, got " + describe(anchor); + } + RouteStep north_row = east; + north_row.tiles = 1; + north_row.end = {"Person", {5, 1}}; + const std::vector beside{{.player = {"Person", {4, 1}}, .trainer = std::nullopt}, {.player = {"Person", {5, 1}}, .trainer = std::nullopt}}; + const std::optional blocked = plan_reanchor(maps, beside, north_row); + if (blocked && blocked->holds[0].direction == Direction::WEST){ + return "Expected no hold west into the person, got " + describe(blocked); + } + return true; +} + + +const OverworldReanchorTestCase OVERWORLD_REANCHOR_CASES[] = { + { + .input = {.name = "rules", .body = test_rules}, + .expectation = {.description = "tests reanchor candidate generation and rules"}, + }, + { + .input = {.name = "timing", .body = test_timing}, + .expectation = {.description = "verifies reanchor hold durations and timing"}, + }, + { + .input = {.name = "a person in the way", .body = test_person_in_the_way}, + .expectation = {.description = "avoids planning reanchor into dynamic map obstacle"}, + }, + { + .input = {.name = "Viridian Mart to Oak's Lab", .body = test_viridian_mart_to_oaks_lab}, + .expectation = {.description = "reanchors along route from Viridian Mart to Oak's Lab"}, + }, + { + .input = {.name = "Pallet Town to Viridian Mart", .body = test_pallet_to_viridian_mart}, + .expectation = {.description = "reanchors along route from Pallet Town to Viridian Mart"}, + }, + { + .input = {.name = "Viridian Forest", .body = test_viridian_forest}, + .expectation = {.description = "reanchors along route through Viridian Forest"}, + }, +}; + +} // namespace + + +void add_tests_OverworldReanchor(UnitTestDatabase& database){ + for (const auto& scenario : OVERWORLD_REANCHOR_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp new file mode 100644 index 0000000000..ce552195c7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -0,0 +1,358 @@ +/* Overworld Recovery + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "PokemonFRLG_OverworldReanchor.h" +#include "PokemonFRLG_OverworldRecovery.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using Pokemon::EndBasis; +using Pokemon::ROUTE_LOG_TAG; + +std::vector route_tiles(const std::optional& position){ + if (!position){ + return {}; + } + return {{position->map, position->point}}; +} + +Pokemon::RouteLogLeg route_log_leg(const RouteStep& step){ + Pokemon::RouteLogLeg leg{.action = Pokemon::RouteLegAction::WALK, .direction = step.direction, .tiles = (size_t)step.tiles, .end = Pokemon::RouteLegEnd::OPEN}; + if (step.action == RouteAction::SURF){ + leg.action = Pokemon::RouteLegAction::SURF; + }else if (step.action == RouteAction::FACE){ + leg.action = Pokemon::RouteLegAction::FACE; + }else if (step.warps){ + leg.end = Pokemon::RouteLegEnd::WARP; + }else if (step.to_wall){ + leg.end = Pokemon::RouteLegEnd::WALL; + } + return leg; +} + +// The farthest sight of the trainers on `maps` who may see `tile`; 0 if +// none does. +int sight_onto(const std::vector& maps, const MapPosition& tile){ + int sight = 0; + for (const MapData& map : maps){ + if (map.name != tile.map){ + continue; + } + for (const MapObject& object : map.objects){ + if (trainer_may_see(map, object, tile.point)){ + sight = std::max(sight, object.trainer->sight); + } + } + } + return sight; +} + +// The route's lines in the route log the games share, as BDSP's walker +// writes them, under the caller's label. +class RouteLogLines{ +public: + RouteLogLines(const RouteCalls& calls, const RoutePlanning* planning) + : m_calls(calls) + , m_label(planning != nullptr ? planning->label : "Route") + {} + void plan(const std::optional& from, const std::vector& steps) const{ + std::vector legs; + for (const RouteStep& step : steps){ + legs.push_back({.leg = route_log_leg(step), .after = route_tiles(step.end)}); + } + m_calls.log(std::string(ROUTE_LOG_TAG) + Pokemon::route_plan_line(m_label, route_tiles(from), legs)); + } + void leg(size_t index, const std::vector& steps) const{ + const RouteStep& step = steps[index]; + m_calls.log(std::string(ROUTE_LOG_TAG) + Pokemon::route_leg_line(index + 1, steps.size(), {.leg = route_log_leg(step), .after = route_tiles(step.end)})); + } + void end(const RouteStep& step, const std::optional& at, EndBasis basis, const std::string& why) const{ + m_calls.log(std::string(ROUTE_LOG_TAG) + Pokemon::route_leg_end_line(m_label, route_log_leg(step), route_tiles(at), basis, why)); + } + void trainer_stopped(const RouteStep& step, const MapPosition& at) const{ + m_calls.log(std::string(ROUTE_LOG_TAG) + Pokemon::route_replan_line(m_label, route_log_leg(step), "stopped by a trainer who saw the player", route_tiles(at))); + } + void found(const MapPosition& at, size_t holds) const{ + m_calls.log(std::string(ROUTE_LOG_TAG) + Pokemon::route_found_line(m_label, route_tiles(at), holds)); + } + // Step `number` (from 1) of a plan whose first `holds` steps are holds + // to walls, walked to its end. + void done(const RouteStep& step, size_t number, size_t holds) const{ + if (number < holds){ + // Where a hold but the last ends depends on where it started. + end(step, std::nullopt, EndBasis::UNKNOWN, "a hold from an unknown tile"); + return; + } + end(step, step.end, EndBasis::WALKED, ""); + if (number == holds){ + found(step.end, holds); + } + } + +private: + const RouteCalls& m_calls; + std::string m_label; +}; + +// Walks each step through `calls`; watches a leg that crosses a trainer's +// sight for the trainer, and logs whether a leg to a wall that ended did +// end at its wall. +class CheckedSteps{ +public: + CheckedSteps(const RouteCalls& calls, WallCheck wall_check) + : m_calls(calls) + , m_wall_check(wall_check) + {} + StepOutcome walk(const RouteStep& step, std::optional facing, const std::optional& crossing){ + const std::string leg = to_string(step); + m_reholds = m_last_late && leg == m_last ? m_reholds + 1 : 0; + StepOutcome outcome = m_calls.walk(step, facing); + if (outcome.end == StepEnd::DONE && crossing && m_calls.watch_for_trainer){ + outcome = StepOutcome{.end = m_calls.watch_for_trainer(step, crossing->approach_tiles), .walked = std::nullopt}; + } + m_last = leg; + m_last_late = outcome.end == StepEnd::LATE; + if (outcome.end == StepEnd::DONE){ + check_wall(step); + } + return outcome; + } + +private: + // TODO(forest drift, 2026-11-01): diagnostic; remove or turn into a recovery once the cause is known. + // Four runs ended the walk to Viridian Forest's north gate off its + // column, which 52 legs walked by hand didn't reproduce: one more tap + // toward a leg's wall moves nobody who stands at it. Only logged: the + // screen check can't tell a bump from a step yet, and failing on it + // stopped good runs. + void check_wall(const RouteStep& step) const{ + if (!step.to_wall || step.warps || step.action != RouteAction::WALK + || m_wall_check == WallCheck::SKIP || !m_calls.moved_past_wall + ){ + return; + } + if (!m_calls.moved_past_wall(step)){ + return; + } + m_calls.log(std::format( + "Position check (logged only): a tap after {} moved the screen as a step would; believed at {}, after {} re-hold(s) " + "for something seen late (the leg's interrupts are the \"Leg:\" lines above).", + to_string(step), to_string(step.end), m_reholds + )); + } + + const RouteCalls& m_calls; + WallCheck m_wall_check = WallCheck::TAP; + std::string m_last; + bool m_last_late = false; + size_t m_reholds = 0; +}; + +// run_route()'s walk: the plan, as rejoined or planned again after a +// stop, which step is next, where the player is and which way they face. +class RouteRun{ +public: + RouteRun(const std::vector& route, std::optional facing, const RoutePlanning* planning, const RouteCalls& calls) + : m_planning(planning) + , m_calls(calls) + , m_lines(calls, planning) + , m_steps(calls, planning != nullptr ? planning->wall_check : WallCheck::TAP) + , m_plan(route) + , m_at(planning != nullptr ? planning->start : std::nullopt) + , m_facing(facing) + {} + + void run(){ + m_lines.plan(m_at, m_plan); + while (m_next < m_plan.size()){ + const RouteStep step = m_plan[m_next]; + m_lines.leg(m_next, m_plan); + // Where a hold that finds the player starts isn't known. + const std::optional crossing = m_next >= m_holds ? crossing_here(step) : std::nullopt; + const StepOutcome outcome = m_steps.walk(step, m_facing, crossing); + if (outcome.end == StepEnd::DONE){ + m_at = step.end; + m_facing = step.facing_after; + m_lines.done(step, ++m_next, m_holds); + continue; + } + const std::optional start = m_next >= m_holds ? m_at : std::nullopt; + m_facing = std::nullopt; // not known after a stop + if (++m_stops > MAX_ROUTE_STOPS){ + m_calls.fail(std::format("walk_overworld_route(): stopped part-way {} times.", m_stops)); + return; + } + if (!after_stop(step, outcome, start, crossing)){ + return; + } + } + } + +private: + const std::vector* maps() const{ + return m_planning != nullptr ? m_planning->maps : nullptr; + } + + std::optional crossing_here(const RouteStep& step) const{ + if (!m_at || maps() == nullptr){ + return std::nullopt; + } + return trainer_crossing(*maps(), *m_at, step); + } + + // After a stop on `step`, from `start` if known. False once the route + // has failed. + bool after_stop( + const RouteStep& step, const StepOutcome& outcome, + const std::optional& start, const std::optional& crossing + ){ + if (step.to_wall){ + return after_wall_stop(step, outcome, start, crossing); + } + if (outcome.end == StepEnd::STOPPED && step.warps && !step.wild){ + m_calls.hold_to_warp(step); + m_at = step.end; + m_facing = step.facing_after; + m_next++; + m_lines.end(step, m_at, EndBasis::ASSUMED, "stopped, then held on to the warp"); + return true; + } + m_lines.end(step, std::nullopt, EndBasis::UNKNOWN, "stopped part-way"); + if (maps() == nullptr){ + m_calls.fail("walk_overworld_route(): stopped part-way on " + to_string(step) + ", with no maps to find the player again."); + return false; + } + const WalkedTiles walked = outcome.walked.value_or(whole_leg(step)); + return rejoin(step, stop_candidates(*maps(), start, step, walked), walked); + } + + // A leg to a wall seen interrupted after its hold is walked again: the + // wall stops the player at its end however far they got. Unless, off + // the grass, the maps place a trainer who saw them on one tile of it: + // they stopped there, and the route goes on from there (Camper Liam, + // console B, 2026-11-01). + bool after_wall_stop( + const RouteStep& step, const StepOutcome& outcome, + const std::optional& start, const std::optional& crossing + ){ + if (outcome.end == StepEnd::STOPPED){ + // Interrupted at once, hold after hold: by something on the + // way that speaks, a sign, which the plan didn't have there. + m_calls.fail("walk_overworld_route(): a hold toward a wall is interrupted right away, again: the player is off the route, on " + to_string(step) + "."); + return false; + } + if (crossing && !step.wild && maps() != nullptr){ + const std::vector candidates = stop_candidates(*maps(), start, step, whole_leg(step)); + if (candidates.size() == 1 && candidates[0].trainer){ + return rejoin(step, candidates, whole_leg(step)); + } + } + m_lines.end(step, std::nullopt, EndBasis::UNKNOWN, "something seen after the hold; walking it again"); + return true; + } + + // Finds the player on one of `candidates`, plans the way back to the + // end of `step` (m_plan[m_next]), and the rest of the route after it. + bool rejoin(const RouteStep& step, const std::vector& candidates, WalkedTiles walked){ + std::string where; + for (const StopCandidate& candidate : candidates){ + where += (where.empty() ? "" : "; ") + to_string(candidate); + } + m_calls.log(std::format( + "Route: {} stopped {} to {} tiles in; the player is on one of: {}.", + to_string(step), walked.min, walked.max, where.empty() ? "nothing (no start to work from)" : where + )); + const std::optional anchor = candidates.empty() + ? std::nullopt + : plan_reanchor(*maps(), candidates, step, m_planning->costs); + if (!anchor){ + m_calls.fail( + "walk_overworld_route(): stopped part-way on " + to_string(step) + + ", and no holds to walls find the player from every tile they may be on." + ); + return false; + } + std::vector plan = anchor->holds; + plan.insert(plan.end(), anchor->back.begin(), anchor->back.end()); + plan.insert(plan.end(), m_plan.begin() + m_next + 1, m_plan.end()); + m_plan = std::move(plan); + m_holds = anchor->holds.size(); + m_next = 0; + if (m_holds > 0){ + m_at = std::nullopt; + m_lines.plan(std::nullopt, m_plan); + return true; + } + // Only one tile: the player stands there, still facing the leg's + // way (also after a trainer walked up: Camper Liam, console B, + // 2026-11-01). + if (candidates[0].trainer){ + m_lines.trainer_stopped(step, anchor->found); + }else{ + m_lines.found(anchor->found, 0); + } + m_at = anchor->found; + m_facing = step.direction; + m_lines.plan(m_at, m_plan); + return true; + } + + const RoutePlanning* m_planning; + const RouteCalls& m_calls; + const RouteLogLines m_lines; + CheckedSteps m_steps; + std::vector m_plan; + std::optional m_at; + std::optional m_facing; + size_t m_next = 0; + size_t m_stops = 0; + size_t m_holds = 0; // of the plan, holds to walls that find the player +}; + +} // namespace + + +std::optional trainer_crossing( + const std::vector& maps, const MapPosition& start, const RouteStep& step +){ + if (step.action != RouteAction::WALK){ + return std::nullopt; + } + TrainerCrossing crossing; + const std::vector tiles = leg_tiles(maps, start, step); + for (size_t c = 1; c < tiles.size(); c++){ + const int sight = sight_onto(maps, tiles[c]); + if (sight > 0){ + crossing.seen.push_back(tiles[c]); + crossing.approach_tiles = std::max(crossing.approach_tiles, sight); + } + } + if (crossing.seen.empty()){ + return std::nullopt; + } + return crossing; +} + +void run_route( + const std::vector& route, std::optional facing, + const RoutePlanning* planning, const RouteCalls& calls +){ + RouteRun(route, facing, planning, calls).run(); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h new file mode 100644 index 0000000000..cef84ccb7d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h @@ -0,0 +1,123 @@ +/* Overworld Recovery + * + * From: https://github.com/PokemonAutomation/ + * + * Runs a planned route step by step, and when a step ends short of where + * it was planned to, gets the player back onto it: + * + * - a leg to a wall interrupted after its hold is walked again; + * - an open leg to a warp, off the grass, stopped by a message (a + * trainer), is held on toward the warp; + * - a leg that crosses a trainer's sight (trainer_crossing()) is watched + * after for long enough that the trainer, if they saw the player, has + * walked up and spoken; + * - any other open leg stopped part-way, or a leg seen stopped by a + * trainer, has the tiles the player may be on worked out from the + * stop's timing and the trainers' sight (stop_candidates()). One tile: + * the route is planned again from it. More: holds to walls that end on + * one tile from all of them find the player (plan_reanchor()), and a + * way back to the stopped leg's end rejoins the route. The rest of the + * route is then walked as planned. + * + * Where the player is is never guessed: when no holds find them from every + * tile they may be on, the route fails, and the caller stops without + * saving. + * + * The console side is passed in, so this is tested with scripted steps. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldRecovery_H +#define PokemonAutomation_PokemonFRLG_OverworldRecovery_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldReanchor.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldTrainerCrossing.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// How one step of a route ended. +enum class StepEnd{ + DONE, + STOPPED, // stopped part-way: where the player is isn't known + LATE, // something was seen after the hold, which may have + // stopped the player before the end +}; + +// How a step ended, and for an open leg STOPPED part-way, how many of its +// tiles the timing of the stop says the player walked. Not set: anywhere +// on the leg. +struct StepOutcome{ + StepEnd end = StepEnd::DONE; + std::optional walked; +}; + +// Whether, after each leg to a wall, the walker taps once more toward the +// wall and logs whether the player moved (see RouteCalls). +enum class WallCheck{ + TAP, + SKIP, +}; + +// What the route was planned with, to plan the way back onto it: the maps +// (with the event flags the caller set) and the costs; and, for the route +// log (Pokemon_RouteLog.h), where it starts and what the caller calls it. +struct RoutePlanning{ + const std::vector* maps = nullptr; + RouteCosts costs = default_route_costs(); + std::optional start; + std::string label = "Route"; + WallCheck wall_check = WallCheck::TAP; +}; + +// The console side. `walk` walks one step from `facing` (unknown after a +// stop); `hold_to_warp` holds on along a stopped leg until its warp; +// `fail` throws. +struct RouteCalls{ + std::function facing)> walk; + std::function hold_to_warp; + std::function log; + std::function fail; + // Taps once more toward the wall a leg to a wall ended at, and says + // whether the screen moved. Only logged: a bump and a step can't be + // told apart reliably yet. Not set (or WallCheck::SKIP): not tapped. + std::function moved_past_wall; + // After a leg that ended as planned but crosses a trainer's sight: + // watches long enough for a trainer who saw the player to walk up + // `approach_tiles` tiles and speak, has what shows cleared (the + // caller's interrupts fight the trainer), and returns LATE if anything + // showed, DONE if not. Not set: not watched. + std::function watch_for_trainer; +}; + + +// How often a route may stop part-way before it gives up. +constexpr size_t MAX_ROUTE_STOPS = 8; + +// Walks `route` from `facing`, logging it in the shared route log lines: +// the plan, each leg as it starts and how it ended, and where the player +// was found again. Without `planning`, a stop that needs the player found +// again fails instead, and no leg is watched for trainers. +void run_route( + const std::vector& route, std::optional facing, + const RoutePlanning* planning, const RouteCalls& calls +); + + +// Registers overworld recovery unit tests. +void add_tests_OverworldRecovery(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery_Tests.cpp new file mode 100644 index 0000000000..3b9ba87f71 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery_Tests.cpp @@ -0,0 +1,548 @@ +/* Overworld Recovery Tests + * + * From: https://github.com/PokemonAutomation/ + * + * run_route() with scripted steps: walk, interruption, recovery, resume. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldReanchor.h" +#include "PokemonFRLG_OverworldRecovery.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +struct OverworldRecoveryInput{ + std::string name; + UnitTestResult (*body)(); +}; + +struct OverworldRecoveryExpectation{ + std::string_view description; +}; + +struct OverworldRecoveryTestCase{ + OverworldRecoveryInput input; + OverworldRecoveryExpectation expectation; +}; + +class Test_OverworldRecovery : public UnitTest{ +public: + explicit Test_OverworldRecovery(OverworldRecoveryTestCase scenario) + : UnitTest("PokemonFRLG::OverworldRecovery - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + OverworldRecoveryTestCase m_scenario; +}; + +// Steps that end as scripted, by the order they are walked in; DONE if not. +struct ScriptedRoute{ + std::map ends; + std::vector walked; + std::vector held_to_warp; + std::vector logs; + std::string failure; + // Whether the tap past a leg's wall moves the player, and the taps made. + bool moves_past_wall = false; + size_t wall_taps = 0; + // The way each walked step started facing. + std::vector> facings; + // How the watches for a trainer end, in order; DONE after these. The + // approach of each watch made. + std::vector watch_ends; + std::vector watches; + + RouteCalls calls(){ + RouteCalls calls; + calls.walk = [this](const RouteStep& step, std::optional facing){ + walked.push_back(step); + facings.push_back(facing); + auto iter = ends.find(walked.size() - 1); + return iter == ends.end() ? StepOutcome{} : iter->second; + }; + calls.hold_to_warp = [this](const RouteStep& step){ held_to_warp.push_back(step); }; + calls.log = [this](const std::string& message){ logs.push_back(message); }; + calls.moved_past_wall = [this](const RouteStep&){ + wall_taps++; + return moves_past_wall; + }; + calls.fail = [this](const std::string& message){ + failure = message; + throw std::runtime_error(message); + }; + calls.watch_for_trainer = [this](const RouteStep&, int approach_tiles){ + watches.push_back(approach_tiles); + return watches.size() <= watch_ends.size() ? watch_ends[watches.size() - 1] : StepEnd::DONE; + }; + return calls; + } + // Runs, and returns whether it failed. + bool run(const std::vector& route, const RoutePlanning* planning){ + try{ + run_route(route, std::nullopt, planning, calls()); + }catch (std::runtime_error&){ + return true; + } + return false; + } +}; + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + +// Passes if each of `parts` is in some line of `logs`. +UnitTestResult expect_logged(const std::vector& logs, const std::vector& parts){ + for (const std::string& part : parts){ + bool found = false; + for (const std::string& line : logs){ + found = found || line.find(part) != std::string::npos; + } + if (!found){ + return "Expected a log line with \"" + part + "\"."; + } + } + return true; +} + +bool same(const RouteStep& a, const RouteStep& b){ + return to_string(a) == to_string(b); +} + +UnitTestResult expect_walked(const std::vector& expected, const std::vector& walked){ + bool match = expected.size() == walked.size(); + for (size_t c = 0; match && c < expected.size(); c++){ + match = same(expected[c], walked[c]); + } + if (!match){ + return "Walked:" + describe(walked) + "\nexpected:" + describe(expected); + } + return true; +} + +StepOutcome stop_part_way(std::optional walked = std::nullopt){ + return StepOutcome{.end = StepEnd::STOPPED, .walked = walked}; +} + +// Viridian Mart to Oak's Lab; the first open leg through grass is stopped +// by a battle halfway, by its timing. The player is found again from the +// tiles around there, walked back to that leg's end, and the rest of the +// route is walked as planned. +UnitTestResult test_stop_recover_resume(){ + const std::vector maps = overworld_maps(); + const MapPosition start{"ViridianCity_Mart", map_point(maps, "ViridianCity_Mart", "clerk_front")}; + const std::optional> route = plan_overworld_route( + maps, start, RouteGoal{{"PalletTown_ProfessorOaksLab", {6, 4}}, std::nullopt} + ); + if (!route){ + return "No route."; + } + size_t stopped = 0; + while (stopped < route->size() && !((*route)[stopped].wild && !(*route)[stopped].to_wall)){ + stopped++; + } + if (stopped == 0 || stopped == route->size()){ + return "Expected an open leg through grass:" + describe(*route); + } + const RouteStep& step = (*route)[stopped]; + const WalkedTiles walked = walked_near(step, step.tiles / 2, std::chrono::milliseconds(267)); + ScriptedRoute script; + script.ends[stopped] = StepOutcome{.end = StepEnd::STOPPED, .walked = walked}; + const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = std::nullopt, .label = "Route", .wall_check = WallCheck::TAP}; + if (script.run(*route, &planning)){ + return "Failed: " + script.failure; + } + + const std::vector candidates = stop_candidates(maps, (*route)[stopped - 1].end, step, walked); + const std::optional anchor = plan_reanchor(maps, candidates, step); + if (candidates.size() != (size_t)(walked.max - walked.min + 1) || !anchor || anchor->holds.empty()){ + return std::format("Expected holds from the {} tiles around the estimate.", walked.max - walked.min + 1); + } + std::vector expected(route->begin(), route->begin() + stopped + 1); + expected.insert(expected.end(), anchor->holds.begin(), anchor->holds.end()); + expected.insert(expected.end(), anchor->back.begin(), anchor->back.end()); + expected.insert(expected.end(), route->begin() + stopped + 1, route->end()); + const UnitTestResult walked_as_expected = expect_walked(expected, script.walked); + if (walked_as_expected.result != UnitTestResult::PASSED){ + return walked_as_expected; + } + return expect_logged(script.logs, { + "): ended at an unknown tile (unknown: stopped part-way).", + std::format("{} stopped {} to {} tiles in; the player is on one of: {};", to_string(step), walked.min, walked.max, to_string(candidates[0])), + ": found again at " + anchor->found.map + " " + Pokemon::to_string(anchor->found.point), + }); +} + +// A corridor with a person at each end: nothing finds the player again. +const std::string TEST_CORRIDOR_JSON = R"({ + "name": "Corridor", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["#######", "#.....#", "#######"], + "elevation": ["3333333", "3333333", "3333333"], + "objects": [ + {"name": "youngster", "kind": "npc", "x": 1, "y": 1}, + {"name": "lass", "kind": "npc", "x": 5, "y": 1} + ] +})"; + +RouteStep walk(Direction direction, int tiles, MapPosition end){ + RouteStep step; + step.direction = direction; + step.tiles = tiles; + step.facing_after = direction; + step.end = std::move(end); + return step; +} + +// With no maps, or no walls to find the player by from every tile they may +// be on, a stop fails the route instead of guessing. +UnitTestResult test_no_recovery(){ + const std::vector maps{parse_map(TEST_CORRIDOR_JSON, "Corridor")}; + const std::vector route{walk(Direction::EAST, 2, {"Corridor", {4, 1}})}; + ScriptedRoute without_maps; + without_maps.ends[0] = stop_part_way(); + if (!without_maps.run(route, nullptr) || without_maps.failure.find("no maps") == std::string::npos){ + return "Expected a failure without maps, got: " + without_maps.failure; + } + ScriptedRoute without_walls; + without_walls.ends[0] = stop_part_way(WalkedTiles{.min = 1, .max = 2}); + const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = std::nullopt, .label = "Route", .wall_check = WallCheck::TAP}; + if (!without_walls.run(route, &planning) || without_walls.failure.find("no holds to walls find the player") == std::string::npos){ + return "Expected a failure without walls, got: " + without_walls.failure; + } + return true; +} + +// A leg to a wall seen interrupted after its hold is walked again; one +// interrupted at once, again and again, fails. +UnitTestResult test_wall_legs(){ + RouteStep wall = walk(Direction::NORTH, 3, {"Corridor", {1, 1}}); + wall.to_wall = true; + ScriptedRoute late; + late.ends[0] = StepOutcome{.end = StepEnd::LATE, .walked = std::nullopt}; + if (late.run({wall}, nullptr) || late.walked.size() != 2){ + return "Expected the leg walked again."; + } + ScriptedRoute blocked; + blocked.ends[0] = stop_part_way(); + if (!blocked.run({wall}, nullptr)){ + return "Expected a blocked leg to a wall to fail."; + } + return true; +} + +// Off the grass, a leg to a warp stopped by a trainer is held on to the +// warp, and the route goes on. +UnitTestResult test_warp_leg(){ + RouteStep door = walk(Direction::SOUTH, 9, {"PewterCity", {16, 18}}); + door.warps = true; + const RouteStep after = walk(Direction::EAST, 2, {"PewterCity", {18, 18}}); + ScriptedRoute script; + script.ends[0] = stop_part_way(); + if (script.run({door, after}, nullptr) || script.held_to_warp.size() != 1 || script.walked.size() != 2){ + return "Expected a hold to the warp, then the next step."; + } + return true; +} + +// After a leg to a wall, a tap toward it that moves the screen is only +// logged (the forest drift diagnostic): a bump and a step can't be told +// apart yet. With the check off there is no tap. Open legs aren't tapped. +UnitTestResult test_wall_check(){ + RouteStep wall = walk(Direction::NORTH, 3, {"Corridor", {1, 1}}); + wall.to_wall = true; + const RouteStep open = walk(Direction::EAST, 2, {"Corridor", {3, 1}}); + struct Case{ + std::string_view name; + bool moves; + WallCheck check; + bool logged; + size_t taps; + }; + const Case cases[] = { + {.name = "the tap moves", .moves = true, .check = WallCheck::TAP, .logged = true, .taps = 1}, + {.name = "the tap bumps", .moves = false, .check = WallCheck::TAP, .logged = false, .taps = 1}, + {.name = "the check is off", .moves = true, .check = WallCheck::SKIP, .logged = false, .taps = 0}, + }; + for (const Case& c : cases){ + const RoutePlanning planning{.maps = nullptr, .costs = default_route_costs(), .start = std::nullopt, .label = "Route", .wall_check = c.check}; + ScriptedRoute script; + script.moves_past_wall = c.moves; + if (script.run({wall, open}, &planning) || script.walked.size() != 2 || script.wall_taps != c.taps){ + return std::format("{}: expected both legs walked after {} tap(s), got {} after {}: {}", + c.name, c.taps, script.walked.size(), script.wall_taps, script.failure); + } + const UnitTestResult logged = expect_logged(script.logs, {"Position check (logged only): a tap after " + to_string(wall)}); + if ((logged.result == UnitTestResult::PASSED) != c.logged){ + return std::string(c.name) + (c.logged ? ": expected the tap logged." : ": didn't expect the tap logged."); + } + } + return true; +} + +// The route log lines the games share (Pokemon_RouteLog.h): the plan from +// the caller's start under its label, then each leg and how it ended. +UnitTestResult test_route_logged(){ + const std::vector route{ + walk(Direction::EAST, 2, {"Corridor", {4, 1}}), + walk(Direction::WEST, 1, {"Corridor", {3, 1}}), + }; + const RoutePlanning planning{.maps = nullptr, .costs = default_route_costs(), .start = MapPosition{"Corridor", {2, 1}}, .label = "test walk", .wall_check = WallCheck::TAP}; + ScriptedRoute script; + if (script.run(route, &planning)){ + return "Failed: " + script.failure; + } + const std::vector expected{ + "[Route] test walk: plan from Corridor (2, 1): east 2 (open) to Corridor (4, 1); west 1 (open) to Corridor (3, 1)", + "[Route] Leg 1/2: east 2 (open) to Corridor (4, 1)", + "[Route] test walk: east 2 (open): ended at Corridor (4, 1) (walked).", + "[Route] Leg 2/2: west 1 (open) to Corridor (3, 1)", + "[Route] test walk: west 1 (open): ended at Corridor (3, 1) (walked).", + }; + for (size_t c = 0; c < expected.size(); c++){ + const std::string got = c < script.logs.size() ? "\"" + script.logs[c] + "\"" : std::string("nothing"); + if (c >= script.logs.size() || script.logs[c] != expected[c]){ + return "Log line " + std::to_string(c) + ": expected \"" + expected[c] + "\", got " + got + "."; + } + } + return true; +} + +// Route 3's Lass Robin (console B, 2026-11-02), shrunk: a corridor along +// row 1, walled at x 6, and below it Robin's column x 3, where she wanders +// y 2..4 looking north and south, sight 3. Every way east along the +// corridor crosses her sight at (3, 1), and nowhere else. +const std::string TEST_ROBIN_JSON = R"({ + "name": "Robin", "source": {"decomp_file": "", "revision": "test", "date": "2026-11-02"}, + "tiles": ["#######", "......#", "###.###", "###.###", "###.###", "#######"], + "objects": [ + {"name": "lass", "kind": "npc", "x": 3, "y": 3, "wander": {"x0": 3, "y0": 2, "x1": 3, "y1": 4}, "trainer": {"sight": 3, "looks": ["north", "south"]}} + ] +})"; + +MapPosition robin(int x, int y){ + return MapPosition{"Robin", {x, y}}; +} + +// East along the corridor crosses Robin's sight on (3, 1) only; west of +// her, or back from the wall, it doesn't. +UnitTestResult test_trainer_crossing(){ + const std::vector maps{parse_map(TEST_ROBIN_JSON, "Robin")}; + RouteStep east = walk(Direction::EAST, 5, robin(5, 1)); + east.to_wall = true; + const std::optional crossing = trainer_crossing(maps, robin(0, 1), east); + if (!crossing || crossing->seen != std::vector{robin(3, 1)} || crossing->approach_tiles != 3){ + return "Expected east along the corridor to cross her sight on (3, 1) only, with an approach of 3."; + } + if (trainer_crossing(maps, robin(0, 1), walk(Direction::EAST, 2, robin(2, 1))) + || trainer_crossing(maps, robin(5, 1), walk(Direction::WEST, 1, robin(4, 1))) + ){ + return "Expected legs off her column to cross no sight."; + } + return true; +} + +// A leg east past Robin, then a turn north: how the leg and the watch for +// her after it end, and whether she saw the player. +struct TrainerCase{ + std::string_view name; + RouteStep leg; + StepEnd walk_end; + std::optional walked; + StepEnd watch_end; + size_t watches; + bool seen; +}; + +// What `c`'s route should walk: the leg, then, if she saw the player, the +// way on from (3, 1) to its end, then the turn. +std::optional> expected_walk(const std::vector& maps, const TrainerCase& c, const RouteStep& face){ + std::vector expected{c.leg}; + if (c.seen){ + const std::optional> way = plan_overworld_route(maps, robin(3, 1), RouteGoal{c.leg.end, std::nullopt}, default_route_costs(), Direction::EAST); + if (!way || way->empty()){ + return std::nullopt; + } + expected.insert(expected.end(), way->begin(), way->end()); + } + expected.push_back(face); + return expected; +} + +UnitTestResult run_trainer_case(const std::vector& maps, const TrainerCase& c){ + RouteStep face = walk(Direction::NORTH, 0, c.leg.end); + face.action = RouteAction::FACE; + const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = robin(0, 1), .label = "Route", .wall_check = WallCheck::SKIP}; + ScriptedRoute script; + script.ends[0] = StepOutcome{.end = c.walk_end, .walked = c.walked}; + script.watch_ends = {c.watch_end}; + if (script.run({c.leg, face}, &planning)){ + return "failed: " + script.failure; + } + const std::optional> expected = expected_walk(maps, c, face); + if (!expected){ + return "expected a way on from (3, 1)."; + } + bool match = expected->size() == script.walked.size() && script.watches.size() == c.watches; + for (size_t i = 0; match && i < expected->size(); i++){ + match = same((*expected)[i], script.walked[i]); + } + if (!match){ + return std::format("walked:{}\nexpected:{}\nafter {} watch(es)", describe(script.walked), describe(*expected), script.watches.size()); + } + if (c.watches > 0 && script.watches[0] != 3){ + return "expected a watch for an approach of 3."; + } + if (c.seen && script.facings[1] != Direction::EAST){ + return "expected the route on from (3, 1) to start facing east."; + } + const UnitTestResult logged = expect_logged(script.logs, {"stopped by a trainer who saw the player, at Robin (3, 1); planning again."}); + if ((logged.result == UnitTestResult::PASSED) != c.seen){ + return c.seen ? "expected the stop logged at (3, 1)." : "didn't expect a stop logged."; + } + return true; +} + +// She sees the player: the leg's watch for her (or the leg itself) is +// interrupted by her message, which the interrupts fight, and the route is +// planned again from (3, 1), facing east. When she doesn't, the route is +// walked as planned, after one watch. +UnitTestResult test_trainer_stops_leg(){ + const std::vector maps{parse_map(TEST_ROBIN_JSON, "Robin")}; + RouteStep wall = walk(Direction::EAST, 5, robin(5, 1)); + wall.to_wall = true; + const RouteStep open = walk(Direction::EAST, 4, robin(4, 1)); + const TrainerCase cases[] = { + {.name = "to a wall, seen", .leg = wall, .walk_end = StepEnd::DONE, .walked = std::nullopt, .watch_end = StepEnd::LATE, .watches = 1, .seen = true}, + {.name = "open, seen", .leg = open, .walk_end = StepEnd::STOPPED, .walked = std::nullopt, .watch_end = StepEnd::DONE, .watches = 0, .seen = true}, + // She stops the player on (3, 1) and speaks only after walking up, + // so the timing puts the stop past her tile: still hers. + {.name = "open, seen, timed late", .leg = open, .walk_end = StepEnd::STOPPED, .walked = WalkedTiles{.min = 3, .max = 4}, .watch_end = StepEnd::DONE, .watches = 0, .seen = true}, + {.name = "to a wall, not seen", .leg = wall, .walk_end = StepEnd::DONE, .walked = std::nullopt, .watch_end = StepEnd::DONE, .watches = 1, .seen = false}, + }; + for (const TrainerCase& c : cases){ + const UnitTestResult result = run_trainer_case(maps, c); + if (result.result != UnitTestResult::PASSED){ + return std::string(c.name) + ": " + result.message; + } + } + return true; +} + + +// On the grass a stop past Robin's column may be a wild battle's anywhere +// on the leg, or hers on (3, 1), after which she stands on (3, 2): the +// player is found again from all of them, then walks back to the leg's end. +UnitTestResult test_grass_in_sight(){ + const std::vector maps{parse_map(TEST_ROBIN_JSON, "Robin")}; + RouteStep grass = walk(Direction::EAST, 4, robin(4, 1)); + grass.wild = true; + RouteStep face = walk(Direction::NORTH, 0, grass.end); + face.action = RouteAction::FACE; + const std::vector candidates = stop_candidates(maps, robin(0, 1), grass, whole_leg(grass)); + const StopCandidate hers{.player = robin(3, 1), .trainer = TrainerStop{.object = 0, .at = robin(3, 2)}}; + if (candidates.size() != 6 || std::find(candidates.begin(), candidates.end(), hers) == candidates.end()){ + return std::format("Expected the leg's 5 tiles and hers, got {} candidates.", candidates.size()); + } + const std::optional anchor = plan_reanchor(maps, candidates, grass); + if (!anchor || anchor->holds.empty()){ + return "Expected holds that find the player."; + } + const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = robin(0, 1), .label = "Route", .wall_check = WallCheck::SKIP}; + ScriptedRoute script; + script.ends[0] = stop_part_way(); + if (script.run({grass, face}, &planning)){ + return "Failed: " + script.failure; + } + std::vector expected{grass}; + expected.insert(expected.end(), anchor->holds.begin(), anchor->holds.end()); + expected.insert(expected.end(), anchor->back.begin(), anchor->back.end()); + expected.push_back(face); + const UnitTestResult walked = expect_walked(expected, script.walked); + if (walked.result != UnitTestResult::PASSED){ + return walked; + } + return expect_logged(script.logs, {"Robin (3, 1) (stopped by a trainer, now at (3, 2))"}); +} + +const OverworldRecoveryTestCase OVERWORLD_RECOVERY_CASES[] = { + { + .input = {.name = "stop, recover, resume", .body = test_stop_recover_resume}, + .expectation = {.description = "verifies full stop, recovery reanchor, and resume sequence"}, + }, + { + .input = {.name = "no recovery", .body = test_no_recovery}, + .expectation = {.description = "handles clean runs where no recovery interruption occurs"}, + }, + { + .input = {.name = "legs to a wall", .body = test_wall_legs}, + .expectation = {.description = "tests wall-stopping leg recovery"}, + }, + { + .input = {.name = "a leg to a warp", .body = test_warp_leg}, + .expectation = {.description = "tests warp arrival leg recovery"}, + }, + { + .input = {.name = "the route is logged", .body = test_route_logged}, + .expectation = {.description = "verifies route execution logging and breadcrumbs"}, + }, + { + .input = {.name = "a leg to a wall ends at it", .body = test_wall_check}, + .expectation = {.description = "validates arrival position at wall terminator"}, + }, + { + .input = {.name = "a leg crosses a trainer's sight", .body = test_trainer_crossing}, + .expectation = {.description = "recovers when traversing through trainer vision cones"}, + }, + { + .input = {.name = "a trainer stops a leg", .body = test_trainer_stops_leg}, + .expectation = {.description = "handles forced stop and battle start from trainer challenge"}, + }, + { + .input = {.name = "a stop on the grass in a trainer's sight", .body = test_grass_in_sight}, + .expectation = {.description = "handles wild encounter in trainer sight line"}, + }, +}; + +} // namespace + + +void add_tests_OverworldRecovery(UnitTestDatabase& database){ + for (const auto& scenario : OVERWORLD_RECOVERY_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp new file mode 100644 index 0000000000..eb158bbe8f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp @@ -0,0 +1,993 @@ +/* Overworld Route + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_LegPlanner.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +std::string to_string(const MapPosition& position){ + return position.map + " " + to_string(position.point); +} + +std::string to_string(const RouteStep& step){ + std::string text; + switch (step.action){ + case RouteAction::WALK: + text = std::format("walk {} {}", direction_name(step.direction), step.tiles); + if (step.warps){ + text += " (warp)"; + } + if (step.to_wall){ + text += " (to wall)"; + } + break; + case RouteAction::SURF: + text = "surf " + std::string(direction_name(step.direction)); + break; + case RouteAction::FACE: + text = "face " + std::string(direction_name(step.direction)); + break; + } + return text + " -> " + to_string(step.end); +} + + + +const RouteCosts& default_route_costs(){ + static const RouteCosts COSTS{ + {RouteCost::TILE, 1}, + {RouteCost::TURN, 2}, + {RouteCost::WARP, 30}, + {RouteCost::SURF, 40}, + {RouteCost::GRASS_TILE, 20}, + {RouteCost::OPEN_STOP, 8}, + {RouteCost::OPEN_WILD_STOP, 300}, + }; + return COSTS; +} + +int route_cost(const RouteCosts& costs, RouteCost kind){ + auto iter = costs.find(kind); + if (iter == costs.end()){ + iter = default_route_costs().find(kind); + } + return iter->second; +} + + + +namespace{ + + +int find_map(const std::vector& maps, const std::string& name){ + for (size_t c = 0; c < maps.size(); c++){ + if (maps[c].name == name){ + return (int)c; + } + } + return -1; +} + +// The player on one of the loaded maps. +struct Located{ + int map = 0; + PlayerState state; + + bool operator==(const Located& other) const{ + return map == other.map + && state.position == other.state.position + && state.elevation == other.state.elevation + && state.surfing == other.state.surfing; + } +}; +struct LocatedHash{ + size_t operator()(const Located& player) const{ + return (((std::hash()(player.state.position) * 31 + player.map) * 16 + + player.state.elevation) * 2) + (player.state.surfing ? 1 : 0); + } +}; + +// What pressing a direction once does to the player. +struct Transition{ + Located next; + RouteAction action = RouteAction::WALK; + bool warped = false; + bool walked_out = false; // the warp ended with the game walking the player out + bool dismounted = false; // stepped off the water onto land +}; + +// The player taking `warp`, or nothing if it leads off the loaded maps. +std::optional take_warp(const std::vector& maps, const MapWarp* warp){ + if (warp == nullptr || !warp->to){ + return std::nullopt; + } + const int destination = find_map(maps, warp->to->map); + if (destination < 0){ + return std::nullopt; + } + const MapData& map = maps[destination]; + const auto arrival = map.points.find(warp->to->point); + if (arrival == map.points.end()){ + return std::nullopt; + } + TilePos position = arrival->second; + Transition transition; + if (walks_out_on_arrival(map, position)){ + position = position.next(Direction::SOUTH); + transition.walked_out = true; + } + transition.next.map = destination; + transition.next.state = PlayerState{position, elevation_at(map, position), false}; + transition.warped = true; + return transition; +} + +// Walking off the map's edge onto the map connected there, if it is loaded. +std::optional cross_edge(const std::vector& maps, const Located& player, Direction direction){ + const MapData& map = maps[player.map]; + for (const MapConnection& connection : map.connections){ + if (connection.side != direction){ + continue; + } + const int destination = find_map(maps, connection.to_map); + if (destination < 0){ + return std::nullopt; + } + const MapData& to = maps[destination]; + const TilePos here = player.state.position; + TilePos point; + switch (direction){ + case Direction::NORTH: + point = {here.x - connection.offset, to.tiles.height - 1}; + break; + case Direction::SOUTH: + point = {here.x - connection.offset, 0}; + break; + case Direction::WEST: + point = {to.tiles.width - 1, here.y - connection.offset}; + break; + case Direction::EAST: + point = {0, here.y - connection.offset}; + break; + } + const StepKind kind = classify_step_onto(map, player.state, direction, to, point); + if (kind == StepKind::BLOCKED){ + return std::nullopt; + } + Transition transition; + transition.next.map = destination; + transition.next.state = after_step_onto(map, player.state, to, point, kind); + transition.action = kind == StepKind::START_SURF ? RouteAction::SURF : RouteAction::WALK; + transition.dismounted = kind == StepKind::STOP_SURFING; + return transition; + } + return std::nullopt; +} + +// Pressing `direction` once (field_control_avatar.c): an exit mat or a door +// warps without the player moving, a step onto a ladder or cave entrance +// warps after it, and anything else is a step by the collision rules. +std::optional press(const std::vector& maps, const Located& player, Direction direction){ + const MapData& map = maps[player.map]; + const TilePos here = player.state.position; + if (exit_mat(map, here) == direction){ + return take_warp(maps, warp_at(map, here)); + } + const TilePos ahead = here.next(direction); + if (direction == Direction::NORTH && is_door(map, ahead) && !player.state.surfing){ + return take_warp(maps, warp_at(map, ahead)); + } + + if (!in_bounds(map, ahead)){ + return cross_edge(maps, player, direction); + } + + const StepKind kind = classify_step(map, player.state, direction); + if (kind == StepKind::BLOCKED){ + return std::nullopt; + } + Transition transition; + transition.next = player; + transition.next.state = after_step(map, player.state, direction, kind); + transition.action = kind == StepKind::START_SURF ? RouteAction::SURF : RouteAction::WALK; + transition.dismounted = kind == StepKind::STOP_SURFING; + const TilePos landed = transition.next.state.position; + if (transition.action == RouteAction::WALK && warps_on_step(map, landed) && warp_at(map, landed) != nullptr){ + return take_warp(maps, warp_at(map, landed)); + } + return transition; +} + +// Whether pressing `direction` takes a warp to a map that isn't loaded, +// which press() refuses as if it were a wall. +bool warps_off_loaded_maps(const std::vector& maps, const Located& player, Direction direction){ + const MapData& map = maps[player.map]; + const TilePos here = player.state.position; + const TilePos ahead = here.next(direction); + const MapWarp* warp = nullptr; + if (exit_mat(map, here) == direction){ + warp = warp_at(map, here); + }else if (direction == Direction::NORTH && is_door(map, ahead) && !player.state.surfing){ + warp = warp_at(map, ahead); + }else if (in_bounds(map, ahead) && warps_on_step(map, ahead) && classify_step(map, player.state, direction) != StepKind::BLOCKED){ + warp = warp_at(map, ahead); + } + return warp != nullptr && !take_warp(maps, warp); +} + +// Whether holding `direction` stops the player where they are: a wall, or +// water they'd need to Surf onto. A leg that ends there can be +// held for longer than it takes, and walked again after an interruption. A +// person in the way doesn't count, since they may have wandered off, and +// neither does an edge to a map that isn't loaded. +bool stops_at(const std::vector& maps, const Located& player, Direction direction){ + const std::optional transition = press(maps, player, direction); + if (transition){ + return transition->action == RouteAction::SURF; + } + // Nor does a warp to a map that isn't loaded: the player takes it (console + // B, 2026-11-02, "west 5 (to wall)" rode Route 4's Pokemon Center + // escalator up to 2F). + if (warps_off_loaded_maps(maps, player, direction)){ + return false; + } + const MapData& map = maps[player.map]; + const TilePos ahead = player.state.position.next(direction); + // Held into a sign moving north or south, the game shows the sign's + // message: the player stops, but the walk is interrupted (console B, + // 2026-11-01, the poster on the bedroom's wall). + if (tile_at(map, ahead) == TileKind::SIGN && (direction == Direction::NORTH || direction == Direction::SOUTH)){ + return false; + } + // Held into a ledge the way it faces, the player hops down it (console + // B, 2026-11-01, Viridian City: "south 2 (to wall)" from the Pokemon + // Center hopped the ledge two rows down). Routes don't hop ledges, so + // none is held into. + if (is_ledge(map, ahead)){ + return false; + } + if (in_bounds(map, ahead)){ + return object_at(map, ahead) == nullptr; + } + for (const MapConnection& connection : map.connections){ + if (connection.side == direction){ + return false; + } + } + return true; +} + +// The search state: a player, the way they face (4 stands for "not known +// yet", before the first step), and whether they are in the middle of a leg +// that could go on, as opposed to just stopped by a warp or Surf. +// The game's step rules for the shared leg planner. +class StepModel{ +public: + using State = Located; + using StateHash = LocatedHash; + + StepModel(const std::vector& maps, const RouteCosts& costs) + : m_maps(maps) + , m_costs(costs) + {} + + std::optional> press(const State& state, Direction direction) const{ + const std::optional transition = PokemonFRLG::press(m_maps, state, direction); + if (!transition){ + return std::nullopt; + } + Pokemon::Step step; + step.next = transition->next; + step.action = transition->action == RouteAction::SURF ? ACTION_SURF : 0; + // Leaving the water: the player walks at half the speed from here. + step.starts_leg = transition->dismounted; + step.ends_leg = transition->warped || transition->dismounted; + step.warped = transition->warped; + step.facing = transition->walked_out ? Direction::SOUTH : direction; + if (transition->action == RouteAction::SURF){ + step.extra_cost += route_cost(m_costs, RouteCost::SURF); + } + if (transition->warped){ + step.extra_cost += route_cost(m_costs, RouteCost::WARP); + } + if (is_tall_grass(m_maps[step.next.map], step.next.state.position)){ + step.extra_cost += route_cost(m_costs, RouteCost::GRASS_TILE); + step.wild = true; + } + if (step.next.state.surfing){ + step.wild = true; + } + return step; + } + bool held_at(const State& state, Direction direction) const{ + return stops_at(m_maps, state, direction); + } + + static constexpr int ACTION_SURF = 1; + +private: + const std::vector& m_maps; + const RouteCosts& m_costs; +}; + +Pokemon::LegCosts to_leg_costs(const RouteCosts& costs){ + Pokemon::LegCosts leg_costs; + leg_costs.per_tile = route_cost(costs, RouteCost::TILE); + leg_costs.per_turn = route_cost(costs, RouteCost::TURN); + leg_costs.per_open_stop = route_cost(costs, RouteCost::OPEN_STOP); + leg_costs.per_open_wild_stop = route_cost(costs, RouteCost::OPEN_WILD_STOP); + return leg_costs; +} + +RouteStep to_route_step(const std::vector& maps, const Pokemon::Leg& leg){ + RouteStep step; + switch (leg.kind){ + case Pokemon::LegKind::WALK: + step.action = RouteAction::WALK; + break; + case Pokemon::LegKind::ACTION: + step.action = RouteAction::SURF; + break; + case Pokemon::LegKind::FACE: + step.action = RouteAction::FACE; + break; + } + step.direction = leg.direction; + step.tiles = leg.kind == Pokemon::LegKind::FACE ? 0 : leg.tiles; + step.warps = leg.warps; + step.surfing = leg.start.state.surfing; + step.to_wall = leg.to_wall; + step.facing_after = leg.facing_after; + step.end = MapPosition{maps[leg.end.map].name, leg.end.state.position}; + if (leg.kind != Pokemon::LegKind::FACE){ + // Tall grass on any map the leg crosses, or the water. Counted on the + // start map only, "north 22" from Pallet Town through Route 1's grass + // wasn't watched for battles (console B, 2026-11-01). + step.wild = leg.wild || leg.start.state.surfing || leg.kind == Pokemon::LegKind::ACTION; + } + return step; +} + +} // namespace + + + +std::optional> plan_overworld_route( + const std::vector& maps, + const MapPosition& start, + const RouteGoal& goal, + const RouteCosts& costs, + std::optional start_facing +){ + const int start_map = find_map(maps, start.map); + const int goal_map = find_map(maps, goal.position.map); + if (start_map < 0 || goal_map < 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route between maps that aren't loaded."); + } + Located first; + first.map = start_map; + first.state.position = start.point; + first.state.elevation = elevation_at(maps[start_map], start.point); + first.state.surfing = is_water(maps[start_map], start.point); + + const StepModel model(maps, costs); + const auto legs = Pokemon::plan_legs( + model, first, start_facing, + std::function([&](const Located& player){ + return player.map == goal_map && player.state.position == goal.position.point; + }), + goal.facing, to_leg_costs(costs) + ); + if (!legs){ + return std::nullopt; + } + + std::vector route; + for (const Pokemon::Leg& leg : *legs){ + route.push_back(to_route_step(maps, leg)); + } + return route; +} + + +namespace{ + +// Further than any straight line on a map. +constexpr int MAX_HOLD_TILES = 128; + +std::optional locate(const std::vector& maps, const MapPosition& position, bool surfing){ + const int map = find_map(maps, position.map); + if (map < 0){ + return std::nullopt; + } + Located player; + player.map = map; + player.state = PlayerState{position.point, elevation_at(maps[map], position.point), surfing}; + return player; +} + +// A plain step: no warp, no Surf, no getting off the water. +std::optional plain_step(const std::vector& maps, const Located& player, Direction direction){ + const std::optional transition = press(maps, player, direction); + if (!transition || transition->warped || transition->dismounted || transition->action != RouteAction::WALK){ + return std::nullopt; + } + return transition->next; +} + +} // namespace + + +namespace{ + +// Holding north into a ledge stops the player: the maps don't keep which way +// a ledge faces, but FRLG's face south, east or west (pokefirered has no +// MB_JUMP_NORTH on any map these load). Only finding the player again +// relies on this; routes never hold into a ledge (stops_at()). +bool ledge_stops_north(const std::vector& maps, const Located& player, Direction direction){ + return direction == Direction::NORTH && is_ledge(maps[player.map], player.state.position.next(direction)); +} + +} // namespace + +std::optional hold_to_wall( + const std::vector& maps, + const MapPosition& from, bool surfing, Direction direction +){ + std::optional player = locate(maps, from, surfing); + WallHold hold; + for (int c = 0; player && c <= MAX_HOLD_TILES; c++){ + if (stops_at(maps, *player, direction) || ledge_stops_north(maps, *player, direction)){ + hold.end = MapPosition{maps[player->map].name, player->state.position}; + hold.tiles = c; + return hold; + } + player = plain_step(maps, *player, direction); + if (player){ + const MapData& map = maps[player->map]; + hold.wild = hold.wild || is_tall_grass(map, player->state.position) || player->state.surfing; + } + } + return std::nullopt; +} + +std::vector leg_tiles( + const std::vector& maps, + const MapPosition& start, const RouteStep& step +){ + std::vector tiles{start}; + std::optional player = locate(maps, start, step.surfing); + const int along = step.tiles - (step.warps ? 1 : 0); + for (int c = 0; player && c < along; c++){ + player = plain_step(maps, *player, step.direction); + if (player){ + tiles.push_back(MapPosition{maps[player->map].name, player->state.position}); + } + } + return tiles; +} + +MapPosition follow_overworld_route( + const std::vector& maps, + const MapPosition& start, + const std::vector& route +){ + Located player; + player.map = find_map(maps, start.map); + if (player.map < 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route from a map that isn't loaded: " + start.map); + } + player.state.position = start.point; + player.state.elevation = elevation_at(maps[player.map], start.point); + player.state.surfing = is_water(maps[player.map], start.point); + + for (const RouteStep& step : route){ + if (step.action == RouteAction::FACE){ + continue; + } + for (int c = 0; c < step.tiles; c++){ + const std::optional transition = press(maps, player, step.direction); + if (!transition || transition->action != step.action){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Step refused at " + to_string(MapPosition{maps[player.map].name, player.state.position}) + ": " + to_string(step) + ); + } + player = transition->next; + } + const MapPosition position{maps[player.map].name, player.state.position}; + if (!(position == step.end)){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Ended at " + to_string(position) + " instead of " + to_string(step.end) + ); + } + } + return MapPosition{maps[player.map].name, player.state.position}; +} + + + +namespace{ + +class Test_OverworldRoute : public UnitTest{ +public: + Test_OverworldRoute(std::string name, std::function body) + : UnitTest("PokemonFRLG::OverworldRoute - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + +// A 5x4 map for the step rules: a pond, a raised ledge reached by a stair +// tile, and a tile that can't be entered moving south. +const MapData& small_map(){ + static const MapData MAP = parse_map(R"({ + "name": "Small", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["#####", "#.8.#", "#.w.#", "#####"], + "elevation": ["33333", "33403", "33133", "33333"] + })", "Small"); + return MAP; +} + +UnitTestResult test_step_rules(){ + const MapData& map = small_map(); + PlayerState state{{1, 1}, 3, false}; + if (classify_step(map, state, Direction::EAST) != StepKind::BLOCKED){ + return "Walked from elevation 3 onto elevation 4."; + } + if (classify_step(map, PlayerState{{2, 0}, 3, false}, Direction::SOUTH) != StepKind::BLOCKED){ + return "Entered a north-blocked tile moving south."; + } + state = PlayerState{{1, 2}, 3, false}; + if (classify_step(map, state, Direction::EAST) != StepKind::START_SURF){ + return "Can't start surfing onto the pond."; + } + state = after_step(map, state, Direction::EAST, StepKind::START_SURF); + if (!state.surfing || state.elevation != 1){ + return "Surfing didn't put the player on the water."; + } + if (classify_step(map, state, Direction::EAST) != StepKind::STOP_SURFING){ + return "Can't land from the pond."; + } + if (classify_step(map, PlayerState{{3, 2}, 3, false}, Direction::NORTH) != StepKind::WALK){ + return "Can't step from elevation 3 onto the elevation-0 stair."; + } + return true; +} + +// The maps after the Hall of Fame, which clears the way to Cerulean Cave. +std::vector post_game_maps(){ + return overworld_maps(map_flag_set(overworld_maps(), "after_hall_of_fame")); +} + +MapPosition point_on(const std::vector& maps, const std::string& map, const std::string& point){ + return MapPosition{map, map_point(maps, map, point)}; +} + +const MapData* map_named(const std::vector& maps, const std::string& name){ + const int index = find_map(maps, name); + return index < 0 ? nullptr : &maps[index]; +} + +UnitTestResult test_maps(){ + const std::vector maps = post_game_maps(); + const MapData* b1f = map_named(maps, "CeruleanCave_B1F"); + const MapData* city = map_named(maps, "CeruleanCity"); + if (b1f == nullptr || city == nullptr || map_named(maps, "CeruleanCity_PokemonCenter_1F") == nullptr){ + return "Missing a map."; + } + if (b1f->tiles.width != 40 || b1f->tiles.height != 23 || city->tiles.width != 48 || city->tiles.height != 40){ + return "Unexpected map size."; + } + const TilePos mewtwo_tile = map_point(maps, "CeruleanCave_B1F", "mewtwo"); + const MapObject* mewtwo = object_at(*b1f, mewtwo_tile); + if (mewtwo == nullptr || mewtwo->name != "mewtwo"){ + return "Mewtwo is not on B1F at " + to_string(mewtwo_tile) + "."; + } + if (object_at(*city, {1, 13}) != nullptr){ + return "The cave guard is still there after the Hall of Fame."; + } + if (object_at(*map_named(overworld_maps(), "CeruleanCity"), {1, 13}) == nullptr){ + return "The cave guard is missing before the Hall of Fame."; + } + return true; +} + +// Plans `start` to `goal`, replays it with the step rules and checks where it ends. +UnitTestResult check_route( + const std::vector& maps, + const MapPosition& start, const RouteGoal& goal, + std::vector& route +){ + const std::optional> planned = plan_overworld_route(maps, start, goal); + if (!planned){ + return "No route from " + to_string(start) + " to " + to_string(goal.position) + "."; + } + route = *planned; + const MapPosition end = follow_overworld_route(maps, start, route); + if (!(end == goal.position)){ + return "Route ends at " + to_string(end) + ":" + describe(route); + } + if (goal.facing && route.back().direction != *goal.facing){ + return "Doesn't end facing " + std::string(direction_name(*goal.facing)) + ":" + describe(route); + } + return true; +} + +// Below Mewtwo, facing it, to talk to it. +RouteGoal facing_mewtwo(const std::vector& maps){ + const TilePos mewtwo = map_point(maps, "CeruleanCave_B1F", "mewtwo"); + return RouteGoal{{"CeruleanCave_B1F", mewtwo.next(Direction::SOUTH)}, Direction::NORTH}; +} + +UnitTestResult test_entrance_to_mewtwo(){ + const std::vector maps = post_game_maps(); + std::vector route; + UnitTestResult result = check_route(maps, point_on(maps, "CeruleanCave_1F", "entrance"), facing_mewtwo(maps), route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + bool surfs = false; + bool reaches_b1f = false; + for (const RouteStep& step : route){ + surfs |= step.action == RouteAction::SURF; + reaches_b1f |= step.warps && step.end.map == "CeruleanCave_B1F"; + } + if (!surfs || !reaches_b1f){ + return "Expected to take the ladder to B1F and to surf:" + describe(route); + } + return true; +} + +UnitTestResult test_pokemon_center_to_mewtwo(){ + const std::vector maps = post_game_maps(); + std::vector route; + UnitTestResult result = check_route( + maps, point_on(maps, "CeruleanCity_PokemonCenter_1F", "pc"), facing_mewtwo(maps), route + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + // Out through the exit mat, onto the city's step below the door, and + // into the cave by its entrance. + std::vector maps_in_order; + for (const RouteStep& step : route){ + if (step.warps){ + maps_in_order.push_back(step.end.map); + } + } + if (maps_in_order.size() < 2 || maps_in_order[0] != "CeruleanCity" || maps_in_order[1] != "CeruleanCave_1F"){ + return "Expected to leave by the mat and enter the cave next:" + describe(route); + } + if (!(route[0].end.map == "CeruleanCity_PokemonCenter_1F" || route[0].warps)){ + return "Unexpected first step:" + describe(route); + } + return true; +} + +UnitTestResult test_cave_guard_blocks(){ + // Before the Hall of Fame the guard stands in the cave entrance. + const std::vector maps = overworld_maps(); + if (plan_overworld_route(maps, point_on(maps, "CeruleanCity_PokemonCenter_1F", "pc"), facing_mewtwo(maps))){ + return "Planned past the cave guard."; + } + return true; +} + +UnitTestResult test_mewtwo_tile_unreachable(){ + const std::vector maps = post_game_maps(); + const std::optional> route = plan_overworld_route( + maps, + point_on(maps, "CeruleanCave_1F", "entrance"), + {point_on(maps, "CeruleanCave_B1F", "mewtwo"), std::nullopt} + ); + if (route){ + return "Planned a route onto Mewtwo itself:" + describe(*route); + } + return true; +} + +UnitTestResult test_story_maps(){ + const std::vector maps = overworld_maps(); + for (std::string_view name : { + "PalletTown_PlayersHouse_2F", "PalletTown_ProfessorOaksLab", "Route1", "ViridianCity_Mart", + "Route22", "Route2", "ViridianForest", "PewterCity", "PewterCity_Museum_1F", "PewterCity_Gym", + }){ + if (map_named(maps, std::string(name)) == nullptr){ + return std::format("Missing map {}.", name); + } + } + return true; +} + +// Which maps `route` warps into, in order. +std::vector maps_warped_into(const std::vector& route){ + std::vector maps; + for (const RouteStep& step : route){ + if (step.warps){ + maps.push_back(step.end.map); + } + } + return maps; +} + +UnitTestResult test_bedroom_to_oaks_lab(){ + const std::vector maps = overworld_maps(); + std::vector route; + UnitTestResult result = check_route( + maps, point_on(maps, "PalletTown_PlayersHouse_2F", "start"), + {point_on(maps, "PalletTown", "oaks_lab_front"), Direction::NORTH}, route + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + const std::vector warped = maps_warped_into(route); + if (warped != std::vector{"PalletTown_PlayersHouse_1F", "PalletTown"}){ + return "Expected to take the stairs and leave by the front door:" + describe(route); + } + return true; +} + +UnitTestResult test_viridian_mart_to_pewter_gym(){ + const std::vector maps = overworld_maps(); + std::vector route; + UnitTestResult result = check_route( + maps, point_on(maps, "ViridianCity_Mart", "clerk_front"), + {point_on(maps, "PewterCity", "gym_front"), Direction::NORTH}, route + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + const std::vector warped = maps_warped_into(route); + if (std::find(warped.begin(), warped.end(), "ViridianForest") == warped.end()){ + return "Expected to go through Viridian Forest:" + describe(route); + } + return true; +} + +// A room with a sign on its north wall, above the third column. +const std::string TEST_SIGN_ROOM_JSON = R"({ + "name": "SignRoom", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["##S##", "#...#", "#...#", "#...#", "#####"], + "elevation": ["33333", "33333", "33333", "33333", "33333"] +})"; + +// Walking north under a sign stops by counting tiles, never by holding into +// the sign; under the wall beside it, the wall stops the player. +UnitTestResult test_no_hold_into_sign(){ + const std::vector maps{parse_map(TEST_SIGN_ROOM_JSON, "SignRoom")}; + std::vector route; + UnitTestResult result = check_route(maps, {"SignRoom", {2, 3}}, {{"SignRoom", {2, 1}}, std::nullopt}, route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + for (const RouteStep& step : route){ + if (step.to_wall && step.end.point == TilePos{2, 1}){ + return "Expected no hold into the sign:" + describe(route); + } + } + route.clear(); + result = check_route(maps, {"SignRoom", {1, 3}}, {{"SignRoom", {1, 1}}, std::nullopt}, route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + if (route.empty() || !route.back().to_wall){ + return "Expected the wall to stop the player beside the sign:" + describe(route); + } + return true; +} + +// A yard with a row of ledges across it. +const std::string TEST_LEDGE_YARD_JSON = R"({ + "name": "LedgeYard", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["#####", "#...#", "#...#", "#vvv#", "#...#", "#####"], + "elevation": ["33333", "33333", "33333", "33333", "33333", "33333"] +})"; + +// A ledge isn't a wall to hold into: moving the way it faces the player +// would hop it, and routes don't hop ledges. Viridian City, +// from the Pokemon Center's door south to the row above the ledge. +UnitTestResult test_no_hold_into_ledge(){ + const std::vector maps{parse_map(TEST_LEDGE_YARD_JSON, "LedgeYard")}; + std::vector route; + UnitTestResult result = check_route(maps, {"LedgeYard", {2, 1}}, {{"LedgeYard", {2, 2}}, std::nullopt}, route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + for (const RouteStep& step : route){ + if (step.to_wall){ + return "Expected no hold into the ledge:" + describe(route); + } + } + route.clear(); + const std::vector world = overworld_maps(); + result = check_route(world, {"ViridianCity", {26, 27}}, {{"ViridianCity", {26, 29}}, std::nullopt}, route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + for (const RouteStep& step : route){ + if (step.to_wall && step.end.point == TilePos{26, 29}){ + return "Expected no hold into the ledge below the Pokemon Center:" + describe(route); + } + } + return true; +} + +// Two small maps that don't need the map files: a room left by the exit mat +// at its bottom, onto the door of a yard, out of which the game walks the +// player. +// No wild battle can start between the bedroom and Oak's Lab: Pallet Town's +// streets have no tall grass. Route 2 and Viridian Forest do. +UnitTestResult test_wild_steps(){ + const std::vector maps = overworld_maps(); + std::vector route; + UnitTestResult result = check_route( + maps, point_on(maps, "PalletTown_PlayersHouse_2F", "start"), + {point_on(maps, "PalletTown", "oaks_lab_front"), Direction::NORTH}, route + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + for (const RouteStep& step : route){ + if (step.wild){ + return "Expected no wild step from the bedroom to Oak's Lab, got " + to_string(step) + ":" + describe(route); + } + } + route.clear(); + result = check_route( + maps, point_on(maps, "ViridianCity_Mart", "clerk_front"), + {point_on(maps, "PewterCity", "gym_front"), Direction::NORTH}, route + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + bool forest = false; + for (const RouteStep& step : route){ + forest = forest || (step.wild && step.end.map == "ViridianForest"); + } + if (!forest){ + return "Expected a wild step in Viridian Forest:" + describe(route); + } + // The leg from Pallet Town north onto Route 1 crosses Route 1's grass + // after the map's edge. + route.clear(); + result = check_route( + maps, point_on(maps, "PalletTown", "oaks_lab_front"), + {point_on(maps, "ViridianCity_Mart", "clerk_front"), std::nullopt}, route + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + for (const RouteStep& step : route){ + if (step.end.map == "Route1" && step.direction == Direction::NORTH && step.tiles > 14 && !step.wild){ + return "Expected the leg from Pallet Town onto Route 1 to be wild, got " + to_string(step) + ":" + describe(route); + } + } + return true; +} + +const std::string TEST_ROOM_JSON = R"({ + "name": "Room", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["#####", "#...#", "#...#", "##.##"], + "elevation": ["33333", "33333", "33333", "33333"], + "points": {"warp_0": [2, 3]}, + "warps": [{"x": 2, "y": 3, "enter": "walk_south", "to_map": "Yard", "to_point": "warp_0"}] +})"; +const std::string TEST_YARD_JSON = R"({ + "name": "Yard", "source": {"decomp_file": "", "revision": "test", "date": "2026-10-31"}, + "tiles": ["#####", "##D##", "#...#", "#####"], + "elevation": ["33333", "33333", "33333", "33333"], + "points": {"warp_0": [2, 1]}, + "warps": [{"x": 2, "y": 1, "enter": "walk_into", "to_map": "Room", "to_point": "warp_0"}] +})"; + +UnitTestResult test_route_through_warp(){ + const std::vector maps{ + parse_map(TEST_ROOM_JSON, "Room"), + parse_map(TEST_YARD_JSON, "Yard"), + }; + std::vector route; + UnitTestResult result = check_route(maps, {"Room", {2, 1}}, {{"Yard", {1, 2}}, std::nullopt}, route); + if (result.result != UnitTestResult::PASSED){ + return result; + } + for (const RouteStep& step : route){ + if (step.warps && step.end.map == "Yard"){ + return true; + } + } + return "Expected to warp into the yard:" + describe(route); +} + +// `json` with its elevation grid replaced by `rows`, or left out if empty. +std::string with_elevation(std::string json, const std::string& rows){ + const size_t begin = json.find("\"elevation\""); + const size_t end = json.find("\n", begin); + json.erase(begin, end - begin + 1); + if (!rows.empty()){ + json.insert(begin, "\"elevation\": " + rows + ",\n"); + } + return json; +} + +// Room and yard as the decompilation writes them, their walls and the +// door at elevation 0, plan the same as with no elevation grid, which +// frlg_maps.py leaves out when every tile the player can stand on is ground. +UnitTestResult test_ground_only_elevation_left_out(){ + const std::vector written{ + parse_map(with_elevation(TEST_ROOM_JSON, R"(["00000", "03330", "03330", "00300"])"), "Room"), + parse_map(with_elevation(TEST_YARD_JSON, R"(["00000", "00000", "03330", "00000"])"), "Yard"), + }; + const std::vector left_out{ + parse_map(with_elevation(TEST_ROOM_JSON, ""), "Room"), + parse_map(with_elevation(TEST_YARD_JSON, ""), "Yard"), + }; + for (const MapPosition& start : {MapPosition{"Room", {1, 1}}, MapPosition{"Room", {3, 2}}}){ + for (const MapPosition& goal : {MapPosition{"Yard", {1, 2}}, MapPosition{"Yard", {3, 2}}, MapPosition{"Room", {2, 2}}}){ + const std::optional> a = plan_overworld_route(written, start, {goal, std::nullopt}); + const std::optional> b = plan_overworld_route(left_out, start, {goal, std::nullopt}); + if (!a || !b || describe(*a) != describe(*b)){ + return "Plans differ from " + to_string(start) + " to " + to_string(goal) + ":" + + (a ? describe(*a) : " none") + "\nwithout elevation:" + (b ? describe(*b) : " none"); + } + } + } + return true; +} + +} // namespace + +void add_tests_OverworldRoute(UnitTestDatabase& database){ + database.add("route through a warp", test_route_through_warp); + database.add("ground-only elevation left out", test_ground_only_elevation_left_out); + database.add("maps to Brock", test_story_maps); + database.add("bedroom to Oak's Lab", test_bedroom_to_oaks_lab); + database.add("Viridian Mart to Pewter Gym", test_viridian_mart_to_pewter_gym); + database.add("wild steps", test_wild_steps); + database.add("no hold into a sign", test_no_hold_into_sign); + database.add("no hold into a ledge", test_no_hold_into_ledge); + database.add("step rules", test_step_rules); + database.add("maps", test_maps); + database.add("Cerulean Cave entrance to Mewtwo", test_entrance_to_mewtwo); + database.add("Cerulean Pokemon Center to Mewtwo", test_pokemon_center_to_mewtwo); + database.add("cave guard blocks the way", test_cave_guard_blocks); + database.add("Mewtwo's tile is blocked", test_mewtwo_tile_unreachable); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h new file mode 100644 index 0000000000..6b10505a73 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h @@ -0,0 +1,82 @@ +/* Overworld Route + * + * From: https://github.com/PokemonAutomation/ + * + * Plans a route over one or more FRLG maps joined by warps: the D-pad legs + * to walk, where to start surfing, and which way to face at the end. FRLG + * moves exactly one tile per step, so a planned route can be walked blind. + * Legs end against walls where that costs little: such a leg can be held + * for longer than it takes, and walked again if something interrupts it. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldRoute_H +#define PokemonAutomation_PokemonFRLG_OverworldRoute_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldMap.h" +#include "PokemonFRLG_OverworldRouteCosts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// The cheapest route from `start`, surfing if it is on water, to +// `goal`, or nothing if there is none. `maps` must hold every map the route +// may pass through; warps to other maps are not taken. Planned with +// Pokemon::plan_legs() on the game's step rules. +std::optional> plan_overworld_route( + const std::vector& maps, + const MapPosition& start, + const RouteGoal& goal, + const RouteCosts& costs = default_route_costs(), + std::optional start_facing = std::nullopt +); + +// Holding `direction` from `from`, on the water if `surfing`: where a wall +// stops the player, how many tiles on, and whether any tile on the way is +// tall grass or water. +struct WallHold{ + MapPosition end; + int tiles = 0; + bool wild = false; +}; +// Nothing unless every step on the way is a plain walk: a warp, Surf, a +// ledge, a person, a sign that would speak, or the edge of the loaded maps +// comes first. +std::optional hold_to_wall( + const std::vector& maps, + const MapPosition& from, bool surfing, Direction direction +); + +// The tiles a WALK `step` from `start` passes through, `start` first, short +// of a warp at its end. +std::vector leg_tiles( + const std::vector& maps, + const MapPosition& start, const RouteStep& step +); + +// Replays `route` from `start` with the game's step rules and returns where +// it ends. Throws InternalProgramError if a step can't be taken as planned. +MapPosition follow_overworld_route( + const std::vector& maps, + const MapPosition& start, + const std::vector& route +); + + +// Registers overworld route unit tests. +void add_tests_OverworldRoute(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h new file mode 100644 index 0000000000..8d4c82b1fc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h @@ -0,0 +1,57 @@ +/* Overworld Route Costs + * + * From: https://github.com/PokemonAutomation/ + * + * What the route planner weighs a route by, and the default costs. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldRouteCosts_H +#define PokemonAutomation_PokemonFRLG_OverworldRouteCosts_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldMap.h" +#include "PokemonFRLG_OverworldRouteSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// What the planner weighs a route by. Each is a cost per occurrence. +enum class RouteCost{ + TILE, + TURN, // extra for a leg in a new direction + WARP, // the fade in and out + SURF, // the dialog and the animation + GRASS_TILE, // extra for tall grass, where wild Pokemon appear + // Extra for a leg that ends where the player could keep walking: it has + // to be timed, and if a message or a battle stops it part-way, where + // the player is can only be estimated. A leg that ends at a wall is + // walked again instead. + OPEN_STOP, + // Extra again when that leg crosses tall grass or water, where a wild + // battle is likely to stop it: the walker can't tell where it did + // (console B, 2026-11-01, Route 1, four runs). + OPEN_WILD_STOP, +}; +// Cost mapping table for path planning. +using RouteCosts = std::map; + +// TILE 1, TURN 2, WARP 30, SURF 40, GRASS_TILE 20, OPEN_STOP 8, +// OPEN_WILD_STOP 300. +const RouteCosts& default_route_costs(); + +// `costs`'s cost for `kind`, or the default if it has none. +int route_cost(const RouteCosts& costs, RouteCost kind); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h new file mode 100644 index 0000000000..c28ddc5fbc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h @@ -0,0 +1,82 @@ +/* Overworld Route Steps + * + * From: https://github.com/PokemonAutomation/ + * + * A planned overworld route's parts: positions on a map, the steps a + * route is walked in, and the goal it is planned to. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldRouteSteps_H +#define PokemonAutomation_PokemonFRLG_OverworldRouteSteps_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldMap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Position on a specific map. +struct MapPosition{ + std::string map; + TilePos point; + + bool operator==(const MapPosition& other) const = default; +}; +// Formats a MapPosition as a string. +std::string to_string(const MapPosition& position); + + +// Action associated with reaching a route waypoint. +enum class RouteAction{ + WALK, // hold `direction` for `tiles` tiles + SURF, // face `direction`, use Surf, and land on the water there + FACE, // turn to `direction` without moving +}; + +// A single step along an overworld path. +struct RouteStep{ + RouteAction action = RouteAction::WALK; + Direction direction = Direction::NORTH; + int tiles = 0; + // WALK: the last tile is a warp (ladder, stairs), so the screen fades + // and the player arrives on another map. + bool warps = false; + // WALK: on the water, where the player moves twice as fast. + bool surfing = false; + // WALK: a wall stops the player at the end, so the leg can be held for + // longer than it takes and still ends on its tile. + bool to_wall = false; + // WALK, SURF: a wild Pokemon can appear on the way: the step crosses + // tall grass or water. Elsewhere (indoors, streets) no wild battle can + // start, so the walker doesn't watch for one. + bool wild = false; + // Which way the player faces after the step. Arriving at a door or a + // cave mouth, the game walks the player a tile out, facing south. + Direction facing_after = Direction::NORTH; + // Where the player is after the step. + MapPosition end; +}; +// Formats a RouteStep as a string. +std::string to_string(const RouteStep& step); + + +// Navigation goal specification. +struct RouteGoal{ + MapPosition position; + // Which way to face on arrival, e.g. towards a Pokemon to talk to. + std::optional facing; +}; + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTileRules.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTileRules.h new file mode 100644 index 0000000000..79cb3944c6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTileRules.h @@ -0,0 +1,52 @@ +/* Overworld Tile Rules + * + * From: https://github.com/PokemonAutomation/ + * + * The walking rules of FRLG's special tiles: grass, ledges, one-way + * edges, warps, doors and exit mats. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldTileRules_H +#define PokemonAutomation_PokemonFRLG_OverworldTileRules_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonFRLG_OverworldTiles.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Whether the tile at point is tall grass terrain. +bool is_tall_grass(const MapData& map, const TilePos& point); +// Whether the tile at point is a one-way ledge. +bool is_ledge(const MapData& map, const TilePos& point); +// Whether the tile itself refuses a step in `direction`: entering it, or +// leaving it. +bool blocks_entering(const MapData& map, const TilePos& point, Direction direction); +// Whether leaving the tile in the given direction is blocked. +bool blocks_leaving(const MapData& map, const TilePos& point, Direction direction); + +// Whether the game takes this tile's warp on stepping onto it (a ladder or +// cave entrance). +bool warps_on_step(const MapData& map, const TilePos& point); +// A door, entered by walking north into it. +bool is_door(const MapData& map, const TilePos& point); +// The direction that takes the exit mat on this tile, if it is one. +std::optional exit_mat(const MapData& map, const TilePos& point); +// Arriving on a door or cave entrance, the game walks the player one +// tile south, out of it. +bool walks_out_on_arrival(const MapData& map, const TilePos& point); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTiles.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTiles.h new file mode 100644 index 0000000000..b25b5715c3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTiles.h @@ -0,0 +1,89 @@ +/* Overworld Tiles + * + * From: https://github.com/PokemonAutomation/ + * + * A map's tiles as FRLG reads them: bounds, tile kinds, elevations, + * walls and water. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldTiles_H +#define PokemonAutomation_PokemonFRLG_OverworldTiles_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Direction enum from Pokemon navigation. +using Pokemon::Direction; +// Grid tile coordinates. +using Pokemon::TilePos; +// Classification of tile terrain. +using Pokemon::TileKind; +// Parsed map representation. +using Pokemon::MapData; +// Warp point connection. +using Pokemon::MapWarp; +// Entity object on a map. +using Pokemon::MapObject; +// Inter-map border connection. +using Pokemon::MapConnection; +// Warp entry trigger definition. +using Pokemon::WarpEntry; +// Finds warp located at specific tile coordinates. +using Pokemon::warp_at; + + +// Elevations with a meaning of their own in the game's rules +// (IsElevationMismatchAt() and ObjectEventUpdateElevation() in +// pokefirered). +// Stairs and ladders: they join every elevation. +constexpr uint8_t ELEVATION_ANY = 0; +// Bridges and the like: they don't change the player's elevation. +constexpr uint8_t ELEVATION_IGNORED = 15; +// Ordinary ground: most walkable tiles in the decompilation's map layouts. +// Surf starts and ends here (CanStopSurfing(), and the Surf field move +// checks the player's elevation is 3). +constexpr uint8_t ELEVATION_GROUND = 3; + + +// How FRLG reads a map's tiles (Pokemon::TileKind) and warps: +// - WALL, DOOR, SIGN and the ledges are walls. A DOOR warps the player who +// walks north into it; a SIGN shows its message to the player who walks +// into it moving north or south (signposts, Center and Mart signs; +// pokefirered TrySetUpWalkIntoSignpostScript()). Ledges are hopped the +// way they face, which isn't modelled, so the planner avoids them. +// - WATER is entered only by starting to Surf. +// - CLOSED_ can't be entered or left through that side. +// - A warp entered by step_on (ladders, escalators) or cave_entrance warps +// the player who steps onto its tile; walk_ (exit mats, stairs +// at the side of a room) warps the player standing on it who walks that +// way. +// A map without an elevation grid is all ground. + +// Whether the given point falls within the map bounds. +bool in_bounds(const MapData& map, const TilePos& point); +// Out-of-bounds tiles are walls. +TileKind tile_at(const MapData& map, const TilePos& point); +// Returns the elevation index at the given coordinate. +uint8_t elevation_at(const MapData& map, const TilePos& point); + +// Whether the tile at point is unwalkable wall terrain. +bool is_wall(const MapData& map, const TilePos& point); +// Whether the tile at point is water terrain. +bool is_water(const MapData& map, const TilePos& point); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTrainerCrossing.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTrainerCrossing.h new file mode 100644 index 0000000000..e00ec3bce5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTrainerCrossing.h @@ -0,0 +1,45 @@ +/* Overworld Trainer Crossing + * + * From: https://github.com/PokemonAutomation/ + * + * Where a leg crosses the sight of its maps' trainers, and how far one + * may walk up to the player. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldTrainerCrossing_H +#define PokemonAutomation_PokemonFRLG_OverworldTrainerCrossing_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldReanchor.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Where a WALK leg crosses the sight of its maps' trainers +// (trainer_may_see()): the tiles of the leg after its start that one may +// see, in order, and the farthest any of them walks up to the player +// (their sight), to watch for them that long. Trainers already beaten are +// counted too: the maps don't know them. +struct TrainerCrossing{ + std::vector seen; + int approach_tiles = 0; +}; +// Nothing if `step`, from `start`, crosses no trainer's sight. +std::optional trainer_crossing( + const std::vector& maps, const MapPosition& start, const RouteStep& step +); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp new file mode 100644 index 0000000000..003ed1fb8d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -0,0 +1,445 @@ +/* Overworld Walk + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" +#include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_StartMenuDetector.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleFlashWatcher.h" +#include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "PokemonFRLG_PlayerFacingReader.h" +#include "PokemonFRLG_OverworldWalk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace std::chrono_literals; +using namespace OverworldWalkSteps; + + +namespace{ + +constexpr Milliseconds FACE_SETTLE = 300ms; // the turn animation, before A reaches what is ahead +// From the end of the hold, through the fade out and in. +constexpr Milliseconds WARP_TIMEOUT = 8000ms; +constexpr Milliseconds SURF_PROMPT_TIMEOUT = 5000ms; +constexpr Milliseconds SURF_ANIMATION = 3000ms; +// After a message closes: a trainer who saw the player speaks first, then +// the battle starts, with " would like to battle!" seconds later. +constexpr Milliseconds TRAINER_BATTLE_WATCH = 6000ms; + + +// A wild battle, seen by the flashes it starts with. +class WildBattleInterrupt : public OverworldInterrupt{ +public: + virtual std::string name() const override{ + return "a wild battle"; + } + virtual std::unique_ptr make_watcher() const override{ + return std::make_unique(COLOR_RED); + } + // The first flash shows about 130ms after the step on the console, and + // the watcher needs it to start fading back. Not calibrated yet. + virtual Milliseconds detection_delay() const override{ + return 300ms; + } + virtual void clear(ConsoleHandle& console, ProControllerContext& context) const override{ + flee_battle(console, context); + } +}; + +// A wild battle whose flashes were missed, seen once "Wild +// appeared!" shows. Where an open leg stopped is then only a rough guess. +class LateWildBattleInterrupt : public WildBattleInterrupt{ +public: + virtual std::string name() const override{ + return "a wild battle (seen late)"; + } + virtual std::unique_ptr make_watcher() const override{ + return std::make_unique(COLOR_RED); + } + // The flashes, the wipe and the opening animation: 3.7s after the step's + // press, twice on Route 1 (console B, 2026-11-01). Other maps open + // battles with other wipes, so elsewhere this is a guess. + virtual Milliseconds detection_delay() const override{ + return 3700ms; + } +}; + +class MessageInterrupt : public OverworldInterrupt{ +public: + virtual std::string name() const override{ + return "a message"; + } + virtual std::unique_ptr make_watcher() const override{ + return std::make_unique(COLOR_RED); + } + // The box shows as the step ends; then video lag and the watcher's + // 250ms. Not calibrated yet. + virtual Milliseconds detection_delay() const override{ + return 400ms; + } + virtual void clear(ConsoleHandle& console, ProControllerContext& context) const override{ + WhiteDialogOverWatcher closed(COLOR_RED); + context.wait_for_all_requests(); + const int ret = run_until( + console, context, + [](ProControllerContext& context){ + for (int c = 0; c < 5; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 840ms); + } + }, + {closed} + ); + if (ret < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "walk_overworld_route(): a message on the overworld didn't close.", + console + ); + } + check_no_trainer_battle(console, context); + } + +private: + // A trainer's battle can't be fled, and the walker must not try (console + // B, 2026-11-01, Viridian Forest): it stops here for the caller. + static void check_no_trainer_battle(ConsoleHandle& console, ProControllerContext& context){ + BattleScreenWatcher battle(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, TRAINER_BATTLE_WATCH, {battle}) >= 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "walk_overworld_route(): trainer battle: a battle started after a message on the overworld.", + console + ); + } + } +}; + +// A message, taken to be "REPEL's effect wore off...", after which another +// Max Repel is used from the Items pocket. +class RepelWoreOffInterrupt : public MessageInterrupt{ +public: + explicit RepelWoreOffInterrupt(int max_repel_slot) + : m_max_repel_slot(max_repel_slot) + {} + virtual std::string name() const override{ + return "a message (Repel wore off?)"; + } + virtual void clear(ConsoleHandle& console, ProControllerContext& context) const override{ + MessageInterrupt::clear(console, context); + use_max_repel_from_bag(console, context, m_max_repel_slot); + } + +private: + int m_max_repel_slot; +}; + + +Pokemon::LegSpec leg_spec(const RouteStep& step, MoveSpeed speed){ + return Pokemon::LegSpec{step.direction, step.tiles, step.to_wall, tile_time(step, speed)}; +} + +} // namespace + + +namespace OverworldWalkSteps{ + +DpadPosition dpad(Direction direction){ + switch (direction){ + case Direction::NORTH: + return DPAD_UP; + case Direction::EAST: + return DPAD_RIGHT; + case Direction::SOUTH: + return DPAD_DOWN; + case Direction::WEST: + return DPAD_LEFT; + } + return DPAD_NONE; +} + +void hold_dpad(ProControllerContext& context, Direction direction, Milliseconds duration){ + pbf_press_dpad(context, dpad(direction), duration, STEP_RELEASE); +} + +void hold_dpad_running(ProControllerContext& context, Direction direction, Milliseconds duration){ + pbf_controller_state(context, BUTTON_B, dpad(direction), {0, 0}, {0, 0}, duration); + pbf_wait(context, STEP_RELEASE); +} + +Milliseconds tile_time(const RouteStep& step, MoveSpeed speed){ + if (step.surfing){ + return SURF_TILE_TIME; + } + return speed == MoveSpeed::RUN ? RUN_TILE_TIME : TILE_TIME; +} + +Pokemon::LegMover leg_mover(const RouteStep& step, MoveSpeed speed){ + if (speed == MoveSpeed::RUN && !step.surfing){ + return hold_dpad_running; + } + return hold_dpad; +} + +Milliseconds leg_hold_time(const RouteStep& step, MoveSpeed speed){ + return Pokemon::leg_hold(leg_spec(step, speed), step.tiles); +} + +std::string speed_note(const RouteStep& step, MoveSpeed speed){ + if (step.action != RouteAction::WALK || !step.to_wall || step.surfing){ + return ""; + } + return std::format( + "[Speed] {} {}: {} tiles in {} ms, held {} ms", + move_speed_name(speed), Pokemon::direction_name(step.direction), step.tiles, + (tile_time(step, speed) * step.tiles).count(), leg_hold_time(step, speed).count() + ); +} + +// One watcher for the whole fade: a ladder's black is short enough to be +// over before a second watcher, started once the fade is seen, looks. +void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ + BlackScreenOverWatcher arrival(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, WARP_TIMEOUT, {arrival}) < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + ".", + console + ); + } +} + +// Fails unless the overworld is up. Under the START menu or a message the +// D-pad only moves a cursor, and legs to a wall seem to go fine: three +// "walked" that way in Viridian Forest without the player moving (console B, +// 2026-11-01). +void check_overworld(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen){ + return; + } + std::string_view open; + if (StartMenuDetector(COLOR_RED).detect(screen)){ + open = "the START menu"; + }else if (SelectionDialogDetector(COLOR_RED).detect(screen)){ + open = "a menu"; + }else if (WhiteDialogDetector(COLOR_RED).detect(screen)){ + open = "a message"; + } + if (!open.empty()){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("walk_overworld_route(): {} is open, before: {}", open, to_string(step)), + console + ); + } +} + +void clear_open_message( + ConsoleHandle& console, ProControllerContext& context, + const OverworldInterrupts& interrupts, const RouteStep& step +){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen || !WhiteDialogDetector(COLOR_RED).detect(screen)){ + return; + } + console.log("Route: a message is open before " + to_string(step) + "; handing it to the leg's interrupts.", COLOR_ORANGE); + Pokemon::clear_late_interrupts(console, context, interrupts, OPEN_MESSAGE_WATCH, 1); +} + +// After a warp's fade: fails, once the battle is fled, if it was a wild +// battle's. In run 7 (console B, 2026-11-01) the player had drifted onto +// Route 1's grass, and the step meant for Oak's Lab's door set off a +// battle; its flashes and wipe passed for the warp's fade, the route went +// on as if inside, and the next screen was the battle's FIGHT menu. +void check_warp_was_no_battle(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ + BattleScreenWatcher battle(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, AFTER_WARP_BATTLE_WATCH, {battle}) < 0){ + return; + } + flee_battle(console, context); + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "walk_overworld_route(): a wild battle, not the warp to " + step.end.map + ": the player is off the route.", + console + ); +} + +// Each leg starts with a turn tap unless it goes the way the player faces. +// A tap while already facing that way takes a step, so a facing not given +// is read from the screen. If that fails too it taps anyway. +std::optional read_facing(ConsoleHandle& console, ProControllerContext& context){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + std::optional facing; + if (screen){ + facing = read_player_facing(screen); + } + console.log(std::string("Route: the player faces ") + (facing ? Pokemon::direction_name(*facing) : "an unknown way") + "."); + return facing; +} + +void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_water){ + // "The water is a deep blue... Would you like to SURF?", with YES selected. + // An A pressed while the player is still turning is lost. + if (!facing_water){ + pbf_press_dpad(context, dpad(direction), FACE_HOLD, FACE_SETTLE); + } + pbf_press_button(context, BUTTON_A, 160ms, 0ms); + SelectionDialogWatcher prompt(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, SURF_PROMPT_TIMEOUT, {prompt}) < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "walk_overworld_route(): no Surf prompt facing the water.", + console + ); + } + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + + // " used SURF!" waits for A, then the player jumps onto the water. + for (int c = 0; c < 5; c++){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen || !WhiteDialogDetector(COLOR_RED).detect(screen)){ + break; + } + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + } + pbf_wait(context, SURF_ANIMATION); +} + +} // namespace OverworldWalkSteps + + + +std::string_view move_speed_name(MoveSpeed speed){ + switch (speed){ + case MoveSpeed::WALK: + return "walk"; + case MoveSpeed::RUN: + return "run"; + } + return "?"; +} + +OverworldInterruptSet overworld_interrupts_with_repel(int max_repel_slot){ + OverworldInterruptSet ret; + ret.wild.emplace_back(std::make_unique()); + ret.wild.emplace_back(std::make_unique()); + ret.wild.emplace_back(std::make_unique(max_repel_slot)); + ret.other.emplace_back(std::make_unique(max_repel_slot)); + return ret; +} + +void use_max_repel_from_bag(ConsoleHandle& console, ProControllerContext& context, int slot){ + console.log(std::format("Using a Max Repel (Items pocket, slot {}).", slot + 1)); + open_bag_from_overworld(console, context); + // The bag is seen while it still slides in, and ignores presses until + // it is done. + pbf_wait(context, 1000ms); + // To the Items pocket, then to the top of it. + for (int c = 0; c < 3; c++){ + pbf_press_dpad(context, DPAD_LEFT, 100ms, 600ms); + } + for (int c = 0; c < 20; c++){ + pbf_press_dpad(context, DPAD_UP, 100ms, 100ms); + } + for (int c = 0; c < slot; c++){ + pbf_press_dpad(context, DPAD_DOWN, 100ms, 300ms); + } + // USE, " used the MAX REPEL.", back to the bag, then out of the + // bag and the start menu. A third A here would open the item's menu again. + pbf_press_button(context, BUTTON_A, 160ms, 800ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + pbf_press_button(context, BUTTON_B, 160ms, 2000ms); + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); +} + +const OverworldInterruptSet& default_overworld_interrupts(){ + // Battles first: their screens are checked before the message box's. + static const OverworldInterruptSet interrupts = []{ + OverworldInterruptSet ret; + ret.wild.emplace_back(std::make_unique()); + ret.wild.emplace_back(std::make_unique()); + ret.wild.emplace_back(std::make_unique()); + ret.other.emplace_back(std::make_unique()); + return ret; + }(); + return interrupts; +} + + +void walk_overworld_route( + ConsoleHandle& console, ProControllerContext& context, + const std::vector& route, + std::optional facing, + const OverworldInterruptSet& interrupts, + MoveSpeed speed +){ + if (!facing){ + facing = read_facing(console, context); + } + for (const RouteStep& step : route){ + console.log("Route: " + to_string(step)); + clear_open_message(console, context, step.wild ? interrupts.wild : interrupts.other, step); + check_overworld(console, context, step); + switch (step.action){ + case RouteAction::WALK: + // Turning first, with a tap, makes the hold start from a standstill + // facing the right way: holding through a turn lost a tile on the + // console, while holds from a standstill were exact over 15 tiles. + if (facing != step.direction){ + pbf_press_dpad(context, dpad(step.direction), TURN_TAP, TURN_SETTLE); + } + if (const std::string note = speed_note(step, speed); !note.empty()){ + console.log(note); + } + Pokemon::walk_leg(console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG); + if (step.warps){ + wait_out_warp(console, context, step); + static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); + check_warp_was_no_battle(console, context, step); + } + break; + case RouteAction::SURF: + start_surf(console, context, step.direction, facing == step.direction); + break; + case RouteAction::FACE: + pbf_press_dpad(context, dpad(step.direction), FACE_HOLD, STEP_RELEASE); + break; + } + if (step.action != RouteAction::FACE){ + Pokemon::clear_late_interrupts( + console, context, step.wild ? interrupts.wild : interrupts.other, + step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG + ); + } + facing = step.facing_after; + } + context.wait_for_all_requests(); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h new file mode 100644 index 0000000000..f8a7b0d71f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -0,0 +1,92 @@ +/* Overworld Walk + * + * From: https://github.com/PokemonAutomation/ + * + * Walks a planned overworld route with the D-pad. FRLG moves one tile per + * 16 frames and finishes a step once it starts, so a leg is one hold timed + * to land mid-way between the last tile and one more. Warps are waited out + * by their fade; Surf goes through its dialog. + * + * A message or a wild battle can stop the player part-way through a leg. + * Each kind is an OverworldInterrupt: the walker watches for all of them + * while it holds the D-pad, and when one shows it stops, has it cleared and + * walks the rest of the leg. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalk_H +#define PokemonAutomation_PokemonFRLG_OverworldWalk_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_LegWalker.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldWalkMoves.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + + +// Walks `route` from where it was planned, at `speed`. The player must be +// standing still on the overworld and not on the bike. `facing` is the way +// the player faces at the start; if not given, it is read from the screen. +// Throws OperationFailedException if a warp's fade or the Surf prompt +// doesn't show, or a leg is interrupted too many times. +void walk_overworld_route( + ConsoleHandle& console, ProControllerContext& context, + const std::vector& route, + std::optional facing = std::nullopt, + const OverworldInterruptSet& interrupts = default_overworld_interrupts(), + MoveSpeed speed = MoveSpeed::WALK +); + + +// The pieces walk_overworld_route() is made of, for a walker that runs a +// route its own way. Each throws OperationFailedException as +// walk_overworld_route() describes. +namespace OverworldWalkSteps{ + +// After a hold onto `step`'s warp: waits out its fade. +void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step); + +// Before `step`: fails unless the overworld is up. +void check_overworld(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step); + +// Before `step`: if a message is open (a trainer who saw the player on the +// last leg and spoke after its watch), hands what shows to `interrupts`, +// once, instead of failing at once. check_overworld() then fails if the +// overworld still isn't up. +void clear_open_message( + ConsoleHandle& console, ProControllerContext& context, + const OverworldInterrupts& interrupts, const RouteStep& step +); + +// After `step`'s warp: fails, once the battle is fled, if its fade was a +// wild battle's. +void check_warp_was_no_battle(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step); + +// The way the player faces, read from the screen; nothing if it can't be read. +std::optional read_facing(ConsoleHandle& console, ProControllerContext& context); + +// Facing `direction` (turning first unless `facing_water`), starts Surf. +void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_water); + +} // namespace OverworldWalkSteps + + +// Registers overworld walk unit tests. +void add_tests_OverworldWalk(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h new file mode 100644 index 0000000000..34fe97123a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h @@ -0,0 +1,65 @@ +/* Overworld Walk Moves + * + * From: https://github.com/PokemonAutomation/ + * + * The presses a leg is walked with: the D-pad held walking or running, + * for how long, and the pace line the walker logs. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkMoves_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkMoves_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_LegWalker.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldWalkWatches.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace OverworldWalkSteps{ + +// Maps Direction to corresponding DpadPosition. +DpadPosition dpad(Direction direction); + +// The leg mover: holds the D-pad. FRLG moves exactly a tile per 16 frames. +void hold_dpad(ProControllerContext& context, Direction direction, Milliseconds duration); + +// The leg mover for running: holds the D-pad with B for the whole hold. +// Turn taps go without B: a tap only turns the player. +void hold_dpad_running(ProControllerContext& context, Direction direction, Milliseconds duration); + +// How long one tile of `step` takes at `speed`: on the water, the Surf +// pace whatever the speed. +Milliseconds tile_time(const RouteStep& step, MoveSpeed speed); + +// The mover for `step` at `speed`: hold_dpad_running() for a run on foot, +// hold_dpad() otherwise (B does nothing on the water). +Pokemon::LegMover leg_mover(const RouteStep& step, MoveSpeed speed); + +// How long the walker holds the D-pad for a WALK `step` at `speed` +// (Pokemon::leg_hold()). +Milliseconds leg_hold_time(const RouteStep& step, MoveSpeed speed); + +// For a leg to a wall on foot, the line the walker logs so a console run +// can check the pace: "[Speed] run west: 40 tiles in 5320 ms, held 5586 ms", +// the tiles at the assumed pace and the hold. Empty for other steps. +std::string speed_note(const RouteStep& step, MoveSpeed speed); + +} // namespace OverworldWalkSteps + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h new file mode 100644 index 0000000000..8473f74c0e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h @@ -0,0 +1,73 @@ +/* Overworld Walk Options + * + * From: https://github.com/PokemonAutomation/ + * + * What a walk of an overworld route is told: what can stop the player + * part-way through a leg (OverworldInterrupt), and how fast to move. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkOptions_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkOptions_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_LegWalker.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Something that stops the player part-way through a leg: a wild battle, a +// message. See Pokemon::LegInterrupt. +using OverworldInterrupt = Pokemon::LegInterrupt; +// Overworld movement interruption triggers. +using OverworldInterrupts = Pokemon::LegInterrupts; + +// What to watch for on a route's steps: `wild` on steps where a wild +// Pokemon can appear (RouteStep::wild), `other` on the rest. Watching for a +// battle where none can start only risks a false one: walking to the edge +// of a small room, the screen darkens like a battle's flash (console B, +// 2026-11-01, the bedroom's east wall). +struct OverworldInterruptSet{ + OverworldInterrupts wild; + OverworldInterrupts other; +}; + +// A wild battle, run from, and a message (e.g. "REPEL's effect wore off..."), +// closed with B. See OverworldInterruptSet. +const OverworldInterruptSet& default_overworld_interrupts(); + +// The same, except that after a message another Max Repel is used, from +// slot `max_repel_slot` (from 0) of the Items pocket. Any message on the +// overworld is taken to be the one saying the last Repel wore off. +OverworldInterruptSet overworld_interrupts_with_repel(int max_repel_slot); + +// From the overworld, uses the Max Repel in `slot` (from 0) of the Items +// pocket and returns to the overworld. +void use_max_repel_from_bag(ConsoleHandle& console, ProControllerContext& context, int slot); + + +// How the player moves on foot: walking, or running with B held, which +// needs the Running Shoes (FLAG_SYS_B_DASH, from Oak's aide in Pewter City +// after Brock). On the water the player surfs at its own pace either way. +enum class MoveSpeed{ + WALK, + RUN, +}; +// Name of a movement speed. +std::string_view move_speed_name(MoveSpeed speed); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h new file mode 100644 index 0000000000..c2a7fa95a5 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h @@ -0,0 +1,57 @@ +/* Overworld Walk Times + * + * From: https://github.com/PokemonAutomation/ + * + * How long a tile, a turn and a press take on the overworld. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkTimes_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkTimes_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_LegWalker.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldWalkOptions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace OverworldWalkSteps{ + +// Walking duration for a single tile (16 frames at 60 fps). +inline constexpr Milliseconds TILE_TIME(267); +// Surfing duration for a single tile. +inline constexpr Milliseconds SURF_TILE_TIME(133); +// 8 frames: running is 2 pixels a frame, twice walking. Not measured on the +// console yet; the walker logs each leg to a wall (speed_note()) for that. +inline constexpr Milliseconds RUN_TILE_TIME(133); +// turns a player facing another way, without a step. +inline constexpr Milliseconds TURN_TAP(40); +// duration to wait after turning to allow state to settle. +inline constexpr Milliseconds TURN_SETTLE(300); +// short enough to turn without stepping. +inline constexpr Milliseconds FACE_HOLD(40); +// duration of button release between movement steps. +inline constexpr Milliseconds STEP_RELEASE(100); +// After a warp's fade: leaving by a door the game walks the player a tile out +// on its own, and a leg started before that ends loses tiles (on the console a +// 600ms wait cost 2 tiles). +inline constexpr Milliseconds AFTER_WARP(1500); + +} // namespace OverworldWalkSteps + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkWatches.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkWatches.h new file mode 100644 index 0000000000..af5ced129a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkWatches.h @@ -0,0 +1,55 @@ +/* Overworld Walk Watches + * + * From: https://github.com/PokemonAutomation/ + * + * How long the walker watches for a battle or a message after a warp + * or a leg, and how often a leg may be interrupted. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkWatches_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkWatches_H + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_LegWalker.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" +#include "PokemonFRLG_OverworldWalkTimes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace OverworldWalkSteps{ + +// After a warp's fade, which a wild battle's flashes and wipe can pass for: +// a battle's HP box shows within this long (console B, 2026-11-01). +inline constexpr Milliseconds AFTER_WARP_BATTLE_WATCH(5000); +// A message set off by a leg's last step shows after the hold ends. Caught +// here, before the next leg's turn tap, which the message would swallow. +inline constexpr Milliseconds AFTER_LEG_WATCH(500); +// The same after a leg through grass. A battle whose flashes are missed is +// seen only by its "Wild appeared!", 3.7s after its step's press +// (twice on Route 1, console B, 2026-11-01, run 7). Unless the walker waits +// that long, the next leg is walked into the battle and lost: there, "east +// 4" and "west 4". +inline constexpr Milliseconds AFTER_WILD_LEG_WATCH(3500); +// How long clear_open_message() watches for the message it saw. +inline constexpr Milliseconds OPEN_MESSAGE_WATCH(1000); +// Maximum interruptions before a leg is abandoned. +inline constexpr size_t MAX_INTERRUPTIONS_PER_LEG = 5; + +} // namespace OverworldWalkSteps + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp new file mode 100644 index 0000000000..54e41463ed --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp @@ -0,0 +1,111 @@ +/* Overworld Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldWalk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace OverworldWalkSteps; + + +namespace{ + +struct OverworldWalkInput{ + std::string_view name; + MoveSpeed speed; + int tiles; + bool to_wall; + bool surfing; +}; + +struct OverworldWalkExpectation{ + Milliseconds hold; + std::string_view note; +}; + +struct OverworldWalkTestCase{ + OverworldWalkInput input; + OverworldWalkExpectation expectation; +}; + +class Test_OverworldWalk : public UnitTest{ +public: + explicit Test_OverworldWalk(OverworldWalkTestCase scenario) + : UnitTest("PokemonFRLG::OverworldWalk - hold: " + std::string(scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + RouteStep step; + step.direction = Direction::WEST; + step.tiles = m_scenario.input.tiles; + step.to_wall = m_scenario.input.to_wall; + step.surfing = m_scenario.input.surfing; + const Milliseconds hold = leg_hold_time(step, m_scenario.input.speed); + if (hold != m_scenario.expectation.hold){ + return std::format("Expected a hold of {}ms, got {}ms.", m_scenario.expectation.hold.count(), hold.count()); + } + const std::string note = speed_note(step, m_scenario.input.speed); + if (note != m_scenario.expectation.note){ + return "Expected the note \"" + std::string(m_scenario.expectation.note) + "\", got \"" + note + "\"."; + } + return true; + } + +private: + OverworldWalkTestCase m_scenario; +}; + +// An open leg lets go half a tile before its last step would end; a leg +// to a wall is held two tiles longer. Walking is 267ms a tile, running and +// surfing 133ms. +const OverworldWalkTestCase OVERWORLD_WALK_CASES[] = { + { + .input = {.name = "walk, open", .speed = MoveSpeed::WALK, .tiles = 5, .to_wall = false, .surfing = false}, + .expectation = {.hold = Milliseconds(4 * 267 + 133), .note = ""}, + }, + { + .input = {.name = "walk, to a wall", .speed = MoveSpeed::WALK, .tiles = 5, .to_wall = true, .surfing = false}, + .expectation = {.hold = Milliseconds(7 * 267), .note = "[Speed] walk west: 5 tiles in 1335 ms, held 1869 ms"}, + }, + { + .input = {.name = "run, open", .speed = MoveSpeed::RUN, .tiles = 5, .to_wall = false, .surfing = false}, + .expectation = {.hold = Milliseconds(4 * 133 + 66), .note = ""}, + }, + { + .input = {.name = "run, to a wall", .speed = MoveSpeed::RUN, .tiles = 40, .to_wall = true, .surfing = false}, + .expectation = {.hold = Milliseconds(42 * 133), .note = "[Speed] run west: 40 tiles in 5320 ms, held 5586 ms"}, + }, + { + .input = {.name = "run, surfing to a wall", .speed = MoveSpeed::RUN, .tiles = 3, .to_wall = true, .surfing = true}, + .expectation = {.hold = Milliseconds(5 * 133), .note = ""}, + }, + { + .input = {.name = "walk, surfing", .speed = MoveSpeed::WALK, .tiles = 3, .to_wall = false, .surfing = true}, + .expectation = {.hold = Milliseconds(2 * 133 + 66), .note = ""}, + }, +}; + +} // namespace + + +void add_tests_OverworldWalk(UnitTestDatabase& database){ + for (const auto& scenario : OVERWORLD_WALK_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h new file mode 100644 index 0000000000..55c0f31082 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h @@ -0,0 +1,49 @@ +/* Overworld Walked Tiles + * + * From: https://github.com/PokemonAutomation/ + * + * How many tiles of a stopped leg the player may have walked, from the + * stop's timing or, when it doesn't place the stop, the whole leg. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkedTiles_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkedTiles_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldMap.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// How many tiles of a stopped leg the player may have walked: from `min` +// to `max`, both included. +struct WalkedTiles{ + int min = 0; + int max = 0; +}; + +// How far off the timing of a stop may be: the interrupts' detection delays +// aren't calibrated, and video lag and the watchers' period add to them. +constexpr Milliseconds STOP_TIMING_SLACK(300); + +// Where the timing puts a stop on `step`: `estimate` tiles walked +// (Pokemon::LegResult::tiles), give or take STOP_TIMING_SLACK at +// `tile_time` a tile: a tile either side walking, two running. +WalkedTiles walked_near(const RouteStep& step, int estimate, Milliseconds tile_time); +// Anywhere on `step`, for a stop the timing doesn't place. +WalkedTiles whole_leg(const RouteStep& step); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp new file mode 100644 index 0000000000..c93346f9e8 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp @@ -0,0 +1,264 @@ +/* Player Facing Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "Tests/TestUtils.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" +#include "PokemonFRLG_PlayerFacingReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +// The sprite sheet's frames are 16x32, and the standing ones are 0 (south), +// 1 (north) and 2 (west). Rows 12 to 30 are drawn; the rest is empty. +constexpr std::string_view PLAYER_SPRITE_SHEET = "PokemonFRLG/PlayerSprites/red_normal.png"; +constexpr int SHEET_FRAME_WIDTH = 16; +constexpr int SHEET_FIRST_ROW = 12; + +constexpr int SPRITE_WIDTH = 16; +constexpr int SPRITE_ROWS = 19; +// Where the sprite's first drawn row sits on the GBA's 240x160 screen while +// the camera follows the player. Measured on the console. +constexpr int SPRITE_X = 112; +constexpr int SPRITE_Y = 56 + 12; +constexpr int GBA_WIDTH = 240; +constexpr int GBA_HEIGHT = 160; + +// Average difference per channel over the sprite's pixels. On the console a +// match scored about 12 and the next best sprite over 50. +constexpr double MATCH_MAX = 25; +constexpr double MATCH_MARGIN = 2.0; + + +ImageRGB32 sheet_frame(const ImageViewRGB32& sheet, int frame){ + return sheet.sub_image(frame * SHEET_FRAME_WIDTH, SHEET_FIRST_ROW, SPRITE_WIDTH, SPRITE_ROWS).copy(); +} + +// How far the screen differs from `sprite`, drawn `dy` GBA pixels lower. +double difference(const ImageViewRGB32& game, const ImageViewRGB32& sprite, bool mirror, int dy){ + const double scale_x = (double)game.width() / GBA_WIDTH; + const double scale_y = (double)game.height() / GBA_HEIGHT; + long total = 0; + int pixels = 0; + for (int row = 0; row < SPRITE_ROWS; row++){ + for (int col = 0; col < SPRITE_WIDTH; col++){ + const Color expected(sprite.pixel(mirror ? SPRITE_WIDTH - 1 - col : col, row)); + if (expected.alpha() == 0){ + continue; + } + const size_t x = (size_t)((SPRITE_X + col + 0.5) * scale_x); + const size_t y = (size_t)((SPRITE_Y + dy + row + 0.5) * scale_y); + if (x >= game.width() || y >= game.height()){ + return std::numeric_limits::max(); + } + const Color pixel(game.pixel(x, y)); + total += std::abs((int)pixel.red() - expected.red()); + total += std::abs((int)pixel.green() - expected.green()); + total += std::abs((int)pixel.blue() - expected.blue()); + pixels++; + } + } + return pixels == 0 ? std::numeric_limits::max() : (double)total / (3 * pixels); +} + +} // namespace + + +const PlayerSprites& player_sprites(){ + static const PlayerSprites SPRITES = []{ + const ImageRGB32 sheet(std::format("{}{}", RESOURCE_PATH(), PLAYER_SPRITE_SHEET)); + return PlayerSprites{sheet_frame(sheet, 0), sheet_frame(sheet, 1), sheet_frame(sheet, 2)}; + }(); + return SPRITES; +} + + +std::optional read_player_facing(const ImageViewRGB32& screen){ + const ImageViewRGB32 game = extract_box_reference(screen, GameSettings::instance().GAME_BOX); + return match_player_facing(game, player_sprites()); +} + +std::optional match_player_facing(const ImageViewRGB32& game, const PlayerSprites& sprites){ + struct Candidate{ + Direction direction; + const ImageViewRGB32& sprite; + bool mirror; + }; + const Candidate candidates[] = { + {Direction::SOUTH, sprites.south, false}, + {Direction::NORTH, sprites.north, false}, + {Direction::WEST, sprites.west, false}, + {Direction::EAST, sprites.west, true}, + }; + + double best = std::numeric_limits::max(); + double second = best; + Direction facing = Direction::SOUTH; + for (const Candidate& candidate : candidates){ + // A pixel either way, for a box that is slightly off. + double score = std::numeric_limits::max(); + for (int dy = -1; dy <= 1; dy++){ + score = std::min(score, difference(game, candidate.sprite, candidate.mirror, dy)); + } + if (score < best){ + second = best; + best = score; + facing = candidate.direction; + }else{ + second = std::min(second, score); + } + } + if (best > MATCH_MAX || second < best * MATCH_MARGIN){ + return std::nullopt; + } + return facing; +} + + + +namespace{ + +class Test_PlayerFacingReader : public UnitTest{ +public: + // The image's name ends with the way the player faces, or "None" where + // no standing player shows: _. + Test_PlayerFacingReader(const std::string& image) + : UnitTest("PokemonFRLG::PlayerFacingReader - " + image) + , m_image(UNIT_TEST_RESOURCE_PATH() + image) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + const std::vector words = parse_words(Filesystem::Path(m_image).stem().string()); + if (words.size() < 2){ + return "Error: filename must be _."; + } + std::string expected = words.back(); + std::transform(expected.begin(), expected.end(), expected.begin(), [](unsigned char c){ return (char)std::tolower(c); }); + + std::optional facing; + try{ + facing = read_player_facing(ImageRGB32(m_image)); + }catch (FileException& e){ + // The screenshots and the sprite sheet aren't in CI's resources yet. + return UnitTestResult(UnitTestResult::SKIPPED, "File not found: " + e.message()); + } + const std::string read = facing ? direction_name(*facing) : "none"; + if (read == expected){ + return true; + } + return "Expected " + expected + ", read " + read; + } + +private: + std::string m_image; +}; + +// Made-up sprites, so the matching is tested without the sprite sheet: +// solid red facing south, solid blue facing north, and green on the left +// half facing west. +PlayerSprites fixture_sprites(){ + PlayerSprites sprites{ + ImageRGB32(SPRITE_WIDTH, SPRITE_ROWS), + ImageRGB32(SPRITE_WIDTH, SPRITE_ROWS), + ImageRGB32(SPRITE_WIDTH, SPRITE_ROWS), + }; + sprites.south.fill(0xffff0000); + sprites.north.fill(0xff0000ff); + sprites.west.fill(0x00000000); + for (int row = 0; row < SPRITE_ROWS; row++){ + for (int col = 0; col < SPRITE_WIDTH / 2; col++){ + sprites.west.pixel(col, row) = 0xff00ff00; + } + } + return sprites; +} + +// A grey GBA screen at twice its size, with `sprite` drawn where the +// player stands. +ImageRGB32 fixture_screen(const ImageViewRGB32* sprite, bool mirror){ + ImageRGB32 game(2 * GBA_WIDTH, 2 * GBA_HEIGHT); + game.fill(0xff808080); + for (int row = 0; sprite != nullptr && row < SPRITE_ROWS; row++){ + for (int col = 0; col < SPRITE_WIDTH; col++){ + const uint32_t pixel = sprite->pixel(mirror ? SPRITE_WIDTH - 1 - col : col, row); + if (Color(pixel).alpha() == 0){ + continue; + } + for (int dy = 0; dy < 2; dy++){ + for (int dx = 0; dx < 2; dx++){ + game.pixel(2 * (SPRITE_X + col) + dx, 2 * (SPRITE_Y + row) + dy) = pixel; + } + } + } + } + return game; +} + +class Test_PlayerFacingFixture : public UnitTest{ +public: + Test_PlayerFacingFixture() + : UnitTest("PokemonFRLG::PlayerFacingReader - made-up sprites") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope& scope) const override{ + const PlayerSprites sprites = fixture_sprites(); + struct Case{ + const ImageViewRGB32* sprite; + bool mirror; + std::optional expected; + }; + const Case cases[] = { + {&sprites.south, false, Direction::SOUTH}, + {&sprites.north, false, Direction::NORTH}, + {&sprites.west, false, Direction::WEST}, + {&sprites.west, true, Direction::EAST}, + {nullptr, false, std::nullopt}, + }; + for (const Case& test : cases){ + const std::optional facing = match_player_facing(fixture_screen(test.sprite, test.mirror), sprites); + if (facing != test.expected){ + return std::string("Read ") + (facing ? direction_name(*facing) : "nothing") + + " instead of " + (test.expected ? direction_name(*test.expected) : "nothing"); + } + } + return true; + } +}; + +} // namespace + +void add_tests_PlayerFacingReader(UnitTestDatabase& database){ + database.add(); + // LeafGreen on the Switch, captured with a 1080p card. + database.add("PokemonFRLG/PlayerFacingReader/Route24_South.png"); + database.add("PokemonFRLG/PlayerFacingReader/Route24_North.png"); + database.add("PokemonFRLG/PlayerFacingReader/CeruleanCave_South.png"); + database.add("PokemonFRLG/PlayerFacingReader/CeruleanCave_North.png"); + database.add("PokemonFRLG/PlayerFacingReader/Surfing_None.png"); + database.add("PokemonFRLG/PlayerFacingReader/Bag_None.png"); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h new file mode 100644 index 0000000000..bbb12c7d11 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h @@ -0,0 +1,59 @@ +/* Player Facing Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Which way the player faces, read from the overworld. The camera keeps the + * player on the same spot of the screen, so the reader compares that spot + * with the player's standing sprites from pret/pokefirered, on the sprite's + * own pixels only, so the ground behind doesn't matter. The sprites come + * from Packages: Resources/PokemonFRLG/PlayerSprites/red_normal.png is the + * decompilation's graphics/object_events/pics/people/red_normal.png. + * + * Only the walking player is known: surfing and biking use other sprites. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_PlayerFacingReader_H +#define PokemonAutomation_PokemonFRLG_PlayerFacingReader_H + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonFRLG_OverworldMap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The standing player's frames, as the game draws them, with transparent +// pixels at alpha 0. Facing east is facing west mirrored. +struct PlayerSprites{ + ImageRGB32 south; + ImageRGB32 north; + ImageRGB32 west; +}; + +// Loads the frames once. Throws FileException if the file is missing. +const PlayerSprites& player_sprites(); + + +// The way the standing player faces, or nothing if no standing sprite +// matches clearly (surfing, on the bike, in a menu, mid-step). +std::optional read_player_facing(const ImageViewRGB32& screen); + +// The same on `game`, the GBA's 240x160 screen at any scale, already cut +// out of the console's. +std::optional match_player_facing(const ImageViewRGB32& game, const PlayerSprites& sprites); + + +// Registers player facing reader unit tests. +void add_tests_PlayerFacingReader(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 114832f2fe..961badd4e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -35,6 +35,12 @@ #include "Inference/PokemonFRLG_StatsReader.h" #include "Inference/PokemonFRLG_TrainerIdReader.h" #include "Inference/PokemonFRLG_WildEncounterReader.h" +#include "Overworld/PokemonFRLG_OverworldMaps.h" +#include "Overworld/PokemonFRLG_OverworldReanchor.h" +#include "Overworld/PokemonFRLG_OverworldRecovery.h" +#include "Overworld/PokemonFRLG_OverworldRoute.h" +#include "Overworld/PokemonFRLG_OverworldWalk.h" +#include "Overworld/PokemonFRLG_PlayerFacingReader.h" #include "PokemonFRLG_Navigation.h" #include "Tests/TestUtils.h" @@ -271,6 +277,9 @@ void add_tests_ExitWildBattle(UnitTestDatabase& database){ } +// The menu readers AutoStory brought: the bag's and Marts' lists, the +// options, the save card, the summary's moves and the teach screens, and +// the screen events. static void add_tests_AutoStoryReaders(UnitTestDatabase& database){ add_tests_ItemListReader(database); add_tests_OptionMenuReader(database); @@ -308,6 +317,12 @@ void add_tests(UnitTestDatabase& database){ add_tests_BagDetector(database); add_tests_AutoStoryReaders(database); add_tests_ExitWildBattle(database); + add_tests_OverworldMaps(database); + add_tests_OverworldRoute(database); + add_tests_OverworldWalk(database); + add_tests_OverworldReanchor(database); + add_tests_OverworldRecovery(database); + add_tests_PlayerFacingReader(database); } diff --git a/SerialPrograms/cmake/PokesimMapResources.cmake b/SerialPrograms/cmake/PokesimMapResources.cmake new file mode 100644 index 0000000000..67d0124ce1 --- /dev/null +++ b/SerialPrograms/cmake/PokesimMapResources.cmake @@ -0,0 +1,15 @@ +# Resolve FRLG's prepared map input. Configuration never prepares or downloads maps. +# Supply -DPOKESIM_TOOLS_SOURCE=/path/to/tools -DPOKESIM_SOURCE_CACHE=/path/to/cache. +# See devtools/maps/RESOURCE_MAPS.md for the explicit prepare step and pinned CI. +function(pa_frlg_map_resources OUT) + get_filename_component(CONSUMER "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../.." ABSOLUTE) + set(POKESIM_TOOLS_SOURCE "$ENV{POKESIM_TOOLS_SOURCE}" CACHE PATH "Pinned PokemonSimulation tools checkout") + set(POKESIM_SOURCE_CACHE "$ENV{POKESIM_SOURCE_CACHE}" CACHE PATH "Approved publishing Git cache") + if(NOT POKESIM_TOOLS_SOURCE OR NOT POKESIM_SOURCE_CACHE) + message(FATAL_ERROR "Set POKESIM_TOOLS_SOURCE and POKESIM_SOURCE_CACHE after preparing devtools/maps/map-resources.lock.json; see devtools/maps/RESOURCE_MAPS.md.") + endif() + include("${POKESIM_TOOLS_SOURCE}/integrations/arduino-source/resource-maps.cmake") + pa_pokesim_map_directory(MAPS frlg "${CONSUMER}" "${POKESIM_SOURCE_CACHE}") + file(RELATIVE_PATH RELATIVE_MAPS "${CMAKE_CURRENT_SOURCE_DIR}" "${MAPS}") + set(${OUT} "${RELATIVE_MAPS}" PARENT_SCOPE) +endfunction() diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 92e0a0d83f..1aea88d355 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1888,6 +1888,35 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Inference/Sounds/PokemonFRLG_CatchFanfareDetector.h Source/VideoGames/PokemonFRLG/Inference/Sounds/PokemonFRLG_ShinySoundDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Sounds/PokemonFRLG_ShinySoundDetector.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldObjects.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteCosts.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTileRules.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTiles.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldTrainerCrossing.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkWatches.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h Source/VideoGames/PokemonFRLG/PokemonFRLG_Panels.cpp diff --git a/devtools/maps/RESOURCE_MAPS.md b/devtools/maps/RESOURCE_MAPS.md new file mode 100644 index 0000000000..3509e98523 --- /dev/null +++ b/devtools/maps/RESOURCE_MAPS.md @@ -0,0 +1,43 @@ +# FRLG map resources + +FRLG's existing `overworld_map_json()` API now embeds JSON from prepared +`Packages/Resources/Pokemon/Maps/frlg`, rather than an authored source-map copy. +Its native map decoder, route/story/recovery code and controller behavior are +unchanged. Resource preparation happens before configuring, with no implicit +fallback to the deleted source directory and no map download during configure. +This is a change of build input, not runtime filesystem loading. + +The resource lock and CI tools pin published PokemonSimulation main +`906956e94fc912ae9adb0e44845da780f3bc7e4c`. The 53-map resource pack now uses the +compact v2 wire format, read by #114's shared decoder. V2 groups records by kind +and omits empty sections; map geometry, triggers and per-kind record order must +match the previous v1 pack. Native schema, map, route/story and recovery tests +verify this adoption; their current results are recorded in the fork PR. +BDSP's held map differences are not imported or overwritten. + +Clone a full tools/data checkout outside deployed Resources, then explicitly +select the published tool version used by CI: + +```sh +git clone https://github.com/dayfine/PokemonSimulation.git /path/to/pokesim +git -C /path/to/pokesim checkout 906956e94fc912ae9adb0e44845da780f3bc7e4c +PYTHONPATH=/path/to/pokesim/src python3 -m pokesim.maps.consumer_sync prepare \ + --layout resources --source /path/to/pokesim --consumer /path/to/Arduino-Source +cmake -S SerialPrograms -B /path/to/build \ + -DPOKESIM_TOOLS_SOURCE=/path/to/pokesim -DPOKESIM_SOURCE_CACHE=/path/to/pokesim +``` + +CI checks out Packages, prepares this same resource lock through the pinned +integration action, and passes its tools/cache paths to CMake. Missing, partial, +modified, extra or unapproved resource data fails before compilation. The pack +includes pinned license/provenance. Generated resources and external caches are +ignored; the resource lock is checked in. + +The duplicate FRLG builder and Python tests are removed. Map-builder tests already live +beside their source in PokemonSimulation. Native game tests remain here. +The shared Sinnoh decomp CLI remains a separate consumer migration. + +Native map, story, transition and recovery tests must run from this tree without +the old map directory before adopting this handoff in the owning chain. This +fork setup is not yet an upstream resource submission: handoff must make the +required data available through the agreed Packages repository/process. diff --git a/devtools/maps/map-resources.lock.json b/devtools/maps/map-resources.lock.json new file mode 100644 index 0000000000..3bded16bc7 --- /dev/null +++ b/devtools/maps/map-resources.lock.json @@ -0,0 +1,11 @@ +{ + "format": "pokesim-map-resource-lock/1", + "repository": "dayfine/PokemonSimulation", + "games": { + "frlg": { + "revision": "906956e94fc912ae9adb0e44845da780f3bc7e4c", + "manifest_path": "data/maps/runtime-manifest.json", + "manifest_sha256": "856e07a265da0b273172a7aa97a2aa335c90ea0a39162d50912b55fb60a86bc7" + } + } +}