From a40f0e034b406b342d9c9e4925d2ea51931543be Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 12:00:36 -0800 Subject: [PATCH 01/74] BDSP navigation: the story maps as JSON, their grids and plan costs, with tests The BDSP maps from new game to Floaroma (Twinleaf to Floaroma, the Oreburgh Mine and Gym, the Ravaged Path), built into the program from JSON by CMake, their tile grids and the joined StoryMaps world, the recorded routes and segment 00's walked lines, and the costs the story's walks are planned with. Carries Pokemon_TileGrid and Pokemon_MapSet unchanged from the BDSP chain (fork #109). Tests: the built-in maps parse, and the planned walks out of the catch area and into Sandgem, the Oreburgh Gym and segment 00's lines plan on the grids. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- SerialPrograms/CMakeLists.txt | 2 + .../Pokemon/Navigation/Pokemon_MapSet.cpp | 102 ++++ .../Pokemon/Navigation/Pokemon_MapSet.h | 63 +++ .../Pokemon/Navigation/Pokemon_TileGrid.cpp | 503 ++++++++++++++++++ .../Pokemon/Navigation/Pokemon_TileGrid.h | 191 +++++++ .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 4 + .../Programs/AutoStory/Data/MAPS.md | 45 ++ .../PokemonBDSP_AutoStory_FloaromaTown.cpp | 81 +++ .../Data/PokemonBDSP_AutoStory_FloaromaTown.h | 36 ++ .../PokemonBDSP_AutoStory_JubilifeCity.cpp | 113 ++++ .../Data/PokemonBDSP_AutoStory_JubilifeCity.h | 45 ++ .../Data/PokemonBDSP_AutoStory_LakeVerity.cpp | 66 +++ .../Data/PokemonBDSP_AutoStory_LakeVerity.h | 27 + .../Data/PokemonBDSP_AutoStory_MapGrids.cpp | 115 ++++ .../Data/PokemonBDSP_AutoStory_MapGrids.h | 52 ++ .../PokemonBDSP_AutoStory_OreburghCity.cpp | 92 ++++ .../Data/PokemonBDSP_AutoStory_OreburghCity.h | 37 ++ .../PokemonBDSP_AutoStory_OreburghGate.cpp | 51 ++ .../Data/PokemonBDSP_AutoStory_OreburghGate.h | 27 + .../PokemonBDSP_AutoStory_OreburghGym.cpp | 61 +++ .../Data/PokemonBDSP_AutoStory_OreburghGym.h | 38 ++ .../PokemonBDSP_AutoStory_OreburghMine.cpp | 65 +++ .../Data/PokemonBDSP_AutoStory_OreburghMine.h | 39 ++ .../Data/PokemonBDSP_AutoStory_PlanCosts.cpp | 47 ++ .../Data/PokemonBDSP_AutoStory_PlanCosts.h | 46 ++ .../PokemonBDSP_AutoStory_RavagedPath.cpp | 62 +++ .../Data/PokemonBDSP_AutoStory_RavagedPath.h | 47 ++ .../Data/PokemonBDSP_AutoStory_Route201.cpp | 82 +++ .../Data/PokemonBDSP_AutoStory_Route201.h | 37 ++ .../Data/PokemonBDSP_AutoStory_Route202.cpp | 101 ++++ .../Data/PokemonBDSP_AutoStory_Route202.h | 49 ++ .../Data/PokemonBDSP_AutoStory_Route203.cpp | 78 +++ .../Data/PokemonBDSP_AutoStory_Route203.h | 32 ++ .../Data/PokemonBDSP_AutoStory_Route204.cpp | 91 ++++ .../Data/PokemonBDSP_AutoStory_Route204.h | 43 ++ .../PokemonBDSP_AutoStory_Route204South.cpp | 87 +++ .../PokemonBDSP_AutoStory_Route204South.h | 44 ++ .../PokemonBDSP_AutoStory_RouteRecords.cpp | 199 +++++++ .../Data/PokemonBDSP_AutoStory_RouteRecords.h | 67 +++ .../PokemonBDSP_AutoStory_SandgemTown.cpp | 96 ++++ .../Data/PokemonBDSP_AutoStory_SandgemTown.h | 49 ++ .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 156 ++++++ .../PokemonBDSP_AutoStory_Segment00Lines.h | 84 +++ .../Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 246 +++++++++ .../Data/PokemonBDSP_AutoStory_StoryMaps.h | 108 ++++ .../PokemonBDSP_AutoStory_TwinleafTown.cpp | 61 +++ .../Data/PokemonBDSP_AutoStory_TwinleafTown.h | 27 + .../PokemonBDSP_AutoStory_VerityLakefront.cpp | 56 ++ .../PokemonBDSP_AutoStory_VerityLakefront.h | 27 + .../Programs/AutoStory/Maps/FloaromaTown.json | 92 ++++ .../Programs/AutoStory/Maps/JubilifeCity.json | 136 +++++ .../Programs/AutoStory/Maps/LakeVerity.json | 62 +++ .../Programs/AutoStory/Maps/OreburghCity.json | 88 +++ .../Programs/AutoStory/Maps/OreburghGate.json | 62 +++ .../Programs/AutoStory/Maps/OreburghGym.json | 68 +++ .../Programs/AutoStory/Maps/OreburghMine.json | 80 +++ .../Programs/AutoStory/Maps/RavagedPath.json | 64 +++ .../Programs/AutoStory/Maps/Route201.json | 43 ++ .../Programs/AutoStory/Maps/Route202.json | 62 +++ .../Programs/AutoStory/Maps/Route203.json | 60 +++ .../AutoStory/Maps/Route204North.json | 74 +++ .../AutoStory/Maps/Route204South.json | 62 +++ .../Programs/AutoStory/Maps/SandgemTown.json | 42 ++ .../Programs/AutoStory/Maps/TwinleafTown.json | 56 ++ .../AutoStory/Maps/VerityLakefront.json | 42 ++ .../PokemonBDSP_AutoStory_MapGrid_Tests.cpp | 256 +++++++++ .../PokemonBDSP_AutoStory_MapGrid_Tests.h | 28 + .../PokemonBDSP_AutoStory_Segment00_Tests.cpp | 266 +++++++++ .../PokemonBDSP_AutoStory_Segment00_Tests.h | 27 + SerialPrograms/cmake/SourceFiles.cmake | 50 ++ devtools/maps/bdsp_maps.py | 53 ++ 71 files changed, 5650 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h create mode 100644 devtools/maps/bdsp_maps.py diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index d0966df32f..021c06a41f 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -197,6 +197,8 @@ 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) +pa_embed_text_files(SerialProgramsLib Source/PokemonBDSP/Programs/AutoStory/Maps + PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_map_json) # Create binary target diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp new file mode 100644 index 0000000000..533dc4f12f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp @@ -0,0 +1,102 @@ +/* Map Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_MapSet.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void MapSet::add(std::string name, const TileGrid& grid, const TilePos& offset){ + for (const Placed& placed : m_maps){ + if (placed.name == name){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Map placed twice: " + name); + } + // Map images show a border of trees past their edges, so two maps + // may share blocked tiles, but nothing else. + for (int y = 0; y < grid.height(); y++){ + for (int x = 0; x < grid.width(); x++){ + const TilePos other{offset.x + x - placed.offset.x, offset.y + y - placed.offset.y}; + if (!placed.grid.in_bounds(other)){ + continue; + } + if (grid.at({x, y}) != TileType::BLOCKED || placed.grid.at(other) != TileType::BLOCKED){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Map " + name + " overlaps " + placed.name + " at its tile " + to_string(TilePos{x, y}) + "." + ); + } + } + } + } + m_maps.push_back(Placed{std::move(name), grid, offset}); + + // Rebuild the joined grid. + TilePos low = m_maps[0].offset; + TilePos high = low; + for (const Placed& placed : m_maps){ + low.x = std::min(low.x, placed.offset.x); + low.y = std::min(low.y, placed.offset.y); + high.x = std::max(high.x, placed.offset.x + placed.grid.width()); + high.y = std::max(high.y, placed.offset.y + placed.grid.height()); + } + m_origin = low; + std::vector rows(high.y - low.y, std::string(high.x - low.x, tile_char(TileType::UNKNOWN))); + for (const Placed& placed : m_maps){ + const std::vector map_rows = placed.grid.rows(); + for (size_t y = 0; y < map_rows.size(); y++){ + rows[placed.offset.y - low.y + y].replace(placed.offset.x - low.x, map_rows[y].size(), map_rows[y]); + } + } + m_world.emplace(rows); +} + +const TileGrid& MapSet::world() const{ + if (!m_world){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No maps placed."); + } + return *m_world; +} + +TilePos MapSet::to_world(const std::string& map, const TilePos& local) const{ + for (const Placed& placed : m_maps){ + if (placed.name == map){ + return { + placed.offset.x - m_origin.x + local.x, + placed.offset.y - m_origin.y + local.y, + }; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown map: " + map); +} + +std::optional MapSet::to_local(const TilePos& world) const{ + for (const Placed& placed : m_maps){ + const TilePos local{ + world.x + m_origin.x - placed.offset.x, + world.y + m_origin.y - placed.offset.y, + }; + if (placed.grid.in_bounds(local)){ + return MapTile{placed.name, local}; + } + } + return std::nullopt; +} + +std::string MapSet::describe(const TilePos& world) const{ + const std::optional local = to_local(world); + if (!local){ + return "world " + to_string(world); + } + return local->map + " " + to_string(local->pos); +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h new file mode 100644 index 0000000000..468213c481 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h @@ -0,0 +1,63 @@ +/* Map Set + * + * From: https://github.com/PokemonAutomation/ + * + * Several tile grids placed side by side on one world grid, so one plan + * can cross from a route into a town. + */ + +#ifndef PokemonAutomation_Pokemon_MapSet_H +#define PokemonAutomation_Pokemon_MapSet_H + +#include +#include +#include +#include "Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct MapTile{ + std::string map; + TilePos pos; +}; + + +class MapSet{ +public: + // Places `grid` with its tile (0,0) at `offset`. Offsets are relative to + // each other and may be negative. Maps may overlap only where both are + // blocked; the map placed first holds those tiles. Throws + // InternalProgramError if the name is taken or the maps conflict. + void add(std::string name, const TileGrid& grid, const TilePos& offset); + + // The maps joined on one grid. Tiles no map covers are UNKNOWN. World + // tile (0,0) is the top-left corner of all the maps together. + const TileGrid& world() const; + + // Throws InternalProgramError for an unknown map name. + TilePos to_world(const std::string& map, const TilePos& local) const; + + // The map that holds a world tile, or nothing between maps. + std::optional to_local(const TilePos& world) const; + + // "Route 201 (45,3)", or the world tile if no map holds it. + std::string describe(const TilePos& world) const; + +private: + struct Placed{ + std::string name; + TileGrid grid; + TilePos offset; + }; + std::vector m_maps; + TilePos m_origin; // offset of world tile (0,0) + std::optional m_world; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp new file mode 100644 index 0000000000..e0a70bc8e5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp @@ -0,0 +1,503 @@ +/* Tile Grid + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_LegPlanner.h" +#include "Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +char tile_char(TileType type){ + switch (type){ + case TileType::BLOCKED: return '#'; + case TileType::WALKABLE: return '.'; + case TileType::TALL_GRASS: return '"'; + case TileType::LEDGE: return 'v'; + case TileType::NPC: return 'N'; + case TileType::SIGN: return 'S'; + case TileType::DOOR: return 'D'; + case TileType::UNKNOWN: return '?'; + } + return '?'; +} + + + + +TileGrid::TileGrid(const std::vector& rows) + : m_width(rows.empty() ? 0 : (int)rows[0].size()) + , m_height((int)rows.size()) +{ + m_tiles.reserve((size_t)m_width * m_height); + for (size_t y = 0; y < rows.size(); y++){ + const std::string& row = rows[y]; + if ((int)row.size() != m_width){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Tile grid row " + std::to_string(y) + " has " + std::to_string(row.size()) + + " tiles, expected " + std::to_string(m_width) + "." + ); + } + for (size_t x = 0; x < row.size(); x++){ + switch (row[x]){ + case '#': m_tiles.push_back(TileType::BLOCKED); break; + case '.': m_tiles.push_back(TileType::WALKABLE); break; + case '"': m_tiles.push_back(TileType::TALL_GRASS); break; + case 'v': m_tiles.push_back(TileType::LEDGE); break; + case 'N': m_tiles.push_back(TileType::NPC); break; + case 'S': m_tiles.push_back(TileType::SIGN); break; + case 'D': m_tiles.push_back(TileType::DOOR); break; + case '?': m_tiles.push_back(TileType::UNKNOWN); break; + default: + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + std::string("Unknown tile '") + row[x] + "' at " + + to_string(TilePos{(int)x, (int)y}) + "." + ); + } + } + } +} + +std::vector TileGrid::rows() const{ + std::vector rows; + for (int y = 0; y < m_height; y++){ + std::string row; + for (int x = 0; x < m_width; x++){ + row += tile_char(at({x, y})); + } + rows.push_back(std::move(row)); + } + return rows; +} + +bool TileGrid::in_bounds(const TilePos& pos) const{ + return 0 <= pos.x && pos.x < m_width && 0 <= pos.y && pos.y < m_height; +} + +TileType TileGrid::at(const TilePos& pos) const{ + if (!in_bounds(pos)){ + return TileType::UNKNOWN; + } + return m_tiles[(size_t)pos.y * m_width + pos.x]; +} + +void TileGrid::set(const TilePos& pos, TileType type){ + if (in_bounds(pos)){ + m_tiles[(size_t)pos.y * m_width + pos.x] = type; + } +} + +bool TileGrid::standable(const TilePos& pos) const{ + const TileType type = at(pos); + return type == TileType::WALKABLE || type == TileType::TALL_GRASS; +} + +std::optional TileGrid::step(const TilePos& from, Direction direction) const{ + const TilePos next = from.next(direction); + if (standable(next)){ + return next; + } + if (at(next) == TileType::LEDGE && direction == Direction::SOUTH){ + const TilePos landing = next.next(direction); + if (standable(landing)){ + return landing; + } + } + return std::nullopt; +} + +bool TileGrid::at_wall(const TilePos& pos, Direction direction) const{ + const TileType next = at(pos.next(direction)); + return next != TileType::DOOR && next != TileType::UNKNOWN && !step(pos, direction).has_value(); +} + + + +WallHit walk_to_wall(const TileGrid& grid, const TilePos& from, Direction direction){ + WallHit hit; + hit.stop = from; + while (true){ + const TilePos before = hit.stop; + const std::optional next = grid.step(before, direction); + if (!next){ + hit.wall = before.next(direction); + hit.anchored = grid.at_wall(before, direction); + return hit; + } + hit.tiles += std::abs(next->x - before.x) + std::abs(next->y - before.y); + hit.stop = *next; + } +} + + + +std::string to_string(const TileLeg& leg){ + return std::string(direction_name(leg.direction)) + " " + std::to_string(leg.tiles) + + (leg.ends_at_wall ? " (to wall)" : " (open)"); +} + + +namespace{ + +// The grid's step rules for the shared leg planner. A ledge hop is one +// press that moves two tiles. +class TileGridModel{ +public: + using State = TilePos; + using StateHash = std::hash; + + TileGridModel(const TileGrid& grid, const TilePlanCosts& costs) + : m_grid(grid) + , m_costs(costs) + {} + + std::optional> press(const State& pos, Direction direction) const{ + const std::optional next = m_grid.step(pos, direction); + if (!next){ + return std::nullopt; + } + Step step; + step.next = *next; + step.facing = direction; + const int tiles = std::abs(next->x - pos.x) + std::abs(next->y - pos.y); + step.extra_cost = m_costs.per_tile * (tiles - 1); + if (m_grid.at(*next) == TileType::TALL_GRASS){ + step.extra_cost += m_costs.per_grass_tile; + } + return step; + } + bool held_at(const State& pos, Direction direction) const{ + return m_grid.at_wall(pos, direction); + } + +private: + const TileGrid& m_grid; + const TilePlanCosts& m_costs; +}; + +} + +std::optional> plan_tile_route( + const TileGrid& grid, + const TilePos& from, const TilePos& to, + const TilePlanCosts& costs +){ + if (!grid.standable(from) || !grid.standable(to)){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Route ends must be standable: " + to_string(from) + " -> " + to_string(to) + "." + ); + } + if (from == to){ + return std::vector(); + } + LegCosts leg_costs; + leg_costs.per_tile = costs.per_tile; + leg_costs.per_turn = costs.per_leg; + leg_costs.per_open_stop = costs.leg_not_at_wall; + const std::optional>> legs = plan_legs( + TileGridModel(grid, costs), from, std::nullopt, + std::function([&](const TilePos& pos){ return pos == to; }), + std::nullopt, leg_costs + ); + if (!legs){ + return std::nullopt; + } + std::vector ret; + for (const Leg& leg : *legs){ + const size_t tiles = std::abs(leg.end.x - leg.start.x) + std::abs(leg.end.y - leg.start.y); + ret.push_back(TileLeg{leg.direction, tiles, leg.to_wall}); + } + return ret; +} + +std::vector sight_tiles(const TileGrid& grid, const TrainerSight& trainer){ + std::vector tiles; + TilePos pos = trainer.pos; + for (int i = 0; i < trainer.range; i++){ + pos = pos.next(trainer.facing); + if (!grid.standable(pos)){ + break; + } + tiles.push_back(pos); + } + return tiles; +} + +std::vector> legs_crossing_sight( + const TileGrid& grid, + const TilePos& from, + const std::vector& legs, + const std::vector& trainers +){ + std::vector> sights; + for (const TrainerSight& trainer : trainers){ + sights.push_back(sight_tiles(grid, trainer)); + } + std::vector> crossings; + TilePos pos = from; + for (const TileLeg& leg : legs){ + const std::vector tiles = trace_legs(grid, pos, {leg}); + std::vector seen_by; + for (size_t t = 0; t < trainers.size(); t++){ + for (size_t i = 1; i < tiles.size(); i++){ + if (std::find(sights[t].begin(), sights[t].end(), tiles[i]) != sights[t].end()){ + seen_by.push_back(trainers[t].name); + break; + } + } + } + crossings.push_back(std::move(seen_by)); + pos = tiles.back(); + } + return crossings; +} + +std::vector trace_legs( + const TileGrid& grid, + const TilePos& from, + const std::vector& legs +){ + std::vector tiles{from}; + for (const TileLeg& leg : legs){ + size_t travelled = 0; + while (travelled < leg.tiles){ + const TilePos pos = tiles.back(); + const std::optional next = grid.step(pos, leg.direction); + if (!next){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Leg " + to_string(leg) + " is stopped at " + to_string(pos) + "." + ); + } + travelled += std::abs(next->x - pos.x) + std::abs(next->y - pos.y); + tiles.push_back(*next); + } + if (travelled != leg.tiles){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Leg " + to_string(leg) + " overshoots on a ledge hop." + ); + } + } + return tiles; +} + + + +std::string to_string(const PlannedLeg& leg){ + std::string out = to_string(leg.leg) + " to"; + for (const TilePos& pos : leg.after){ + out += " " + to_string(pos); + } + return out; +} + +namespace{ + +// Where `from` ends up after `tiles` steps in `direction`, stopping early at +// anything that stops the player. Nothing if a step would leave the map or +// enter a door: the plan cannot tell what happens then. +std::optional step_tiles( + const TileGrid& grid, TilePos from, Direction direction, int tiles, int& grass +){ + int travelled = 0; + while (travelled < tiles){ + const std::optional next = grid.step(from, direction); + if (!next){ + if (!grid.at_wall(from, direction)){ + return std::nullopt; + } + break; + } + travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); + if (grid.at(*next) == TileType::TALL_GRASS){ + grass++; + } + from = *next; + } + return from; +} + +using Spread = std::vector; + +bool spread_less(const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; +} +void normalize(Spread& spread){ + std::sort(spread.begin(), spread.end(), spread_less); + spread.erase(std::unique(spread.begin(), spread.end()), spread.end()); +} +struct SpreadLess{ + bool operator()(const Spread& a, const Spread& b) const{ + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), spread_less); + } +}; + +} + +std::optional> plan_robust_route( + const TileGrid& grid, + const TilePos& from, const TilePos& to, + const RobustPlanCosts& costs +){ + if (!grid.standable(from) || !grid.standable(to)){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Route ends must be standable: " + to_string(from) + " -> " + to_string(to) + "." + ); + } + return plan_robust_route(grid, std::vector{from}, [&](const TilePos& pos){ return pos == to; }, costs); +} + +std::optional> plan_robust_route( + const TileGrid& grid, + const std::vector& from, const std::function& goal, + const RobustPlanCosts& costs +){ + for (const TilePos& pos : from){ + if (!grid.standable(pos)){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Route starts must be standable: " + to_string(pos) + "." + ); + } + } + // Only the start may be wider than costs.max_spread: every leg must bring + // the player within it. + const size_t max_spread = costs.max_spread; + auto reached = [&](const Spread& spread){ + return std::all_of(spread.begin(), spread.end(), goal); + }; + + struct Node{ + long long cost; + Spread parent; + PlannedLeg leg; + bool done = false; + }; + std::map nodes; + using Entry = std::pair; + auto entry_greater = [](const Entry& a, const Entry& b){ return a.first > b.first; }; + std::priority_queue, decltype(entry_greater)> queue(entry_greater); + + Spread start = from; + normalize(start); + nodes[start] = Node{0, {}, {}}; + queue.emplace(0, start); + + auto relax = [&](const Spread& spread, long long cost, Spread next, PlannedLeg leg){ + normalize(next); + if (next.size() > max_spread || next == spread){ + return; + } + auto iter = nodes.find(next); + if (iter != nodes.end() && iter->second.cost <= cost){ + return; + } + leg.after = next; + nodes[next] = Node{cost, spread, std::move(leg)}; + queue.emplace(cost, std::move(next)); + }; + + size_t searched = 0; + while (!queue.empty()){ + const Entry top = queue.top(); + queue.pop(); + const long long cost = top.first; + const Spread& spread = top.second; + Node& node = nodes[spread]; + if (node.done || node.cost != cost){ + continue; + } + node.done = true; + if (++searched > costs.max_searched){ + return std::nullopt; + } + if (reached(spread)){ + std::vector legs; + for (Spread at = spread; at != start; ){ + const Node& step = nodes[at]; + legs.push_back(step.leg); + at = step.parent; + } + std::reverse(legs.begin(), legs.end()); + return legs; + } + + for (Direction direction : ALL_DIRECTIONS){ + // To the wall: every position walks until stopped. + { + Spread next; + size_t longest = 0; + int grass = 0; + bool ok = true; + for (const TilePos& pos : spread){ + const WallHit hit = walk_to_wall(grid, pos, direction); + if (!hit.anchored){ + ok = false; + break; + } + int leg_grass = 0; + step_tiles(grid, pos, direction, (int)hit.tiles, leg_grass); + grass = std::max(grass, leg_grass); + longest = std::max(longest, hit.tiles); + next.push_back(hit.stop); + } + if (ok && longest > 0){ + const long long step = (long long)costs.per_leg + + (long long)costs.per_tile * longest + (long long)costs.per_grass_tile * grass; + relax(spread, cost + step, std::move(next), PlannedLeg{TileLeg{direction, longest, true}, {}}); + } + } + // Open: about `tiles` tiles, give or take `open_error`. + for (int tiles = 1; tiles <= costs.max_open_tiles; tiles++){ + Spread next; + int grass = 0; + bool ok = true; + for (const TilePos& pos : spread){ + const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; + for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ + int leg_grass = 0; + const std::optional end = step_tiles(grid, pos, direction, n, leg_grass); + if (!end){ + ok = false; + break; + } + grass = std::max(grass, leg_grass); + next.push_back(*end); + } + if (!ok){ + break; + } + } + if (!ok){ + break; + } + const long long step = (long long)costs.per_leg + costs.leg_not_at_wall + + (long long)(costs.per_tile + costs.per_open_tile) * tiles + (long long)costs.per_grass_tile * grass; + relax(spread, cost + step, std::move(next), PlannedLeg{TileLeg{direction, (size_t)tiles, false}, {}}); + } + } + } + + return std::nullopt; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h new file mode 100644 index 0000000000..c8ae8ba9d9 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h @@ -0,0 +1,191 @@ +/* Tile Grid + * + * From: https://github.com/PokemonAutomation/ + * + * An overworld map as a grid of tiles, and a planner that turns a walk from + * one tile to another into straight legs. Timed stick holds drift by a tile; + * a leg that ends against a wall does not, because the player stops there + * however long the stick is held. The planner prefers such legs. + */ + +#ifndef PokemonAutomation_Pokemon_TileGrid_H +#define PokemonAutomation_Pokemon_TileGrid_H + +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Legend of the ASCII rows a grid is parsed from. +enum class TileType{ + BLOCKED, // '#': trees, walls, items on the ground + WALKABLE, // '.': open ground and paths + TALL_GRASS, // '"': walkable, with wild encounters + LEDGE, // 'v': crossed only southward, hopping to the tile past it + NPC, // 'N': a standing NPC or trainer; blocks like a wall + SIGN, // 'S': a sign; blocks like a wall + DOOR, // 'D': walking into it enters a building + UNKNOWN, // '?': off the map; an exit or ground we have no map of +}; +char tile_char(TileType type); + +class TileGrid{ +public: + // Every row must have the same length and use only the legend's characters. + // Throws InternalProgramError otherwise. + explicit TileGrid(const std::vector& rows); + + // The grid as the ASCII rows it parses from. + std::vector rows() const; + + int width() const{ return m_width; } + int height() const{ return m_height; } + bool in_bounds(const TilePos& pos) const; + + // Out-of-bounds tiles read as UNKNOWN. + TileType at(const TilePos& pos) const; + + // Changes one tile, e.g. to block one found in the way on the console. + // Out-of-bounds tiles are left alone. + void set(const TilePos& pos, TileType type); + + // Whether the player can stand on this tile. + bool standable(const TilePos& pos) const; + + // Where one step from `from` lands, or nothing if the player is stopped. + // A south step onto a ledge hops to the tile past it. + std::optional step(const TilePos& from, Direction direction) const; + + // Whether a step from `pos` is refused by a tile that holds the player + // in place. Doors and unknown tiles are not walls: walking into a door + // enters the building, and unknown ground may be an exit. + bool at_wall(const TilePos& pos, Direction direction) const; + +private: + int m_width = 0; + int m_height = 0; + std::vector m_tiles; +}; + + +// Where the player stops when walking in one direction until stopped. +struct WallHit{ + TilePos stop; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + TilePos wall; // the first tile the player could not enter + bool anchored = false; // the player is held at `stop` (see TileGrid::at_wall()) +}; +WallHit walk_to_wall(const TileGrid& grid, const TilePos& from, Direction direction); + + +// A straight run in one direction. +struct TileLeg{ + Direction direction; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + bool ends_at_wall = false; // the next tile in `direction` stops the player +}; +std::string to_string(const TileLeg& leg); + +struct TilePlanCosts{ + int per_tile = 1; + int per_grass_tile = 4; // extra for each tall-grass tile entered + int per_leg = 8; + int leg_not_at_wall = 50; // extra for a leg that stops in the open +}; + +// Cheapest legs from `from` to `to`, moving 4 ways, or nothing if `to` +// cannot be reached. Both tiles must be standable. +std::optional> plan_tile_route( + const TileGrid& grid, + const TilePos& from, const TilePos& to, + const TilePlanCosts& costs = TilePlanCosts() +); + +// A trainer sees the tiles in a straight line in front of them, up to +// `range` tiles or the first tile the player cannot stand on. +struct TrainerSight{ + std::string name; + TilePos pos; + Direction facing; + int range = 4; +}; +std::vector sight_tiles(const TileGrid& grid, const TrainerSight& trainer); + +// For each leg, the trainers whose sight line it enters. +std::vector> legs_crossing_sight( + const TileGrid& grid, + const TilePos& from, + const std::vector& legs, + const std::vector& trainers +); + +// The tiles a list of legs visits, starting with `from`. Throws +// InternalProgramError if a leg is stopped before its end. +std::vector trace_legs( + const TileGrid& grid, + const TilePos& from, + const std::vector& legs +); + + +// A leg of a plan that allows for open legs going a tile short or long. A +// leg to a wall is walked until the player stops; an open leg is walked for +// `leg.tiles` tiles' worth of time. `after` lists every tile the player may +// stand on once the leg is done. +struct PlannedLeg{ + TileLeg leg; + std::vector after; +}; +std::string to_string(const PlannedLeg& leg); + +struct RobustPlanCosts : TilePlanCosts{ + // An open leg of n tiles may end open_error + n / open_error_per tiles + // short or long: on the console 7 tiles went 9. + int open_error = 1; + int open_error_per = 5; + // Open legs this many tiles or shorter land exactly: a short hold moves + // whole tiles. 0 keeps every open leg uncertain. + int exact_open_tiles = 0; + // Extra per tile of an open leg: its timing error grows with its length, + // so a short step after a wall beats a long open leg. + int per_open_tile = 0; + int max_open_tiles = 12; // longest open leg to consider + size_t max_spread = 5; // most tiles the player may be on after a leg + // Most sets of possible tiles to search before giving up. The search is + // over sets, not tiles, so it grows far faster than the map: all of + // Jubilife City from six start tiles ran for minutes with no plan + // (r224a, 2026-10-31); 200000 sets took 31 s there, so this gives up + // after about 3. Use town costs in towns (a whole-Jubilife plan then + // takes 1 s) and crop the map to the part a leg needs rather than + // raising this. + size_t max_searched = 20000; +}; + +// Cheapest legs that take the player from any of the tiles in `from` to tiles +// that are all `goal`, even if every open leg ends up to `open_error` tiles +// off: the walls of later legs must bring the possible positions together. +// Legs that would leave the map or enter a door are not used. Nothing if no +// such plan exists, or none is found within `costs.max_searched` sets. +std::optional> plan_robust_route( + const TileGrid& grid, + const std::vector& from, const std::function& goal, + const RobustPlanCosts& costs = RobustPlanCosts() +); +// The same, from one tile to exactly `to`. +std::optional> plan_robust_route( + const TileGrid& grid, + const TilePos& from, const TilePos& to, + const RobustPlanCosts& costs = RobustPlanCosts() +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index b8ff5e26a5..608126f0db 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -5,6 +5,8 @@ */ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -14,6 +16,8 @@ namespace PokemonBDSP{ void add_tests(UnitTestDatabase& database){ + add_tests_AutoStory_MapGrids(database); + add_tests_AutoStory_Segment00(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md new file mode 100644 index 0000000000..2c37d39a69 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md @@ -0,0 +1,45 @@ +# AutoStory map grids: source and status + +Each map file's header starts with the same three lines, kept current with the code: + +- **Map source**: where the tiles come from. "Decomp" means a decompilation's + collision table (pret/pokediamond `land_data` narc, or pret/pokeplatinum + `map_data_NNN.bin`) with the objects from its events file; BDSP keeps + Diamond/Pearl's layout, and Platinum's few changes show up on the console. "DP image" means a Bulbapedia map image + traced by hand or by colour; those images have 12 px rows for 16 px columns, so + a traced grid has 3/4 of a tile per row and drifts by the map's height + differences (cliffs are painted taller than their tiles). +- **Console checks**: the anchors measured on the Switch (D-pad taps, sign reads, + recorded human walks), with the run or date. +- **Status**: the checkpoints that pass on this exact grid, and the next change. + +| map | source | checkpoints passing | next | +|---|---|---|---| +| Route 201 | decomp (Diamond) | none yet (00.02-00.04 and mart_lady passed on the image grid) | re-run them | +| Route 202 | decomp (Diamond) | none yet (00.04 passed on the image grid) | re-run 00.04; the save-spot legs grew three rows | +| Sandgem Town | decomp (Diamond) | none yet (00.04, 00.05 passed with image rows 0-6) | re-run; the Route 202 entry stop is (29,1) | +| Jubilife City | decomp (Diamond), console NPCs | none yet (00.05, 01.01, 01.06, 01.07 passed on the image grid) | re-run; re-anchor the Mart clown and the steps walk | +| Oreburgh Mine B2F | decomp (Diamond) | none yet (01.02, 01.03 passed 3x on the stretched image grid) | re-run both | +| Route 203 | decomp (Diamond) | none yet (01.06 passed on the image grid) | re-run; the row to Jubilife is 18, four sand rows | +| Route 204 South | decomp | 01.08 (1x) | more passes | +| Ravaged Path | decomp rows 30-53 | 01.09 by hand | program pass | +| Route 204 North | decomp | 01.10 (1x) | probe column 23; (12,6) marked from the console | +| Oreburgh City | decomp (pokediamond) | none yet (01.04, 01.05 run as records) | probe the Center doorstep (x 46 or 47) | +| Oreburgh Gate | decomp (pokediamond) | none yet | | +| Floaroma Town | decomp (pokediamond), the old couple from the console | 01.11 (1x, as a record) | | +| Twinleaf Town | decomp (pokediamond) | none: 00.01 replays recorded stick inputs (#1717); its lines and records are on the grid (Segment00Lines, task #22), tested offline | a new-game run of the lines, then switch 00.01 to them | +| Verity Lakefront | decomp (pokediamond) | none: 00.01 to 00.03 replay recorded stick inputs (#1717); lines and records on the grid, tested offline | the run must say which entrance tile the lake's scene leaves us on | +| Lake Verity | decomp (pokediamond) | none, and no walk: the scene carries us in and the game warps us out | none | +| Oreburgh Gym | decomp (pokediamond) | none: 01.04 walks it as a record (north until a trainer stops us), traced on the grid | a plan on it if the record ever fails | + +Rules: terrain from the decomp, people and Platinum-only edits from the console; +a route is coded only over tiles a human or a probe has walked; a map change +re-runs every checkpoint listed on it. Scenes' trigger rectangles come from the +decomp too (the events files' coord events: Diamond's binaries parsed by hand, +Platinum's JSON readable), listed in `Segment00Lines::scene_triggers()` for +00.01 to 00.03; a line into a scene must step into its rectangle on its last +tile only, which the Segment 00 tests check. The decomp comparison that found the 3/4 +rows is the 2026-10-31 report (`compare.md`, with the decoded grids); the +re-derivation of 2026-10-31 took every grid above from `devtools/maps decomp +--repo pret/pokediamond` and translated each file's named tiles with its +console anchors. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp new file mode 100644 index 0000000000..c91f67d5ea --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp @@ -0,0 +1,81 @@ +/* BDSP AutoStory - Floaroma Town tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_FloaromaTown.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace FloaromaTown{ + +using namespace Pokemon; + + +// Console: the old couple stands at (2, 25) and (3, 25) ('N'), placed from +// the 2026-10-31 walk; they are not in the DP data (a Camper and a Lass are). +// Map source: the decomp (Diamond land_data 0032 = Platinum map_data_032, +// 2026-10-31) with the objects from its events file. +// Console checks: none yet. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0032: one cell of the +// Sinnoh matrix at column 5, row 20; map_data_032 in pret/pokeplatinum), +// with the objects from its events file (zone_event narc_0404, +// events_floaroma_town.json in Platinum); BDSP keeps Diamond/Pearl's layout. +// Local (x, y) = world (x - 160, z - 640); 32 x 32 tiles. The cell above +// (column 5, row 19, land_data 0033) carries the same map header but is cut +// off from the town (its bottom rows are wall; the town's row 0 is a +// dead-end strip under them), so it is left out. +// The flower field is the west half, columns 0 to 17, rows 2 to 22; +// Diamond's data puts a Camper at (6, 10) and a Lass wandering row 5 in it. +// The old couple BDSP shows there are not in the Diamond/Pearl data: place +// them as 'N' from the console. Exits: Route 204 south through (10..12, +// 30..31) (and the one-tile gap (8, 30..31), which joins a side path on the +// route); Route 205 east at (31, 19..22). Warp tiles the player stands on +// are written as '.': (20, 11), the Flower Shop's entrance, and (2, 1), (3, +// 1) into Floaroma Meadow, where the two Galactic grunts stand ('N' wins +// there) until the Valley Windworks is cleared (flag 447). Objects, from the +// events file: +// door (16, 26) to the Pokemon Center; door (24, 26) to the south-east +// house; +// door (24, 17) to the Poke Mart; its signboard (29, 15); +// door (11, 14) to the middle house; +// Flower Shop entrance (20, 11), its signboard (17, 11) and the two berry +// patches (18, 11) and (22, 11), as '#'; +// map signpost (13, 19); +// Grunt M (2, 1), looks east, and Grunt M (3, 1), looks west, not +// trainers, hidden by flag 447; +// Camper (6, 10), looks around, not a trainer; +// Lass (23, 11), looks west, not a trainer; +// Pokemon Breeder F (19, 21), looks around, not a trainer; +// a man with Cyrus's sprite (11, 26), looks around, not a trainer, hidden +// by flag 449 (Diamond/Pearl only; whether he is there when the story +// arrives is for the console); +// Lass wanders west and east from (10, 5), columns 9 to 11, row 5: off the +// grid; +// School Kid M wanders around (16, 16), columns 15 to 17, rows 15 to 17: +// off the grid. +// No trainers. Platinum differs in one row and one person: its row 30 opens +// columns 8 to 13 where Diamond opens 8 and 10 to 12 (Route 204 North's top +// rows are '########.#...###' in both games, so Diamond's is the border BDSP +// has), and it has a Beauty at (10, 19) looking south instead of the man at +// (11, 26). +const TileGrid& grid(){ + return story_grid("FloaromaTown"); +} + +const TilePos ROUTE_204_ARRIVAL{11, 29}; +const TilePos OLD_WOMAN{3, 25}; +const TilePos OLD_MAN{2, 25}; +const TilePos POKEMON_CENTER_DOOR{16, 26}; + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h new file mode 100644 index 0000000000..43384adc6b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h @@ -0,0 +1,36 @@ +/* BDSP AutoStory - Floaroma Town tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see + * the .cpp's header for the cells, the offset and the objects. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_FloaromaTown_H +#define PokemonAutomation_PokemonBDSP_AutoStory_FloaromaTown_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace FloaromaTown{ + + +const Pokemon::TileGrid& grid(); + +// Where 01.10's walk north from Route 204 ends on the town's banner and +// saves (r248a, r251a): the path's middle column, three rows in. +extern const Pokemon::TilePos ROUTE_204_ARRIVAL; +// The old couple in the flower field, placed from the console (2026-10-31 +// hand walk and r251a: eight tiles west of the arrival, then three north +// to the tile below her); not in the DP data. +extern const Pokemon::TilePos OLD_WOMAN; +extern const Pokemon::TilePos OLD_MAN; +extern const Pokemon::TilePos POKEMON_CENTER_DOOR; + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp new file mode 100644 index 0000000000..16089d130c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp @@ -0,0 +1,113 @@ +/* BDSP AutoStory - Jubilife City tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_JubilifeCity.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace JubilifeCity{ + +using namespace Pokemon; + + +// Map source: the decomp (pret/pokediamond land_data narc_0018, 0016, 0017 +// and 0015, 2026-10-31) with the objects from its events file. Platinum +// differs only around the Global Terminal (columns 14..26, rows 30..45). +// Console checks (2026-10-30/31): the lamps (43,53) and (49,53), north from +// (52,53) to the Pokemon Center's door, the School's door from the +// Center's doorstep, the east street to Route 203 (01.06, r230a), the +// north street (01.07), and the four 00.05 people, placed from the +// console on the tiles the events file gives them. +// Status: no checkpoint has run on this grid yet. 00.05, 01.01, 01.06 and +// 01.07 passed on the colour-classified image grid it replaces (48 rows +// for 64) and must be re-run; re-check the Mart clown's tile (he wanders +// 182..184 on row 33 in Diamond) and the hand walk from the steps' top +// east to the house and north to the Center (the decomp has the plaza +// only 171..177 wide on rows 58..59). +// +// Decoded from Pokemon Diamond's collision table: cells (23..24, 4..5) of +// the Sinnoh matrix, with the objects from its events file. Local (x, y) = +// world (x - 128, z - 736); 64 x 64 tiles. The console's measurements on +// the image grid were a column east of its doors; on this grid the lamps, +// the doors and the four people all land where the console put them. +// +// Exits: south, the 3-wide neck (45..47, 61) down to Route 202; east, the +// street (rows 21..24) to Route 203; north, (42..55, 0..1) to Route 204; +// west, the Route 218 gate on rows 22..23 (its warp tiles are 'D'). Doors +// are 'D' tiles walked into from below; the Trainers' School's doorway +// (40,40) and the Global Terminal's (21,42) are warp tiles stepped onto and +// marked 'D' as well, so a plan never steps on them. The main road runs +// from the steps (46..47, 60..62) north between the lamps (43,53), (49,53) +// and on up to the north exit; the doors' row 40 is open between the School +// and the Center (43..49), and the plaza below it is rows 41..52. +// People who stand still, from the events file: the Poketch president +// (46,35) and the clown west of the TV station (36,16), the 00.05 story +// people (hidden by flags before and after); an Ace Trainer (36,25) on the +// north road's west side, a Cashier (26,42), an Expert (44,44), two kids +// (52,46), (54,46) on the plaza and a School Kid (17,55): none of these +// five has been seen on the console yet. The clown by the Mart (55,33) and +// the one by the Poketch Company (15,18) wander three tiles in Diamond but +// stood still on the console (00.05, three runs): on the grid at their +// spawn tiles. Wanderers left off: an Ace Trainer along row 20 (21..23), +// one along row 21 (45..47), a Twin around (33,18), a School Kid on column +// 51 (rows 33..35), a Pokefan around (41,30). Rowan and the grunts at the +// north exit, the Collectors and Dawn are hidden by story flags. +const TileGrid& grid(){ + return story_grid("JubilifeCity"); +} + +// Checked on the console (2026-10-30, CFR "walk"): 00.05's save stands +// below the steps, against the wall just east of them (the banner reads +// Jubilife City). West along that wall does not stop at the steps (it runs +// to the trees); a tile west, then north, climbs them. North up the main +// road from the steps passes the lamps (43,53), (49,53) and does not stop +// before the north exit. From the lamps' row, west stops at the house at +// (37..42, 47..52) and east at the house at (53..57, 49..56); north from +// (52,53) stops in front of the Pokemon Center. The steps are columns +// 45..47 of row 61; the save stands at (48,62) against (48,61), and the +// tile west then north puts us on column 47, a few rows up. On this grid +// east from rows 58..60 stops at column 49 and north from there at the lamp +// (49,53), not the Center: the climb must end on row 57 or above, or BDSP's +// plaza is wider than Diamond's there (re-check on the console). +const std::vector& up_the_steps(){ + static const std::vector tiles{{46, 58}, {47, 58}, {46, 59}, {47, 59}, {46, 60}, {47, 60}}; + return tiles; +} + +// The School's doorway is a warp tile stepped onto from (40,41); the +// Center's door is walked into from (52,41). On the console (2026-10-30) +// eleven one-tile holds west from the Center's doorstep put us under the +// School's door: the doorstep was the tile east of the door's column, as +// story_door_front() allows. +const TilePos TRAINERS_SCHOOL_DOOR{40, 40}; +const TilePos POKEMON_CENTER_DOOR{52, 40}; +const TilePos TV_STATION_DOOR{36, 15}; + +// On the main road, five rows north of the School's and the Center's +// doors' row and six columns west of the Center's door. Talked to from the +// east, facing west (also works from the south). +const TilePos POKETCH_PRESIDENT{46, 35}; +// Below the Poke Mart's planters, where the road meets the plaza: his spawn +// tile; he wanders a tile either side in Diamond, and the console had him +// a tile east of it. +const TilePos CLOWN_MART{55, 33}; +// West of the TV station door, right below it. +const TilePos CLOWN_TV_STATION{36, 16}; +// East of the Poketch Company's sign, a row below it. Talked to from the +// south on the console; from the east a walk west along row 18 stops right +// beside him. +const TilePos CLOWN_POKETCH_COMPANY{15, 18}; + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h new file mode 100644 index 0000000000..941b89ff77 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h @@ -0,0 +1,45 @@ +/* BDSP AutoStory - Jubilife City tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Jubilife City as a tile grid, from the Diamond decompilation's collision + * table, with the places and people of checkpoint 00.05. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_JubilifeCity_H +#define PokemonAutomation_PokemonBDSP_AutoStory_JubilifeCity_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace JubilifeCity{ + + +const Pokemon::TileGrid& grid(); + +// Where we may stand after climbing the steps from where 00.05 starts: +// below them, against the wall just east of them, then a tile west and +// about two tiles north. +const std::vector& up_the_steps(); + +// Doors: walk north from the tile below to enter. +extern const Pokemon::TilePos TRAINERS_SCHOOL_DOOR; +extern const Pokemon::TilePos POKEMON_CENTER_DOOR; +extern const Pokemon::TilePos TV_STATION_DOOR; + +// The Poketch Company president and the three coupon clowns. +extern const Pokemon::TilePos POKETCH_PRESIDENT; +extern const Pokemon::TilePos CLOWN_MART; +extern const Pokemon::TilePos CLOWN_TV_STATION; +extern const Pokemon::TilePos CLOWN_POKETCH_COMPANY; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp new file mode 100644 index 0000000000..3198d18e18 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp @@ -0,0 +1,66 @@ +/* BDSP AutoStory - Lake Verity tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_LakeVerity.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace LakeVerity{ + +using namespace Pokemon; + + +// Map source: the decomp (Diamond land_data 0512 = Platinum map_data_541, +// 2026-10-31) with the objects from its events file. +// Console checks: none yet. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0512: the cell at column +// 1, row 1 of the lake's own matrix 101, which is 3 x 2 cells; map_data_541 +// of matrix 102 in pret/pokeplatinum), with the objects from its events file +// (zone_event narc_0298, events_lake_verity.json in Platinum); BDSP keeps +// Diamond/Pearl's layout. Local (x, y) = world (x - 32, z - 32) in that +// matrix; 32 x 32 tiles. Only this cell is reachable on foot: the shore +// where the starter scene plays, columns 10 to 25, rows 4 to 22. The lake is +// '#'; the tiles at (0..6, 4..9) are shallow water (puddle, behaviour 0x16), +// walkable in the data but closed in by the lake. The west shore with TM38 +// (cells to the west) needs Surf. +// Entrance: the warp tiles (14, 22) and (15, 22), arrived on from Verity +// Lakefront, written as '.'; walking south off them leaves. The scene's +// actors are hidden-flag objects, drawn where the events file puts them +// because that is where the walk ends: Rowan and the briefcase on (16, 11) +// and the player's counterpart on (17, 11), at the water's edge. Objects, +// from the events file: +// Prof. Rowan (16, 11), looks north, hidden by flag 403; the briefcase on +// the same tile, hidden by flag 404; +// the counterpart (Dawn/Lucas, object "Var 0") (17, 11), looks north, +// hidden by flag 434; +// Starly (16, 19), looks north, hidden by flag 429, drawn as 'N' (a scene +// actor on open ground); +// Starly (25, 11), looks west, hidden by flag 429, perched on a blocked +// tile: stays '#'; +// Barry (15, 22), looks north, hidden by flag 436, on the entrance warp +// tile: '.' wins; +// no one wanders here, and no trainers. +// Platinum differs: it stages its scene elsewhere (Rowan (21, 7), the +// counterpart (22, 6), Mars (23, 6), four Galactic grunts with sight 4 to 6, +// no Starly or Barry), walls off the puddle tiles at (0..6, 4..9) and opens +// a path to the Verity Cavern warp at (0, 0). The shore, columns 10 to 25, +// decodes the same tile for tile. Diamond keeps its Galactic version as a +// separate map (MAP_LAKE_VERITY_GALACTIC), reached from the same Lakefront +// warp tiles. +const TileGrid& grid(){ + return story_grid("LakeVerity"); +} + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h new file mode 100644 index 0000000000..a5eb838e8f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Lake Verity tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see + * the .cpp's header for the cells, the offset and the objects. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_LakeVerity_H +#define PokemonAutomation_PokemonBDSP_AutoStory_LakeVerity_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace LakeVerity{ + + +const Pokemon::TileGrid& grid(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp new file mode 100644 index 0000000000..0b7a20d966 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp @@ -0,0 +1,115 @@ +/* BDSP AutoStory - Map grids + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonBDSP_AutoStory_MapGrids.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::MapData; +using Pokemon::TileGrid; +using Pokemon::TileKind; +using Pokemon::TilePos; +using Pokemon::TileType; + + +namespace{ + +std::optional tile_type_of(TileKind kind){ + switch (kind){ + case TileKind::WALL: return TileType::BLOCKED; + case TileKind::OPEN: return TileType::WALKABLE; + case TileKind::TALL_GRASS: return TileType::TALL_GRASS; + case TileKind::LEDGE_SOUTH: return TileType::LEDGE; + case TileKind::DOOR: return TileType::DOOR; + case TileKind::SIGN: return TileType::SIGN; + default: return std::nullopt; + } +} + +} + +TileGrid tile_grid_from_map(const MapData& map){ + std::vector rows; + for (int y = 0; y < map.tiles.height; y++){ + std::string row; + for (int x = 0; x < map.tiles.width; x++){ + const TileKind kind = map.tiles.at(TilePos{x, y}); + const std::optional type = tile_type_of(kind); + if (!type){ + throw ParseException(std::format( + "{}: glyph '{}' at {} has no BDSP tile.", map.name, Pokemon::glyph_of(kind), Pokemon::to_string(TilePos{x, y}) + )); + } + row += Pokemon::tile_char(*type); + } + rows.push_back(std::move(row)); + } + for (const Pokemon::MapObject& object : map.objects){ + if (object.kind != Pokemon::ObjectKind::NPC || object.wander){ + throw ParseException(std::format("{}: object {} is not a person standing still.", map.name, object.name)); + } + rows[object.y][object.x] = Pokemon::tile_char(TileType::NPC); + } + return TileGrid(rows); +} + +std::optional grid_difference(const TileGrid& here, const TileGrid& there){ + if (here.width() != there.width() || here.height() != there.height()){ + return std::format("{} x {} here, {} x {} there", here.width(), here.height(), there.width(), there.height()); + } + for (int y = 0; y < here.height(); y++){ + for (int x = 0; x < here.width(); x++){ + const TilePos pos{x, y}; + if (here.at(pos) != there.at(pos)){ + return std::format( + "{}: '{}' here, '{}' there", + Pokemon::to_string(pos), Pokemon::tile_char(here.at(pos)), Pokemon::tile_char(there.at(pos)) + ); + } + } + } + return std::nullopt; +} + + +namespace{ + +const std::map& story_grids(){ + static const std::map grids = []{ + std::map parsed; + for (const auto& [name, json] : bdsp_map_json()){ + const MapData map = Pokemon::parse_map(parse_json(json), name + ".json"); + if (map.name != name){ + throw ParseException(std::format("{}.json: name is \"{}\".", name, map.name)); + } + parsed.emplace(name, tile_grid_from_map(map)); + } + return parsed; + }(); + return grids; +} + +} + +const TileGrid& story_grid(const std::string& name){ + const std::map& grids = story_grids(); + if (auto iter = grids.find(name); iter != grids.end()){ + return iter->second; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No BDSP story map named \"" + name + "\"."); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h new file mode 100644 index 0000000000..41f0d61d64 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h @@ -0,0 +1,52 @@ +/* BDSP AutoStory - Map grids + * + * From: https://github.com/PokemonAutomation/ + * + * The story's maps are JSON files in the shared map schema + * (Pokemon_MapData.h), PokemonBDSP/Programs/AutoStory/Maps, built into the + * program by CMake, read with the shared loader and turned into the tile + * grids the planner walks. Each map's X::grid() returns story_grid("X"). + * + * TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonBDSP/Maps) when ready + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_MapGrids_H +#define PokemonAutomation_PokemonBDSP_AutoStory_MapGrids_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_MapData.h" +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// (name, JSON text) of each map in PokemonBDSP/Programs/AutoStory/Maps/, +// built into the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). +const std::vector>& bdsp_map_json(); + +// A map's tiles as a tile grid: walls, open ground, tall grass, south +// ledges, doors and signs; a standing person ("npc" object) is an NPC tile. +// Throws ParseException, naming the map, for what BDSP's grids have no +// tile for (water, ledges other than south, items, wanderers). +Pokemon::TileGrid tile_grid_from_map(const Pokemon::MapData& map); + +// "(x, y): 'N' here, '.' there", or nothing when the grids are the same +// size and equal cell for cell. +std::optional grid_difference(const Pokemon::TileGrid& here, const Pokemon::TileGrid& there); + +// The grid of the map `name`, read from bdsp_map_json() once. Throws +// InternalProgramError for a name it does not have. +const Pokemon::TileGrid& story_grid(const std::string& name); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp new file mode 100644 index 0000000000..781af0c643 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp @@ -0,0 +1,92 @@ +/* BDSP AutoStory - Oreburgh City tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_OreburghCity.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghCity{ + +using namespace Pokemon; + + +// Map source: the decomp (Diamond land_data 0022, 0023, 0175, 0024 = +// Platinum map_data_022/023/175/024, 2026-10-31) with the objects from +// its events file. +// Console checks: none yet. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0022, 0023, 0175 and +// 0024: four cells of the Sinnoh matrix, columns 8 and 9, rows 23 and 24; +// the same cells are map_data_022, 023, 175 and 024 in pret/pokeplatinum), +// with the objects from its events file (zone_event narc_0044, +// events_oreburgh_city.json in Platinum); BDSP keeps Diamond/Pearl's layout. +// Local (x, y) = world (x - 256, z - 736); 64 x 64 tiles. The town sits on +// the upper rows (10 to 26); row 27 is the cliff, and the stairs down it are +// the road at columns 44 to 48 (rows 27 to 43), which opens into the mine +// yard at row 44. The two one-tile stubs south of the gym, (24, 27..29) and +// (31, 27..29), and the pocket at (35..42, 28..29) are walkable in the data +// but closed off: dead ends, not stairs. +// Exits: Oreburgh Gate west through the cave mouth (1, 13), entered from the +// warp tile (2, 13); Route 207 north up columns 41 to 46 (rows 0 to 9); the +// Mine south over the warp tiles (44..48, 59), walked onto heading south. +// Warp tiles the player stands on are written as '.': (2, 13), (44..48, 59), +// and (49, 11), the Mining Museum's entrance. Objects, from the events file: +// door (26, 20) to the Gym; its signpost (22, 20); +// door (47, 20) to the Pokemon Center; +// door (29, 10) to the Poke Mart; doors (15, 10) and (22, 10) to the +// north-west and north houses; door (17, 20) to the west house; door (37, +// 16) to the middle house; door (56, 28) to the east house; door (51, 36) +// to the south house; +// map signposts (4, 11) and (44, 1); signboards (45, 12) and (45, 56); +// steam vents (9, 26), (11, 26), (13, 26), (60, 52), (60, 53), objects +// that block, as '#'; +// Youngster (10, 16), looks north, not a trainer; +// Worker (11, 25), looks south and west, not a trainer; +// Hiker wanders around (47, 26), columns 46 to 48, rows 25 to 27: off the +// grid; +// School Kid F wanders around (32, 18), column 32, rows 16 to 20: off the +// grid; +// Guitarist wanders around (23, 13), columns 22 to 24, rows 10 to 16: off +// the grid; +// Camper walks back and forth from (36, 19), columns 33 to 39, row 19: off +// the grid; +// Battle Girl wanders around (36, 23), column 36, rows 21 to 25: off the +// grid; +// Pokefan F wanders around (45, 38), column 45, rows 37 to 39: off the +// grid; +// Worker wanders around (37, 39), columns 36 to 38, rows 38 to 40: off the +// grid; +// Worker wanders around (50, 41), column 50, rows 38 to 44: off the grid; +// Worker wanders around (56, 57), columns 55 to 57, rows 54 to 60: off the +// grid; +// Machop wanders around (55, 56), columns 53 to 57, rows 54 to 58: off the +// grid; +// Barry (26, 21), in front of the Gym door, "wander" with no range (hidden +// by flag 410 once the story moves on): off the grid, listed so the route +// knows he may stand there. +// None of the people here is a trainer. Platinum (pret/pokeplatinum) decodes +// the same terrain tile for tile; it adds items on the ground at (35, 37) +// and (39, 38), a Battle Girl at (51, 21), a Machop at (56, 46) and a +// wandering Machop around (35, 45), none of which Diamond has. +const TileGrid& grid(){ + return story_grid("OreburghCity"); +} + +const TilePos POKEMON_CENTER_DOOR{47, 20}; +const TilePos POKEMON_CENTER_DOORSTEP{46, 21}; +const TilePos GYM_DOOR{26, 20}; +const TilePos GYM_DOORSTEP{26, 21}; +const TilePos GATE_MOUTH{1, 13}; + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h new file mode 100644 index 0000000000..7a3f66901b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h @@ -0,0 +1,37 @@ +/* BDSP AutoStory - Oreburgh City tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see + * the .cpp's header for the cells, the offset and the objects. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghCity_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghCity_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghCity{ + + +const Pokemon::TileGrid& grid(); + +// Doors are the tiles walked into. The Center's doorstep: the decomp's door +// tile is (47, 20), and 20 D-pad taps west from the doorstep stand under +// the Gym's door (26, 20) on the console (r204 to r215), which puts the +// doorstep at x 46: one of the two is a tile off, a probe decides. +extern const Pokemon::TilePos POKEMON_CENTER_DOOR; +extern const Pokemon::TilePos POKEMON_CENTER_DOORSTEP; +extern const Pokemon::TilePos GYM_DOOR; +extern const Pokemon::TilePos GYM_DOORSTEP; +// The Oreburgh Gate's east mouth, walked into heading west from (2, 13). +extern const Pokemon::TilePos GATE_MOUTH; + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp new file mode 100644 index 0000000000..310728cda5 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp @@ -0,0 +1,51 @@ +/* BDSP AutoStory - Oreburgh Gate 1F tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_OreburghGate.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghGate{ + +using namespace Pokemon; + + +// Map source: the decomp (Diamond land_data 0418 = Platinum map_data_441, +// 2026-10-31) with the objects from its events file. +// Console checks: none yet. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0418: one cell, the only +// one of matrix 003, at column 0, row 0; map_data_441 in pret/pokeplatinum), +// with the objects from its events file (zone_event narc_0250, +// events_oreburgh_gate_1f.json in Platinum); BDSP keeps Diamond/Pearl's +// layout. Local (x, y) = world (x - 0, z - 0) in the cave's own matrix; 32 x +// 32 tiles. The cave floor is '.'; the rocks Rock Smash breaks are '#' +// (eight of them, each hidden once smashed). +// Exits: the warp tiles the player stands on are written as '.': (4, 22) +// leaves west to Route 203 and (27, 22) east to Oreburgh City; the cave +// mouths behind them, (3, 22) and (28, 22), are 'D'. (20, 5) is the stairs +// down to B1F (a warp tile too). Objects, from the events file: +// Picnicker Diana (24, 21), looks south, sees 3; +// Camper Curtis (17, 25), looks north, sees 3; +// Hiker (7, 20), looks south, not a trainer (the Rock Smash HM); +// rocks (19, 6), (14, 4), (12, 10), (11, 11), (11, 25), (13, 26), (15, +// 26), (25, 24), as '#'. +// The two trainers face the row-22 corridor from either side: Diana sees +// (24, 22..24) and Curtis (17, 22..24). Platinum decodes this cave +// identically, terrain and objects. +const TileGrid& grid(){ + return story_grid("OreburghGate"); +} + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h new file mode 100644 index 0000000000..f0e2984230 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Oreburgh Gate tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see + * the .cpp's header for the cells, the offset and the objects. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghGate_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghGate_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghGate{ + + +const Pokemon::TileGrid& grid(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp new file mode 100644 index 0000000000..915bdc1474 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp @@ -0,0 +1,61 @@ +/* BDSP AutoStory - Oreburgh Gym tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_OreburghGym.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghGym{ + +using namespace Pokemon; + + +// Map source: the decomp (Diamond land_data 0228, 2026-10-31) with the +// objects from its events file. +// Console checks: none yet. 01.04 walks it as a record (north until a +// trainer stops us), not as a plan. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0228: the only cell of +// matrix 113, at column 0, row 0; MAP_OREBURGH_GYM in +// include/constants/maps.h), with the objects from its events file +// (zone_event narc_0046, events_oreburgh_gym.json in Platinum); BDSP keeps +// Diamond/Pearl's layout. Local (x, y) = world (x - 0, z - 0) in the Gym's +// own matrix; 32 x 32 tiles, of which the floor is columns 1 to 10, rows 3 +// to 24. The tiers' edges and the pillars are '#'. +// Door: (5, 24), walked into heading south to leave; coming in puts us on +// (5, 23). Column 5 runs straight from there to Roark on row 3: the Gym is +// walked north up the middle. Objects, from the events file: +// Roark (5, 3), looks south; +// Gym Guide (6, 23), looks south, beside the entrance; +// Youngster (4, 18), looks east, sees 3: (5..7, 18); +// Youngster (7, 11), looks west, sees 4: (3..6, 11); +// the two wall signs, (3, 23) and (7, 23), read from row 23: 'S'. +// Both trainers see the middle column, so a walk north from the entrance +// is stopped twice before Roark (01.04's record). +const TileGrid& grid(){ + return story_grid("OreburghGym"); +} + +const TilePos ENTRANCE{5, 23}; +const TilePos ROARK{5, 3}; + +std::vector trainer_sights(){ + return { + {"Youngster (first tier)", {4, 18}, Direction::EAST, 3}, + {"Youngster (second tier)", {7, 11}, Direction::WEST, 4}, + }; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h new file mode 100644 index 0000000000..2cb6dc8489 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h @@ -0,0 +1,38 @@ +/* BDSP AutoStory - Oreburgh Gym tiles + * + * From: https://github.com/PokemonAutomation/ + * + * The Gym's inside, decoded from the Pokemon Diamond decompilation + * (pret/pokediamond); see the .cpp's header for the cell, the offset and + * the objects. For checkpoint 01.04's walk up to Roark. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghGym_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghGym_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghGym{ + + +const Pokemon::TileGrid& grid(); + +// Where coming in through the door puts us: the tile above it, beside the +// Gym Guide. Roark stands at the top of the same column. +extern const Pokemon::TilePos ENTRANCE; +extern const Pokemon::TilePos ROARK; + +// The two Youngsters, who face the column up the middle from either side: +// walking north from the entrance meets both. +std::vector trainer_sights(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp new file mode 100644 index 0000000000..53e2d1dd6d --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp @@ -0,0 +1,65 @@ +/* BDSP AutoStory - Oreburgh Mine tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_OreburghMine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghMine{ + +using namespace Pokemon; + + +// Map source: the decomp (pret/pokediamond land_data narc_0314, matrix 006; +// 2026-10-31) with the objects from its events file; Platinum's +// map_data_337 is the same. +// Console checks (2026-10-28): the corridor's rocks zigzag a row at a time, +// the room's second row passes under the worker on the first, Roark +// stands a row above the bottom row between two rocks; the walk north +// from the corridor's corner reached the entrance hall (r99). +// Status: no checkpoint has run on this grid yet. 01.02 and 01.03 passed +// 3x on the stretched image grid it replaces, which had every row one +// lower, the top corridor a row short, the room's second row blocked +// and no ledge in the west corridor; re-run both. +// +// Decoded from Pokemon Diamond's collision table: the one cell of matrix +// 006, with the objects from its events file. Local (x, y) = world (x, z); +// 32 x 32 tiles. The way up to the entrance hall is the warp tile (15,1), +// marked 'D': stepping onto it leaves the room. The console walked north +// into the hall from column 14 (r99), where this table has the way up only +// at column 15: a stick hold drifts, or BDSP's stairs are wider. +// The corridor from the top (13..17, 2..6) zigzags down to the room's first +// row (15); the room's second row (17) is open from 2 to 29 and passes +// under the worker and his Machop on the first; the coal block fills +// (7..24, 18..25) with the corridors either side; the west corridor has a +// ledge (2..4, 19), crossed southward only; the bottom rows 28..29 run +// under the block. +// Objects, from the events file: Roark (18,28), between two rocks (17,28) +// and (19,28); workers who stand still at (8,28) looking north, (26,20) +// looking west and (21,15) with Machop at (20,15) and (27,15); Poke Balls +// at (4,28) and (26,24), walls until picked up. A Machop wanders along row +// 28, columns 11..13, and is left off the grid. +const TileGrid& grid(){ + return story_grid("OreburghMine"); +} + +// The first open row below the warp tile, where the walk in from the hall +// leaves us (or the row below: the plan's first legs run to walls and meet). +const std::vector& corridor_top(){ + static const std::vector tiles{{14, 2}, {15, 2}, {16, 2}}; + return tiles; +} + +const TilePos ROARK{18, 28}; +const TilePos CORRIDOR_EXIT_START{14, 10}; + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h new file mode 100644 index 0000000000..4dc823b486 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h @@ -0,0 +1,39 @@ +/* BDSP AutoStory - Oreburgh Mine tiles + * + * From: https://github.com/PokemonAutomation/ + * + * The Oreburgh Mine's coal room (Bulbapedia's "B2F") as a tile grid, with + * Roark, for checkpoint 01.03. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghMine_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghMine_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace OreburghMine{ + + +const Pokemon::TileGrid& grid(); + +// Where the walk in from the entrance hall leaves us: the top of the rocky +// corridor, the first open row below the warp tile. +const std::vector& corridor_top(); + +// Roark, between two rocks a row above the room's bottom row. Talked to from +// the tile below him, facing north. +extern const Pokemon::TilePos ROARK; +// The corridor's corner a wall-to-wall route ends on, below a straight +// walk north out into the entrance hall. +extern const Pokemon::TilePos CORRIDOR_EXIT_START; + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp new file mode 100644 index 0000000000..1593266d18 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp @@ -0,0 +1,47 @@ +/* BDSP AutoStory - Plan Costs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_PlanCosts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::RobustPlanCosts; + + +RobustPlanCosts route_plan_costs(){ + RobustPlanCosts costs; + costs.exact_open_tiles = costs.max_open_tiles; + costs.per_open_tile = 2; + costs.leg_not_at_wall = 6; + return costs; +} + +RobustPlanCosts waypoint_plan_costs(){ + RobustPlanCosts costs; + costs.exact_open_tiles = costs.max_open_tiles; + costs.per_open_tile = 0; + costs.leg_not_at_wall = 0; + return costs; +} + +RobustPlanCosts town_plan_costs(){ + RobustPlanCosts costs; + // A tile's hold moves exactly a tile; a longer open leg may end a tile + // either way ("south 5" went 6 in r134a), so the plan ends on a wall. + costs.exact_open_tiles = 1; + costs.open_error_per = 8; + costs.leg_not_at_wall = 6; + costs.per_open_tile = 2; + return costs; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h new file mode 100644 index 0000000000..825ef24312 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h @@ -0,0 +1,46 @@ +/* BDSP AutoStory - Plan Costs + * + * From: https://github.com/PokemonAutomation/ + * + * The costs the story's walks are planned with on the BDSP maps + * (Pokemon::plan_robust_route()), apart from the walker, so the map + * tests plan each walk the way the program does. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlanCosts_H +#define PokemonAutomation_PokemonBDSP_AutoStory_PlanCosts_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The default: open legs are whole tiles on the D-pad, so they land exactly +// at any length; a wall at a leg's end is still worth a little, and each +// open tile a little more. +Pokemon::RobustPlanCosts route_plan_costs(); + +// Between two corners of a walked line: whole tiles on the D-pad land +// exactly, so an open leg costs nothing extra and the straight leg to the +// corner beats a run to a wall and a tap back (r244a: "west 10 to the +// wall, east 1" through the wandering Youngster lost the count; "west 9" +// in taps keeps it). +Pokemon::RobustPlanCosts waypoint_plan_costs(); + +// In town: a one-tile step lands exactly, a short open leg a tile either +// way, and both cost little more than a leg to a wall, so a plan steps a +// tile across and walks straight through a gap rather than going round the +// town to end every leg on a wall (Sandgem: 13 legs, r127a and r128b +// walked into the Lab and the Mart). Pair it with a check at the end (a +// sign read) for the timed legs. +Pokemon::RobustPlanCosts town_plan_costs(); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp new file mode 100644 index 0000000000..500bc58358 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp @@ -0,0 +1,62 @@ +/* BDSP AutoStory - Ravaged Path tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_RavagedPath.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RavagedPath{ + +using namespace Pokemon; + + +// Map source: rows 30 to 53 from the decomp (map_data_435/436, 2026-10-31); +// the rows above from the DP image, unused by any route. +// Console checks: entrance (19,50), the stairs, the three-wide corridor, the +// rocks, the east end and the exit tile (2026-10-31 probes). +// Status: 01.09 reaches the exit by hand; no program pass yet. +// +// Rows 30 to 53 are decoded from Pokemon Platinum's collision table for +// this map (the pret/pokeplatinum decompilation, land data 435/436 of map +// matrix 051) with the objects from its events file; BDSP keeps the layout. +// Water and the items on the ground are '#'; the smashable rocks are '#' +// too and listed in rocks(). Checked on the console 2026-10-31 (r235b and +// D-pad probes): in from the south door onto (19, 50), up the stairs +// (rows 45 to 47, columns 18 to 20) and north to the wall at row 39; the +// corridor is three wide up to row 41 and opens east on rows 42 to 44, +// with the rocks at (22, 42) and (22, 43), the Potion ball at (22, 44) and +// a rock at (23, 44). Rows 0 to 29 are still the hand trace from +// Bulbapedia's Ravaged_Path_DP.png (stretched from 528x672 to 528x864), with +// '?' where the untraced west chambers continue; nothing we walk is there. +const TileGrid& grid(){ + return story_grid("RavagedPath"); +} + +const std::vector& rocks(){ + static const std::vector tiles{ + {11, 36}, {7, 37}, {12, 37}, {8, 38}, {10, 38}, {10, 39}, {13, 39}, + {7, 40}, {9, 40}, {17, 40}, {12, 41}, {22, 42}, {22, 43}, {23, 44}, + }; + return tiles; +} + +const TilePos ENTRANCE{19, 50}; + +const std::vector& before_rocks(){ + static const std::vector tiles{{21, 42}, {21, 43}}; + return tiles; +} + +const TilePos EAST_END{29, 44}; +const TilePos ABOVE_EXIT{28, 44}; + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h new file mode 100644 index 0000000000..4f03dacf39 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h @@ -0,0 +1,47 @@ +/* BDSP AutoStory - Ravaged Path tiles + * + * From: https://github.com/PokemonAutomation/ + * + * The Ravaged Path (the cave on Route 204) as a tile grid, for checkpoint + * 01.05: from its south door, where Route 204's south half enters, east + * along its lower corridor to the door out onto Route 204's north half. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RavagedPath_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RavagedPath_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RavagedPath{ + + +// With every Rock Smash rock in place (blocked). +const Pokemon::TileGrid& grid(); + +// The Rock Smash rocks of the traced part, blocked in grid(). Each breaks +// for good once smashed, so a plan after a smash opens that tile. +const std::vector& rocks(); + +// Where walking in from Route 204's south half leaves us: the tile above the +// south door, at the foot of the room below the stairs. +extern const Pokemon::TilePos ENTRANCE; +// The tiles west of the two rocks across the lower corridor: from either, +// facing east, A offers Rock Smash, and the corridor is open to its east end. +const std::vector& before_rocks(); +// The corridor's east end on its bottom row, where walls stop a walk east +// and south: a route can end here, and nowhere else near the way out. +extern const Pokemon::TilePos EAST_END; +// The tile above the door out onto Route 204's north half, a tile west of +// EAST_END: walk south. +extern const Pokemon::TilePos ABOVE_EXIT; + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp new file mode 100644 index 0000000000..2a79840580 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp @@ -0,0 +1,82 @@ +/* BDSP AutoStory - Route 201 tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_Route201.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route201{ + +using namespace Pokemon; + + +// Map source: the decomp (pret/pokediamond land_data narc_0005 and +// narc_0006, 2026-10-31) with the objects from its events file; +// Platinum's map_data_005/006 have the same terrain. +// Console checks: the border sign read from (54,4) facing east, row 3 open +// east of the grass to Sandgem's fence, row 5 to Sandgem without a stop, +// the Potion lady on row 3 (2026-10-28 to 30, CFR "walk"). +// Status: no checkpoint has run on this grid yet. 00.02 to 00.04 and the +// mart_lady checkpoint passed on the image-traced grid it replaces (3/4 +// of a tile per row) and must be re-run. +// +// Decoded from Pokemon Diamond's collision table: cells (26,3) and (26,4) +// of the Sinnoh matrix, with the objects from its events file. Local (x, y) +// = world (x - 96, z - 839); 64 x 25 tiles, rows 0..2 are padding. The +// columns are the ones the image-traced grid had (its anchors matched the +// decomp exactly); the rows are the game's: the image gave 20 rows for 25. +// Sandgem Town's grid joins at column 64, row -3 (its front row is row 4). +// +// Edges: west, rows 6..7 and 11 (Lake Verity, off the map); south, the +// Twinleaf gap (14..17, 21..24); east, rows 3..6, into Sandgem. Ledges: +// row 12 (0..3 and 8..31) and (53..57, 9) in the north-east; both are +// jumped southward only. The north-east grass (42..52, 3..6) is four rows +// deep and its tree stub (51..52) stands on rows 7..12; the middle grass +// (20..29, 13..16) four rows; the south-east grass (42..57, 18) and +// (46..57, 19..20). +// Objects, from the events file: the signs (55,4) to Sandgem (BORDER_SIGN), +// (13,17) to Twinleaf and the Trainer Tips sign (40,12); a School Kid who +// stands at (57,8) looking west (not yet seen on the console). Route 201 +// has no trainers and no items on the ground. Wanderers, left off the grid: +// a Breeder around (27,15), columns 26..28, rows 14..16; a Lass along row +// 16, columns 44..48. The Poke Mart lady, who gives 10 Potions, stands +// still at (44,3) in Diamond's events file and on the console (the user, +// 2026-11-01): left off the grid, since her talk is walked to, not planned +// (r113a..r120a missed her by the walk, not by her moving). Rowan, Barry +// and the briefcase by the lake are hidden by story flags and left off. +const TileGrid& grid(){ + return story_grid("Route201"); +} + + +// The arrow sign to Sandgem Town, world (151,843), on the row of Sandgem's +// doors (its row 7). Checked on the console (2026-10-30, CFR "walk"): a row +// south of the lady's row (row 3), east stops at the sign's west side and A +// reads "Route 201 -> Sandgem Town" (a green box); north from there is one +// row, to row 3. Row 3 runs on east past the sign's north side to the Lab's +// fence. Row 5, the path, runs from the grass's west edge to Sandgem without +// a stop. +const TilePos BORDER_SIGN{55, 4}; +// Her spawn tile in Diamond is (44,3), the east end of the top grass row. +// On the console (by hand, then through the Lab Console; 99715d5d6 and +// f823453e9 on bdsp/new-game-intro-v2) she stood at (43,3), and walking +// west along row 3 from the trees at its east end stopped at (44,3), facing +// her; her lines need one A each, 1.5 s apart. r113a..r120a +// missed her talk walking to her, not because she moved. +// Checked on the console (2026-10-30, CFR "walk"), twice: from the grass's +// west edge on row 5, north stops at the trees 2 rows up, and east from +// there stops at her. r135a missed her walking west along row 4. +const TilePos POTION_GIVER{43, 3}; +const TilePos POTION_GIVER_TALK_FROM{44, 3}; + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h new file mode 100644 index 0000000000..24481753bf --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h @@ -0,0 +1,37 @@ +/* BDSP AutoStory - Route 201 tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Route 201 (Twinleaf Town to Sandgem Town) as a tile grid, from the + * Diamond decompilation's collision table; BDSP keeps DP's tile layout. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route201_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Route201_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route201{ + + +const Pokemon::TileGrid& grid(); + +// The sign by the Sandgem Town border, at the east end of the route. +extern const Pokemon::TilePos BORDER_SIGN; +// The Poke Mart lady, who gives 10 Potions: at the west end of the top +// grass row. Not on the grid: she turns and may wander. +extern const Pokemon::TilePos POTION_GIVER; +// East of her: walking west along her row from the open ground east of the +// grass stops here, facing her. +extern const Pokemon::TilePos POTION_GIVER_TALK_FROM; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp new file mode 100644 index 0000000000..9bb6b1a2a3 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp @@ -0,0 +1,101 @@ +/* BDSP AutoStory - Route 202 tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_Route202.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route202{ + +using namespace Pokemon; + + +// Map source: the decomp (pret/pokediamond land_data narc_0014, with the +// margins from narc_0006, 0007 and 0173; 2026-10-31) and the objects +// from its events file; Platinum's map_data_014 has the same terrain. +// Console checks: the player under the south ledge at (22,24) beside the +// trees at (21,24), the sign a row below at (24,25), the save spot +// (30,24) against the east trees, Natalie's challenge at (22,22), east +// along the row above the ledge stops at column 30 and column 30 runs +// north to row 4 (r75), the catch spot's walls (2026-10-29/30); trees, +// not grass, at (15..20, 28..29) below the catch patch (r253: west +// along row 29 stopped at column 21, beside the trees); a tree at +// (21, 30), south of the pocket at (21, 29) where the catch's save +// loads (r254: south from there was blocked at once). +// Status: no checkpoint has run on this grid yet. 00.04 passed on the +// image-traced grid it replaces (26 rows for 32) and must be re-run; +// its legs south of the catch spot are three rows longer here. +// +// Decoded from Pokemon Diamond's collision table: cell (25,5) of the Sinnoh +// matrix, with the objects from its events file. Local (x, y) = world +// (x - 159, z - 800); 36 x 32 tiles, the whole cell, so the grid's edges +// are where the game changes its location banner. The columns are the ones +// the image-traced grid had (its ledges, tree pillars and signs matched the +// decomp exactly); the rows are the game's: the image gave 26 rows for 32. +// Sandgem Town's grid starts on the row below row 31, at column 1. +// +// Exits: north, the gap (11..18, 0) to Jubilife City (EXIT_JUBILIFE in its +// middle); south, (21..30, 31) into Sandgem, where the road narrows to +// 25..30 for two rows. Ledges: row 10 (9..13 and +// 22..27) and row 23 (9..13 and 22..30), jumped southward only. The east +// wall is column 33 from row 10 to 20, column 32 on row 21 and column 31 on +// row 22, the row right above the south ledge: east along that row stops at +// column 30 (r75), and column 30 is open north from there to row 4 under +// Logan's row. +// Objects, from the events file: three trainers who stand still, Youngster +// Tristan (7,13), Lass Natalie (22,18) and Youngster Logan (26,4), all +// facing south, with the sight ranges the events give; a Potion ball (3,6), +// a wall until picked up; the signs (17,4) to Jubilife, (15,16) Trainer Tips +// and (24,25) to Sandgem. BDSP has trees where Diamond's catch patch has +// its two bottom rows, (15..20, 28..29): the console's patch is three rows +// between tree rows, as the image-traced grid had it. A Youngster who is not a trainer wanders along row +// 8, columns 9..11, and is left off the grid (the image-traced grid had him +// as a fourth trainer facing east). Dawn's tile (15,27) is hidden by a +// story flag. +const TileGrid& grid(){ + return story_grid("Route202"); +} + + +// Where 00.03's save after the catch stands: the bottom row of the +// tall-grass patch at (15..20, 25..27), world (178,827). On the console the +// sign at (24,25) is 5 columns right and 2 rows up, walking east stops at +// the trees after 11 tiles and north at the trees after 2; south are trees +// (the decomp's two more grass rows are trees in BDSP, r253). +const TilePos CATCH_SPOT{19, 27}; +// Where 00.04 saves once it has Potions, before Route 202's trainers (the +// console's saves from r113a..r117a stand here too): under the south ledge, +// against the east trees, world (189,824). +const TilePos SAVE_SPOT{30, 24}; + +// From the events file: each trainer's tile, facing and sight range. +// Natalie challenged us at (22,22), walking east along the row above the +// ledge (r75), the fourth tile of her sight. +const TilePos TRAINER_TRISTAN{7, 13}; +const TilePos TRAINER_NATALIE{22, 18}; +const TilePos TRAINER_LOGAN{26, 4}; + +const std::vector& trainer_sights(){ + static const std::vector sights{ + {"tristan", TRAINER_TRISTAN, Direction::SOUTH, 5}, + {"natalie", TRAINER_NATALIE, Direction::SOUTH, 4}, + {"logan", TRAINER_LOGAN, Direction::SOUTH, 5}, + }; + return sights; +} + +// The middle of the 8-tile gap at (11..18, 0), world (174,800), below the +// 3-wide neck of Jubilife's south exit (173..175). +const TilePos EXIT_JUBILIFE{15, 0}; + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h new file mode 100644 index 0000000000..cee0a1e49a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h @@ -0,0 +1,49 @@ +/* BDSP AutoStory - Route 202 tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Route 202 (Sandgem Town to Jubilife City) as a tile grid, from the + * Diamond decompilation's collision table; BDSP keeps DP's tile layout. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route202_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Route202_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route202{ + + +const Pokemon::TileGrid& grid(); + +// Where the player stands in the tall grass after the catching tutorial. +extern const Pokemon::TilePos CATCH_SPOT; +// Under the south ledge, against the east trees: where the console's 00.04 +// save stands. Two walls pin it. +extern const Pokemon::TilePos SAVE_SPOT; + +// The three trainers, from the events file: Youngster Tristan in the west +// field, Lass Natalie above the south ledge, Youngster Logan by the east +// grass. All face south. +extern const Pokemon::TilePos TRAINER_TRISTAN; +extern const Pokemon::TilePos TRAINER_NATALIE; +extern const Pokemon::TilePos TRAINER_LOGAN; + +// Their sight lines, in this map's tiles. The story wants these battles. +const std::vector& trainer_sights(); + +// A tile in the gap of the north edge; walking north from it leaves for +// Jubilife City. +extern const Pokemon::TilePos EXIT_JUBILIFE; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp new file mode 100644 index 0000000000..642168d015 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp @@ -0,0 +1,78 @@ +/* BDSP AutoStory - Route 203 tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_Route203.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route203{ + +using namespace Pokemon; + + +// Map source: the decomp (pret/pokediamond land_data narc_0019 and +// narc_0020, with Jubilife's column 0 from narc_0016; 2026-10-31) and +// the objects from its events file. Platinum adds an X Defense ball at +// (40,14). +// Console checks (r227 hand pass, 2026-10-31): the Gate's warp at column +// 55, the ledge on row 15 (38..48), the beaten girl at column 43 on the +// second sand row, the row below her straight west to Jubilife (35 +// taps, no row change), the blue-haired trainer at the sand's west end. +// Status: no checkpoint has run on this grid yet. 01.06 passed on the +// image-traced grid it replaces (its east stretch corrected on the +// console) and must be re-run: the decomp has four sand rows under the +// ledge where the console counted three (9 taps south from (55,9); the +// decomp has 10 open tiles, so the first tap may only have turned). +// +// Decoded from Pokemon Diamond's collision table: cells (23,6) and (23,7) +// of the Sinnoh matrix, with the objects from its events file. Local +// (x, y) = world (x - 191, z - 740); 61 x 24 tiles. Column 0 is Jubilife's +// east edge. The columns are the ones the image-traced grid had (its gate +// warp, ledge and signs matched the decomp exactly); the rows are the +// game's: the image squeezed the west and middle stretches. +// - West stretch (columns 5..22): the field (5..22, 4..19) with grass at +// 5..8 (8..13), a ledge (18..22, 13), and the road on rows 17..19 that +// runs to Jubilife at column 0. +// - Middle stretch (23..37): the pond (29..34, 7..11) cuts the strip north +// of it, by the Repel ball (31,5), off from the rest: r222g's walk got +// stuck up there. The way through is along the bottom, rows 16..19. +// - East stretch (38..55): the Gate's mouth is (56,9), its warp tile +// (55,9). South from (55,9) is open to row 19. The ledge on row 15 +// (38..48) is crossed southward only. The sand below it is four rows, +// 16..19: the blue-haired trainer (Youngster Dallas, looks south, sees +// 4) at the sand's west end on its first row, the girl (Youngster +// Sebastian in the events file, looks west, sees 5) at (43,17) on its +// second. +// Row 18 runs in one straight line west from the sand to Jubilife; row 17 +// is blocked by the girl and the trainer, row 19 by trees at (36..37, 19). +// Objects, from the events file: trainers who stand still, 'N': Youngster +// Michael (13,10), looks west, sees 2; Dallas (31,16); Sebastian (43,17); +// Lass Madeline (49,8), looks south, sees 5. Items that block their tile +// until picked up, '#': a Poke Ball (20,10) and a Repel (31,5). Signs: to +// Jubilife (9,16), Trainer Tips (26,10) and (47,12), to Oreburgh (53,7); +// Jubilife's own sign to Route 203 stands at (7,16) in its events, not in +// this map's. Left off: a Lass who wanders along row 17 (14..16) and the +// Youngster at (54,16) who stands still in Diamond but wanders in BDSP (the +// blue-haired man near the Gate, on the console); Barry (10,17) is hidden +// by a story flag. +const TileGrid& grid(){ + return story_grid("Route203"); +} + +// The warp tile the Gate puts us on, and its open neighbours. +const std::vector& gate_exit(){ + static const std::vector tiles{{55, 9}, {54, 9}, {55, 8}, {55, 10}}; + return tiles; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h new file mode 100644 index 0000000000..9bf526197b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h @@ -0,0 +1,32 @@ +/* BDSP AutoStory - Route 203 tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Route 203 as a tile grid, for checkpoint 01.06: from the Oreburgh Gate's + * west exit to Jubilife City's east edge. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route203_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Route203_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route203{ + + +const Pokemon::TileGrid& grid(); + +// Where stepping out of the Oreburgh Gate may leave us when Route 203's +// banner shows: the warp tile west of the cave's mouth and its neighbours. +const std::vector& gate_exit(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp new file mode 100644 index 0000000000..eee289d1ce --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp @@ -0,0 +1,91 @@ +/* BDSP AutoStory - Route 204 tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_Route204.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route204{ + +using namespace Pokemon; + + +// Map source: the decomp (map_data_031, 2026-10-31) with the objects from +// its events file; before that the DP image, 3/4 rows. +// Console checks: row 27 open under the cliff, the stairs, Taylor's sight at +// column 17 (recorded human walk, 2026-10-31). Suspects: column 23 rows +// 12 to 19 blocked on the console (r242a); three open rows under the +// cave, not four (r241a, r243a). +// Status: 01.10 not passed yet; the route is the recorded human line +// (floaroma_waypoints()). +// +// Decoded from Pokemon Platinum's collision table for this map (the +// pret/pokeplatinum decompilation, map_data_031.bin: one cell of the Sinnoh +// matrix, column 5, row 21; local (x, y) = world (x - 160, z - 672)) with +// the objects from its events file; BDSP keeps the layout. Water and the +// items on the ground are '#'. Objects: the Ravaged Path's door, arriving +// on (20, 26); the twins (15, 7) and (16, 7) looking south; Aroma Lady +// Taylor (17, 20) looking south and east; Bug Catcher Brandon walking back +// and forth, on row 12 on the console (r246a), drawn at (20, 12) by the DP +// map, (22, 13) in Platinum's data; the arrow signpost +// (17, 9); a Youngster who is not a trainer wanders rows 27 and 28 below +// the cave, off the grid. The path north into Floaroma is columns 10 to 12 +// at the top. +// The 2026-10-29 hand run went out of the cave, west to the stairs, up them +// into the pocket the ledge (row 15) closes, back down, east and north +// through the tall grass, and west below the flower beds past the twins. +// Before 2026-10-31 this grid was traced from Bulbapedia's DP map image, +// whose rows are 12 px to the columns' 16: every row was 3/4 of a tile. +const TileGrid& north_grid(){ + return story_grid("Route204North"); +} + +const TilePos CAVE_EXIT{20, 26}; + +bool in_floaroma_path(const TilePos& pos){ + return pos.x >= 10 && pos.x <= 12 && pos.y <= 5; +} + +std::vector north_trainer_sights(){ + return { + {"Twins (left)", {15, 7}, Direction::SOUTH, 3}, + {"Twins (right)", {16, 7}, Direction::SOUTH, 4}, + {"Aroma Lady Taylor", {17, 20}, Direction::SOUTH, 4}, + {"Aroma Lady Taylor", {17, 20}, Direction::EAST, 4}, + // Bug Catcher Brandon paces east and west below the flower beds + // and stopped us on row 12 (r246a: "Say, what's your opinion on bug + // Pokemon?"); the DP map draws him at (20, 12), Platinum's data + // has him at (22, 13). The tile is a guess until a shot fixes it. + {"Bug Catcher Brandon", {20, 12}, Direction::WEST, 4}, + {"Bug Catcher Brandon", {20, 12}, Direction::EAST, 4}, + }; +} + +std::vector floaroma_waypoints(){ + // The line a human walked on 2026-10-31 (recorded; drawn over the DP + // map image): a tile south out of the cave's mouth; west along the row + // under the cliff, where the Youngster wanders (he stood a row below + // as we passed; the walker waits for him when he is in the way); north + // up the middle of the stairs; east along the corridor, where Aroma + // Lady Taylor sees us at column 17 and walks over for her battle; north + // up column 19 through the tall grass; west below the flower beds; + // north between the beds. The DP image shows a trainer sprite at + // (20, 12), by the corner where the line turns west: not seen yet on + // the console. The ledge on row 15 closes the stairs' column going + // north, so the line goes round through the grass. + // Column 11 for the last stretch: (12, 6) is blocked on the console + // (r248a, twice), grass in Platinum's data; the detour through (11, 6) + // passed. + return {{20, 27}, {11, 27}, {11, 22}, {19, 22}, {19, 12}, {11, 12}, {11, 5}}; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h new file mode 100644 index 0000000000..edd4b29cc0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h @@ -0,0 +1,43 @@ +/* BDSP AutoStory - Route 204 tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Route 204's north half as a tile grid, for checkpoint 01.05: from the + * door out of the Ravaged Path up to the path into Floaroma Town. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route204_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Route204_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route204{ + + +const Pokemon::TileGrid& north_grid(); + +// Where leaving the Ravaged Path puts us: the tile below its door. +extern const Pokemon::TilePos CAVE_EXIT; + +// Whether a tile is in the path north into Floaroma, between the flower +// beds' fences: walking north from here leaves the route. +bool in_floaroma_path(const Pokemon::TilePos& pos); + +// The twins below the right-hand flower bed: a double battle when they see +// us walk past below them. +std::vector north_trainer_sights(); + +// The corners of the line into Floaroma from the cave's exit, as a human +// walked it (2026-10-31): the last is in the path into Floaroma. +std::vector floaroma_waypoints(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp new file mode 100644 index 0000000000..4f022f4dce --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp @@ -0,0 +1,87 @@ +/* BDSP AutoStory - Route 204 South tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_Route204South.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route204South{ + +using namespace Pokemon; + + +// Map source: the decomp (map_data_021, 2026-10-31) with the objects from +// its events file. +// Console checks: column 14 stops at the signpost (14,17), column 13 is +// grass to the cliff, Sarah fights on row 21 (r233a, r234a, probes). +// Status: 01.08 passes once (r235a). +// +// Decoded from Pokemon Platinum's collision table for this map (the +// pret/pokeplatinum decompilation, res/field/maps/data/map_data_021.bin: +// 32 x 32 tiles, one cell of the Sinnoh matrix at column 5, row 22), with +// the objects from its events file (events_route_204_south.json); BDSP +// keeps Diamond/Pearl's layout. Local (x, y) = world (x - 160, z - 704). +// Water is '#'. Objects, from the events file: +// door to the Ravaged Path (11, 1); its signboard (10, 2); +// the "204" arrow signpost (14, 17), which stops a walk north up the +// street's column 14 (r233a, r234a); +// Lass Samantha (11, 8), looks south; Lass Sarah (12, 21), looks north +// and east by turns; Youngster Tyler (7, 18), looks west and east; +// items on the ground (17, 18), (29, 12), (2, 28), as '#'; +// a Youngster who is not a trainer wanders west and east along row 2 in +// front of the door: off the grid, the walker waits for him. +// Checked on the console 2026-10-31 (r233a, r234a, probes): north up +// column 14 from Jubilife stops at the signpost (14, 17); column 13 is +// tall grass all the way up and stops at the cliff (13, 2), the door two +// columns west; Sarah walked up and fought us once on row 21. +// Row 31, columns 12 to 15, joins the top of Jubilife's north street: +// walking south there leaves the route. +const TileGrid& grid(){ + return story_grid("Route204South"); +} + +std::vector jubilife_entry(){ + // The walk north looks between 400 ms holds, so it may stop up to two + // tiles past the border. + return {{14, 31}, {14, 30}, {14, 29}}; +} + +const TilePos BELOW_DOOR{11, 2}; + +std::vector trainer_sights(){ + // Sarah turns between north and east; her east line crosses the + // street's columns, so a walk north meets it or not by luck (r233a + // passed, r234a fought). The planner cannot avoid it: she is listed + // so the route knows whom it may meet, with the range that fits. + return { + {"Lass Samantha", {11, 8}, Direction::SOUTH, 4}, + {"Lass Sarah", {12, 21}, Direction::NORTH, 4}, + {"Lass Sarah", {12, 21}, Direction::EAST, 4}, + {"Youngster Tyler", {7, 18}, Direction::EAST, 4}, + {"Youngster Tyler", {7, 18}, Direction::WEST, 4}, + }; +} + +std::vector tiles_to_avoid(){ + std::vector tiles; + for (const TrainerSight& trainer : trainer_sights()){ + if (trainer.name == "Lass Sarah" && trainer.facing == Direction::EAST){ + continue; + } + for (const TilePos& pos : sight_tiles(grid(), trainer)){ + tiles.push_back(pos); + } + } + return tiles; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h new file mode 100644 index 0000000000..d03ed47c1b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h @@ -0,0 +1,44 @@ +/* BDSP AutoStory - Route 204 South tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Route 204's south half as a tile grid, for checkpoint 01.08: from the top + * of Jubilife City's north street to the door of the Ravaged Path. The + * north half (Route204::north_grid) is reached only through the cave, so + * the two halves are separate maps. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route204South_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Route204South_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Route204South{ + + +const Pokemon::TileGrid& grid(); + +// Where walking north out of Jubilife's street puts us: its column on the +// route's bottom rows: the walk stops within two tiles of the border. +std::vector jubilife_entry(); + +// The tile below the Ravaged Path's door; walking north from it enters. +extern const Pokemon::TilePos BELOW_DOOR; + +// The trainers whose sight lines a route may cross. +std::vector trainer_sights(); + +// The sight-line tiles a route can keep out of: all but Sarah's east line, +// which crosses the whole street. +std::vector tiles_to_avoid(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp new file mode 100644 index 0000000000..fc0c0b7b61 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -0,0 +1,199 @@ +/* BDSP AutoStory - Route records + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_RouteRecords.h" +#include "PokemonBDSP_AutoStory_JubilifeCity.h" +#include "PokemonBDSP_AutoStory_Route201.h" +#include "PokemonBDSP_AutoStory_Route203.h" +#include "PokemonBDSP_AutoStory_Route204.h" +#include "PokemonBDSP_AutoStory_RavagedPath.h" +#include "PokemonBDSP_AutoStory_OreburghCity.h" +#include "PokemonBDSP_AutoStory_OreburghGym.h" +#include "PokemonBDSP_AutoStory_FloaromaTown.h" +#include "PokemonBDSP_AutoStory_SandgemTown.h" +#include "PokemonBDSP_AutoStory_Segment00Lines.h" +#include "PokemonBDSP_AutoStory_TwinleafTown.h" +#include "PokemonBDSP_AutoStory_VerityLakefront.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RouteRecords{ + +using namespace Pokemon; + +namespace{ +const TileGrid* twinleaf(){ return &TwinleafTown::grid(); } +const TileGrid* route201(){ return &Route201::grid(); } +const TileGrid* lakefront(){ return &VerityLakefront::grid(); } +const TileGrid* sandgem(){ return &SandgemTown::grid(); } +const TileGrid* jubilife(){ return &JubilifeCity::grid(); } +const TileGrid* route203(){ return &Route203::grid(); } +const TileGrid* ravaged_path(){ return &RavagedPath::grid(); } +const TileGrid* route204_north(){ return &Route204::north_grid(); } +const TileGrid* oreburgh_city(){ return &OreburghCity::grid(); } +const TileGrid* oreburgh_gym(){ return &OreburghGym::grid(); } +const TileGrid* floaroma(){ return &FloaromaTown::grid(); } + +// 00.01: the house, Twinleaf, Route 201 and the Lakefront out to the lake. +std::vector checkpoint_0001_records(){ + return { + {"00.01", "The house's doorstep to Barry's door", "Twinleaf Town", twinleaf, true, Segment00Lines::HOUSE_DOORSTEP, { + {Direction::WEST, 7, LegEnd::COUNT, "along row 22 to column 13, clear of the south-west house"}, + {Direction::NORTH, 10, LegEnd::COUNT, "up column 13 to row 12, below Barry's mailbox"}, + {Direction::WEST, 4, LegEnd::COUNT, "onto (9, 12), the one tile that starts Barry's scene: he bursts out of his door"}, + {Direction::NORTH, 1, LegEnd::DOOR, "after the scene, into Barry's house; the stairs, his room and the way back out are replays"}, + }, "Segment00Lines line 1, not walked by the program yet; the Twinleaf grid and the scene's tile from the Diamond decomp (land_data 0000, zone_event 0389)"}, + {"00.01", "Barry's doorstep to Route 201", "Twinleaf Town", twinleaf, true, Segment00Lines::BARRY_DOORSTEP, { + {Direction::EAST, 6, LegEnd::COUNT, "along row 12 to column 15"}, + {Direction::NORTH, 12, LegEnd::COUNT, "up column 15 to (15, 0), the last tile in town; the guitarist's stop on row 3 is inert once Barry has talked upstairs"}, + {Direction::NORTH, 0, LegEnd::BANNER, "on north onto Route 201"}, + }, "Segment00Lines line 2, not walked by the program yet"}, + {"00.01", "Route 201: Barry's tall-grass warning, then west to the Lakefront", "Route 201", route201, true, Segment00Lines::ROUTE_201_ARRIVAL, { + {Direction::NORTH, 6, LegEnd::COUNT, "up the exit path to (15, 18): Barry's warning fires on that row"}, + {Direction::WEST, 3, LegEnd::COUNT, "after the scene, along row 18 to column 12"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 16, the lower level's row to the Lakefront"}, + {Direction::WEST, 12, LegEnd::COUNT, "to (0, 16), the route's last tile"}, + {Direction::WEST, 0, LegEnd::BANNER, "on west onto the Verity Lakefront"}, + }, "Segment00Lines lines 2 and 3, not walked by the program yet; traced on Route201::grid(), the decomp's since #111"}, + {"00.01", "Verity Lakefront: to below the lake's entrance", "Verity Lakefront", lakefront, true, Segment00Lines::LAKEFRONT_ARRIVAL, { + {Direction::WEST, 11, LegEnd::COUNT, "along row 23 to column 20"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 21"}, + {Direction::WEST, 3, LegEnd::COUNT, "to column 17, the entrance path's east column"}, + {Direction::NORTH, 7, LegEnd::COUNT, "up column 17 to (17, 14), two tiles short of the lake's scene; 00.01 ends here"}, + }, "Segment00Lines line 3, not walked by the program yet"}, + }; +} + +// 00.02 and 00.03: into the lake's scene, and back to Sandgem. +std::vector checkpoints_0002_0003_records(){ + return { + {"00.02", "Into the lake's scene", "Verity Lakefront", lakefront, true, Segment00Lines::BELOW_LAKE_ENTRANCE, { + {Direction::NORTH, 2, LegEnd::COUNT, "onto (17, 12): Barry hears Rowan and the two of us walk into Lake Verity"}, + {Direction::NORTH, 0, LegEnd::SCENE, "the starter, the Starly and the way back out to (17, 12) are the game's; nothing is walked at the lake"}, + }, "starter_nav() presses north twice from where 00.01 ends; Segment00Lines line 3's last two tiles; the scene's tiles from the Diamond decomp (zone_event 0319)"}, + {"00.03", "Verity Lakefront: from the lake's entrance back onto Route 201", "Verity Lakefront", lakefront, true, Segment00Lines::LAKE_ENTRANCE, { + {Direction::SOUTH, 9, LegEnd::COUNT, "down column 17 to row 21"}, + {Direction::EAST, 12, LegEnd::COUNT, "along row 21 to column 29"}, + {Direction::EAST, 0, LegEnd::BANNER, "on east onto Route 201"}, + }, "Segment00Lines line 4, not walked by the program yet; which of the two entrance tiles the scene leaves us on is for the console"}, + {"00.03", "Route 201: Rowan's scene, then east through the grass to Sandgem", "Route 201", route201, true, Segment00Lines::ROUTE_201_RETURN, { + {Direction::EAST, 5, LegEnd::COUNT, "to (5, 14): Rowan and Dawn's scene fires on that column"}, + {Direction::EAST, 12, LegEnd::COUNT, "after the scene, along row 14 to column 17"}, + {Direction::EAST, 12, LegEnd::COUNT, "through the tall grass to column 29; the Breeder wanders rows 14 to 16 there"}, + {Direction::EAST, 12, LegEnd::COUNT, "to column 41"}, + {Direction::NORTH, 7, LegEnd::COUNT, "up column 41 to row 7, beside the north-east grass"}, + {Direction::EAST, 1, LegEnd::COUNT, "into the grass"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 5"}, + {Direction::EAST, 10, LegEnd::COUNT, "through the grass to (52, 5), its last tile"}, + {Direction::EAST, 11, LegEnd::COUNT, "to (63, 5), the route's last tile"}, + {Direction::EAST, 0, LegEnd::BANNER, "on east into Sandgem Town"}, + }, "Segment00Lines lines 4 and 5, not walked by the program yet; the grass legs need the wild-battle handling of the replay's walk_through_grass(); traced on Route201::grid()"}, + {"00.03", "Sandgem Town: Dawn at the entrance", "Sandgem Town", sandgem, true, Segment00Lines::SANDGEM_ARRIVAL, { + {Direction::EAST, 4, LegEnd::COUNT, "along row 12 to (4, 12): Dawn's scene, which leads us into Rowan's lab for the Pokedex"}, + {Direction::EAST, 0, LegEnd::SCENE, "the lab is the game's; 00.03 ends in front of Rowan"}, + }, "Segment00Lines line 5, not walked by the program yet; on Sandgem's row 12, where its coord event (zone_event 0396) is"}, + }; +} + +// 01.01 to 01.05: Jubilife to Oreburgh and back out. +std::vector segment01_records_to_oreburgh(){ + return { + {"01.01", "Jubilife Pokemon Center to Barry on Route 203", "Jubilife City", jubilife, true, std::nullopt, { + {Direction::SOUTH, 0, LegEnd::NPC, "out of the Center's door; a girl below it stops us"}, + {Direction::WEST, 4, LegEnd::COUNT, "stick 720 ms: onto the main road", false}, + {Direction::NORTH, 16, LegEnd::COUNT, "stick 3960 ms: up to the street east to Route 203", false}, + {Direction::SOUTH, 2, LegEnd::COUNT, "stick 600 ms: back onto the street", false}, + {Direction::EAST, 0, LegEnd::NPC, "along the street onto Route 203 until Barry stops us; rows retried 0, +1, +1, -3, -1 when a wall comes first"}, + }, "jubilife_to_barry(); stick holds from the console, 2026-10-29, counted in tiles on the image grid's 3/4 rows: recount in taps before giving this record a start tile (task #21)"}, + {"01.02", "Barry to Oreburgh City through the Oreburgh Gate", "Route 203", route203, true, std::nullopt, { + {Direction::EAST, 0, LegEnd::WALL, "along the row Barry stopped us on"}, + {Direction::NORTH, 0, LegEnd::WALL, "to the top wall, then a row south at a time until east goes on (up to ten)"}, + {Direction::EAST, 0, LegEnd::NPC, "to the Hiker"}, + {Direction::EAST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate"}, + {Direction::EAST, 0, LegEnd::TRANSITION, "through the Gate into Oreburgh City"}, + }, "route203_to_oreburgh(); no start tile: Barry stops us on whichever row we came along"}, + {"01.04", "Oreburgh Pokemon Center doorstep to the Gym", "Oreburgh City", oreburgh_city, true, OreburghCity::POKEMON_CENTER_DOORSTEP, { + {Direction::WEST, 20, LegEnd::COUNT, "D-pad taps along the Center's row to below the Gym's door"}, + {Direction::NORTH, 1, LegEnd::DOOR, "into the Gym (the fade)"}, + }, "oreburgh_street_to_gym(); 20 taps measured on the console (r204 to r215, 3 runs on the same tile); the decomp's Center door is at x 47, the taps say the doorstep is x 46"}, + {"01.04", "Inside the Oreburgh Gym", "Oreburgh Gym", oreburgh_gym, true, OreburghGym::ENTRANCE, { + {Direction::NORTH, 0, LegEnd::NPC, "up column 5 from the entrance to Roark on row 3; the Youngsters at (4, 18) and (7, 11) see the column and stop us on rows 18 and 11 on the way"}, + }, "oreburgh_gym_battles(); the Gym's grid from the Diamond decomp (land_data 0228), its trainers and their sight from the events file (zone_event 0046)"}, + {"01.05", "Oreburgh Gym to the Gate and out onto Route 203", "Oreburgh City", oreburgh_city, true, OreburghCity::GYM_DOORSTEP, { + {Direction::EAST, 20, LegEnd::COUNT, "D-pad taps from the Gym's doorstep back to the Center's door"}, + {Direction::WEST, 0, LegEnd::WALL, "to the stairs' cliff"}, + {Direction::NORTH, 0, LegEnd::WALL, "along the cliff"}, + {Direction::EAST, 2, LegEnd::COUNT, "to the stairs' column"}, + {Direction::NORTH, 0, LegEnd::WALL, "up the stairs"}, + {Direction::WEST, 0, LegEnd::WALL, "along the platform"}, + {Direction::SOUTH, 1, LegEnd::COUNT, "onto the Gate's row"}, + {Direction::WEST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate (a row probed when a wall comes first)"}, + {Direction::WEST, 0, LegEnd::BANNER, "through the Gate until Route 203's banner"}, + }, "oreburgh_gym_to_center(), oreburgh_to_route203(); the Center visit between the two taps legs is not a walk"}, + }; +} + +// 01.07 to 01.11: Jubilife north to Floaroma. +std::vector segment01_records_from_jubilife(){ + return { + {"01.07", "Jubilife's east edge to Rowan's scene", "Jubilife City", jubilife, true, std::nullopt, { + {Direction::WEST, 14, LegEnd::COUNT, "stick 2 x 1120 ms along the long road to the crossroads with the north street", false}, + {Direction::NORTH, 0, LegEnd::SCENE, "up the street until Rowan's scene starts (about 6 s); the green-haired man may stand in the way"}, + }, "jubilife_to_rowan(); by hand 2026-10-31 (18 presses), r230b; the stick hold's count was taken on the image grid's 3/4 rows, so no start tile yet"}, + {"01.08", "Jubilife's north street onto Route 204", "Jubilife City", jubilife, true, std::nullopt, { + {Direction::NORTH, 0, LegEnd::BANNER, "up the street until Route 204's banner; the planned walk to the Ravaged Path door follows"}, + }, "jubilife_to_ravaged_path() step 1"}, + {"01.09", "Ravaged Path's east end out onto Route 204 North", "Ravaged Path", ravaged_path, true, RavagedPath::EAST_END, { + {Direction::WEST, 1, LegEnd::COUNT, "onto the tile above the way out"}, + {Direction::SOUTH, 0, LegEnd::TRANSITION, "out of the cave"}, + }, "ravaged_path() exit; the planned legs before it are tested as plans"}, + {"01.10", "Route 204 North's path into Floaroma", "Route 204 North", route204_north, true, TilePos{11, 5}, { + {Direction::NORTH, 0, LegEnd::BANNER, "from (11, 5) until Floaroma Town's banner; the waypoint line before it is tested as plans"}, + }, "route204_to_floaroma(); r248a"}, + {"01.11", "Floaroma's old couple", "Floaroma Town", floaroma, true, FloaromaTown::ROUTE_204_ARRIVAL, { + {Direction::WEST, 8, LegEnd::COUNT, "D-pad taps along the flower field's bottom row"}, + {Direction::NORTH, 0, LegEnd::NPC, "until the old woman stops us (3 tiles on r251a)"}, + {Direction::WEST, 1, LegEnd::COUNT, "below the old man"}, + {Direction::NORTH, 0, LegEnd::NPC, "until the old man stops us (a turn)"}, + }, "floaroma_old_couple(); by hand 2026-10-31 (batches m1 to m9), r251a"}, + }; +} + +} + +// The walks planned on a grid (00.04 and 00.05's walk_route goals, 01.03's +// Mine legs, 01.06's Route 203 and Jubilife legs, 01.08's Route 204 South, +// 01.09's Ravaged Path, 01.10's waypoints) are data already, tested in +// PokemonBDSP_AutoStory_Tests.cpp; these are the rest. +// +// 00.01 to 00.03 (the house, Twinleaf, Route 201, the Lakefront and the +// lake) still replay the stick inputs Butters recorded for #1717 +// (tutorial_part_1_navigation, entry_visible, tutorial_part_2_navigation, +// starter_nav: timed holds, diagonals among them, and "move until +// transition"), off which no tile count can be read. Their records below +// are the same walks as lines on the decomp grids +// (Data/PokemonBDSP_AutoStory_Segment00Lines, task #22), legs the program +// does not walk yet: a new-game run has to confirm where each scene leaves +// the player before Segment_00 switches to them. The house interiors (the +// player's, Barry's) have no grid and stay replays. +const std::vector& all(){ + static const std::vector records = []{ + std::vector all; + for (auto part : {checkpoint_0001_records, checkpoints_0002_0003_records, segment01_records_to_oreburgh, segment01_records_from_jubilife}){ + const std::vector records = part(); + all.insert(all.end(), records.begin(), records.end()); + } + return all; + }(); + return records; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h new file mode 100644 index 0000000000..5fbcc8b09d --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h @@ -0,0 +1,67 @@ +/* BDSP AutoStory - Route records + * + * From: https://github.com/PokemonAutomation/ + * + * Every walk a checkpoint makes that is not planned on a grid, written + * down as legs: the direction, the count or the thing that ends the leg + * (a wall, a person, a door, a location banner, a map transition, a + * scene). The checkpoints run their own code today; these records say + * what that code does, so a test can trace each leg on the map once the + * map is right, and so the next version can run the record instead. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RouteRecords{ + + +// What ends a leg. +enum class LegEnd{ + COUNT, // exactly `tiles` tiles (D-pad taps, or a stick hold timed for them) + WALL, // walks until the map stops the player; `tiles` is the expected count, 0 if unknown + NPC, // walks until a person stops the player + DOOR, // walks into a door or cave mouth (a fade) + BANNER, // walks until the next map's location banner shows + TRANSITION, // walks until a map transition (the screen goes dark) + SCENE, // walks until a cutscene takes over +}; + +struct RouteLeg{ + Pokemon::Direction direction; + size_t tiles; + LegEnd end; + std::string note; + // A counted leg walked by D-pad taps (or a leg the map ends) is exact; + // a count from a timed stick hold is an estimate, a tile or two either + // way, until someone counts it on the console in taps. + bool exact = true; +}; + +struct RouteRecord{ + std::string checkpoint; // "01.05" + std::string title; + std::string map; // the map the legs are on ("" when none exists yet) + const Pokemon::TileGrid* (*grid)(); // that map's grid, nullptr when none + bool traceable; // the grid's rows are the game's (decomp or console), so legs can be traced + std::optional start; // where the record starts on that grid + std::vector legs; + std::string source; // the code and the console runs behind it +}; + +const std::vector& all(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp new file mode 100644 index 0000000000..84afae03f1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp @@ -0,0 +1,96 @@ +/* BDSP AutoStory - Sandgem Town tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_SandgemTown.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace SandgemTown{ + +using namespace Pokemon; + + +// Map source: the decomp (pret/pokediamond land_data narc_0007, 2026-10-31) +// with the signs and doors from its events file; Platinum's map_data_007 +// is the same. The rows from the doors down have been the decomp's since +// 2026-10-29; the four rows above the doors were the image's, and the +// grid now starts where the game's map does, four rows higher. +// Console checks: all three doors, five signs, the row below the doors east +// to the trees and north from it, the Lab's sign read facing west, the +// walk south from Route 202 stopping above the Mart (2026-10-29/30). +// Status: no checkpoint has run on this grid yet. 00.04, 00.05 and the +// Sandgem Center and Mart lady checkpoints passed with the image's rows +// above the doors; changed since: every tile is 4 rows lower (the grid +// begins at the map's edge), the road from Route 202 narrows on row 6 +// (the walk south from Route 202 stops at (29,5)), and the gap between +// the Lab's fence and the Center on the doors' row is four wide (11..14). +// Re-run them all. +// +// Decoded from Pokemon Diamond's collision table: cell (26,5) of the Sinnoh +// matrix, with the signs and doors from its events file. Local (x, y) = +// world (x - 160, z - 832); 34 x 32 tiles, the whole cell, so the grid's +// edges are where the game changes its location banner. Route 201 joins at +// column -64, row 7 (its row 4 is this grid's row 11); Route 202's road +// comes down onto row 0 at columns 24..29. +// +// Buildings are blocked; each door is the tile the player walks into, on +// the building's front row (row 10). Top left: Professor Rowan's lab, with a +// fence running west along row 10 to the map edge. Top middle: Pokemon +// Center. Top right: Poke Mart. Exits: west, rows 11..15 (Route 201); north, +// (24..29, 0) (Route 202: the road is 6 wide on rows 0..1, 10 wide on rows +// 2..5 and 6 wide again, columns 20..25, on rows 6..9); south, (20..25, 31) +// (the beach). +// +// The image squeezed the rows below the doors: it put both houses' doors +// three rows too high and the east house's wall where the game has open +// ground; r123a planned a west leg to that wall, ran on past it and entered +// the west house's door going north. The townspeople south of the Mart (a +// youngster and two breeders, who stand still in Diamond at (11,22) and +// (23,20)) wander on the console: not marked. Rowan, Barry and Dawn are +// hidden by story flags. +// +// Checked on the console: walking south from Route 202 along its column 30 +// stops above the Poke Mart, where the road narrows (counted as two rows +// above the signs' row on the image grid; the decomp has the wall at (29,6), +// so the stop is (29,5)), and walking west from there stops at (20,5). The +// lab's sign stands on row 11, in front of the fence: walking west along +// row 11 stops at it. +const TileGrid& grid(){ + return story_grid("SandgemTown"); +} + + +const TilePos ROUTE_202_ENTRY_STOP{29, 5}; +// The lab's door, between its two front windows. +const TilePos LAB_DOOR{8, 10}; +// The Pokemon Center's glass door. +const TilePos POKEMON_CENTER_DOOR{17, 10}; +// On the console, walking south along the road's west edge above it stops +// at (20,9), above it. +const TilePos POKEMON_CENTER_SIGN{20, 10}; +// The Poke Mart's door. +const TilePos POKE_MART_DOOR{27, 10}; +// Walking east along the doors' front row stops here, against the trees. +// Checked on the console (2026-10-30, CFR "walk"): east along row 12 (the +// path under the Lab's sign) from Route 201 stops at (29,12), and north from +// there stops here. From below the Center's sign (20,11), west stops at the +// Lab's sign, which reads facing west; south from there stops at the house +// 4 rows down, and north back at the sign's row; west of the house's north +// side is trees. A 200 ms hold south took one row; 300 ms took one or two. +const TilePos FRONT_ROW_EAST_END{29, 11}; + +std::vector below_sign_gap(){ + return {{21, 11}, {22, 11}, {23, 11}, {24, 11}}; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h new file mode 100644 index 0000000000..cb5d223828 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h @@ -0,0 +1,49 @@ +/* BDSP AutoStory - Sandgem Town tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Sandgem Town as a tile grid, from the Diamond decompilation's collision + * table; BDSP keeps DP's tile layout. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SandgemTown_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SandgemTown_H + +#include +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace SandgemTown{ + + +const Pokemon::TileGrid& grid(); + +// Where the walk south from Route 202 down the road's east side stops, +// above the Poke Mart where the road narrows. +extern const Pokemon::TilePos ROUTE_202_ENTRY_STOP; +extern const Pokemon::TilePos LAB_DOOR; +extern const Pokemon::TilePos POKEMON_CENTER_DOOR; +// The sign east of the Pokemon Center's door. Walking north from row 14 in +// its column stops on the tile below it. +extern const Pokemon::TilePos POKEMON_CENTER_SIGN; +extern const Pokemon::TilePos POKE_MART_DOOR; +// The east end of the row below the Center's and the Mart's doors, at the +// trees: one known tile to plan the way north to Route 202 from. From the +// Mart's door, a tile either side of its column, no plan north is robust. +extern const Pokemon::TilePos FRONT_ROW_EAST_END; +// The doors' front row below the gap between the Center's sign and the +// Mart's, columns 21..24: the only way north from that row that passes no +// door. Walking north from any of them leaves town for Route 202. Walking +// north from anywhere else on the row between columns 18 and 26 stops at a +// sign or a wall; the Center's door is at 17, the Mart's at 27. +std::vector below_sign_gap(); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp new file mode 100644 index 0000000000..fe4bed1a06 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -0,0 +1,156 @@ +/* BDSP AutoStory - Segment 00's walked lines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Route201.h" +#include "PokemonBDSP_AutoStory_SandgemTown.h" +#include "PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP_AutoStory_TwinleafTown.h" +#include "PokemonBDSP_AutoStory_VerityLakefront.h" +#include "PokemonBDSP_AutoStory_Segment00Lines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Segment00Lines{ + +using namespace Pokemon; + + +const char* const MAP_TWINLEAF_TOWN = "Twinleaf Town"; +const char* const MAP_VERITY_LAKEFRONT = "Verity Lakefront"; + + +// Offsets are the decomp's world coordinates of each map's tile (0, 0): +// the Sinnoh matrix's cells are 32 tiles square, the Lakefront is cell +// (column 2, row 26), Route 201 cells (3..4, 26), Twinleaf (3, 27) and +// Sandgem (5, 26). Route201::grid() leaves off the cell's seven wall rows +// at the top, so it starts 7 rows lower; SandgemTown::grid() is its whole +// cell. +const MapSet& segment00_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_TWINLEAF_TOWN, TwinleafTown::grid(), {96, 864}); + maps.add(MAP_ROUTE_201, Route201::grid(), {96, 839}); + maps.add(MAP_VERITY_LAKEFRONT, VerityLakefront::grid(), {64, 832}); + maps.add(MAP_SANDGEM_TOWN, SandgemTown::grid(), {160, 832}); + return maps; + }(); + return maps; +} + + +// From the Diamond decomp's coord events (zone_event narc_0389 Twinleaf, +// 0327 Route 201, 0319 Verity Lakefront, 0396 Sandgem; Lake Verity's +// narc_0298 has none: its scene is the map's own script, run on arrival). +// Each is a rectangle in world tiles with the story variable and value it +// fires at; Platinum's readable events files name the variables and carry +// the same rectangles for Twinleaf and the Lakefront. Listed as local +// tiles of our grids. Not here, having no grid: the player's house's door +// tile (6, 10), where Mom's warning fires on the way out (narc_0392, value +// 1). +const std::vector& scene_triggers(){ + static const std::vector triggers{ + {"Barry's door", MAP_TWINLEAF_TOWN, {9, 12}, 1, 1, + "before Barry has burst out of his house (var 0x40e6 = 0)"}, + {"the guitarist stops us leaving", MAP_TWINLEAF_TOWN, {12, 3}, 8, 1, + "between Barry's door and his talk upstairs (var 0x4070 = 1; 2 after it)"}, + {"Barry's tall-grass warning", MAP_ROUTE_201, {14, 18}, 6, 1, + "the first time north of Twinleaf (var 0x4086 = 0)"}, + {"Route 201's row 19 after the warning", MAP_ROUTE_201, {14, 19}, 6, 1, + "after the warning and before the lake (var 0x4086 = 1); its script is Diamond's binary, not read"}, + {"Rowan and Dawn on the way back", MAP_ROUTE_201, {5, 14}, 1, 3, + "after the lake (var 0x4086 = 2)"}, + {"Barry at the lake's entrance", MAP_VERITY_LAKEFRONT, {16, 12}, 2, 1, + "the first visit (var 0x4082 = 0): he hears Rowan and the two walk into Lake Verity; the same tiles fire again at 3, later in the story"}, + {"Dawn at Sandgem's entrance", MAP_SANDGEM_TOWN, {4, 11}, 1, 5, + "the first time in from Route 201 (var 0x4071 = 0): she leads us to Rowan's lab"}, + }; + return triggers; +} + +bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile){ + return tile.map == trigger.map && + tile.pos.x >= trigger.corner.x && tile.pos.x < trigger.corner.x + trigger.width && + tile.pos.y >= trigger.corner.y && tile.pos.y < trigger.corner.y + trigger.height; +} + + +const TilePos HOUSE_DOORSTEP{20, 22}; +const TilePos BARRY_DOORSTEP{9, 12}; +const TilePos TWINLEAF_NORTH_EXIT{15, 0}; +const TilePos ROUTE_201_ARRIVAL{15, 24}; +const TilePos BARRY_WARNING{15, 18}; +const TilePos LAKEFRONT_ARRIVAL{31, 23}; +const TilePos BELOW_LAKE_ENTRANCE{17, 14}; +const TilePos LAKE_ENTRANCE{17, 12}; +const TilePos ROUTE_201_RETURN{0, 14}; +const TilePos ROWAN_STOP{5, 14}; +const TilePos ROUTE_201_EAST_END{63, 5}; +const TilePos SANDGEM_ARRIVAL{0, 12}; +const TilePos DAWN_STOP{4, 12}; + +// Corners are chosen on the maps' features (a row clear of the houses, +// the exit path, a map's last tile, the tile a scene fires on); where a +// straight run is longer than the planner's 12-tile open leg (the row +// through the Lakefront, the row along Route 201) it is split at the +// twelfth tile. The lower level of Route 201 (rows 13 to 16) is the way +// both to and from the lake: the upper level's ledges only drop onto it. +// Row 16 is used westward and row 14 eastward: on the way out Rowan and +// the counterpart are not yet on (8, 14..15) and Barry is gone from (16, +// 16), but 16 keeps the line one row off the Breeder's range; on the way +// back 14 reaches Rowan's column with the fewest corners. +// +// What a new-game run must confirm before the segment switches to these: +// where each scene leaves the player (Barry's warning and Rowan's scene +// are assumed to leave us on the trigger tile; the lake's scene to warp +// us back onto (17, 12), the right-hand entrance tile, facing south), and +// that the stretches through tall grass are walked with the wild-battle +// handling the replay's walk_through_grass() has, which walk_waypoints() +// does not. +namespace{ +// Corners on each map, and a line from them: parentheses keep the table +// flat enough for the code-health linter's brace limit. +MapTile twinleaf(const TilePos& pos){ return {MAP_TWINLEAF_TOWN, pos}; } +MapTile route201(const TilePos& pos){ return {MAP_ROUTE_201, pos}; } +MapTile lakefront(const TilePos& pos){ return {MAP_VERITY_LAKEFRONT, pos}; } +MapTile sandgem(const TilePos& pos){ return {MAP_SANDGEM_TOWN, pos}; } +WalkedLine walked( + std::string checkpoint, std::string name, std::vector corners, + std::string ends_in, std::vector live_triggers +){ + return {std::move(checkpoint), std::move(name), std::move(corners), std::move(ends_in), std::move(live_triggers)}; +} +} + +const std::vector& lines(){ + static const std::vector lines{ + walked("00.01", "the house's doorstep to Barry's door", { + twinleaf(HOUSE_DOORSTEP), twinleaf({13, 22}), twinleaf({13, 12}), twinleaf(BARRY_DOORSTEP), + }, "Barry's door", {"Barry's door"}), + walked("00.01", "Barry's doorstep to Route 201", { + twinleaf(BARRY_DOORSTEP), twinleaf({15, 12}), twinleaf(TWINLEAF_NORTH_EXIT), route201(BARRY_WARNING), + }, "Barry's tall-grass warning", {"Barry's tall-grass warning"}), + walked("00.01", "Route 201's west half to the lake's entrance", { + route201(BARRY_WARNING), route201({12, 18}), route201({12, 16}), route201({0, 16}), + lakefront({20, 23}), lakefront({20, 21}), lakefront({17, 21}), lakefront(LAKE_ENTRANCE), + }, "Barry at the lake's entrance", {"Barry at the lake's entrance", "Route 201's row 19 after the warning"}), + walked("00.03", "the lake's entrance back to Rowan", { + lakefront(LAKE_ENTRANCE), lakefront({17, 21}), lakefront({29, 21}), route201(ROWAN_STOP), + }, "Rowan and Dawn on the way back", {"Rowan and Dawn on the way back"}), + walked("00.03", "Rowan to Dawn at Sandgem's entrance", { + route201(ROWAN_STOP), route201({17, 14}), route201({29, 14}), route201({41, 14}), + route201({41, 7}), route201({42, 7}), route201({42, 5}), route201({52, 5}), + route201(ROUTE_201_EAST_END), sandgem(DAWN_STOP), + }, "Dawn at Sandgem's entrance", {"Dawn at Sandgem's entrance"}), + }; + return lines; +} + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h new file mode 100644 index 0000000000..8269643c84 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h @@ -0,0 +1,84 @@ +/* BDSP AutoStory - Segment 00's walked lines + * + * From: https://github.com/PokemonAutomation/ + * + * Checkpoints 00.01 to 00.03 (the house, Twinleaf, Route 201, the Verity + * Lakefront, the lake, and back to Sandgem) replay recorded stick holds + * today. These are the same walks as lines on the grids: corner to corner, + * each stretch one straight leg, ending on the tile that starts the next + * scene. The scenes' trigger rectangles come from the Diamond decomp's + * events files, so a test can show each line steps into its scene on its + * last tile and not before. Nothing runs them on the console yet (task + * #22); the segment keeps its replays until a new-game run has checked + * the lines. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_MapSet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Segment00Lines{ + + +// Map names in segment00_maps(); Route 201 and Sandgem Town go by +// StoryMaps' MAP_ROUTE_201 and MAP_SANDGEM_TOWN. +extern const char* const MAP_TWINLEAF_TOWN; +extern const char* const MAP_VERITY_LAKEFRONT; + +// Twinleaf Town, Route 201, the Verity Lakefront and Sandgem Town joined on +// one grid at their world offsets from the decomp. Lake Verity is not in +// it: its own matrix, and the scene walks us in and the game warps us out, +// so no line is walked there. +const Pokemon::MapSet& segment00_maps(); + +// A rectangle of tiles that starts a scene when the player steps in while +// the story is in `when`. From the decomp's coord events, as local tiles. +struct SceneTrigger{ + std::string name; + std::string map; + Pokemon::TilePos corner; // north-west tile + int width; + int height; + std::string when; // the story state it fires in +}; +const std::vector& scene_triggers(); +bool trigger_covers(const SceneTrigger& trigger, const Pokemon::MapTile& tile); + +// A line walked corner to corner: every stretch between two corners is one +// straight open leg (whole tiles, as the D-pad walks them). +struct WalkedLine{ + std::string checkpoint; + std::string name; + std::vector corners; // the first is where the line starts + std::string ends_in; // the scene the last corner steps into, "" for none + std::vector live_triggers; // the scenes armed while this line is walked +}; +const std::vector& lines(); + +// Named tiles on the lines, where the route records start and end. +extern const Pokemon::TilePos HOUSE_DOORSTEP; // Twinleaf: below the player's door +extern const Pokemon::TilePos BARRY_DOORSTEP; // Twinleaf: below Barry's door; his scene's tile +extern const Pokemon::TilePos TWINLEAF_NORTH_EXIT; // Twinleaf: the last tile before Route 201 +extern const Pokemon::TilePos ROUTE_201_ARRIVAL; // Route 201: the first tile north of Twinleaf +extern const Pokemon::TilePos BARRY_WARNING; // Route 201: Barry's tall-grass warning +extern const Pokemon::TilePos LAKEFRONT_ARRIVAL; // Lakefront: the first tile west of Route 201 +extern const Pokemon::TilePos BELOW_LAKE_ENTRANCE; // Lakefront: two tiles short of the lake's scene +extern const Pokemon::TilePos LAKE_ENTRANCE; // Lakefront: the lake's scene; where it leaves us +extern const Pokemon::TilePos ROUTE_201_RETURN; // Route 201: the first tile east of the Lakefront +extern const Pokemon::TilePos ROWAN_STOP; // Route 201: Rowan and Dawn's scene +extern const Pokemon::TilePos ROUTE_201_EAST_END; // Route 201: the last tile before Sandgem +extern const Pokemon::TilePos SANDGEM_ARRIVAL; // Sandgem: the first tile east of Route 201 +extern const Pokemon::TilePos DAWN_STOP; // Sandgem: Dawn's scene + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp new file mode 100644 index 0000000000..25f7180d5f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -0,0 +1,246 @@ +/* BDSP AutoStory - Story maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_JubilifeCity.h" +#include "PokemonBDSP_AutoStory_OreburghMine.h" +#include "PokemonBDSP_AutoStory_RavagedPath.h" +#include "PokemonBDSP_AutoStory_Route203.h" +#include "PokemonBDSP_AutoStory_Route204.h" +#include "PokemonBDSP_AutoStory_Route204South.h" +#include "PokemonBDSP_AutoStory_OreburghCity.h" +#include "PokemonBDSP_AutoStory_FloaromaTown.h" +#include "PokemonBDSP_AutoStory_Route201.h" +#include "PokemonBDSP_AutoStory_Route202.h" +#include "PokemonBDSP_AutoStory_SandgemTown.h" +#include "PokemonBDSP_AutoStory_StoryMaps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const char* const MAP_ROUTE_201 = "Route 201"; +const char* const MAP_SANDGEM_TOWN = "Sandgem Town"; +const char* const MAP_ROUTE_202 = "Route 202"; +const char* const MAP_JUBILIFE_CITY = "Jubilife City"; +const char* const MAP_OREBURGH_MINE = "Oreburgh Mine"; +const char* const MAP_RAVAGED_PATH = "Ravaged Path"; +const char* const MAP_ROUTE_204 = "Route 204"; +const char* const MAP_OREBURGH_CITY = "Oreburgh City"; +const char* const MAP_FLOAROMA_TOWN = "Floaroma Town"; +const char* const MAP_ROUTE_204_SOUTH = "Route 204 South"; +const char* const MAP_ROUTE_203 = "Route 203"; + + +// Offsets are the maps' places in the game's world grid (the decomp's +// cells): Route 201 at world (96,839), Sandgem Town at (160,832), Route 202 +// at (159,800). Route 201's row 4 is Sandgem's row 11, below the doors, and +// Route 202's road comes down off its row 31 onto Sandgem's row 0. +const MapSet& story_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_ROUTE_201, Route201::grid(), {0, 0}); + maps.add(MAP_SANDGEM_TOWN, SandgemTown::grid(), {64, -7}); + maps.add(MAP_ROUTE_202, Route202::grid(), {63, -39}); + return maps; + }(); + return maps; +} + +const MapSet& jubilife_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_JUBILIFE_CITY, JubilifeCity::grid(), {0, 0}); + return maps; + }(); + return maps; +} + +// Planned one map at a time: Route 203 and Jubilife joined ran for minutes +// without a plan (r224a, 2026-10-31). +const MapSet& route203_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_ROUTE_203, Route203::grid(), {0, 0}); + return maps; + }(); + return maps; +} + +bool on_route203_west_line(const TilePos& pos){ + return pos.y == 18 && pos.x >= 24 && pos.x <= 42; +} + +// Columns 42..63, rows 12..25 of the Jubilife grid (world x 170..191, +// z 748..761), as a map of its own: the cut is the map's edge, which no leg +// may cross or stop on, not a wall a plan could walk "to". +namespace{ +const TilePos JUBILIFE_EAST_CORNER{42, 12}; +const int JUBILIFE_EAST_BOTTOM = 25; +} +const MapSet& jubilife_east_maps(){ + static const MapSet maps = []{ + const TileGrid& city = JubilifeCity::grid(); + const TilePos corner = JUBILIFE_EAST_CORNER; + std::vector rows; + for (int y = corner.y; y <= JUBILIFE_EAST_BOTTOM; y++){ + std::string row; + for (int x = corner.x; x < city.width(); x++){ + row += tile_char(city.at({x, y})); + } + rows.push_back(row); + } + MapSet maps; + maps.add(MAP_JUBILIFE_CITY, TileGrid(rows), {0, 0}); + return maps; + }(); + return maps; +} + +// Route 203's road (rows 17..19 of its grid) meets Jubilife's east street, +// rows 21..24 of its grid, at its east edge; the banner shows a tile or two +// in. Both in the corner map's tiles, from the Jubilife grid's. +const std::vector& jubilife_east_entrance(){ + static const std::vector tiles = []{ + std::vector tiles; + for (int y = 21; y <= 24; y++){ + for (int x = 61; x <= 63; x++){ + tiles.push_back({x - JUBILIFE_EAST_CORNER.x, y - JUBILIFE_EAST_CORNER.y}); + } + } + return tiles; + }(); + return tiles; +} + +// The north road where it leaves the plaza, columns 44..48 of rows 16..20. +bool on_jubilife_north_road(const TilePos& pos){ + const int x = pos.x + JUBILIFE_EAST_CORNER.x; + const int y = pos.y + JUBILIFE_EAST_CORNER.y; + return x >= 44 && x <= 48 && y >= 16 && y <= 20; +} + +const MapSet& oreburgh_mine_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_OREBURGH_MINE, OreburghMine::grid(), {0, 0}); + return maps; + }(); + return maps; +} + +MapSet ravaged_path_maps(const std::vector& smashed){ + TileGrid grid = RavagedPath::grid(); + for (const TilePos& rock : smashed){ + grid.set(rock, TileType::WALKABLE); + } + MapSet maps; + maps.add(MAP_RAVAGED_PATH, grid, {0, 0}); + return maps; +} + +const MapSet& oreburgh_city_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_OREBURGH_CITY, OreburghCity::grid(), {0, 0}); + return maps; + }(); + return maps; +} + +const MapSet& floaroma_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_FLOAROMA_TOWN, FloaromaTown::grid(), {0, 0}); + return maps; + }(); + return maps; +} + +const MapSet& route204_north_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_ROUTE_204, Route204::north_grid(), {0, 0}); + return maps; + }(); + return maps; +} + +const MapSet& route204_south_maps(){ + static const MapSet maps = []{ + MapSet maps; + maps.add(MAP_ROUTE_204_SOUTH, Route204South::grid(), {0, 0}); + return maps; + }(); + return maps; +} + +bool story_map_plannable(const std::string& map){ + return map == MAP_ROUTE_201 || map == MAP_ROUTE_202; +} + +bool story_at_jubilife_exit(const TilePos& world){ + const std::optional tile = story_maps().to_local(world); + return tile && tile->map == MAP_ROUTE_202 && tile->pos.y <= 3; +} + +std::vector story_save_spots(){ + const MapSet& maps = story_maps(); + return { + maps.to_world(MAP_ROUTE_202, Route202::CATCH_SPOT), + maps.to_world(MAP_ROUTE_202, Route202::SAVE_SPOT), + }; +} + +std::vector story_door_front(const char* map, const TilePos& door){ + const TilePos below = story_maps().to_world(map, door.next(Direction::SOUTH)); + return {below.next(Direction::WEST), below, below.next(Direction::EAST)}; +} + +std::vector story_catch_save_area(){ + const MapSet& maps = story_maps(); + std::vector area; + for (int y = 25; y <= 29; y++){ + for (int x = 15; x <= 21; x++){ + const TilePos pos = maps.to_world(MAP_ROUTE_202, {x, y}); + if (maps.world().standable(pos)){ + area.push_back(pos); + } + } + } + return area; +} + +std::vector story_after_training_area(){ + const MapSet& maps = story_maps(); + const TilePos catch_spot = maps.to_world(MAP_ROUTE_202, Route202::CATCH_SPOT); + std::vector area; + for (int y = catch_spot.y - 2; y <= catch_spot.y + 2; y++){ + for (int x = catch_spot.x - 1; x <= catch_spot.x + 1; x++){ + // The rows below the catch spot are trees in BDSP. + if (maps.world().standable({x, y})){ + area.push_back({x, y}); + } + } + } + return area; +} + +std::vector story_trainer_sights(){ + std::vector sights = Route202::trainer_sights(); + for (TrainerSight& sight : sights){ + sight.pos = story_maps().to_world(MAP_ROUTE_202, sight.pos); + } + return sights; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h new file mode 100644 index 0000000000..3e27b3dc7a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h @@ -0,0 +1,108 @@ +/* BDSP AutoStory - Story maps + * + * From: https://github.com/PokemonAutomation/ + * + * The maps the story walks through, joined on one grid. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H + +#include "Pokemon/Navigation/Pokemon_MapSet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +extern const char* const MAP_ROUTE_201; +extern const char* const MAP_SANDGEM_TOWN; +extern const char* const MAP_ROUTE_202; +extern const char* const MAP_JUBILIFE_CITY; +extern const char* const MAP_OREBURGH_MINE; +extern const char* const MAP_RAVAGED_PATH; +extern const char* const MAP_ROUTE_204; +extern const char* const MAP_ROUTE_204_SOUTH; +extern const char* const MAP_ROUTE_203; + +// Route 201, Sandgem Town and Route 202. +const Pokemon::MapSet& story_maps(); + +// Jubilife City on its own: 00.05 starts there after Dawn's scene, so it is +// not joined to Route 202. +const Pokemon::MapSet& jubilife_maps(); +// Route 203 on its own (01.06), and whether a tile is on row 18 between the +// two cliffs: row 18 runs straight west from there under the west cliff +// into Jubilife, so the plan ends there (no leg may leave the map) and a +// walk west until Jubilife's banner shows goes on from there. +const Pokemon::MapSet& route203_maps(); +bool on_route203_west_line(const Pokemon::TilePos& pos); +// Jubilife City's north-east corner (01.06), at Jubilife's own tile +// coordinates: the rest of the city is walled off, so the plan searches only +// the part the walk needs. Where Route 203's road enters it, and whether a +// tile is on the north road below the plaza: walking north from there goes +// up the road to Route 204 (and Rowan's scene). +const Pokemon::MapSet& jubilife_east_maps(); +const std::vector& jubilife_east_entrance(); +bool on_jubilife_north_road(const Pokemon::TilePos& pos); +// The Oreburgh Mine's coal room on its own (01.03). +const Pokemon::MapSet& oreburgh_mine_maps(); + +// The Ravaged Path on its own (01.05), with the rocks in `smashed` open. +Pokemon::MapSet ravaged_path_maps(const std::vector& smashed = {}); + +// Route 204's north half on its own (01.05). +const Pokemon::MapSet& route204_north_maps(); + +// Route 204's south half on its own (01.08): it joins the north half only +// through the Ravaged Path, so the two are separate maps. +const Pokemon::MapSet& route204_south_maps(); + +// Oreburgh City alone (01.04, 01.05), and Floaroma Town alone (01.11). +extern const char* const MAP_OREBURGH_CITY; +extern const char* const MAP_FLOAROMA_TOWN; +const Pokemon::MapSet& oreburgh_city_maps(); +const Pokemon::MapSet& floaroma_maps(); + +// Whether a plan may cross this map. Routes are traced from the DP maps and +// their tree walls carried over to BDSP; towns changed more in the remake, so +// a town is crossed by screen-driven legs until the console has confirmed its +// grid. +bool story_map_plannable(const std::string& map); + +// The open rows at the top of Route 202, in world tiles: walking north from +// any of them enters Jubilife City. +bool story_at_jubilife_exit(const Pokemon::TilePos& world); + +// Where the post-catch half of 00.04 may start, in world tiles: the catch +// spot (00.03 saves there after the catch) and the save spot under the +// ledge (00.04 saves there once it has Potions, before Route 202's trainers). +std::vector story_save_spots(); + +// Where 00.04b's save after the catch may stand, in world tiles: wherever +// the catch's walks in the grass ended, the patch (15..20, 25..27) and the +// lawn column east of it, (21, 25..29), down to the pocket behind the tree +// row where r252's catch ended and saved (the save loads there: (21, 29) +// by the screen, the 202 sign 3 columns right and 4 rows up). +std::vector story_catch_save_area(); + +// Where a walk out of the door `door` of `map` may leave us, in world tiles: +// the tile below it and its neighbours either side, since the door opening +// is not lined up with one tile (Jubilife's Center, r85). +std::vector story_door_front(const char* map, const Pokemon::TilePos& door); + +// Where we may stand after training in the catch grass, in world tiles: the +// training walks up and down the catch spot's column, between the tree walls +// north and south of the grass, so a battle may stop us on any of its +// three rows. A column either side allows for where the catch left us. +std::vector story_after_training_area(); + +// Route 202's trainers, in world tiles of story_maps(). +std::vector story_trainer_sights(); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp new file mode 100644 index 0000000000..b7d0f60bb6 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp @@ -0,0 +1,61 @@ +/* BDSP AutoStory - Twinleaf Town tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_TwinleafTown.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace TwinleafTown{ + +using namespace Pokemon; + + +// Map source: the decomp (Diamond land_data 0000 = Platinum map_data_000, +// 2026-10-31) with the objects from its events file. +// Console checks: none yet. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0000: one cell of the +// Sinnoh matrix at column 3, row 27; map_data_000 in pret/pokeplatinum), +// with the objects from its events file (zone_event narc_0389, +// events_twinleaf_town.json in Platinum); BDSP keeps Diamond/Pearl's layout. +// Local (x, y) = world (x - 96, z - 864); 32 x 32 tiles. The pond at the +// bottom, (12..19, 27..31), is water, '#'. The pockets (7..10, 1..2) and +// (21..24, 1..2) are walkable in the data but closed in. +// Exit: Route 201 north through columns 12 to 19 at row 0 (the route's +// bottom rows open the same eight columns). The player's house is the +// south-east one, door (20, 21), and Barry's the north-west one, door (9, +// 11): behind (20, 21) the interior has Mom and the TV, behind (9, 11) only +// Barry's mother, and Platinum's scripts name the mailbox at (18, 21) the +// player's. pret/pokediamond's map constants call them the other way round +// (MAP_TWINLEAF_PLAYER_HOUSE_1F is the house behind (9, 11)); the interiors +// say otherwise. Objects, from the events file: +// door (20, 21), the player's house; its mailbox (18, 21), read like a +// sign, 'S'; +// door (9, 11), Barry's house; its mailbox (13, 11), 'S'; Barry himself +// stands on the door tile at the start (looks south, hidden by flag 402): +// the door keeps its 'D'; +// door (20, 11) to the north-east house; door (10, 21) to the south-west +// house; +// map signpost (16, 14); +// Guitarist (12, 5), looks north, west and east, not a trainer; +// Collector (12, 25), looks around, not a trainer; +// Pokemon Breeder F wanders around (23, 14), columns 22 to 24, row 14: off +// the grid. +// No trainers. Platinum decodes the same terrain and objects; its one extra, +// an arrow signpost at world (109, 856), stands in Route 201's cell. +const TileGrid& grid(){ + return story_grid("TwinleafTown"); +} + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h new file mode 100644 index 0000000000..7e4de02893 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Twinleaf Town tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see + * the .cpp's header for the cells, the offset and the objects. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TwinleafTown_H +#define PokemonAutomation_PokemonBDSP_AutoStory_TwinleafTown_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace TwinleafTown{ + + +const Pokemon::TileGrid& grid(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp new file mode 100644 index 0000000000..a696281964 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp @@ -0,0 +1,56 @@ +/* BDSP AutoStory - Verity Lakefront tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_MapGrids.h" +#include "PokemonBDSP_AutoStory_VerityLakefront.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace VerityLakefront{ + +using namespace Pokemon; + + +// Map source: the decomp (Diamond land_data 0004 = Platinum map_data_004, +// 2026-10-31) with the objects from its events file. +// Console checks: none yet. +// Status: no checkpoint passes on this grid yet. +// +// Decoded from Pokemon Diamond's collision table for this map (the +// pret/pokediamond decompilation, +// files/fielddata/land_data/land_data_release/narc_0004: one cell of the +// Sinnoh matrix at column 2, row 26; map_data_004 in pret/pokeplatinum), +// with the objects from its events file (zone_event narc_0319, +// events_verity_lakefront.json in Platinum); BDSP keeps Diamond/Pearl's +// layout. Local (x, y) = world (x - 64, z - 832); 32 x 32 tiles. The map +// header covers four cells (columns 1 and 2, rows 25 and 26); the other +// three are trees and an 8 x 8 patch of shallow water, so only this one is +// kept. The pocket (0..3, 0..3) is that water (puddle, behaviour 0x16), +// closed in. +// Route 201's west edge is this cell's column 31: open on rows 14 to 18 (the +// upper level) and 20 to 23 (the lower), with Route 201's x = 96 at our x = +// 32. From the upper level the way west is over the ledge at column 20 (rows +// 14 to 18, jumped west, shown as a wall), landing on columns 14 to 19; the +// lower level joins it at (16..19, 20). The ledges on row 19, 'v', drop +// south onto the lower level. The lake's entrance is the warp tiles (16, 11) +// and (17, 11), walked onto heading north, written as '.'; their destination +// is Lake Verity, or its Galactic version once that story state is set. +// Objects, from the events file: +// arrow signpost (15, 14), beside the path to the lake; +// Barry (16, 11), looks south, hidden by flag 435, standing on the warp +// tile: '.' wins; +// no one else, and no trainers. +// Platinum decodes the same terrain; it has no Barry object here and calls +// the sign a trainer-tips signpost. +const TileGrid& grid(){ + return story_grid("VerityLakefront"); +} + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h new file mode 100644 index 0000000000..3ededdc534 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Verity Lakefront tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see + * the .cpp's header for the cells, the offset and the objects. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_VerityLakefront_H +#define PokemonAutomation_PokemonBDSP_AutoStory_VerityLakefront_H + +#include "Pokemon/Navigation/Pokemon_TileGrid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace VerityLakefront{ + + +const Pokemon::TileGrid& grid(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json new file mode 100644 index 0000000000..733c172f5c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json @@ -0,0 +1,92 @@ +{ + "name": "FloaromaTown", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "######........................##", + "##..##........................##", + "..............................##", + "..............................##", + "..............................##", + "..............................##", + "..............................##", + "..................#####.......##", + "..................#####.......##", + "..................#####.......##", + "..................#####.......##", + "..........####...S##.##.......##", + "..........####................##", + "..........####................##", + "..........#D##................##", + ".......................####..S##", + ".......................####...##", + ".......................#D##...##", + "..............................##", + ".............S..................", + "................................", + "................................", + "................................", + "..............#####....####...##", + "..............#####....####...##", + "..............#####....####...##", + "..............##D##....#D##...##", + "..............................##", + "..............................##", + "..............................##", + "########.#...###################", + "########.#...###################" + ], + "objects": [ + { + "name": "npc_2_1", + "kind": "npc", + "x": 2, + "y": 1 + }, + { + "name": "npc_3_1", + "kind": "npc", + "x": 3, + "y": 1 + }, + { + "name": "npc_6_10", + "kind": "npc", + "x": 6, + "y": 10 + }, + { + "name": "npc_23_11", + "kind": "npc", + "x": 23, + "y": 11 + }, + { + "name": "npc_19_21", + "kind": "npc", + "x": 19, + "y": 21 + }, + { + "name": "npc_2_23", + "kind": "npc", + "x": 2, + "y": 23 + }, + { + "name": "npc_3_23", + "kind": "npc", + "x": 3, + "y": 23 + }, + { + "name": "npc_11_26", + "kind": "npc", + "x": 11, + "y": 26 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json new file mode 100644 index 0000000000..7c7c5574c0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json @@ -0,0 +1,136 @@ +{ + "name": "JubilifeCity", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "##########################################..............########", + "##########################################..............########", + "############################################.....###############", + "############################################......##############", + "############################################......##############", + "############################################......##############", + "############################################......##############", + "#############################################....###############", + "############################....#########.......S.##############", + "############################....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..##D###D##..######....####D####.........##############", + "#########.............######...............#.....#######....####", + "#########.............######......................######....####", + "..#######.............######......................######....####", + "..###########S......########...........S.........S##D###....####", + "..#.S.#.......................#..........................#.S####", + "................................................................", + "D...............................................................", + "D...............................................................", + "................................................................", + "..#...#.......................#..........................#..####", + "..############.............####......####...................####", + "..############.............####......####................#######", + "##############.################...##.####..#.....######..#######", + "##############.################...##.####.........#####..#######", + "##############.################...................#D############", + "################################.........................#######", + "################################.........................##D####", + "################################.........................#######", + "################################.........................#######", + "###############............#####.........................#######", + "###############............#####......#####..............#######", + "###############..#########.#####.##########.......######.#######", + "###############..#########.#####.##########.......######.#######", + "###############..#########.#####.###########.....#######.#######", + "##################################..S.##D##.......##D###########", + "###############..#########.#####.........................#######", + "##############...####D####..###..........................#######", + "##############...........................................#######", + "##############.....S.....................................#######", + "##############...........................................#######", + "##############.............#########.....................#######", + "###############............#########.#####...............#######", + "###############............#########.#####...............#######", + "###############.####..####.###############...............#######", + "###############.####..####.###############...............#######", + "###############.####..####.###############...........###########", + "############D##.####..####.############D##...........###########", + "##########.................#########.......#.....#...########.##", + "##########.................#########.................########.##", + "##########............#..#.#########......S..........########.##", + "##########............#..#.#########.................########.##", + "##########.................#########.................########.##", + "###########################################.......##############", + "###########################################.......##############", + "########################################.##.......##############", + "########################################.####...################", + "########################################..........##############", + "########################################..........##############" + ], + "objects": [ + { + "name": "npc_36_16", + "kind": "npc", + "x": 36, + "y": 16 + }, + { + "name": "npc_15_18", + "kind": "npc", + "x": 15, + "y": 18 + }, + { + "name": "npc_36_25", + "kind": "npc", + "x": 36, + "y": 25 + }, + { + "name": "npc_55_33", + "kind": "npc", + "x": 55, + "y": 33 + }, + { + "name": "npc_46_35", + "kind": "npc", + "x": 46, + "y": 35 + }, + { + "name": "npc_26_42", + "kind": "npc", + "x": 26, + "y": 42 + }, + { + "name": "npc_44_44", + "kind": "npc", + "x": 44, + "y": 44 + }, + { + "name": "npc_52_46", + "kind": "npc", + "x": 52, + "y": 46 + }, + { + "name": "npc_54_46", + "kind": "npc", + "x": 54, + "y": 46 + }, + { + "name": "npc_17_55", + "kind": "npc", + "x": 17, + "y": 55 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json new file mode 100644 index 0000000000..74cc0b162e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json @@ -0,0 +1,62 @@ +{ + "name": "LakeVerity", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "################################", + "################################", + "################################", + "################################", + "......############....##########", + "......############....##########", + ".......###########......########", + ".......###########......########", + ".......###########~.....########", + ".......###########~~....########", + "################~~~~....########", + "################..~~....########", + "##############.~~~~~..##########", + "##############.~~~~...##########", + "############...~~~..############", + "############........############", + "##########..........############", + "##########..........############", + "############......##############", + "############......##############", + "############......##############", + "############......##############", + "##############..################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "objects": [ + { + "name": "npc_16_11", + "kind": "npc", + "x": 16, + "y": 11 + }, + { + "name": "npc_17_11", + "kind": "npc", + "x": 17, + "y": 11 + }, + { + "name": "npc_16_19", + "kind": "npc", + "x": 16, + "y": 19 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json new file mode 100644 index 0000000000..2e5dfc89b8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json @@ -0,0 +1,88 @@ +{ + "name": "OreburghCity", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "#########################################......#################", + "#########################################...S..#################", + "#########################################......#################", + "#########################################......#################", + "#########################################...####################", + "#########################################...####################", + "#########################################....###################", + "############.#####.######.#.############.....###################", + "###########..#####..#####...############.....###################", + "#########....#####..#####...############.....###################", + "##.....########D######D######D##########.....###################", + "##..S..###..........................####........#.#...##########", + "##..................................####.....S........##########", + "#D..................................####..............##########", + "##..................................####..............####.#####", + "##..................................####..............####.#####", + "##.....###.............#######......#D##..............####.#####", + "##.....##.......####...#######...............#####....####.#####", + "#########.......####.#.#######..............######......#.######", + "#########.......####...#######..............######.....#########", + "#########.......#D####S###D###...............##D##.....#########", + "#########........................................#.....#########", + "#########........................................#.....#########", + "#########........................................#....##########", + "#########........................................#....##########", + "#########........................................#....##########", + "##########.#.#..########.........................#....##########", + "########################.######.############.....#....##########", + "########################.######.###........#.....#....##D#######", + "########################.######.###.#..#...#.....#.........#####", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....##D############", + "###################################.########.....#...........###", + "###################################.....####.....#...........###", + "###################################.....####.....#...........###", + "###################################....#####.....#...........###", + "#####################################..#.........#...........###", + "#####################################..#..#.#....#....#.#....###", + "#####################################..#..#.#....#....#.#....###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################..###..#.#................###", + "###################################..###..#.#...#.#########.####", + "###################################..###........#.#########.####", + "###################################....#..........#####.....####", + "###################################...............#####.....####", + "#####################################.............##.........###", + "#####################################..####.#.....###.....######", + "#####################################..####.#S....###.....######", + "###########################################.......####.......###", + "############################################.....#####.......###", + "############################################.....#####.....#####", + "######################################################..#..#####", + "################################################################", + "################################################################", + "################################################################" + ], + "objects": [ + { + "name": "npc_10_16", + "kind": "npc", + "x": 10, + "y": 16 + }, + { + "name": "npc_11_25", + "kind": "npc", + "x": 11, + "y": 25 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json new file mode 100644 index 0000000000..4d5c076f41 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json @@ -0,0 +1,62 @@ +{ + "name": "OreburghGate", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "################################", + "################################", + "################################", + "################################", + "############..#......###########", + "###########..........###########", + "###########........#.###########", + "###########..###################", + "###########..###################", + "###########..###################", + "###########.####################", + "############.###################", + "###########.####################", + "###########..###################", + "###########..###################", + "###########..###################", + "###########..###################", + "###########..###################", + "############.###################", + "###########..###################", + "#####...##...##########...#.####", + "####....##...##########.....####", + "###D........................D###", + "####...#....................####", + "###########..............#.#####", + "############.......#############", + "###########..#.#...#############", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "objects": [ + { + "name": "npc_7_20", + "kind": "npc", + "x": 7, + "y": 20 + }, + { + "name": "npc_24_21", + "kind": "npc", + "x": 24, + "y": 21 + }, + { + "name": "npc_17_25", + "kind": "npc", + "x": 17, + "y": 25 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json new file mode 100644 index 0000000000..ad30eae0d7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json @@ -0,0 +1,68 @@ +{ + "name": "OreburghGym", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp", + "revision": "ce701d495c94", + "date": "2026-11-01" + }, + "tiles": [ + "################################", + "################################", + "################################", + "#..........#####################", + "#..........#####################", + "#..........#####################", + "#..##.##...#####################", + "#..........#####################", + "#..##.##...#####################", + "#..........#####################", + "#..........#####################", + "###.....#.######################", + "#..........#####################", + "#####.##...#####################", + "#####.##...#####################", + "#..........#####################", + "#..........#####################", + "#..........#####################", + "#..........#####################", + "##.#....########################", + "##.#....########################", + "#..........#####################", + "#..#...#...#####################", + "#..S...S...#####################", + "#....D.....#####################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "objects": [ + { + "name": "npc_5_3", + "kind": "npc", + "x": 5, + "y": 3 + }, + { + "name": "npc_7_11", + "kind": "npc", + "x": 7, + "y": 11 + }, + { + "name": "npc_4_18", + "kind": "npc", + "x": 4, + "y": 18 + }, + { + "name": "npc_6_23", + "kind": "npc", + "x": 6, + "y": 23 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json new file mode 100644 index 0000000000..64d1f82b96 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json @@ -0,0 +1,80 @@ +{ + "name": "OreburghMine", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "################################", + "###############D################", + "#############.....##############", + "#############.....##############", + "#############.....##############", + "#############.....##############", + "#############.....##############", + "#############...################", + "#############...################", + "#############.....##############", + "#############..#..##############", + "###############...##############", + "#############...################", + "#############.....##############", + "###############...##############", + "########...####..............###", + "######.....##.................##", + "##.#..........................##", + "##....####################....##", + "##vvv##..................#....##", + "##....#..................#....##", + "##.##.#..................#....##", + "##..###..................###..##", + "##..###..................###..##", + "##....#..................##...##", + "##.##.#..................#....##", + "####..####################....##", + "####..####################....##", + "#####............#.#........####", + "######......................####", + "################################", + "################################" + ], + "objects": [ + { + "name": "npc_20_15", + "kind": "npc", + "x": 20, + "y": 15 + }, + { + "name": "npc_21_15", + "kind": "npc", + "x": 21, + "y": 15 + }, + { + "name": "npc_27_15", + "kind": "npc", + "x": 27, + "y": 15 + }, + { + "name": "npc_26_20", + "kind": "npc", + "x": 26, + "y": 20 + }, + { + "name": "npc_8_28", + "kind": "npc", + "x": 8, + "y": 28 + }, + { + "name": "npc_18_28", + "kind": "npc", + "x": 18, + "y": 28 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json new file mode 100644 index 0000000000..3f366c4d02 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json @@ -0,0 +1,64 @@ +{ + "name": "RavagedPath", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "#################################", + "..#####################.........#", + "....############................#", + "....############................#", + "....############................#", + "....############................#", + "....############................#", + "....##.#####.###................#", + "....##.#....#.##................#", + "....##.##.#...#########.........#", + "....##....#..##########.........#", + "....##.#.#.......#...############", + "....###.....######...############", + "....##############....#.......###", + "....##############....#.......###", + "..............####....##......###", + "..............####...#######D####", + "..............####...############", + "..............####...####.......#", + "..............####...####.......#", + "..............####...####.......#", + "..............####...####.......#", + "..............#####D#####.......#", + "..............###########.......#", + "..............###########.......#" + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json new file mode 100644 index 0000000000..e2e53e12d1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json @@ -0,0 +1,43 @@ +{ + "name": "Route201", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "################################################################", + "################################################################", + "################################################################", + "##########################################~~~~~~~~~~~...........", + "##########################################~~~~~~~~~~~..S........", + "##########################################~~~~~~~~~~~...........", + "##########################################~~~~~~~~~~~...........", + "....####..........######..##....##..####..~~~~~~~~~##...........", + "....####..........######..##....##..####..~~~~~~~~~##...........", + "##........####............................~~~~~~~~~##vvvvv######", + "##........####............................~~~~~~~~~##.....######", + "..........................................~~~~~~~~~##.....######", + "vvvv####vvvvvvvvvvvvvvvvvvvvvvvv........S.~~~~~~~~~##.....######", + "....####............~~~~~~~~~~............................######", + "....................~~~~~~~~~~............................######", + "....................~~~~~~~~~~............................######", + "....................~~~~~~~~~~............................######", + "########.....S......##########............................######", + "########............##########............~~~~~~~~~~~~~~~~######", + "##############....############################~~~~~~~~~~~~######", + "##############....############################~~~~~~~~~~~~######", + "##############....##############################################", + "##############....##############################################", + "##############....##############################################", + "##############....##############################################" + ], + "objects": [ + { + "name": "npc_57_8", + "kind": "npc", + "x": 57, + "y": 8 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json new file mode 100644 index 0000000000..362f4e0df8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json @@ -0,0 +1,62 @@ +{ + "name": "Route202", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "###########........#################", + "###########........#################", + "###########........#################", + "###########........#################", + "###~~~~~~........S..~~~~~......#####", + "###~~~~~~...........~~~~~......#####", + "####~~~~~...........~~~~~......#####", + "###~~~~~~...........~~~~~......#####", + "###~~~~~~...........~~~~~......#####", + "###~~~~~~.....########.........#####", + "#########vvvvv########vvvvvv...~~###", + "#########.....########~~~~~~~~~~~###", + "#######.......########~~~~~~~~~~~###", + "#######...........####~~~~~~~~~~~###", + "###...............####~~~~~~~~~~~###", + "###...............####~~~~~~~~~~~###", + "###............S..####~~~~~~~~~~~###", + "###...............####~~~~~~~~~~~###", + "###...............####..~~~~~~~~~###", + "###~~~~##...............~~~~~~~~~###", + "###~~~~##.................~~~~~~~###", + "###~~~~##....................~~~~###", + "###~~~~##......................#####", + "###~~~~##vvvvv########vvvvvvvvv#####", + "###~~~~##.....########.........#####", + "###~~~~~~......~~~~~~...S......#####", + "###~~~~~~......~~~~~~..........#####", + "###~~~~~~......~~~~~~..........#####", + "###~~~~~~......######..........#####", + "###~~~~~~......######..........#####", + "######################.........#####", + "#####################..........#####" + ], + "objects": [ + { + "name": "npc_26_4", + "kind": "npc", + "x": 26, + "y": 4 + }, + { + "name": "npc_7_13", + "kind": "npc", + "x": 7, + "y": 13 + }, + { + "name": "npc_22_18", + "kind": "npc", + "x": 22, + "y": 18 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json new file mode 100644 index 0000000000..b646ec65c9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json @@ -0,0 +1,60 @@ +{ + "name": "Route203", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "#############################################################", + "#############################################################", + "#############################################################", + "#############################################################", + "#####..............###########..~~~~#########################", + "#####..............###########.#.~~~..~~~~~~~~~~~~~~#########", + "#####..................#######........~~~~~~~~~~~~~.....#####", + "#####..................###############~~~~~~~~~~~....S..#####", + "#####~~~~##...####.....#......########~~~~~~~~~~~.......#####", + "#####~~~~##...####.....#......########~~~~~~~~~~~.......D####", + "#####~~~~##...####..#..#..S...########~~~~~~~~~~~.......#####", + "#####~~~~##...####.....#......########~~~~~~~~~~~.......#####", + "#####~~~~##...####.....#....~~~~~~~~##~~~~~~~~~S...~~~..#####", + "#####~~~~##...####vvvvv#...~~...~.~~##~~~~~~~~~....~~~..#####", + "#####~~................#....######~~##.....~~....##~~~..#####", + "#####..................#....######~~##vvvvvvvvvvv##~~~..#####", + "#####....S.............#....~~~..~~~.............~~~~~..#####", + "...........................~~~~...~~.............~~~~~..#####", + "...........................~~.....~~.............~~~~~..#####", + "..........................~~~~.....~##..........~~~~~~..#####", + "..........................~~~~~.~~~~#########################", + "#############################################################", + "#############################################################", + "#############################################################" + ], + "objects": [ + { + "name": "npc_49_8", + "kind": "npc", + "x": 49, + "y": 8 + }, + { + "name": "npc_13_10", + "kind": "npc", + "x": 13, + "y": 10 + }, + { + "name": "npc_31_16", + "kind": "npc", + "x": 31, + "y": 16 + }, + { + "name": "npc_43_17", + "kind": "npc", + "x": 43, + "y": 17 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json new file mode 100644 index 0000000000..6ec036b174 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json @@ -0,0 +1,74 @@ +{ + "name": "Route204North", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "########.#...###################", + "########.#...###################", + "####.....#...########.##########", + "##########...#......#.##########", + "#####....#...#......#...........", + "#####....#~~~#......#...######..", + "#####....#~~####################", + "##########~~~.........##########", + "##........~~~~~.......##########", + "##..######.~~~~..S....##########", + "###.#....#.~~~........##########", + "##..#....#.~~.........##########", + "##########..............########", + "##########..............########", + "##########...####~~~~~~~########", + "##########vvv####~~~~~~~########", + "##########...######~~~~~########", + "##########...######~~~~~########", + "##########...######~~~~~########", + "##########...######~.~~~########", + "##########............~~########", + "##########............##########", + "##########............##########", + "##########...##.....#.##########", + "##########...##.......##########", + "##########...###################", + "##########...#######.###########", + "##########............##########", + "##########............##########", + "##########............##########", + "##########............##########", + "##########...###################" + ], + "objects": [ + { + "name": "npc_31_4", + "kind": "npc", + "x": 31, + "y": 4 + }, + { + "name": "npc_15_7", + "kind": "npc", + "x": 15, + "y": 7 + }, + { + "name": "npc_16_7", + "kind": "npc", + "x": 16, + "y": 7 + }, + { + "name": "npc_20_12", + "kind": "npc", + "x": 20, + "y": 12 + }, + { + "name": "npc_17_20", + "kind": "npc", + "x": 17, + "y": 20 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json new file mode 100644 index 0000000000..752d5baf82 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json @@ -0,0 +1,62 @@ +{ + "name": "Route204South", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "################################", + "###########D###.################", + "########..S.....################", + "########........################", + "########........################", + "##########...~##################", + "##########...~##################", + "##########..~~##################", + "##########..~~##################", + "####~~~~~~~~~~##################", + "####~~~~~~~~~~##################", + "####~~~~~~~~~~##################", + "####~~~~~~~~~~############...###", + "####~~~~~~~~~~############....##", + "####~~~~~~~~~~#..###############", + "##~~~~~~~~~~~~#..###############", + "##~~~~~~~~~~~~#..###############", + "##~~~~~~~~~~~~S.################", + "##~~~~~.........################", + "##~~~~~.........#.##############", + "##~~~~~.........#.##############", + "##.#########....#.##############", + "############....#......~########", + "############....######~~########", + "############....######~~########", + "############....######~~########", + "############....######~~########", + "############....######~~########", + "###.######.#....#..~~~~~########", + "##..######.#....#...~~~~########", + "##########.#....#.......########", + "############....######..########" + ], + "objects": [ + { + "name": "npc_11_8", + "kind": "npc", + "x": 11, + "y": 8 + }, + { + "name": "npc_7_18", + "kind": "npc", + "x": 7, + "y": 18 + }, + { + "name": "npc_12_21", + "kind": "npc", + "x": 12, + "y": 21 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json new file mode 100644 index 0000000000..b7fcdb8c29 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -0,0 +1,42 @@ +{ + "name": "SandgemTown", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "########################......####", + "########################......####", + "####################..........####", + "####################..........####", + "####################..........####", + "####################..........####", + "####################......########", + "####################......########", + "####################......########", + "####################......########", + "########D##....##D##S....S#D######", + ".....S........................####", + "..............................####", + "..............................####", + "..............................####", + "..............................####", + "######........................####", + "######........................####", + "######.........#####..........####", + "##########.....#####..........####", + "##########.....#####..........####", + "##########.....#####..........####", + "#######D##....S#D###..S.......####", + "######........................####", + "######........................####", + "######........................####", + "######....................########", + "####################......########", + "####################......########", + "####################......########", + "####################......########", + "####################......########" + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json new file mode 100644 index 0000000000..92dfcf72c1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json @@ -0,0 +1,56 @@ +{ + "name": "TwinleafTown", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "############........############", + "#######....#........#....#######", + "#######....#........#....#######", + "############........############", + "######....................######", + "######....................######", + "######....................######", + "######..#####.............######", + "######..#####......####...######", + "######..#####......####...######", + "######..######.....####...######", + "######..#D###S.....#D##...######", + "######....................######", + "######....................######", + "######..........S.........######", + "######....................######", + "######....................######", + "######.............#####..######", + "######...####......#####..######", + "######...####......#####..######", + "######...####.....######..######", + "######...#D##.....S#D###..######", + "######....................######", + "######....................######", + "######....................######", + "######....................######", + "######....................######", + "######......########......######", + "################################", + "################################", + "################################", + "################################" + ], + "objects": [ + { + "name": "npc_12_5", + "kind": "npc", + "x": 12, + "y": 5 + }, + { + "name": "npc_12_25", + "kind": "npc", + "x": 12, + "y": 25 + } + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json new file mode 100644 index 0000000000..d82818b601 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json @@ -0,0 +1,42 @@ +{ + "name": "VerityLakefront", + "source": { + "decomp_file": "SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp", + "revision": "ddcbdb21c1dc", + "date": "2026-11-01" + }, + "tiles": [ + "....############################", + "....############################", + "....############################", + "....############################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################..##############", + "################..##############", + "################..##############", + "##############.S....#...........", + "##############......#.....####..", + "##############......#.....####..", + "##############......#...........", + "##############......#...........", + "##############......#vvvvv##vvvv", + "################..........##....", + "################................", + "##################..............", + "##################..............", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp new file mode 100644 index 0000000000..a42684c862 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp @@ -0,0 +1,256 @@ +/* BDSP AutoStory Map Grid Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "Pokemon/Navigation/Pokemon_MapSet.h" +#include "Pokemon/Navigation/Pokemon_TileGrid.h" +#include "Data/PokemonBDSP_AutoStory_MapGrids.h" +#include "Data/PokemonBDSP_AutoStory_Route202.h" +#include "Data/PokemonBDSP_AutoStory_SandgemTown.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_MapGrid_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::MapSet; +using Pokemon::TileGrid; +using Pokemon::TilePos; +using Pokemon::TileType; + +// 00.04's training walks up and down the catch patch, three grass rows +// between tree rows, and needs the walk there to end in its grass: r253 +// and r254 loaded the catch's save in the pocket behind the trees at +// (21, 29), planned from the catch spot instead, and walked up and down +// the lawn east of the grass for three minutes without a battle. +class Test_Route202CatchGrass : public UnitTest{ +public: + Test_Route202CatchGrass() + : UnitTest("PokemonBDSP::AutoStory - Route 202: the catch patch and the walk to it") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const TileGrid& route = Route202::grid(); + for (int x = 15; x <= 20; x++){ + const Pokemon::WallHit up = Pokemon::walk_to_wall(route, {x, 27}, Direction::NORTH); + const Pokemon::WallHit down = Pokemon::walk_to_wall(route, {x, 25}, Direction::SOUTH); + if (!(up.stop == TilePos{x, 25}) || !(down.stop == TilePos{x, 27})){ + return "Catch patch column " + std::to_string(x) + ": north from row 27 stops at " + + Pokemon::to_string(up.stop) + ", south from row 25 at " + Pokemon::to_string(down.stop) + + "; expected rows 25 and 27, between tree rows."; + } + } + const MapSet& maps = story_maps(); + const std::vector area = story_after_training_area(); + const auto in_grass = [&](const TilePos& pos){ + return maps.world().at(pos) == TileType::TALL_GRASS && std::find(area.begin(), area.end(), pos) != area.end(); + }; + // As walk_route() plans: the route costs, else the default costs. + // From the whole area the catch's save may stand in, and from the + // pocket behind the trees alone, where r252 saved. + const TilePos pocket = maps.to_world(MAP_ROUTE_202, {21, 29}); + const std::vector>> starts{ + {"the catch's save area", story_catch_save_area()}, + {"the pocket behind the trees", {pocket}}, + }; + std::optional> legs; + for (const auto& [name, from] : starts){ + legs = Pokemon::plan_robust_route(maps.world(), from, in_grass, route_plan_costs()); + if (!legs){ + legs = Pokemon::plan_robust_route(maps.world(), from, in_grass, Pokemon::RobustPlanCosts()); + } + if (!legs || legs->empty()){ + return "From " + name + " to the catch grass: no plan."; + } + for (const TilePos& pos : legs->back().after){ + if (!in_grass(pos)){ + return "From " + name + " to the catch grass: the walk may end on " + maps.describe(pos) + ", not in the grass."; + } + } + logger.log("From " + name + " to the catch grass: " + std::to_string(legs->size()) + " legs, ending in the grass."); + } + return true; + } +}; + +// 00.04's way to Sandgem's Pokemon Center ends below the Center's sign, +// walking north into it, then taps west along the doors' row to below the +// door: the row must be open there, the door straight north of where the +// taps end, and nothing else (a sign, the Mart's door) on the way. +class Test_SandgemCenterApproach : public UnitTest{ +public: + Test_SandgemCenterApproach() + : UnitTest("PokemonBDSP::AutoStory - Sandgem Town: below the Center's sign to below its door") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const TileGrid& town = SandgemTown::grid(); + const TilePos sign = SandgemTown::POKEMON_CENTER_SIGN; + const TilePos door = SandgemTown::POKEMON_CENTER_DOOR; + if (town.at(sign) != TileType::SIGN || town.at(door) != TileType::DOOR || door.y != sign.y || door.x >= sign.x){ + return "The Center's sign " + Pokemon::to_string(sign) + " and door " + Pokemon::to_string(door) + + " are not a sign and a door west of it on one row."; + } + TilePos pos = sign.next(Direction::SOUTH); + for (int tap = 0; tap < sign.x - door.x; tap++){ + const std::optional next = town.step(pos, Direction::WEST); + if (!next){ + return "West from " + Pokemon::to_string(pos) + " is blocked."; + } + if (town.at(next->next(Direction::NORTH)) != TileType::BLOCKED && *next != door.next(Direction::SOUTH)){ + return "Above " + Pokemon::to_string(*next) + " is not the Center's wall."; + } + pos = *next; + } + if (!(pos == door.next(Direction::SOUTH))){ + return "The taps end at " + Pokemon::to_string(pos) + ", not below the door " + Pokemon::to_string(door) + "."; + } + logger.log("Sandgem: below the sign " + Pokemon::to_string(sign.next(Direction::SOUTH)) + ", " + + std::to_string(sign.x - door.x) + " taps west to below the door " + Pokemon::to_string(door) + "."); + return true; + } +}; + +// After training, 00.04 walks from wherever the training left us into +// Sandgem, to where the road stops above the Mart, with the default costs +// (heal_at_sandgem_center()): from the whole area and from each of its +// tiles alone, a plan must exist and end there. +class Test_TrainingToSandgem : public UnitTest{ +public: + Test_TrainingToSandgem() + : UnitTest("PokemonBDSP::AutoStory - Route 202: from every tile of the training area into Sandgem") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const MapSet& maps = story_maps(); + const TilePos entry = maps.to_world(MAP_SANDGEM_TOWN, SandgemTown::ROUTE_202_ENTRY_STOP); + const std::vector area = story_after_training_area(); + std::vector> starts{area}; + for (const TilePos& pos : area){ + starts.push_back({pos}); + } + for (const std::vector& from : starts){ + const auto legs = Pokemon::plan_robust_route(maps.world(), from, + [&](const TilePos& pos){ return pos == entry; }, Pokemon::RobustPlanCosts()); + const std::string name = from.size() == 1 ? maps.describe(from[0]) : "the whole training area"; + if (!legs || legs->empty()){ + return "From " + name + " into Sandgem: no plan."; + } + if (legs->back().after.size() != 1 || !(legs->back().after[0] == entry)){ + return "From " + name + " into Sandgem: the plan does not end on " + maps.describe(entry) + "."; + } + logger.log("From " + name + " into Sandgem: " + std::to_string(legs->size()) + " legs."); + } + return true; + } +}; + +// The maps (the JSON files built in, bdsp_map_json()) all parse through +// the shared loader into tile grids, each named as its file. +class Test_BuiltInMaps : public UnitTest{ +public: + Test_BuiltInMaps() + : UnitTest("PokemonBDSP::AutoStory - Map grids: the built-in JSON maps load") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + if (bdsp_map_json().empty()){ + return std::string("No built-in maps."); + } + for (const auto& [name, json] : bdsp_map_json()){ + try{ + const TileGrid& grid = story_grid(name); + logger.log(std::format("{}: {} x {}", name, grid.width(), grid.height())); + }catch (Exception& e){ + return std::format("{}: {}: {}", name, e.name(), e.message()); + } + } + return true; + } +}; + +// The JSON glyphs as BDSP tiles: every BDSP tile and a person standing; +// water and a wanderer have none. +struct GlyphCase{ + std::string name; + std::string json; + // The grid's rows, or empty when reading it must throw. + std::vector rows; +}; + +class Test_MapGlyphs : public UnitTest{ +public: + Test_MapGlyphs() + : UnitTest("PokemonBDSP::AutoStory - Map grids: JSON glyphs as tile grids") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + { + .name = "every BDSP tile, and a person standing", + .json = R"({"name": "T", "source": {"decomp_file": "f", "revision": "r", "date": "d"}, + "tiles": ["#.~", "vDS"], + "objects": [{"name": "npc_1_0", "kind": "npc", "x": 1, "y": 0}]})", + .rows = {"#N\"", "vDS"}, + }, + { + .name = "water has no BDSP tile", + .json = R"({"name": "T", "source": {"decomp_file": "f", "revision": "r", "date": "d"}, "tiles": ["#w"]})", + .rows = {}, + }, + { + .name = "a wanderer has no BDSP tile", + .json = R"({"name": "T", "source": {"decomp_file": "f", "revision": "r", "date": "d"}, "tiles": ["#.."], + "objects": [{"name": "lass", "kind": "npc", "x": 1, "y": 0, "wander": {"x0": 1, "y0": 0, "x1": 2, "y1": 0}}]})", + .rows = {}, + }, + }; + for (const GlyphCase& item : cases){ + std::optional grid; + std::string error; + try{ + grid = tile_grid_from_map(Pokemon::parse_map(parse_json(item.json), item.name)); + }catch (ParseException& e){ + error = e.message(); + } + if (item.rows.empty() != !grid){ + return item.name + (grid ? ": read a grid, expected a ParseException." : ": expected a grid, read: " + error); + } + if (grid){ + if (const std::optional difference = grid_difference(*grid, TileGrid(item.rows))){ + return item.name + ": differs from the expected rows at " + *difference + "."; + } + } + } + return true; + } +}; + +} + + +void add_tests_AutoStory_MapGrids(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h new file mode 100644 index 0000000000..a7f7250b2b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory Map Grid Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_MapGrid_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_MapGrid_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Offline checks of the decomp grids against what the console showed: +// Route 202's catch patch between tree rows and the walks in and out of +// it, and Sandgem's Pokemon Center door, its sign and the row below them. +void add_tests_AutoStory_MapGrids(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp new file mode 100644 index 0000000000..4f85f52a85 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp @@ -0,0 +1,266 @@ +/* BDSP AutoStory Segment 00 Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_MapSet.h" +#include "Pokemon/Navigation/Pokemon_TileGrid.h" +#include "Data/PokemonBDSP_AutoStory_OreburghGym.h" +#include "Data/PokemonBDSP_AutoStory_Segment00Lines.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_Segment00_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::MapSet; +using Pokemon::MapTile; +using Pokemon::TileGrid; +using Pokemon::TilePos; +using Pokemon::TileType; +using Segment00Lines::SceneTrigger; +using Segment00Lines::WalkedLine; + +std::string describe(const MapTile& tile){ + return tile.map + " " + Pokemon::to_string(tile.pos); +} + +const SceneTrigger* find_trigger(const std::string& name){ + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (trigger.name == name){ + return &trigger; + } + } + return nullptr; +} + +// Plans one stretch of a line with the waypoint costs and returns the leg, +// or an error. The stretch must be the one straight leg a human took: to a +// wall or open, as the grid has it, ending exactly on the corner. +struct Stretch{ + Pokemon::TileLeg leg; + std::string error; +}; +Stretch plan_stretch(const MapSet& maps, const TilePos& from, const TilePos& to, const std::string& name){ + const auto plan = Pokemon::plan_robust_route(maps.world(), std::vector{from}, + [&](const TilePos& pos){ return pos == to; }, waypoint_plan_costs()); + if (!plan){ + return {{}, name + ": no plan."}; + } + if (plan->size() != 1){ + std::string text = name + ": " + std::to_string(plan->size()) + " legs, expected the one straight leg:"; + for (const Pokemon::PlannedLeg& leg : *plan){ + text += " " + to_string(leg.leg); + } + return {{}, text}; + } + const Pokemon::PlannedLeg& leg = (*plan)[0]; + if (leg.after.size() != 1 || !(leg.after[0] == to)){ + return {{}, name + ": the leg " + to_string(leg.leg) + " does not end exactly on the corner."}; + } + return {leg.leg, ""}; +} + +// Every tile a line stands on, its start first, as local tiles; logs each +// stretch's leg. Empty with `error` set when a stretch does not plan. +std::vector line_tiles(Logger& logger, const MapSet& maps, const WalkedLine& line, std::string& error){ + const std::string name = line.checkpoint + " " + line.name; + std::vector tiles{line.corners[0]}; + TilePos at = maps.to_world(line.corners[0].map, line.corners[0].pos); + std::string text = name + ": from " + describe(line.corners[0]); + for (size_t i = 1; i < line.corners.size(); i++){ + const MapTile& corner = line.corners[i]; + const TilePos goal = maps.to_world(corner.map, corner.pos); + const Stretch stretch = plan_stretch(maps, at, goal, name + " stretch " + std::to_string(i) + " to " + describe(corner)); + if (!stretch.error.empty()){ + error = stretch.error; + return {}; + } + text += "\n " + to_string(stretch.leg) + " to " + describe(corner); + for (size_t k = 0; k < stretch.leg.tiles; k++){ + at = at.next(stretch.leg.direction); + const std::optional local = maps.to_local(at); + if (!local){ + error = name + ": the line leaves the maps at " + Pokemon::to_string(at) + "."; + return {}; + } + tiles.push_back(*local); + } + } + logger.log(text); + return tiles; +} + +// The last tile steps into the line's scene; no earlier tile is in any +// scene armed while the line is walked (an inert one is only logged). +std::string check_triggers(Logger& logger, const WalkedLine& line, const std::vector& tiles){ + const std::string name = line.checkpoint + " " + line.name; + for (const std::string& live : line.live_triggers){ + if (find_trigger(live) == nullptr){ + return name + ": no scene trigger named \"" + live + "\"."; + } + } + const auto armed = [&](const std::string& trigger){ + return std::ranges::find(line.live_triggers, trigger) != line.live_triggers.end(); + }; + if (!line.ends_in.empty() && !armed(line.ends_in)){ + return name + ": the scene it ends in, \"" + line.ends_in + "\", is not among its live triggers."; + } + for (size_t i = 0; i < tiles.size(); i++){ + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (!Segment00Lines::trigger_covers(trigger, tiles[i])){ + continue; + } + const bool live = armed(trigger.name); + const bool last = i + 1 == tiles.size(); + logger.log(name + ": tile " + std::to_string(i + 1) + " of " + std::to_string(tiles.size()) + ", " + describe(tiles[i]) + + ", is in \"" + trigger.name + "\" (" + (live ? "armed" : "inert: " + trigger.when) + ")."); + if (live && !(last && trigger.name == line.ends_in)){ + return name + ": steps into the armed scene \"" + trigger.name + "\" at " + describe(tiles[i]) + ", before its end."; + } + } + } + if (!line.ends_in.empty() && !Segment00Lines::trigger_covers(*find_trigger(line.ends_in), tiles.back())){ + return name + ": its last tile " + describe(tiles.back()) + " is not in \"" + line.ends_in + "\"."; + } + return ""; +} + +// The tiles the route records start and end on, each of which must lie on +// one of the lines. +struct NamedTile{ + const char* name; + MapTile tile; +}; +std::vector named_tiles(){ + return { + {"HOUSE_DOORSTEP", {Segment00Lines::MAP_TWINLEAF_TOWN, Segment00Lines::HOUSE_DOORSTEP}}, + {"BARRY_DOORSTEP", {Segment00Lines::MAP_TWINLEAF_TOWN, Segment00Lines::BARRY_DOORSTEP}}, + {"TWINLEAF_NORTH_EXIT", {Segment00Lines::MAP_TWINLEAF_TOWN, Segment00Lines::TWINLEAF_NORTH_EXIT}}, + {"ROUTE_201_ARRIVAL", {MAP_ROUTE_201, Segment00Lines::ROUTE_201_ARRIVAL}}, + {"BARRY_WARNING", {MAP_ROUTE_201, Segment00Lines::BARRY_WARNING}}, + {"LAKEFRONT_ARRIVAL", {Segment00Lines::MAP_VERITY_LAKEFRONT, Segment00Lines::LAKEFRONT_ARRIVAL}}, + {"BELOW_LAKE_ENTRANCE", {Segment00Lines::MAP_VERITY_LAKEFRONT, Segment00Lines::BELOW_LAKE_ENTRANCE}}, + {"LAKE_ENTRANCE", {Segment00Lines::MAP_VERITY_LAKEFRONT, Segment00Lines::LAKE_ENTRANCE}}, + {"ROUTE_201_RETURN", {MAP_ROUTE_201, Segment00Lines::ROUTE_201_RETURN}}, + {"ROWAN_STOP", {MAP_ROUTE_201, Segment00Lines::ROWAN_STOP}}, + {"ROUTE_201_EAST_END", {MAP_ROUTE_201, Segment00Lines::ROUTE_201_EAST_END}}, + {"SANDGEM_ARRIVAL", {MAP_SANDGEM_TOWN, Segment00Lines::SANDGEM_ARRIVAL}}, + {"DAWN_STOP", {MAP_SANDGEM_TOWN, Segment00Lines::DAWN_STOP}}, + }; +} + +// The lines 00.01 to 00.03 would walk (Data/PokemonBDSP_AutoStory_Segment00Lines): +// every stretch plans as one straight leg on the decomp grids, and each +// line enters its scene's trigger rectangle on its last tile only. The +// named tiles the route records start from all lie on the lines. +class Test_Segment00Lines : public UnitTest{ +public: + Test_Segment00Lines() + : UnitTest("PokemonBDSP::AutoStory - Segment 00: the lines into each scene") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const MapSet& maps = Segment00Lines::segment00_maps(); + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (trigger.width <= 0 || trigger.height <= 0){ + return "Scene trigger \"" + trigger.name + "\" has no tiles."; + } + maps.to_world(trigger.map, trigger.corner); // throws for a map not in the set + } + std::vector walked; + for (const WalkedLine& line : Segment00Lines::lines()){ + if (line.corners.size() < 2){ + return line.checkpoint + " " + line.name + ": a line needs two corners."; + } + std::string error; + const std::vector tiles = line_tiles(logger, maps, line, error); + if (!error.empty()){ + return error; + } + error = check_triggers(logger, line, tiles); + if (!error.empty()){ + return error; + } + walked.insert(walked.end(), tiles.begin(), tiles.end()); + } + for (const NamedTile& tile : named_tiles()){ + const bool on_a_line = std::ranges::any_of(walked, [&](const MapTile& t){ + return t.map == tile.tile.map && t.pos == tile.tile.pos; + }); + if (!on_a_line){ + return std::string(tile.name) + " " + describe(tile.tile) + " is on none of the lines."; + } + } + return true; + } +}; + +// The Oreburgh Gym's inside (Data/PokemonBDSP_AutoStory_OreburghGym): the +// column up from the entrance runs to Roark with nothing in the way but the +// two Youngsters' sight lines, which is what 01.04's "north until a trainer +// stops us" relies on. +class Test_OreburghGymGrid : public UnitTest{ +public: + Test_OreburghGymGrid() + : UnitTest("PokemonBDSP::AutoStory - Oreburgh Gym: the column up to Roark") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const TileGrid& gym = OreburghGym::grid(); + if (!gym.standable(OreburghGym::ENTRANCE)){ + return "The entrance tile is not standable."; + } + if (gym.at(OreburghGym::ENTRANCE.next(Direction::SOUTH)) != TileType::DOOR){ + return "The door is not below the entrance tile."; + } + if (gym.at(OreburghGym::ROARK) != TileType::NPC){ + return "Roark is not on an NPC tile."; + } + const Pokemon::WallHit up = Pokemon::walk_to_wall(gym, OreburghGym::ENTRANCE, Direction::NORTH); + if (!(up.wall == OreburghGym::ROARK)){ + return "North from the entrance stops at " + Pokemon::to_string(up.stop) + ", not in front of Roark."; + } + logger.log("Oreburgh Gym: north from the entrance walks " + std::to_string(up.tiles) + " tiles to Roark."); + for (const Pokemon::TrainerSight& trainer : OreburghGym::trainer_sights()){ + if (gym.at(trainer.pos) != TileType::NPC){ + return trainer.name + " is not on an NPC tile."; + } + const std::vector seen = Pokemon::sight_tiles(gym, trainer); + const bool sees_column = std::ranges::any_of(seen, [&](const TilePos& pos){ + return pos.x == OreburghGym::ENTRANCE.x && pos.y < OreburghGym::ENTRANCE.y && pos.y > OreburghGym::ROARK.y; + }); + if (!sees_column){ + return trainer.name + " does not see the column up to Roark."; + } + std::string text = "Oreburgh Gym: " + trainer.name + " sees"; + for (const TilePos& pos : seen){ + text += " " + Pokemon::to_string(pos); + } + logger.log(text); + } + return true; + } +}; + +} + + +void add_tests_AutoStory_Segment00(UnitTestDatabase& database){ + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h new file mode 100644 index 0000000000..a956b4073c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory Segment 00 Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Offline checks of Segment 00's walked lines against the grids and the +// scenes' trigger rectangles, and of the Oreburgh Gym's inside. +void add_tests_AutoStory_Segment00(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a97fc4ebb0..d0c16d6bac 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1452,6 +1452,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_MapData.cpp Source/Pokemon/Navigation/Pokemon_MapData.h Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp + Source/Pokemon/Navigation/Pokemon_MapSet.cpp + Source/Pokemon/Navigation/Pokemon_MapSet.h Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h Source/Pokemon/Navigation/Pokemon_RouteLog.cpp Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -1459,6 +1461,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_StoryEvents.cpp Source/Pokemon/Navigation/Pokemon_StoryEvents.h Source/Pokemon/Navigation/Pokemon_StoryEvents_Tests.cpp + Source/Pokemon/Navigation/Pokemon_TileGrid.cpp + Source/Pokemon/Navigation/Pokemon_TileGrid.h Source/Pokemon/Navigation/Pokemon_StorySegments.cpp Source/Pokemon/Navigation/Pokemon_StorySegments.h Source/Pokemon/Navigation/Pokemon_StorySegments_Tests.cpp @@ -1526,6 +1530,52 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Resources/Pokemon_PokemonNames.h Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp Source/Pokemon/Resources/Pokemon_PokemonSlugs.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py new file mode 100644 index 0000000000..51e8e3c2e0 --- /dev/null +++ b/devtools/maps/bdsp_maps.py @@ -0,0 +1,53 @@ +"""Checks that Packages' BDSP AutoStory maps are the ones in this repository. + +Usage: + python3 devtools/maps/bdsp_maps.py --check --json-dir Packages/Resources/PokemonBDSP/Maps + +The maps are JSON files in the shared map schema +(SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h). They live in +SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps, where CMake builds +them into the program (pa_embed_text_files()). Once Packages has copies in +Resources/PokemonBDSP/Maps, the two must be the same files: --check exits +1, naming the first that differs, if they are not. + +TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonBDSP/Maps) when ready. +Until then the program reads only the repository's copies, and this check +is for that move. + +The files were converted once (at ddcbdb21c) from the C++ tables that +pret/pokediamond's maps had been decoded into; nothing builds them now. +""" +import argparse +import os +import sys + +REPO_MAPS = 'SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps' + + +def json_files(folder): + return sorted(name for name in os.listdir(folder) if name.endswith('.json')) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) + parser.add_argument('--check', action='store_true', required=True, + help='compare the repository\'s maps with --json-dir\'s, byte for byte') + parser.add_argument('--json-dir', required=True, help='Packages\' Resources/PokemonBDSP/Maps') + parser.add_argument('--repo', default='.', help='Arduino-Source checkout') + args = parser.parse_args() + repo_maps = os.path.join(args.repo, REPO_MAPS) + ours, theirs = json_files(repo_maps), json_files(args.json_dir) + if ours != theirs: + print('The map files differ: only here ' + str(sorted(set(ours) - set(theirs))) + + ', only in ' + args.json_dir + ' ' + str(sorted(set(theirs) - set(ours))) + '.') + sys.exit(1) + for name in ours: + with open(os.path.join(repo_maps, name), 'rb') as a, open(os.path.join(args.json_dir, name), 'rb') as b: + if a.read() != b.read(): + print(name + ': differs from ' + os.path.join(args.json_dir, name) + '.') + sys.exit(1) + print(str(len(ours)) + ' maps: the same files.') + + +if __name__ == '__main__': + main() From c3c16c89a34d2b519dfd37306c4e4b591b92157a Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 12:08:46 -0800 Subject: [PATCH 02/74] BDSP navigation: the walker, with battles passed in Walks the planned routes on the BDSP story maps: Walk holds a direction and stops on what the screen shows (a dialogue, a transition, a wall), RouteWalk walks a plan's legs, tracks the tiles the player may be on and plans again after a trainer, and leaves buildings by indoors() and the door's fade. The walker sees wild battles and trainers start but does not fight them: a WildBattleEscape runs from a wild battle and a RouteTrainerFight fights a trainer, both passed in by the program. Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters, kept nearly as written: the AutoStory OverworldDetector and TransitionWatchers, which the walker uses to see the overworld and an encounter's white flash. Tests: indoors() on synthetic screens and screenshots, the door's fade, and the location banner reads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_TransitionWatchers.cpp | 36 + .../PokemonBDSP_TransitionWatchers.h | 56 ++ .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...okemonBDSP_AutoStory_OverworldDetector.cpp | 135 +++ .../PokemonBDSP_AutoStory_OverworldDetector.h | 98 ++ .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 225 +++++ .../PokemonBDSP_AutoStory_Walk_Tests.h | 27 + .../Utils/PokemonBDSP_AutoStory_Indoors.cpp | 60 ++ .../Utils/PokemonBDSP_AutoStory_Indoors.h | 33 + .../Utils/PokemonBDSP_AutoStory_Location.cpp | 135 +++ .../Utils/PokemonBDSP_AutoStory_Location.h | 65 ++ .../PokemonBDSP_AutoStory_OverlayLog.cpp | 42 + .../Utils/PokemonBDSP_AutoStory_OverlayLog.h | 27 + .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 926 ++++++++++++++++++ .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 203 ++++ .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 469 +++++++++ .../Utils/PokemonBDSP_AutoStory_Walk.h | 172 ++++ SerialPrograms/cmake/SourceFiles.cmake | 16 + 18 files changed, 2727 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp new file mode 100644 index 0000000000..3655b5244d --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp @@ -0,0 +1,36 @@ +#include "PokemonBDSP_TransitionWatchers.h" +namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +WhiteScreenOverWatcher::WhiteScreenOverWatcher( + Color color, const ImageFloatBox& box, + double min_rgb_sum, + double max_stddev_sum, + std::chrono::milliseconds hold_duration, + std::chrono::milliseconds release_duration +) + : VisualInferenceCallback("WhiteScreenOverWatcher") + , m_on(color, box, min_rgb_sum, max_stddev_sum, WhiteScreenWatcher::FinderType::PRESENT, hold_duration) + , m_off(color, box, min_rgb_sum, max_stddev_sum, WhiteScreenWatcher::FinderType::GONE, release_duration) +{} +void WhiteScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ + m_on.make_overlays(items); +} +bool WhiteScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (m_white_is_over.load(std::memory_order_acquire)){ + return true; + } + if (!m_has_been_white){ + m_has_been_white = m_on.process_frame(frame, timestamp); + return false; + } + bool is_over = m_off.process_frame(frame, timestamp); + if (!is_over){ + return false; + } + m_white_is_over.store(true, std::memory_order_release); + return true; +} +bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ + return m_white_is_over.load(std::memory_order_acquire); +} + +}}} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h new file mode 100644 index 0000000000..ce5a34d2cb --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h @@ -0,0 +1,56 @@ +#pragma once +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +// AutoStory-specific transition handling; shared watchers retain upstream behavior. +class WhiteScreenWatcher : public DetectorToFinder{ +public: + WhiteScreenWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double min_rgb_sum = 500, + double max_stddev_sum = 10, + FinderType finder_type = FinderType::PRESENT, + std::chrono::milliseconds duration = std::chrono::milliseconds(100) + ) + : DetectorToFinder("WhiteScreenWatcher", finder_type, duration, color, box, min_rgb_sum, max_stddev_sum) + {} +}; + +class BlackScreenFlashWatcher : public BlackScreenOverWatcher{ +public: + BlackScreenFlashWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(20), + std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) + ) + : BlackScreenOverWatcher(color, box, max_rgb_sum, max_stddev_sum, hold_duration, release_duration) + {} +}; + +class WhiteScreenOverWatcher : public VisualInferenceCallback{ +public: + WhiteScreenOverWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double min_rgb_sum = 500, + double max_stddev_sum = 10, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(100), + std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) + ); + + bool white_is_over(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + WhiteScreenWatcher m_on; + WhiteScreenWatcher m_off; + bool m_has_been_white = false; + std::atomic m_white_is_over = false; +}; +}}} diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 608126f0db..56338bad77 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -7,6 +7,7 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -18,6 +19,7 @@ namespace PokemonBDSP{ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_MapGrids(database); add_tests_AutoStory_Segment00(database); + add_tests_AutoStory_Walk(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp new file mode 100644 index 0000000000..3e4e0f41ca --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp @@ -0,0 +1,135 @@ +/* BDSP AutoStory - Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/Images/SolidColorTest.h" + +#include "PokemonBDSP_AutoStory_OverworldDetector.h" + +using namespace std::chrono_literals; + +namespace PokemonAutomation { +namespace NintendoSwitch { +namespace PokemonBDSP { + + +// --------------------------------------------------------------------------- +// OverworldDetector +// --------------------------------------------------------------------------- + +OverworldDetector::OverworldDetector(Color color) + : m_color(color) + , m_battle_menu(BattleType::STANDARD, color){ +} + +void OverworldDetector::make_overlays(VideoOverlaySet& items) const { + m_dialog.make_overlays(items); + m_battle_menu.make_overlays(items); + m_menu.make_overlays(items); +} + +bool OverworldDetector::detect(const ImageViewRGB32& screen){ + // We are in the overworld when none of the overlay screens are present. + if (m_dialog.detect(screen)){ + return false; + } + if (m_battle_menu.detect(screen)){ + return false; + } + if (m_menu.detect(screen)){ + return false; + } + return true; +} + + +// --------------------------------------------------------------------------- +// OverworldWatcher +// --------------------------------------------------------------------------- + +OverworldWatcher::OverworldWatcher(Color color) + : OverworldDetector(color) + , VisualInferenceCallback("OverworldWatcher"){ +} + +void OverworldWatcher::make_overlays(VideoOverlaySet& items) const { + OverworldDetector::make_overlays(items); +} + +bool OverworldWatcher::process_frame(const ImageViewRGB32& frame, WallClock /*timestamp*/){ + return detect(frame); +} + + +// --------------------------------------------------------------------------- +// PoketchButtonDetector +// --------------------------------------------------------------------------- + +PoketchButtonDetector::PoketchButtonDetector(Color color) + : m_color(color) + , m_button(0.968, 0.170, 0.022, 0.120){ +} + +void PoketchButtonDetector::make_overlays(VideoOverlaySet& items) const { + items.add(m_color, m_button); +} + +bool PoketchButtonDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats = image_stats(extract_box_reference(screen, m_button)); + // The button is a glossy red with a highlight, so allow a wide stddev. + return is_solid(stats, {0.74, 0.10, 0.16}, 0.12, 80); +} + +PoketchButtonWatcher::PoketchButtonWatcher(Color color) + : PoketchButtonDetector(color) + , VisualInferenceCallback("PoketchButtonWatcher"){ +} + +void PoketchButtonWatcher::make_overlays(VideoOverlaySet& items) const { + PoketchButtonDetector::make_overlays(items); +} + +bool PoketchButtonWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ + return detect(frame); +} + + +static bool look_for_poketch_button(VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + PoketchButtonWatcher watcher; + return wait_until(stream, context, 2s, {{watcher}}) == 0; +} + +bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context){ + for (size_t attempt = 0; attempt < 3; attempt++){ + if (look_for_poketch_button(stream, context)){ + return true; + } + stream.log("[AutoStory] Poketch button not found. Attempt " + std::to_string(attempt + 1) + " of 3.", + COLOR_ORANGE); + + if (attempt == 0){ + // Most likely hidden: one tap shows it. + pbf_press_button(context, BUTTON_R, 205ms, 0ms); + }else{ + // Long press hides it, then a tap shows it at the normal size. + pbf_press_button(context, BUTTON_R, 1548ms, 0ms); + pbf_wait(context, 1418ms); + pbf_press_button(context, BUTTON_R, 143ms, 0ms); + } + } + + // Check the result of the last press sequence. + return look_for_poketch_button(stream, context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h new file mode 100644 index 0000000000..4741325711 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h @@ -0,0 +1,98 @@ +/* BDSP AutoStory - Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detects that the player is in the free-roaming overworld state: + * no dialog box, no battle menu, and no in-game menu open. + * + * BDSP does not ship a standalone OverworldDetector in PokemonBDSP/Inference/, + * so this composite detector is defined here for AutoStory use. + * + * Reuses: + * - ShortDialogDetector (PokemonBDSP_DialogDetector.h) — absence required + * - BattleMenuDetector (PokemonBDSP_BattleMenuDetector.h) — absence required + * - MenuDetector (PokemonBDSP_MenuDetector.h) — absence required + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OverworldDetector_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OverworldDetector_H + +#include "Common/Cpp/Color.h" + +#include "CommonFramework/Tools/VideoStream.h" + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" + +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" + +namespace PokemonAutomation { +namespace NintendoSwitch { +namespace PokemonBDSP { + + +// Static (single-frame) version — use when you already have a frame. +class OverworldDetector : public StaticScreenDetector { +public: + OverworldDetector(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Returns true when none of: short dialog, battle menu, or in-game menu + // are present on the given frame. + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ShortDialogDetector m_dialog; + BattleMenuDetector m_battle_menu; + MenuDetector m_menu; +}; + + +// Watcher (callback) version — use with run_until<> or wait_until(). +class OverworldWatcher : public OverworldDetector, public VisualInferenceCallback { +public: + OverworldWatcher(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + +// Detects the big red button on the right edge of the Poketch overlay. +// Present only while the Poketch is shown at its normal size. +class PoketchButtonDetector : public StaticScreenDetector { +public: + PoketchButtonDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_button; +}; + +class PoketchButtonWatcher : public PoketchButtonDetector, public VisualInferenceCallback { +public: + PoketchButtonWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + +// Tries up to 3 times to get the Poketch button on screen using R presses. +// Returns true if the button was seen. +bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp new file mode 100644 index 0000000000..cb6ab3bb54 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -0,0 +1,225 @@ +/* BDSP AutoStory Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Utils/PokemonBDSP_AutoStory_Indoors.h" +#include "Utils/PokemonBDSP_AutoStory_Location.h" +#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_Walk_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// indoors() decides when leave_door_south() is out: r257 walked on south +// past Sandgem's road into a house after leaving the Center, because the +// evening tint made the outside as warm as a room. Synthetic screens: the +// evening outside (warm all over), a room (warm, black along the bottom), +// a fade (black all over), and warm with a thin dark edge (a shadow). +struct IndoorsCase{ + std::string name; + uint32_t fill; + double dark_bottom; // how much of the screen's height, from the bottom, is black + bool indoors; +}; + +class Test_IndoorsAnyLight : public UnitTest{ +public: + Test_IndoorsAnyLight() + : UnitTest("PokemonBDSP::AutoStory - indoors() under the evening tint") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "evening outside, orange all over", .fill = 0xffe0a040, .dark_bottom = 0, .indoors = false}, + {.name = "a room: orange, black below its floor", .fill = 0xffe0a040, .dark_bottom = 0.10, .indoors = true}, + {.name = "a fade: black all over", .fill = 0xff000000, .dark_bottom = 0, .indoors = false}, + {.name = "orange with a thin shadow at the bottom", .fill = 0xffe0a040, .dark_bottom = 0.01, .indoors = false}, + {.name = "daytime grass", .fill = 0xff60b040, .dark_bottom = 0.10, .indoors = false}, + }; + for (const IndoorsCase& item : cases){ + ImageRGB32 screen(1920, 1080); + const size_t dark_from = (size_t)(1080 * (1 - item.dark_bottom)); + for (size_t y = 0; y < 1080; y++){ + for (size_t x = 0; x < 1920; x++){ + screen.pixel(x, y) = y >= dark_from ? 0xff000000 : item.fill; + } + } + if (indoors(screen) != item.indoors){ + return item.name + (item.indoors ? ": read as outside." : ": read as inside."); + } + } + return true; + } +}; + +// door_fade_look(): out of a door is a dark look, then a bright one that is +// not a room. r259 turned round in Sandgem's lit Center, read "not a room" +// once at full brightness, and walked east inside it as if outside. +struct DoorLook{ + double brightness; + bool room; +}; +struct DoorCase{ + std::string name; + std::vector looks; + // The look (1-based) that reads out, or 0 for none. + size_t out_at; +}; + +class Test_DoorFade : public UnitTest{ +public: + Test_DoorFade() + : UnitTest("PokemonBDSP::AutoStory - out of a door needs its fade") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "r259: a bright look in the Center that misses the room", .looks = {{458, true}, {440, false}, {457, true}}, .out_at = 0}, + {.name = "the fade, then the town", .looks = {{458, true}, {300, true}, {60, false}, {310, false}}, .out_at = 4}, + {.name = "the fade, then the room again", .looks = {{458, true}, {60, false}, {420, true}}, .out_at = 0}, + {.name = "the fade, still dim", .looks = {{60, false}, {150, false}, {320, false}}, .out_at = 3}, + }; + for (const DoorCase& item : cases){ + DoorFadeWatch watch; + size_t out_at = 0; + for (size_t i = 0; i < item.looks.size() && out_at == 0; i++){ + if (door_fade_look(watch, item.looks[i].brightness, item.looks[i].room)){ + out_at = i + 1; + } + } + if (out_at != item.out_at){ + return item.name + ": out at look " + std::to_string(out_at) + ", expected " + std::to_string(item.out_at) + "."; + } + } + return true; + } +}; + + +class Test_LocationBanner : public UnitTest{ +public: + Test_LocationBanner() + : UnitTest("PokemonBDSP::AutoStory - location banner match") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + struct Case{ + const char* read; + const char* expected; + bool match; + }; + const Case cases[] = { + {"sandgemtown", "Sandgem Town", true}, + {"andgemltown", "Sandgem Town", true}, // r109's OCR + {"Route 202", "Route 202", true}, + {"route2o2", "Route 202", false}, // a digit read as a letter is not trusted + {"route201", "Route 202", false}, + {"jubilifecity", "Sandgem Town", false}, + {"twinleaftown", "Sandgem Town", false}, + {"", "Sandgem Town", false}, + }; + for (const Case& c : cases){ + if (location_banner_matches(c.read, c.expected) != c.match){ + return std::string("Banner \"") + c.read + "\" for " + c.expected + + (c.match ? " should match." : " should not match."); + } + } + return true; + } +}; + + +class Test_Indoors : public UnitTest{ +public: + Test_Indoors() + : UnitTest("PokemonBDSP::AutoStory - indoors") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + struct Case{ const char* file; bool inside; }; + const Case cases[] = { + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c4.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterInsideUpper-20261030-r151a.png", true}, + {"PokemonBDSP/AutoStory/SandgemCenterInside-20261030-053555.png", true}, + {"PokemonBDSP/AutoStory/JubilifeSchoolInside-20261030.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", false}, + {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep-20261030.png", false}, + {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep2-20261030.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterFrontDoor-20261030-q2.png", false}, + {"PokemonBDSP/AutoStory/SandgemCenterBelowSign-20261030-053527.png", false}, + {"PokemonBDSP/AutoStory/SandgemMartDoorUpRight-20261030-023443.png", false}, + }; + for (const Case& c : cases){ + const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; + if (!Filesystem::is_regular_file(path)){ + return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); + } + const bool inside = indoors(ImageRGB32(path)); + logger.log(std::string(c.file) + ": " + (inside ? "indoors" : "outside")); + if (inside != c.inside){ + return std::string(c.file) + ": expected " + (c.inside ? "indoors" : "outside") + "."; + } + } + return true; + } +}; + + +class Test_LocationBannerShowing : public UnitTest{ +public: + Test_LocationBannerShowing() + : UnitTest("PokemonBDSP::AutoStory - location banner showing") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + struct Case{ const char* file; bool banner; }; + const Case cases[] = { + {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", true}, + {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep-20261030.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c4.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterInsideUpper-20261030-r151a.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterFrontDoor-20261030-q2.png", false}, + }; + for (const Case& c : cases){ + const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; + if (!Filesystem::is_regular_file(path)){ + return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); + } + const bool banner = location_banner_showing(ImageRGB32(path)); + logger.log(std::string(c.file) + ": banner " + (banner ? "shows" : "none")); + if (banner != c.banner){ + return std::string(c.file) + ": expected " + (c.banner ? "a banner" : "no banner") + "."; + } + } + return true; + } +}; + + +} + + +void add_tests_AutoStory_Walk(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); + database.add(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h new file mode 100644 index 0000000000..ac120c6244 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Walk_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Walk_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The walker's screen reads: indoors() on synthetic screens and +// screenshots, the door's fade, and the location banner. +void add_tests_AutoStory_Walk(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp new file mode 100644 index 0000000000..8819372066 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp @@ -0,0 +1,60 @@ +/* BDSP AutoStory - Indoors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "PokemonBDSP_AutoStory_Indoors.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// Near-black pixels in one edge strip of the screen, out of all its pixels. +struct EdgeDark{ + size_t dark = 0; + size_t count = 0; +}; +void add_pixel(EdgeDark& edge, bool dark){ + edge.dark += dark; + edge.count++; +} +bool mostly_dark(const EdgeDark& edge){ + return edge.count > 0 && edge.dark * 100 >= edge.count * 15; +} + +} + +bool indoors(const ImageViewRGB32& screen){ + const size_t width = screen.width(), height = screen.height(); + const size_t strip_h = height * 12 / 100, strip_w = width * 12 / 100; + size_t warm = 0; + size_t count = 0; + EdgeDark top, bottom, left, right; + for (size_t y = 0; y < height; y += 8){ + for (size_t x = 0; x < width; x += 8){ + const Color pixel(screen.pixel(x, y)); + count++; + warm += pixel.red() > 150 && pixel.red() > pixel.blue() + 70 && pixel.green() > pixel.blue() + 20; + const bool dark = pixel.red() + pixel.green() + pixel.blue() < 60; + if (y < strip_h){ add_pixel(top, dark); } + if (y >= height - strip_h){ add_pixel(bottom, dark); } + if (x < strip_w){ add_pixel(left, dark); } + if (x >= width - strip_w){ add_pixel(right, dark); } + } + } + if (count == 0 || warm * 4 <= count){ + return false; + } + return mostly_dark(top) || mostly_dark(bottom) || mostly_dark(left) || mostly_dark(right); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h new file mode 100644 index 0000000000..0d469836d0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h @@ -0,0 +1,33 @@ +/* BDSP AutoStory - Indoors + * + * From: https://github.com/PokemonAutomation/ + * + * Whether the screen shows a room: the walker leaves a building by it. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Indoors_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Indoors_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Whether the screen shows a building's inside: its warm walls and floor +// fill much of the view (Pokemon Centers, the Trainers' School: 42..65% of +// the screen), and the room floats in black, which shows along at least one +// edge (15% or more of a strip 12% deep). Warmth alone is not enough: the +// evening tint makes outside 50..72% warm (r256, r257, Sandgem), and +// Oreburgh's ground 58..69% by day. Of 1412 lab screenshots, the rule calls +// every outside one outside, at all hours, and the rooms rooms. A fade is +// dark everywhere but not warm, so it is not inside. +bool indoors(const ImageViewRGB32& screen); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp new file mode 100644 index 0000000000..ecf90056c7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -0,0 +1,135 @@ +/* BDSP AutoStory - Location + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Language.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_RawTesseractOCR.h" +#include "PokemonBDSP_AutoStory_Location.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// The location banner: a white box at the top left that names a map for a +// few seconds after the player enters it. Left of the centred name it is plain +// white (251 on console B, against 27-75 for the trees there otherwise). +const ImageFloatBox LOCATION_BANNER_WHITE{0.035, 0.035, 0.085, 0.050}; +const ImageFloatBox LOCATION_BANNER_TEXT{0.100, 0.025, 0.300, 0.080}; + +// The save card's header: the map's name in salmon (255, 152, 140) on near +// white (245), top left, right of the card's red border. Too faint for OCR +// as it is: the reddish pixels are made black on white first. +const ImageFloatBox SAVE_SCREEN_LOCATION{0.036, 0.045, 0.274, 0.070}; +const uint32_t SAVE_SCREEN_TEXT_MIN = 0xff960000; +const uint32_t SAVE_SCREEN_TEXT_MAX = 0xffffa9a9; + +std::string digits_of(const std::string& text){ + std::string out; + for (char ch : text){ + if (std::isdigit((unsigned char)ch)){ + out.push_back(ch); + } + } + return out; +} + +} + + +std::string normalize_location_name(const std::string& text){ + std::string out; + for (unsigned char ch : text){ + if (std::isalnum(ch)){ + out.push_back((char)std::tolower(ch)); + } + } + return out; +} + +Language g_story_language = Language::English; + +bool story_reads_text(){ + return story_reads_text(g_story_language); +} + +bool story_reads_text(Language language){ + return language == Language::English; +} + +bool location_banner_showing(const ImageViewRGB32& screen){ + const ImageStats white = image_stats(extract_box_reference(screen, LOCATION_BANNER_WHITE)); + return white.average.sum() >= 690 && white.stddev.sum() <= 30; +} + +std::string location_banner_stats(const ImageViewRGB32& screen){ + const ImageStats white = image_stats(extract_box_reference(screen, LOCATION_BANNER_WHITE)); + return "mean " + std::to_string((int)white.average.sum()) + ", spread " + std::to_string((int)white.stddev.sum()); +} + +std::string read_location_banner(const ImageViewRGB32& screen){ + if (!location_banner_showing(screen)){ + return ""; + } + if (!story_reads_text()){ + return UNREAD_LOCATION; + } + return normalize_location_name(OCR::tesseract_ocr_read(Language::English, + extract_box_reference(screen, LOCATION_BANNER_TEXT))); +} + +std::string read_save_screen_location(const ImageViewRGB32& screen){ + if (!story_reads_text()){ + return UNREAD_LOCATION; + } + const ImageRGB32 text = to_blackwhite_rgb32_range( + extract_box_reference(screen, SAVE_SCREEN_LOCATION), true, SAVE_SCREEN_TEXT_MIN, SAVE_SCREEN_TEXT_MAX); + return normalize_location_name(OCR::tesseract_ocr_read(Language::English, text)); +} + +bool location_banner_matches(const std::string& read, const std::string& expected){ + // No reader for the game's language: a banner (or the save card) that + // showed is all there is; where we stand is the walk's to say. + if (read == UNREAD_LOCATION){ + return true; + } + const std::string a = normalize_location_name(read); + const std::string b = normalize_location_name(expected); + if (a.empty() || b.empty()){ + return false; + } + if (digits_of(a) != digits_of(b)){ + return false; + } + // Levenshtein distance. + std::vector row(b.size() + 1); + for (size_t j = 0; j <= b.size(); j++){ + row[j] = j; + } + for (size_t i = 1; i <= a.size(); i++){ + size_t diagonal = row[0]; + row[0] = i; + for (size_t j = 1; j <= b.size(); j++){ + const size_t above = row[j]; + row[j] = std::min({row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)}); + diagonal = above; + } + } + return row[b.size()] <= std::max(1, b.size() / 4); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h new file mode 100644 index 0000000000..4294ede6eb --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h @@ -0,0 +1,65 @@ +/* BDSP AutoStory - Location + * + * From: https://github.com/PokemonAutomation/ + * + * Where the game says the player is: the location banner shown on entering + * a map, and the map named on the save screen's card. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Location_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Location_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Lower-case letters and digits only: "Route 202" and "ROUTE 2O2 " compare +// by "route202". +std::string normalize_location_name(const std::string& text); + +// The game's language, for the reads that still use text (item names, the +// location banner, a sign's or talk's first box), set from the program's +// options (StoryRunOptions). story_reads_text() says whether those reads +// have a model and dictionary for it (English only, so far); when not, +// callers use language-free checks: the banner's box showing, a sign's box +// opening, the first row of a Bag pocket. +extern Language g_story_language; +bool story_reads_text(); +bool story_reads_text(Language language); + +// What the reads below return for a banner or save card that showed, when +// there is no text reader for the game's language (story_reads_text()): +// location_banner_matches() takes it as a match. +inline const std::string UNREAD_LOCATION = "(unread)"; + +// The location banner (the white box at the top left that names a map for a +// few seconds after the player enters it), read by OCR and normalized; +// empty when no banner shows. +std::string read_location_banner(const ImageViewRGB32& screen); +// Whether the location banner's white box shows, without reading it. +bool location_banner_showing(const ImageViewRGB32& screen); +// The banner box's mean and spread, for the log. +std::string location_banner_stats(const ImageViewRGB32& screen); + +// The map named at the top left of the save screen's card ("Sandgem Town", +// "Route 202"), read by OCR and normalized; empty if nothing reads. +std::string read_save_screen_location(const ImageViewRGB32& screen); + +// Whether the location banner's OCR `read` names the map `expected`. Both +// are compared as lower-case letters and digits. OCR drops or swaps letters +// ("andgemltown" for Sandgem Town on r109), so up to a quarter of the name's +// letters may differ; the digits must match exactly, so Route 201 is never +// read as Route 202. +bool location_banner_matches(const std::string& read, const std::string& expected); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp new file mode 100644 index 0000000000..7ac01390db --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp @@ -0,0 +1,42 @@ +/* BDSP AutoStory - Overlay Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_OverlayLog.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color){ + // The log box is 35% of the video wide at a font 4% of its height: about + // 34 characters. + constexpr size_t WIDTH = 34; + std::string line; + size_t start = 0; + while (start < text.size()){ + size_t end = text.find(' ', start); + if (end == std::string::npos){ + end = text.size(); + } + const std::string word = text.substr(start, end - start); + if (!line.empty() && line.size() + 1 + word.size() > WIDTH){ + overlay.add_log(line, color); + line = " "; + } + line += (line.empty() || line == " " ? "" : " ") + word; + start = end + 1; + } + if (!line.empty()){ + overlay.add_log(line, color); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h new file mode 100644 index 0000000000..f030b54f1c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Overlay Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OverlayLog_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OverlayLog_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Adds `text` to the video overlay's log, split at spaces into lines short +// enough for the log box, which draws each line on one row and cuts it off. +void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp new file mode 100644 index 0000000000..8b32093da4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -0,0 +1,926 @@ +/* BDSP AutoStory - Route Walk + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" +#include "PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_Walk.h" +#include "PokemonBDSP_AutoStory_Indoors.h" +#include "PokemonBDSP_AutoStory_OverlayLog.h" +#include "PokemonBDSP_AutoStory_RouteWalk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using namespace Pokemon; + + +namespace{ + +bool across(Direction direction){ + return direction == Direction::EAST || direction == Direction::WEST; +} + +Milliseconds ms_per_tile(Direction direction){ + return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; +} + +// The left stick for a direction. Row 0 is the top of a map, and the stick's +// y is positive upward. +void stick_for(Direction direction, double& x, double& y){ + x = 0; + y = 0; + switch (direction){ + case Direction::NORTH: y = 1; break; + case Direction::EAST: x = 1; break; + case Direction::SOUTH: y = -1; break; + case Direction::WEST: x = -1; break; + } +} + +// World tiles as tiles of the named maps, for the shared route log +// (Pokemon_RouteLog.h); a tile no map holds is a "world" tile. +std::vector route_tiles(const MapSet& maps, const std::vector& tiles){ + std::vector out; + for (const TilePos& pos : tiles){ + const std::optional local = maps.to_local(pos); + out.push_back(local ? RouteTile{local->map, local->pos} : RouteTile{"world", pos}); + } + return out; +} + +std::string describe(const MapSet& maps, const std::vector& tiles){ + return Pokemon::describe(route_tiles(maps, tiles)); +} + +RouteLogLeg route_log_leg(const TileLeg& leg){ + return {.action = RouteLegAction::WALK, .direction = leg.direction, .tiles = leg.tiles, + .end = leg.ends_at_wall ? RouteLegEnd::WALL : RouteLegEnd::OPEN}; +} + +PlannedRouteLeg planned_route_leg(const MapSet& maps, const PlannedLeg& leg){ + return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; +} + +void log_plan(VideoStream& stream, const MapSet& maps, const std::string& label, const std::vector& from, const std::vector& legs){ + std::vector logged; + for (const PlannedLeg& leg : legs){ + logged.push_back(planned_route_leg(maps, leg)); + } + stream.log(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged)); +} + +// Logs a leg that ended on its planned tiles, and how that is known: an +// open leg counts its taps through a wild battle, so its end is assumed; a +// leg to a wall is walked again to its wall. +void log_leg_done(VideoStream& stream, const MapSet& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ + const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; + stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), + assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); +} + +// The tiles the player passes when walking `tiles` tiles from `from`, the +// first one after `from` first. Stops early where the player is stopped. +std::vector leg_path(const TileGrid& grid, TilePos from, Direction direction, size_t tiles){ + std::vector path; + size_t travelled = 0; + while (travelled < tiles){ + const std::optional next = grid.step(from, direction); + if (!next){ + break; + } + travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); + from = *next; + path.push_back(from); + } + return path; +} + +// Holding toward a wall with people or Pokemon moving beside us never reads +// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking +// scrolls the view far more (35 to 90). True if holding toward (x, y) for +// 1.6 s changes the screen less than walking would: we stand at a wall. +bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ + constexpr double WALKING_CHANGE = 25.0; + context.wait_for_all_requests(); + VideoSnapshot before = stream.video().snapshot(); + double most = 0; + for (size_t chunk = 0; chunk < 4 && before; chunk++){ + pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); + context.wait_for_all_requests(); + VideoSnapshot after = stream.video().snapshot(); + if (!after){ + return false; + } + most = std::max(most, walk_screen_change(*before.frame, *after.frame)); + before = std::move(after); + } + stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + + (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); + return before && most < WALKING_CHANGE; +} + +// The map all of `tiles` are on, or empty if they are on several or none. +std::string map_of(const MapSet& maps, const std::vector& tiles){ + std::string name; + for (const TilePos& pos : tiles){ + const std::optional tile = maps.to_local(pos); + if (!tile || (!name.empty() && tile->map != name)){ + return ""; + } + name = tile->map; + } + return name; +} + +} + + +bool route_wall_readable(const TileGrid& grid, const std::vector& after){ + return std::none_of(after.begin(), after.end(), [&](const TilePos& pos){ + return grid.at(pos) == TileType::TALL_GRASS; + }); +} + +void route_status(VideoStream& stream, const std::string& text){ + stream.log("[Route] " + text, COLOR_BLUE); + add_wrapped_log(stream.overlay(), text, COLOR_WHITE); +} + +Milliseconds route_open_hold(Direction direction, size_t tiles){ + const Milliseconds step = ms_per_tile(direction); + return step * tiles - step / 2; +} + +void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ + double x, y; + stick_for(direction, x, y); + stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); + pbf_move_left_joystick(context, {x, y}, ROUTE_TURN_TAP, 300ms); + context.wait_for_all_requests(); +} + +std::optional talk_to_adjacent_npc( + VideoStream& stream, ProControllerContext& context, + const std::vector& directions, + const std::string& label, Milliseconds wait +){ + for (Direction direction : directions){ + route_turn(stream, context, direction); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, wait, {{dialog}}) == 0){ + stream.log("[Route] " + label + ": answered from the " + direction_name(direction) + "."); + return direction; + } + } + stream.log("[Route] " + label + ": nobody answered next to us."); + return std::nullopt; +} + +bool talk_with_nudges( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + Direction facing, const std::string& label, Milliseconds wait, + const std::function& accept +){ + const bool vertical = facing == Direction::NORTH || facing == Direction::SOUTH; + const Direction minus = vertical ? Direction::WEST : Direction::NORTH; + const Direction plus = vertical ? Direction::EAST : Direction::SOUTH; + int at = 0; + for (int offset : {0, -1, 1, -2, 2}){ + const Direction side = offset < at ? minus : plus; + for (; at != offset; at += offset < at ? -1 : 1){ + double x, y; + stick_for(side, x, y); + pbf_move_left_joystick(context, {x, y}, ROUTE_NUDGE_TAP, 300ms); + } + if (offset != 0){ + route_turn(stream, context, facing); + // A tap in a cave or in grass can start a wild battle, after + // which we are not where the nudges think: let the caller line up again. + if (run_from_late_encounter(stream, context, escape, label + ": nudge")){ + return false; + } + } + context.wait_for_all_requests(); + const VideoSnapshot before = stream.video().snapshot(); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, wait, {{dialog}}) == 0){ + const VideoSnapshot after = stream.video().snapshot(); + if (!accept || (before && after && accept(*before.frame, *after.frame))){ + stream.log("[Route] " + label + ": answered " + std::to_string(offset) + " nudge(s) from where we stood."); + return true; + } + stream.log("[Route] " + label + ": something else answered " + std::to_string(offset) + " nudge(s) from where we stood; closing it."); + for (size_t press = 0; press < 3; press++){ + pbf_press_button(context, BUTTON_B, 80ms, 700ms); + } + context.wait_for_all_requests(); + } + } + stream.log("[Route] " + label + ": nobody answered within two nudges either side."); + return false; +} + +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const MapSet& maps, + std::vector from, + const std::function& goal, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const std::vector& avoid, + const RobustPlanCosts& costs +){ + // Our own copy, so things found in the way can be added to it. Tiles to + // avoid are ground the game lets us walk on (a trainer's line of sight), + // so they are off the map, not walls: a leg must not end "at" one, or + // the walk would run on through it. + TileGrid grid = maps.world(); + for (const TilePos& pos : avoid){ + if (std::find(from.begin(), from.end(), pos) == from.end()){ + grid.set(pos, TileType::UNKNOWN); + } + } + // Which way the player faces, once a leg has set it. + std::optional facing; + // Every banner read on the way, to check the map we arrive on against. + const std::string map_start = map_of(maps, from); + std::vector all_banners; + for (size_t plans = 0; plans < 8; plans++){ + std::optional> legs = plan_robust_route(grid, from, goal, costs); + if (!legs){ + // From a few possible tiles the exact-open-leg costs found no + // plan where the default ones did (r240a, three tiles on Route + // 204's row 27); the default plan is longer but sound. + stream.log("[Route] " + label + ": no plan with the route costs from " + describe(maps, from) + + "; trying the default costs.", COLOR_ORANGE); + legs = plan_robust_route(grid, from, goal, RobustPlanCosts()); + } + if (!legs){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": no plan from " + describe(maps, from) + ".", stream); + } + route_status(stream, label + ": " + std::to_string(legs->size()) + " legs planned"); + log_plan(stream, maps, label, from, *legs); + + bool replanned = false; + size_t leg_number = 0; + for (const PlannedLeg& planned : *legs){ + const TileLeg& leg = planned.leg; + leg_number++; + route_status(stream, route_leg_line(leg_number, legs->size(), planned_route_leg(maps, planned))); + double x, y; + stick_for(leg.direction, x, y); + const std::string leg_label = label + ": " + to_string(leg); + + // Note the location banners the walk passes, to check map changes. + // A wild battle or a second walk to the wall may follow the + // banner: any banner seen during the leg counts. + const std::string map_before = map_of(maps, from); + const std::string map_after = map_of(maps, planned.after); + std::vector banners; + auto banner_ok = [&]{ + return std::any_of(banners.begin(), banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_after); + }); + }; + auto watch_banner = [&](const ImageViewRGB32& screen){ + if (banners.empty() || (!map_after.empty() && !banner_ok() && banners.size() < 8)){ + const std::string read = read_location_banner(screen); + if (!read.empty() && (banners.empty() || banners.back() != read)){ + banners.push_back(read); + } + } + return false; + }; + + WalkResult result; + // Tiles the first tap of an open leg moved (see below). + size_t turn_moved = 0; + if (leg.ends_at_wall){ + // Run (B held) on the D-pad: a leg to a wall ends at the wall + // however fast we get there, and the D-pad keeps to the row. + const Milliseconds per_tile = ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; + // Long enough to reach the wall from the farthest tile, with room + // for a slow start; past the wall the player stands still. + const Milliseconds limit = ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; + result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + // A wild battle may end the walk early. Walking to a wall again + // ends in the same place, so finish the leg. + const bool interrupted = result.wild_battles > 0; + for (size_t again = 0; again < 3 && result.wild_battles > 0 && + (result.stop == WalkStop::LIMIT || result.stop == WalkStop::BLOCKED); again++ + ){ + stream.log("[Route] " + leg_label + ": a wild battle on the way; walking to the wall again."); + result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + } + // A wall well before the nearest one the map has: something the + // map does not know is in the way. Work out where we stopped from + // the time walked, put it on our map and plan again from there. + size_t nearest = SIZE_MAX; + for (const TilePos& pos : from){ + nearest = std::min(nearest, walk_to_wall(grid, pos, leg.direction).tiles); + } + auto tiles_moved = [&](const WalkResult& walk){ + const Milliseconds moving = walk.walked - ROUTE_START_DELAY - + (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); + return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); + }; + size_t walked_tiles = tiles_moved(result); + // A stick walk can catch a corner when we stand part of a tile + // off centre, where a D-pad tap, which moves whole tiles, gets + // through: on Route 203's stairs the walk west stopped nine + // times in a row and two taps crossed (r225a, 2026-10-31). + // Tap twice, then walk on to the wall. + if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ + const DpadPosition dpad = + leg.direction == Direction::NORTH ? DPAD_UP : + leg.direction == Direction::SOUTH ? DPAD_DOWN : + leg.direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; + stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); + for (size_t tap = 0; tap < 2; tap++){ + pbf_press_dpad(context, dpad, 160ms, 640ms); + } + context.wait_for_all_requests(); + result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + walked_tiles += tiles_moved(result); + } + // Someone walking about may stand in the way for a moment: wait + // and walk to the wall again before calling it an obstacle. + for (size_t again = 0; !interrupted && again < 2 && + result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++ + ){ + stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + walked_tiles += tiles_moved(result); + } + // Any stop short of the wall's distance: someone who stays put + // is talked to, and the leg is planned again from where we are. + // Within the time count's slack this may be the wall itself, + // where A does nothing and the new plan walks no further (r239a: + // a wanderer 3 tiles short passed as "about 8 of 10", and every + // later leg was off by those tiles). + if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ + // Someone who stays put: talk to them. A trainer we walked up + // to from the side starts the battle this way. + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + { + ShortDialogWatcher dialog(COLOR_YELLOW); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, leg_label + ": someone is in the way; talking to them."); + fight("someone in the way"); + } + } + std::vector stopped; + for (const TilePos& pos : from){ + const std::vector path = leg_path(grid, pos, leg.direction, SIZE_MAX); + for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ + stopped.push_back(k == 0 ? pos : path[k - 1]); + } + } + std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": stopped early, and no tile fits.", stream); + } + if (stopped.size() == 1){ + const TilePos blocker = stopped[0].next(leg.direction); + grid.set(blocker, TileType::BLOCKED); + stream.log("[Route] " + leg_label + ": something the map lacks is at " + + maps.describe(blocker) + "; marked it.", COLOR_ORANGE); + } + stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), + "stopped early after about " + std::to_string(walked_tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); + facing = leg.direction; + from = stopped; + replanned = true; + break; + } + // A leg to the wall that ran out of time is not at its wall: + // the open leg before it stopped short, and it ran along + // another row (r127a went west along Sandgem's row 13 for row + // 14, and the next leg north walked into the lab). Out of tall + // grass a stop reads, so walk on: a player still moving is + // not where the plan has him. + if (!interrupted && result.stop == WalkStop::LIMIT && route_wall_readable(grid, planned.after)){ + const WalkResult check = walk_until_dpad(stream, context, escape, x, y, 2000ms, leg_label + ": at the wall?", nullptr, true); + if (check.stop == WalkStop::DIALOG){ + // A trainer who saw us froze the walk (the "!") until + // its time ran out, then walked over (r241a: Aroma Lady + // Taylor's line crosses Route 204's corridor). Battle, + // then plan again from where a sight line crosses the leg. + route_status(stream, leg_label + ": a trainer stopped us on the way; battling."); + fight("a trainer on the way"); + // Where they saw us from is not reliable (BDSP's trainers + // stand a few tiles from Platinum's, r242a), so do not + // guess the tile: a leg to a wall ends at its wall however + // far it got. Walk on to it. + stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); + result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label + ": on to the wall", watch_banner, true); + } + if (check.stop != WalkStop::BLOCKED && + !(check.stop == WalkStop::LIMIT && holding_against_wall(stream, context, x, y, leg_label + ": at the wall?")) + ){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": ran out of time short of the wall, and walking on gets " + + walk_stop_name(check.stop) + ": not where the plan has us.", stream); + } + } + }else{ + // Whole tiles on the D-pad, a tap each: a tap moves exactly + // one tile, while a stick hold timed for three moved one in + // the Ravaged Path (r235b) and the belief drifted four rows. + // The first tap of a leg was meant to turn, but a 160 ms + // D-pad tap turns and steps whichever way the player faced + // (r248a: all seven did; r246a: "south 1" out of the cave + // went two tiles, onto the Youngster's row), so the tap is + // measured like any other and a step counts for the leg. + if (facing != leg.direction){ + const DpadPosition dpad = x < 0 ? DPAD_LEFT : x > 0 ? DPAD_RIGHT : y > 0 ? DPAD_UP : DPAD_DOWN; + context.wait_for_all_requests(); + VideoSnapshot before = stream.video().snapshot(); + pbf_press_dpad(context, dpad, 160ms, 700ms); + context.wait_for_all_requests(); + VideoSnapshot after = stream.video().snapshot(); + if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ + turn_moved = 1; + stream.log("[Route] " + leg_label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); + } + } + if (leg.tiles > turn_moved){ + result = walk_tiles_dpad(stream, context, escape, x, y, leg.tiles - turn_moved, leg_label); + }else{ + result = WalkResult{WalkStop::LIMIT, 0ms, 0}; + } + // A wild battle starts once the step onto the grass is done, + // so the taps still count; the walk went on after it. + if (result.wild_battles > 0){ + stream.log("[Route] " + leg_label + ": " + std::to_string(result.wild_battles) + + " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); + } + // Taps that moved nothing: someone stands in the way (the + // Youngster below the Ravaged Path wanders across the row + // under the cliff, r239a, r240a). Two still taps end the walk, + // so the tiles moved are the taps less those two. Wait for + // them to move on and tap the rest; someone who stays is + // talked to, put on the map, and the leg planned again from + // the tile we stand on, which the taps give exactly. + auto taps_moved = [](const WalkResult& walk){ return walk.moved_chunks; }; + size_t moved = std::min(leg.tiles, taps_moved(result) + turn_moved); + // One wait: a wanderer in the way steps off in a few seconds; + // anything still there after that is talked to (r246a lost + // 20 s per block on three waits). + for (size_t again = 0; again < 1 && result.stop == WalkStop::BLOCKED && moved < leg.tiles; again++){ + stream.log("[Route] " + leg_label + ": blocked after " + std::to_string(moved) + " of " + + std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + const WalkResult rest = walk_tiles_dpad(stream, context, escape, x, y, leg.tiles - moved, leg_label + ": the rest"); + moved = std::min(leg.tiles, moved + taps_moved(rest)); + result.stop = rest.stop; + result.walked += rest.walked; + result.wild_battles += rest.wild_battles; + } + if (result.stop == WalkStop::BLOCKED && moved < leg.tiles){ + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + { + ShortDialogWatcher dialog(COLOR_YELLOW); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, leg_label + ": someone is in the way; talking to them."); + fight("someone in the way"); + } + } + std::vector stopped; + for (const TilePos& pos : from){ + const std::vector path = leg_path(grid, pos, leg.direction, moved); + stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); + } + std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); + if (stopped.size() == 1){ + const TilePos blocker = stopped[0].next(leg.direction); + grid.set(blocker, TileType::BLOCKED); + stream.log("[Route] " + leg_label + ": something the map lacks is at " + + maps.describe(blocker) + "; marked it.", COLOR_ORANGE); + } + stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), + "blocked after " + std::to_string(moved) + " of " + std::to_string(leg.tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); + facing = leg.direction; + from = stopped; + replanned = true; + break; + } + } + facing = leg.direction; + { + context.wait_for_all_requests(); + if (VideoSnapshot screen = stream.video().snapshot()){ + watch_banner(*screen.frame); + } + } + std::string banner_text; + for (const std::string& read : banners){ + banner_text += (banner_text.empty() ? "\"" : ", \"") + read + "\""; + } + all_banners.insert(all_banners.end(), banners.begin(), banners.end()); + // Entering another map shows its name; a missing or wrong name means + // the walk did not end where the plan says. From tiles on several + // maps (a leg not confirmed) the banner may already have shown. + if (!map_before.empty() && !map_after.empty() && map_after != map_before && !banner_ok()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": expected to enter " + map_after + ", but the location banner read " + + (banner_text.empty() ? "nothing" : banner_text) + ".", stream); + } + if (!banner_text.empty()){ + stream.log("[Route] " + leg_label + ": location banner " + banner_text + "."); + } + // Where each leg ended, to compare with the plan after a run. + if (VideoSnapshot screen = stream.video().snapshot()){ + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; + Filesystem::create_directories(Filesystem::Path(folder)); + screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(leg_label) + ".png"); + } + if (result.stop == WalkStop::TRANSITION){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": unexpected transition.", stream); + } + // A trainer who sees us freezes the player and walks over; the + // dialogue may open after the walk has ended. + const std::vector> paths = [&]{ + std::vector> out; + for (const TilePos& pos : from){ + out.push_back(leg_path(grid, pos, leg.direction, + leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); + } + return out; + }(); + std::vector watching; + for (size_t t = 0; t < trainers.size(); t++){ + const std::vector sight = sight_tiles(grid, trainers[t]); + for (const std::vector& path : paths){ + if (std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ + return std::find(sight.begin(), sight.end(), pos) != sight.end(); + })){ + watching.push_back(t); + break; + } + } + } + bool talking = result.stop == WalkStop::DIALOG; + if (!talking){ + ShortDialogWatcher dialog(COLOR_YELLOW); + const Milliseconds wait = watching.empty() ? 500ms : 4000ms; + talking = wait_until(stream, context, wait, {{dialog}}) == 0; + } + if (!talking){ + from = planned.after; + log_leg_done(stream, maps, label, planned, result.wild_battles); + continue; + } + + if (watching.empty()){ + // A trainer the map does not have. Fight, then plan again from + // anywhere the leg could have stopped. + std::vector anywhere = from; + for (const std::vector& path : paths){ + anywhere.insert(anywhere.end(), path.begin(), path.end()); + } + std::sort(anywhere.begin(), anywhere.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + anywhere.erase(std::unique(anywhere.begin(), anywhere.end()), anywhere.end()); + route_status(stream, label + ": a trainer the map lacks stopped us; fighting."); + fight("unknown trainer"); + if (leg.ends_at_wall){ + const Milliseconds limit = ROUTE_START_DELAY + + ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; + stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); + walk_until_dpad(stream, context, escape, x, y, limit, leg_label + ": on to the wall", watch_banner, true); + from = planned.after; + log_leg_done(stream, maps, label, planned, 0); + continue; + } + from = anywhere; + replanned = true; + break; + } + // Each possible start tile was stopped on the first tile of its path + // inside a watching trainer's sight. + const TrainerSight trainer = trainers[watching[0]]; + std::vector stopped; + for (const std::vector& path : paths){ + for (const TilePos& pos : path){ + bool seen = false; + for (size_t t : watching){ + const std::vector sight = sight_tiles(grid, trainers[t]); + seen |= std::find(sight.begin(), sight.end(), pos) != sight.end(); + } + if (seen){ + stopped.push_back(pos); + break; + } + } + } + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": " + trainer.name + " talked, but no path enters their sight.", stream); + } + stream.log(ROUTE_LOG_TAG + route_trainer_line(label, trainer.name, route_tiles(maps, stopped))); + route_status(stream, "Fighting " + trainer.name + "."); + fight(trainer.name); + trainers.erase(trainers.begin() + watching[0]); + // Their sight line only says roughly where: BDSP's trainers stand a + // few tiles from Platinum's (r242a). A leg to a wall ends at its + // wall however far it got: walk on to it and carry on. An open leg + // counts its taps: the step that brought us into sight was complete. + if (leg.ends_at_wall){ + const Milliseconds limit = ROUTE_START_DELAY + + ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; + stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); + walk_until_dpad(stream, context, escape, x, y, limit, leg_label + ": on to the wall", watch_banner, true); + from = planned.after; + log_leg_done(stream, maps, label, planned, 0); + continue; + } + // Only the taps that moved count: the trainer freezes the player + // on the tile they saw, and the taps pressed while they walk over + // move nobody (r248a: "4 taps" were 2 steps; the belief of two + // tiles then cost a 12-tile run to a wall and 5 back). + const size_t taps = std::min(leg.tiles, result.moved_chunks + turn_moved); + std::vector by_taps; + for (const TilePos& pos : from){ + const std::vector path = leg_path(grid, pos, leg.direction, leg.tiles); + const size_t k = std::min(taps, path.size()); + by_taps.push_back(k == 0 ? pos : path[k - 1]); + } + std::sort(by_taps.begin(), by_taps.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + by_taps.erase(std::unique(by_taps.begin(), by_taps.end()), by_taps.end()); + stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), + std::to_string(taps) + " taps before the battle", route_tiles(maps, by_taps)), COLOR_ORANGE); + from = by_taps; + replanned = true; + break; + } + if (!replanned){ + // Legs whose ends span two maps skip the per-leg check; the walk + // as a whole must still have seen the banner of the map it ends on. + const std::string map_end = map_of(maps, from); + const bool changed_map = !map_start.empty() && !map_end.empty() && map_end != map_start; + if (changed_map && std::none_of(all_banners.begin(), all_banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_end); + })){ + std::string seen; + for (const std::string& read : all_banners){ + seen += (seen.empty() ? "\"" : ", \"") + read + "\""; + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": arrived at " + describe(maps, from) + " on the map, but " + map_end + + "'s location banner never showed (read " + (seen.empty() ? "nothing" : seen) + ").", stream); + } + stream.log(ROUTE_LOG_TAG + route_arrived_line(label, route_tiles(maps, from))); + return from; + } + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": too many plans.", stream); +} + + + +std::vector walk_waypoints( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const MapSet& maps, + std::vector from, + const std::vector& waypoints, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const RobustPlanCosts& costs +){ + for (size_t i = 0; i < waypoints.size(); i++){ + const TilePos goal = waypoints[i]; + from = walk_route(stream, context, escape, maps, from, + [&](const TilePos& pos){ return pos == goal; }, + trainers, fight, + label + " (" + std::to_string(i + 1) + "/" + std::to_string(waypoints.size()) + ", to " + maps.describe(goal) + ")", + {}, costs); + } + return from; +} + +void talk_to_npc( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const MapSet& maps, + std::vector& at, + const TilePos& npc, + const std::vector& sides, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label +){ + for (Direction side : sides){ + const TilePos stand = npc.next(side); + if (!maps.world().standable(stand)){ + continue; + } + at = walk_route(stream, context, escape, maps, at, [&](const TilePos& pos){ return pos == stand; }, + trainers, fight, label); + // Face the NPC: the opposite of the side we stand on. + const Direction face = + side == Direction::NORTH ? Direction::SOUTH : + side == Direction::SOUTH ? Direction::NORTH : + side == Direction::EAST ? Direction::WEST : Direction::EAST; + route_turn(stream, context, face); + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, label + ": talking from " + maps.describe(stand) + "."); + return; + } + route_status(stream, label + ": nobody answered from " + maps.describe(stand) + "; trying another side."); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": no side of " + maps.describe(npc) + " started a dialogue.", stream); +} + +void finish_dialogue( + VideoStream& stream, ProControllerContext& context, + Button button, const std::string& label, Milliseconds timeout +){ + // No line counts: talks differ in length (r115a: 8 A left the Poke Mart + // lady's Potions talk open). The box blinks off between lines and during + // "obtained" jingles, so only a stable absence ends the talk. + const WallClock none = WallClock::max(); + ShortDialogDetector dialog; + OverworldDetector overworld; + const WallClock deadline = current_time() + timeout; + WallClock quiet_since = none; + WallClock unknown_since = none; + while (current_time() < deadline){ + context.wait_for_all_requests(); + const auto frame = stream.video().snapshot(); + const WallClock now = current_time(); + const bool talking = frame && dialog.detect(frame); + if (frame && !talking && overworld.detect(frame)){ + unknown_since = none; + if (quiet_since == none){ + quiet_since = now; + }else if (now - quiet_since >= 1500ms){ + return; + } + context.wait_for(200ms); + continue; + } + quiet_since = none; + // Press only on a box (an A on the overworld talks again), or on a + // screen that is neither for 3 s. + if (talking || (unknown_since != none && now - unknown_since >= 3000ms)){ + unknown_since = none; + pbf_press_button(context, button, 80ms, 1200ms); + continue; + } + if (unknown_since == none){ + unknown_since = now; + } + context.wait_for(200ms); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": the dialogue did not end within " + + std::to_string(std::chrono::duration_cast(timeout).count()) + " s.", stream); +} + +void enter_door_north(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ + // Sideways steps to try after a blocked walk: east, then back west and + // one more. + const Direction steps[] = {Direction::EAST, Direction::WEST, Direction::WEST}; + for (size_t attempt = 0; attempt <= 3; attempt++){ + const WalkResult walk = walk_until(stream, context, escape, 0, 1, 2500ms, label); + if (walk.stop == WalkStop::TRANSITION){ + context.wait_for(1500ms); + return; + } + if (attempt == 3){ + break; + } + route_status(stream, label + ": the door frame stopped us; one tile " + + (steps[attempt] == Direction::EAST ? "east." : "west.")); + route_turn(stream, context, steps[attempt]); + const double x = steps[attempt] == Direction::EAST ? 1 : -1; + pbf_move_left_joystick(context, {x, 0}, route_open_hold(steps[attempt], 1), 200ms); + context.wait_for_all_requests(); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": could not go through the door.", stream); +} + +bool door_fade_look(DoorFadeWatch& watch, double brightness, bool room){ + if (brightness < DOOR_FADE_DARK){ + watch.saw_dark = true; + } + return watch.saw_dark && !room && brightness >= DOOR_OUTSIDE_BRIGHT; +} + +bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room){ + // Both are asked: the fade watch keeps what it has seen. + const bool faded = door_fade_look(watch, brightness, room); + return faded || !room; +} + +namespace{ + +// Three looks half a second apart, none a room: outside, whatever the fade +// did. A look of a lit Center can miss its black edge (r259 at 800 ms), +// three in a row standing still do not. +bool outside_for_three_looks(VideoStream& stream, ProControllerContext& context, const std::string& label){ + for (size_t look = 0; look < 3; look++){ + context.wait_for_all_requests(); + VideoSnapshot now = stream.video().snapshot(); + const bool room = !now || indoors(*now.frame); + stream.log("[Route] " + label + ": standing look " + std::to_string(look + 1) + ": " + (room ? "a room" : "not a room") + "."); + if (room){ + return false; + } + pbf_wait(context, 500ms); + } + return true; +} + +} + +void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ + // A last line of talk may still be up, and it would stop the walk. + pbf_mash_button(context, BUTTON_B, 2000ms); + context.wait_for_all_requests(); + // Stop the walk at the fade or at the first look that is not a room: a + // stick held on walks on outside (r124a ten rows south of the Mart's + // door, r257 into a house, r261 three rows). Standing looks then confirm. + DoorFadeWatch watch; + auto out_of_door = [&](const ImageViewRGB32& screen){ + const double brightness = image_stats(screen).average.sum(); + const bool room = indoors(screen); + const bool out = door_walk_stops(watch, brightness, room); + stream.log(std::format("[Route] {}: look: brightness {:.0f}, {}, fade {}.", label, brightness, + room ? "a room" : "not a room", watch.saw_dark ? "seen" : "not seen")); + return out; + }; + bool out = false; + for (size_t tries = 0; tries < 5 && !out; tries++){ + const WalkResult walk = walk_until(stream, context, escape, 0, -1, 6000ms, label, out_of_door); + if (walk.stop == WalkStop::DIALOG){ + pbf_mash_button(context, BUTTON_B, 2000ms); + } + // Let the fade-in finish, then look again standing still. + pbf_wait(context, 1500ms); + out = walk.stop == WalkStop::TRANSITION || outside_for_three_looks(stream, context, label); + if (!out){ + stream.log("[Route] " + label + ": still indoors; walking on."); + } + } + if (!out){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": did not get back out.", stream); + } + // Let the fade-in finish. + pbf_wait(context, 1500ms); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h new file mode 100644 index 0000000000..b7057b6303 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -0,0 +1,203 @@ +/* BDSP AutoStory - Route Walk + * + * From: https://github.com/PokemonAutomation/ + * + * Walks a plan made on the story maps: legs to a wall are held until the + * player stops, open legs for their length in time. Tracks every tile the + * player may be on, and plans again after a trainer stops the walk. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteWalk_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteWalk_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/Navigation/Pokemon_MapSet.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Walking time per tile, measured on the console from the post-catch save: +// a row is deeper than a column is wide under the tilted camera. +constexpr Milliseconds ROUTE_MS_PER_TILE_ACROSS = Milliseconds(160); // east or west +constexpr Milliseconds ROUTE_MS_PER_TILE_UP_DOWN = Milliseconds(240); // north or south +// From pressing the stick to the first step, when standing still. +constexpr Milliseconds ROUTE_START_DELAY = Milliseconds(250); +// Running (B held) covers a tile in this fraction of the walking time. B +// held with the D-pad did not run: r238a walked the Ravaged Path's corridor +// at 160 ms a tile, and a limit set for twice that speed cut a wall leg +// short by two tiles. 1 until running is measured to work. +constexpr int ROUTE_RUN_SPEEDUP = 1; + +// How long to hold the stick for an open leg of `tiles` tiles, for a player +// already facing that way: a step once started is always finished, so stop +// half a tile early. On the console a 1290ms hold west went 9 tiles and an +// 800ms hold south 4: the player starts at once and finishes the step. +Milliseconds route_open_hold(Pokemon::Direction direction, size_t tiles); + +// A tap this short turns a player who faces another way, without a step: on +// the console a 150ms tap south after walking north only turned the player. +constexpr Milliseconds ROUTE_TURN_TAP = Milliseconds(100); + +// Turns the player to face `direction` without moving. Only for a player who +// faces another way: one already facing it may take a step. +void route_turn(VideoStream& stream, ProControllerContext& context, Pokemon::Direction direction); + +// Talks to someone on a tile next to ours, without trusting the tile we +// counted ourselves onto: for each of `directions` in order, turns that way, +// presses A and waits up to `wait` for a dialogue. Returns the direction that +// answered, its dialogue open, or none if nobody did. Turns are taps (see +// route_turn()), so do not list the way the player already faces first. +std::optional talk_to_adjacent_npc( + VideoStream& stream, ProControllerContext& context, + const std::vector& directions, + const std::string& label, Milliseconds wait = Milliseconds(1500) +); + +// Talks to someone straight ahead in `facing`, where we may stand a little +// off their tile: BDSP moves by any distance, and a sideways tap moves about +// a third of a tile (a 50ms tap 0.2 to 0.45 tiles, a 100ms turn tap 0.4, on +// the console 2026-10-31). Presses A, and while nobody answers shifts by one +// such tap at a time to -1, +1, -2, +2 taps from the start and tries again. +// Never turns away and back between tries: each turn is a tap that moves us +// (s03e2 drifted east of Roark a third of a tile per try). Returns whether a +// dialogue opened, left open; false also after a wild battle on a nudge, +// which leaves us off the place we were. +// `accept`, if given, looks at the screen before A and once the dialogue +// is open, and says whether it is the one wanted: a rock or a sign next to +// someone answers A too (r187a read "It's a rugged rock" beside Roark). A +// dialogue it turns down is closed with B and the nudges go on. +bool talk_with_nudges( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + Pokemon::Direction facing, const std::string& label, + Milliseconds wait = Milliseconds(3000), + const std::function& accept = nullptr +); +constexpr Milliseconds ROUTE_NUDGE_TAP = Milliseconds(50); + +// Whether a walk to the wall that ends on any of `after` can tell it has +// stopped: not in tall grass, whose sway keeps the screen changing at a +// wall. Elsewhere, a walk to the wall that stops confirms where it ended. +bool route_wall_readable(const Pokemon::TileGrid& grid, const std::vector& after); + +// Shows what the route walk is doing in the log and the video overlay. +void route_status(VideoStream& stream, const std::string& text); + +// Called when a trainer's dialogue has opened, or when someone standing in +// the way was talked to. Fights the battle if one starts, and returns to the +// overworld either way. +using RouteTrainerFight = std::function; + +// Walks from any of the world tiles `from` of `maps` until every tile the +// player may be on is `goal`, and returns those tiles. Trainers in +// `trainers` who see the player are fought with `fight` and taken off the +// list. Tiles in `avoid` (where someone wanders) are planned as walls. +// Fails with a screenshot +// on a transition, a dialogue no trainer explains, a wild battle during an +// open leg, or when no plan exists. A walk from one map to another must see +// the second map's location banner on the way: a walk whose legs all ended +// on walls can still end in the wrong place (r124a saved in Sandgem Town +// after "arriving" on Route 202). +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const Pokemon::MapSet& maps, + std::vector from, + const std::function& goal, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const std::vector& avoid = {}, + const Pokemon::RobustPlanCosts& costs = route_plan_costs() +); + +// Walks `from` to each of `waypoints` in turn, with walk_route() for every +// stretch, and returns where the last one ended. The corners of a line a +// human walked, so the plan is that line, with the walker's handling of +// trainers and blocks on each stretch (Route 204 North, 2026-10-31). +std::vector walk_waypoints( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const Pokemon::MapSet& maps, + std::vector from, + const std::vector& waypoints, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const Pokemon::RobustPlanCosts& costs = waypoint_plan_costs() +); + +// Walks next to the NPC on world tile `npc`, faces them and presses A, trying +// the sides in `sides` (the side of the NPC to stand on) in order until a +// dialogue opens. `at` is where the player may be, and is updated. Fails with +// a screenshot if no side starts a dialogue. A press from a diagonal tile, +// or from a tile a row off, talks to nobody, so each side is tried in turn. +void talk_to_npc( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const Pokemon::MapSet& maps, + std::vector& at, + const Pokemon::TilePos& npc, + const std::vector& sides, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label +); + +// Finishes a dialogue that has opened, however many lines it has: presses +// `button` while a dialogue box shows, and returns once the overworld has +// shown with no box for 1.5 s (the box blinks off between lines and during +// "obtained" jingles). Use A where the talk asks Yes/No or gives an item (A +// answers Yes and closes "obtained" lines; B would answer No), B elsewhere +// (B never starts a new talk). Fails with a screenshot after `timeout`. +void finish_dialogue( + VideoStream& stream, ProControllerContext& context, + Button button, const std::string& label, + Milliseconds timeout = std::chrono::seconds(40) +); + +// For a player on the tile below a door: walks north through it. If a wall +// stops the walk (the door frame, a tile off the opening), steps a tile east, +// then west, and tries again. Fails with a screenshot if no step goes in. +void enter_door_north(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); + +// For a player inside a building whose door is straight south: closes any +// talk still up and walks south out of it, stopping at the door's fade or +// the first look that is not a room, so it ends a tile or so outside. Out is +// then three standing looks in a row that are not a room: one look of a lit +// Center can miss its black edge (r259). Fails with a screenshot if five +// walks south get nowhere. +void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); + +// Brightness (mean r + g + b) below which a look is the door's fade, and +// above which a look that is not a room is outside. +inline constexpr double DOOR_FADE_DARK = 120.0; +inline constexpr double DOOR_OUTSIDE_BRIGHT = 200.0; + +// What leave_door_south() has seen of the door's fade so far. +struct DoorFadeWatch{ + bool saw_dark = false; +}; +// Takes one look (its brightness, and whether indoors() read a room) and +// returns whether we are out: a dark look seen, and now a bright one that +// is not a room. +bool door_fade_look(DoorFadeWatch& watch, double brightness, bool room); +// Whether leave_door_south()'s walk stops at this look: at the door's fade +// out (door_fade_look()), or at the first look that is not a room, so a +// held stick does not walk on outside (r261 three rows). +bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp new file mode 100644 index 0000000000..eb0ec4ce02 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -0,0 +1,469 @@ +/* BDSP AutoStory - Walk + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; + + +const char* walk_stop_name(WalkStop stop){ + switch (stop){ + case WalkStop::ARRIVED: return "arrived"; + case WalkStop::DIALOG: return "dialog"; + case WalkStop::TRANSITION: return "transition"; + case WalkStop::BLOCKED: return "blocked"; + case WalkStop::LIMIT: return "limit"; + } + return "?"; +} + +double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after){ + // Small copies: only the whole-view scroll matters, not detail. + return ImageMatch::pixel_RMSD(before.scale_to(192, 108), after.scale_to(192, 108)); +} + + +namespace{ + +// The battle's text box, held for 250ms. +class BattleDialogWatcher : public DetectorToFinder{ +public: + explicit BattleDialogWatcher(Color color) + : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) + {} +}; + +VideoSnapshot snapshot_or_fail(VideoStream& stream, const std::string& label){ + VideoSnapshot frame = stream.video().snapshot(); + if (!frame){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": No video frame.", stream); + } + return frame; +} + +// After a black screen: a wild battle if a battle screen shows up, else a transition. +bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context){ + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + BlackScreenWatcher gone(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 100, 10, + BlackScreenWatcher::FinderType::GONE, 500ms); + const int ret = wait_until(stream, context, 10s, {{battle_menu}, {battle_dialog}, {gone}}); + if (ret == 2){ + // The battle intro also starts from black; give its first screen a moment. + BattleMenuWatcher late_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher late_dialog(COLOR_YELLOW); + return wait_until(stream, context, 2s, {{late_menu}, {late_dialog}}) >= 0; + } + return ret >= 0; +} + +// A grass encounter opens with a leaf animation, neither white nor black, and +// shows the battle's text box a few seconds later. After a change of the +// whole screen that walking cannot make, wait for the battle to show. +bool battle_follows(VideoStream& stream, ProControllerContext& context){ + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + return wait_until(stream, context, 5s, {{battle_menu}, {battle_dialog}}) >= 0; +} + +} + +// A step in tall grass that was started before the stick was released still +// finishes, and its encounter starts after the walk has ended. Watch a little +// longer, and run from it. Returns whether there was one. +bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ + VideoSnapshot before = stream.video().snapshot(); + WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); + BlackScreenWatcher black(COLOR_RED); + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + const int ret = wait_until(stream, context, 1200ms, {{encounter_flash}, {black}, {battle_menu}, {battle_dialog}}); + bool battle = ret == 0 || ret == 2 || ret == 3 || (ret == 1 && black_screen_was_battle(stream, context)); + if (ret < 0){ + VideoSnapshot after = stream.video().snapshot(); + battle = before && after && walk_screen_change(*before.frame, *after.frame) > WALK_SCENE_CHANGE && + battle_follows(stream, context); + } + if (!battle){ + return false; + } + stream.log("[Walk] " + label + ": wild battle after the walk; running."); + escape(stream, context); + context.wait_for_all_requests(); + return true; +} +namespace{ + +// Samples the screen every 100ms for probe_walk() and stops it once the view +// has been still for 800ms. +class WalkProbeSampler : public VisualInferenceCallback{ +public: + WalkProbeSampler(WalkProbe& result, double moving_change, WallClock start) + : VisualInferenceCallback("WalkProbeSampler") + , m_result(result) + , m_moving_change(moving_change) + , m_start(start) + {} + virtual void make_overlays(VideoOverlaySet&) const override{} + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + if (m_has_last && timestamp - m_last_time < 100ms){ + return false; + } + const Milliseconds at = std::chrono::duration_cast(timestamp - m_start); + ImageRGB32 small = frame.scale_to(192, 108); + if (m_has_last){ + const double change = ImageMatch::pixel_RMSD(m_last, small); + m_result.samples.push_back({at, change}); + if (change >= m_moving_change){ + if (m_result.first_move < 0ms){ + m_result.first_move = at; + } + m_result.last_move = at; + } + } + m_last = std::move(small); + m_last_time = timestamp; + m_has_last = true; + const Milliseconds still_since = m_result.last_move < 0ms ? 0ms : m_result.last_move; + return at - still_since >= 800ms; + } + +private: + WalkProbe& m_result; + double m_moving_change; + WallClock m_start; + ImageRGB32 m_last; + WallClock m_last_time; + bool m_has_last = false; +}; + +} + + +namespace{ +WalkResult walk_until_impl( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + const std::function& arrived, + bool wild, bool dpad, bool run, bool taps = false +); +} + +WalkResult walk_until( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + const std::function& arrived +){ + return walk_until_impl(stream, context, escape, x, y, limit, label, arrived, true, false, false); +} + +WalkResult walk_until_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + const std::function& arrived, + bool run +){ + return walk_until_impl(stream, context, escape, x, y, limit, label, arrived, true, true, run); +} + +WalkResult walk_tiles_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, size_t tiles, const std::string& label +){ + return walk_until_impl(stream, context, escape, x, y, 800ms * tiles, label, nullptr, true, true, false, true); +} + +WalkResult walk_until_no_wild( + VideoStream& stream, ProControllerContext& context, + double x, double y, Milliseconds limit, const std::string& label +){ + // With no wild Pokemon any battle is a trainer's, and the walk stops at + // it (DIALOG) without running. + const WildBattleEscape no_wild = [](VideoStream& stream, ProControllerContext&){ + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "walk_until_no_wild() ran from a battle."); + }; + return walk_until_impl(stream, context, no_wild, x, y, limit, label, nullptr, false, false, false); +} + +namespace{ +WalkResult walk_until_impl( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + const std::function& arrived, + bool wild, bool dpad, bool run, bool taps +){ + // A tile a tap: 160 ms held, the rest released, so each chunk is one tile. + const Milliseconds CHUNK = taps ? 800ms : 400ms; + const DpadPosition dpad_direction = x < 0 ? DPAD_LEFT : x > 0 ? DPAD_RIGHT : y > 0 ? DPAD_UP : DPAD_DOWN; + WalkResult result{WalkStop::LIMIT, 0ms, 0}; + size_t unchanged = 0; + // The largest change a chunk of this walk made: a step. A bump into an + // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old + // woman), over the fixed line of 16, so "still" is also anything under + // 40% of the walk's own steps. + double largest = 0; + + context.wait_for_all_requests(); + VideoSnapshot before = snapshot_or_fail(stream, label); + auto finish = [&](WalkStop stop){ + result.stop = stop; + if (wild && (stop == WalkStop::LIMIT || stop == WalkStop::BLOCKED) && + run_from_late_encounter(stream, context, escape, label) + ){ + result.wild_battles++; + } + stream.log("[Walk] " + label + ": " + walk_stop_name(stop) + " after " + + std::to_string(result.walked.count()) + "ms, " + + std::to_string(result.wild_battles) + " wild battle(s)."); + return result; + }; + + while (true){ + if (arrived && arrived(*before.frame)){ + return finish(WalkStop::ARRIVED); + } + if (result.walked >= limit){ + return finish(WalkStop::LIMIT); + } + const Milliseconds chunk = std::min(CHUNK, limit - result.walked); + + WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); + BlackScreenWatcher black(COLOR_RED); + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + ShortDialogWatcher dialog(COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + const int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + if (taps){ + pbf_press_dpad(context, dpad_direction, 160ms, chunk - 160ms); + }else if (dpad && run){ + ssf_press_button(context, BUTTON_B, 0ms, chunk, 0ms); + ssf_press_dpad(context, dpad_direction, chunk, chunk, 0ms); + }else if (dpad){ + pbf_press_dpad(context, dpad_direction, chunk, 0ms); + }else{ + pbf_move_left_joystick(context, {x, y}, chunk, 0ms); + } + }, + {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} + ); + result.walked += chunk; + + bool battle = ret == 0 || ret == 2 || ret == 4; + if (ret == 1){ + battle = black_screen_was_battle(stream, context); + if (!battle){ + return finish(WalkStop::TRANSITION); + } + } + if (battle && !wild){ + stream.log("[Walk] " + label + ": a battle started; a trainer's here."); + return finish(WalkStop::DIALOG); + } + if (battle){ + result.wild_battles++; + stream.log("[Walk] " + label + ": wild battle; running."); + escape(stream, context); + context.wait_for_all_requests(); + before = snapshot_or_fail(stream, label); + unchanged = 0; + continue; + } + if (ret == 3){ + return finish(WalkStop::DIALOG); + } + + context.wait_for_all_requests(); + VideoSnapshot after = snapshot_or_fail(stream, label); + const double change = walk_screen_change(*before.frame, *after.frame); + stream.log("[Walk] " + label + ": " + std::to_string(result.walked.count()) + + "ms, screen change " + std::to_string(change) + "."); + if (change > WALK_SCENE_CHANGE && !wild && battle_follows(stream, context)){ + stream.log("[Walk] " + label + ": a battle started; a trainer's here."); + return finish(WalkStop::DIALOG); + } + if (change > WALK_SCENE_CHANGE && battle_follows(stream, context)){ + result.wild_battles++; + stream.log("[Walk] " + label + ": wild battle (leaf opening); running."); + escape(stream, context); + context.wait_for_all_requests(); + before = snapshot_or_fail(stream, label); + unchanged = 0; + continue; + } + // Two still chunks in a row, so one dropped frame does not stop us. A + // frame exactly the same is a stalled video or a game hitch, not a wall: + // standing at a wall still animates. + if (change == 0){ + before = std::move(after); + continue; + } + largest = std::max(largest, change); + const double line = taps ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * largest) : WALK_BLOCKED_CHANGE; + const bool still = change < line; + if (!still){ + result.moved_chunks++; + } + unchanged = still ? unchanged + 1 : 0; + if (unchanged >= 2){ + return finish(WalkStop::BLOCKED); + } + before = std::move(after); + } +} +} + +WalkResult walk_for( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds duration, const std::string& label +){ + WalkResult result{WalkStop::LIMIT, duration, 0}; + context.wait_for_all_requests(); + WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); + BlackScreenWatcher black(COLOR_RED); + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + ShortDialogWatcher dialog(COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + const int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_move_left_joystick(context, {x, y}, duration, 0ms); + }, + {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} + ); + bool battle = ret == 0 || ret == 2 || ret == 4; + if (ret == 1){ + battle = black_screen_was_battle(stream, context); + if (!battle){ + result.stop = WalkStop::TRANSITION; + } + } + if (battle){ + result.wild_battles = 1; + stream.log("[Walk] " + label + ": wild battle; running."); + escape(stream, context); + context.wait_for_all_requests(); + } + if (ret == 3){ + result.stop = WalkStop::DIALOG; + } + // An encounter after the hold leaves us where the walk ended, so it does + // not count as cutting the walk short. + if (ret < 0){ + run_from_late_encounter(stream, context, escape, label); + } + stream.log("[Walk] " + label + ": " + walk_stop_name(result.stop) + " after a " + + std::to_string(duration.count()) + "ms hold, " + std::to_string(result.wild_battles) + " wild battle(s)."); + return result; +} + +WalkResult walk_to_talk( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label +){ + WalkResult total{WalkStop::LIMIT, 0ms, 0}; + while (total.walked < limit){ + const WalkResult step = walk_until(stream, context, escape, x, y, + std::min(400ms, limit - total.walked), label); + total.walked += step.walked; + total.wild_battles += step.wild_battles; + if (step.stop == WalkStop::DIALOG || step.stop == WalkStop::TRANSITION){ + total.stop = step.stop; + return total; + } + ShortDialogWatcher dialog(COLOR_YELLOW); + const int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 80ms, 720ms); + }, + {{dialog}} + ); + if (ret == 0){ + total.stop = WalkStop::DIALOG; + stream.log("[Walk] " + label + ": talking after " + std::to_string(total.walked.count()) + "ms."); + return total; + } + } + stream.log("[Walk] " + label + ": nobody to talk to within " + std::to_string(limit.count()) + "ms."); + return total; +} + +WalkProbe probe_walk( + VideoStream& stream, ProControllerContext& context, + double x, double y, Milliseconds limit, + double moving_change, const std::string& label +){ + WalkProbe result; + context.wait_for_all_requests(); + WalkProbeSampler sampler(result, moving_change, current_time()); + run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_move_left_joystick(context, {x, y}, limit, 0ms); + }, + {{sampler}} + ); + context.wait_for_all_requests(); + stream.log("[Walk] " + label + ": probe moved from " + std::to_string(result.first_move.count()) + + "ms to " + std::to_string(result.last_move.count()) + "ms."); + return result; +} + +WalkResult walk_to_wall( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label +){ + const WalkResult result = walk_until(stream, context, escape, x, y, limit, label); + if (result.stop == WalkStop::DIALOG || result.stop == WalkStop::TRANSITION){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": " + walk_stop_name(result.stop) + " instead of a wall.", stream); + } + if (result.stop == WalkStop::LIMIT){ + stream.log("[Walk] " + label + ": held for the whole limit without seeing the stop; taking the wall as reached."); + } + return result; +} + +WalkResult walk_expecting( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + WalkStop expected, + const std::function& arrived +){ + const WalkResult result = walk_until(stream, context, escape, x, y, limit, label, arrived); + if (result.stop != expected){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": expected " + walk_stop_name(expected) + ", got " + + walk_stop_name(result.stop) + ".", stream); + } + return result; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h new file mode 100644 index 0000000000..15622b26f4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -0,0 +1,172 @@ +/* BDSP AutoStory - Walk + * + * From: https://github.com/PokemonAutomation/ + * + * Walking that reads the screen instead of trusting a duration: hold a + * direction and stop on whatever the screen says happened. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Walk_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Walk_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Runs from a wild battle that has interrupted a walk, and returns once the +// player stands on the overworld again. The walker only sees that a battle +// started; how to leave it is the program's battle code, passed in. +using WildBattleEscape = std::function; + +enum class WalkStop{ + ARRIVED, // `arrived` matched. + DIALOG, // A dialogue box opened: an NPC or a trainer stopped us. + TRANSITION, // The screen went black and came back without a battle: a door or a new area. + BLOCKED, // The screen stopped changing: we are walking into a wall. + LIMIT, // Walked `limit` without any of the above. +}; +const char* walk_stop_name(WalkStop stop); + +struct WalkResult{ + WalkStop stop; + Milliseconds walked; + size_t wild_battles; + // Chunks whose screen change passed the blocked threshold: on a tap + // walk, the taps that moved a tile. A trainer's freeze and a bump do + // not count (r248a: "4 taps before the battle" were 2 steps and 2 + // taps into Taylor's freeze). + size_t moved_chunks = 0; +}; + +// Holds the left stick at (x, y) until one of the WalkStop events. Wild battles on +// the way are run from, and walking resumes. Does not throw for any WalkStop; the +// caller decides which ones are expected. +WalkResult walk_until( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + const std::function& arrived = nullptr +); + +// walk_until() on the D-pad, for a straight walk along a row or a column +// ((x, y) is one of the four directions). The D-pad moves whole tiles and +// keeps to the row: the stick drifts off it, catches tree corners and slides +// a row on stairs (Route 203, r226a and r227b; by hand the D-pad went +// through the same places). With `run`, B is held too: twice as fast, and +// as tile-true. +WalkResult walk_until_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + const std::function& arrived = nullptr, + bool run = false +); + +// A set number of whole tiles on the D-pad, a tap a tile (a tap moves +// exactly one tile; a stick hold timed for n tiles is a tile or two off), +// with the same watch for wild battles and dialogue as walk_until(). Ends +// LIMIT after `tiles` taps, or BLOCKED when two taps in a row move nothing. +WalkResult walk_tiles_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, size_t tiles, const std::string& label +); + +// walk_until() where there are no wild Pokemon (a gym, a building): any +// battle that starts is a trainer's, so the walk stops with DIALOG, left in +// the battle for the caller to fight, instead of trying to run from it +// (r206d tried to run from the second Oreburgh Gym trainer). +WalkResult walk_until_no_wild( + VideoStream& stream, ProControllerContext& context, + double x, double y, Milliseconds limit, const std::string& label +); + +// Holds the left stick at (x, y) for `duration` in one go, for a walk of a +// set length: walk_until() checks the screen between short holds, and each +// break can cost a step. Stops early for a dialog or a transition. A wild +// battle is run from and ends the walk with `wild_battles` 1, at a place the +// caller cannot know. +WalkResult walk_for( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds duration, const std::string& label +); + +// walk_until() that requires `expected`. Fails with the screenshot otherwise. +WalkResult walk_expecting( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label, + WalkStop expected, + const std::function& arrived = nullptr +); + +// After a move that may have walked onto an encounter tile (a tap in a cave +// or in tall grass): waits briefly for a wild battle and runs from it. +// Returns whether there was one; we may then be off the place we expected. +bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); + +// walk_until() toward a wall the route was measured to end at. Seeing the +// stop only ends the hold early: holding on for the whole `limit` also +// counts as there, as people or animations nearby can keep the screen +// changing at a wall (s03a1: a hiker and a child by the Mart fence; s03c1: +// Roark's pickaxe; r162a: Jubilife's TV). A wrong place is caught by the +// next gate. Fails on a dialog or a transition: we are not where we think. +WalkResult walk_to_wall( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label +); + +// Walks toward someone to talk to: after each short stretch, presses A and stops +// once a dialogue opens. Use it where walking into the person does not read as +// BLOCKED, e.g. in tall grass, whose sway keeps the screen changing. +WalkResult walk_to_talk( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + double x, double y, Milliseconds limit, const std::string& label +); + +// How much the screen changed between two frames, 0 for identical. Walking scrolls +// the whole view: 16 to 85 per 400ms on Route 202, against about 6 for running in +// place against trees. +double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after); +constexpr double WALK_BLOCKED_CHANGE = 10.0; +// For whole-tile D-pad taps: a tap that moves changes the screen by 21 to 50 +// (r244a: 40 per tap along Route 204's row 27); a tap into a wall or an NPC +// bumps for 10 to 13.4, and an NPC walking past does the same, so 10 counted +// bumps as steps (r244a, 2026-10-31). +constexpr double WALK_TAP_BLOCKED_CHANGE = 16.0; +// More than walking changes in 400ms: a new scene, such as a battle opening. +constexpr double WALK_SCENE_CHANGE = 120.0; + + +// One straight walk timed finely, to check a map against the game: holds the +// stick at (x, y) and samples the screen every 100ms until the view has been +// still for 800ms or `limit` runs out. Times count from the start of the hold. +// A sample moved if it changed by at least `moving_change`: still is 4 to 7, +// walking 16 to 85. Handles no battles or dialogs: use it on open ground, +// away from tall grass. +struct WalkProbe{ + Milliseconds first_move{-1}; // the first sample that moved; -1 if none did + Milliseconds last_move{-1}; // the last sample that moved; -1 if none did + struct Sample{ + Milliseconds at; + double change; // walk_screen_change() since the previous sample + }; + std::vector samples; +}; +WalkProbe probe_walk( + VideoStream& stream, ProControllerContext& context, + double x, double y, Milliseconds limit, + double moving_change, const std::string& label +); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index d0c16d6bac..30d16298fc 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1574,8 +1574,20 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp @@ -1602,6 +1614,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h + Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp @@ -1652,6 +1666,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/PokemonBDSP_Panels.h Source/PokemonBDSP/PokemonBDSP_Settings.cpp Source/PokemonBDSP/PokemonBDSP_Settings.h + Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp + Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h Source/PokemonBDSP/PokemonBDSP_Tests.cpp Source/PokemonBDSP/PokemonBDSP_Tests.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp From 4383d4e324f105bd460be107f03ee04b342dd62d Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 12:33:08 -0800 Subject: [PATCH 03/74] Unit tests: run the PokemonBDSP tests PokemonBDSP::add_tests() was never called, so the BDSP map tests did not run in CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 592144c1f1..20068e308d 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -29,6 +29,7 @@ #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" #include "Pokemon/Navigation/Pokemon_Navigation_Tests.h" +#include "PokemonBDSP/PokemonBDSP_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" #include "VideoGames/PokemonLA/PokemonLA_Tests.h" @@ -71,6 +72,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); NintendoSwitch::Typewriter::add_tests_TypewriterTextMapping(ret); + NintendoSwitch::PokemonBDSP::add_tests(ret); NintendoSwitch::PokemonFRLG::add_tests(ret); NintendoSwitch::PokemonRSE::add_tests(ret); NintendoSwitch::PokemonHome::add_tests(ret); From de27314980c4552817e46473d449bd527f46a39b Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:20:18 -0800 Subject: [PATCH 04/74] BDSP maps: the story's maps as JSON, generated from the Diamond decomp devtools/maps/bdsp_maps.py writes each map from its world rectangle of the pret/pokediamond decompilation (Platinum's for the Ravaged Path), with the named points and regions the story walks to, the objects BDSP shows, and the tiles the console measured as patches. --check regenerates them and fails on any difference. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Programs/AutoStory/Maps/FloaromaTown.json | 56 ++ .../Programs/AutoStory/Maps/JubilifeCity.json | 139 +++++ .../Programs/AutoStory/Maps/LakeVerity.json | 43 ++ .../Programs/AutoStory/Maps/OreburghCity.json | 91 +++ .../Programs/AutoStory/Maps/OreburghGate.json | 43 ++ .../Programs/AutoStory/Maps/OreburghGym.json | 50 ++ .../Programs/AutoStory/Maps/OreburghMine.json | 56 ++ .../Programs/AutoStory/Maps/RavagedPath.json | 87 +++ .../Programs/AutoStory/Maps/Route201.json | 46 ++ .../Programs/AutoStory/Maps/Route202.json | 68 +++ .../Programs/AutoStory/Maps/Route203.json | 64 ++ .../AutoStory/Maps/Route204North.json | 83 +++ .../AutoStory/Maps/Route204South.json | 56 ++ .../Programs/AutoStory/Maps/SandgemTown.json | 55 ++ .../Programs/AutoStory/Maps/TwinleafTown.json | 48 ++ .../AutoStory/Maps/VerityLakefront.json | 43 ++ devtools/maps/bdsp_maps.py | 555 ++++++++++++++++++ 17 files changed, 1583 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json create mode 100644 devtools/maps/bdsp_maps.py diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json new file mode 100644 index 0000000000..db9cf8a5df --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json @@ -0,0 +1,56 @@ +{ + "name": "FloaromaTown", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0032.bin; zone_event narc_0404", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "######........................##", + "##..##........................##", + "..............................##", + "..............................##", + "..............................##", + "..............................##", + "..............................##", + "..................#####.......##", + "..................#####.......##", + "..................#####.......##", + "..................#####.......##", + "..........####...S##.##.......##", + "..........####................##", + "..........####................##", + "..........#D##................##", + ".......................####..S##", + ".......................####...##", + ".......................#D##...##", + "..............................##", + ".............S..................", + "................................", + "................................", + "................................", + "..............#####....####...##", + "..............#####....####...##", + "..............#####....####...##", + "..............##D##....#D##...##", + "..............................##", + "..............................##", + "..............................##", + "########.#...###################", + "########.#...###################" + ], + "points": { + "route_204_arrival": [11, 29], + "old_woman": [3, 25], + "old_man": [2, 25], + "pokemon_center_door": [16, 26] + }, + "objects": [ + {"name": "pokemon_breeder_f_0", "kind": "npc", "x": 19, "y": 21}, + {"name": "lass_1", "kind": "npc", "x": 10, "y": 5, "wander": {"x0": 9, "y0": 5, "x1": 11, "y1": 5}}, + {"name": "school_kid_m_2", "kind": "npc", "x": 16, "y": 16, "wander": {"x0": 15, "y0": 15, "x1": 17, "y1": 17}}, + {"name": "cyrus_3", "kind": "npc", "x": 11, "y": 26}, + {"name": "lass_4", "kind": "npc", "x": 23, "y": 11, "facing": "west"}, + {"name": "grunt_m_7", "kind": "npc", "x": 2, "y": 1, "facing": "east"}, + {"name": "grunt_m_8", "kind": "npc", "x": 3, "y": 1, "facing": "west"}, + {"name": "camper_12", "kind": "npc", "x": 6, "y": 10}, + {"name": "old_woman", "kind": "npc", "x": 3, "y": 25}, + {"name": "old_man", "kind": "npc", "x": 2, "y": 25} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json new file mode 100644 index 0000000000..71aed1d875 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json @@ -0,0 +1,139 @@ +{ + "name": "JubilifeCity", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0015.bin, files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0017.bin, files/fielddata/land_data/land_data_release/narc_0018.bin; zone_event narc_0002", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "##########################################..............########", + "##########################################..............########", + "############################################.....###############", + "############################################......##############", + "############################################......##############", + "############################################......##############", + "############################################......##############", + "#############################################....###############", + "############################....#########.......S.##############", + "############################....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..#########..######....#########.........##############", + "#########..##D###D##..######....####D####.........##############", + "#########.............######...............#.....#######....####", + "#########.............######......................######....####", + "..#######.............######......................######....####", + "..###########S......########...........S.........S##D###....####", + "..#.S.#.......................#..........................#.S####", + "................................................................", + "D...............................................................", + "D...............................................................", + "................................................................", + "..#...#.......................#..........................#..####", + "..############.............####......####...................####", + "..############.............####......####................#######", + "##############.################...##.####..#.....######..#######", + "##############.################...##.####.........#####..#######", + "##############.################...................#D############", + "################################.........................#######", + "################################.........................##D####", + "################################.........................#######", + "################################.........................#######", + "###############............#####.........................#######", + "###############............#####......#####..............#######", + "###############..#########.#####.##########.......######.#######", + "###############..#########.#####.##########.......######.#######", + "###############..#########.#####.###########.....#######.#######", + "##################################..S.##D##.......##D###########", + "###############..#########.#####.........................#######", + "##############...####D####..###..........................#######", + "##############...........................................#######", + "##############.....S.....................................#######", + "##############...........................................#######", + "##############.............#########.....................#######", + "###############............#########.#####...............#######", + "###############............#########.#####...............#######", + "###############.####..####.###############...............#######", + "###############.####..####.###############...............#######", + "###############.####..####.###############...........###########", + "############D##.####..####.############D##...........###########", + "##########.................#########.......#.....#...########.##", + "##########.................#########.................########.##", + "##########............#..#.#########......S..........########.##", + "##########............#..#.#########.................########.##", + "##########.................#########.................########.##", + "###########################################.......##############", + "###########################################.......##############", + "########################################.##.......##############", + "########################################.####...################", + "########################################..........##############", + "########################################..........##############" + ], + "points": { + "trainers_school_door": [40, 40], + "pokemon_center_door": [52, 40], + "tv_station_door": [36, 15], + "poketch_president": [46, 35], + "clown_mart": [55, 33], + "clown_tv_station": [36, 16], + "clown_poketch_company": [15, 18], + "up_the_steps.1": [46, 58], + "up_the_steps.2": [47, 58], + "up_the_steps.3": [46, 59], + "up_the_steps.4": [47, 59], + "up_the_steps.5": [46, 60], + "up_the_steps.6": [47, 60], + "east_entrance.1": [61, 21], + "east_entrance.2": [62, 21], + "east_entrance.3": [63, 21], + "east_entrance.4": [61, 22], + "east_entrance.5": [62, 22], + "east_entrance.6": [63, 22], + "east_entrance.7": [61, 23], + "east_entrance.8": [62, 23], + "east_entrance.9": [63, 23], + "east_entrance.10": [61, 24], + "east_entrance.11": [62, 24], + "east_entrance.12": [63, 24], + "north_road.1": [44, 16], + "north_road.2": [45, 16], + "north_road.3": [46, 16], + "north_road.4": [47, 16], + "north_road.5": [48, 16], + "north_road.6": [44, 17], + "north_road.7": [45, 17], + "north_road.8": [46, 17], + "north_road.9": [47, 17], + "north_road.10": [48, 17], + "north_road.11": [44, 18], + "north_road.12": [45, 18], + "north_road.13": [46, 18], + "north_road.14": [47, 18], + "north_road.15": [48, 18], + "north_road.16": [44, 19], + "north_road.17": [45, 19], + "north_road.18": [46, 19], + "north_road.19": [47, 19], + "north_road.20": [48, 19], + "north_road.21": [44, 20], + "north_road.22": [45, 20], + "north_road.23": [46, 20], + "north_road.24": [47, 20], + "north_road.25": [48, 20] + }, + "objects": [ + {"name": "ace_trainer_f_0", "kind": "npc", "x": 22, "y": 20, "wander": {"x0": 21, "y0": 20, "x1": 23, "y1": 20}}, + {"name": "ace_trainer_m_1", "kind": "npc", "x": 46, "y": 21, "wander": {"x0": 45, "y0": 21, "x1": 47, "y1": 21}}, + {"name": "school_kid_m_2", "kind": "npc", "x": 17, "y": 55}, + {"name": "twin_3", "kind": "npc", "x": 33, "y": 18, "wander": {"x0": 32, "y0": 17, "x1": 34, "y1": 19}}, + {"name": "expert_m_4", "kind": "npc", "x": 44, "y": 44}, + {"name": "school_kid_m_5", "kind": "npc", "x": 51, "y": 34, "wander": {"x0": 51, "y0": 33, "x1": 51, "y1": 35}}, + {"name": "pokefan_m_6", "kind": "npc", "x": 41, "y": 30, "wander": {"x0": 40, "y0": 29, "x1": 42, "y1": 31}}, + {"name": "ace_trainer_m_22", "kind": "npc", "x": 36, "y": 25}, + {"name": "poketch_president", "kind": "npc", "x": 46, "y": 35}, + {"name": "clown_mart", "kind": "npc", "x": 55, "y": 33}, + {"name": "clown_poketch_company", "kind": "npc", "x": 15, "y": 18}, + {"name": "cashier_m_27", "kind": "npc", "x": 26, "y": 42}, + {"name": "clown_tv_station", "kind": "npc", "x": 36, "y": 16}, + {"name": "kid_with_nds_29", "kind": "npc", "x": 52, "y": 46}, + {"name": "kid_with_nds_30", "kind": "npc", "x": 54, "y": 46} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json new file mode 100644 index 0000000000..f7b521b3cb --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json @@ -0,0 +1,43 @@ +{ + "name": "LakeVerity", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0512.bin; zone_event narc_0298", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "wwwwwwwwwwwwwwww################", + "wwwwwwwwwwwwwwww################", + "wwwwwwwwwwwwwwww################", + "wwwwwwwwwwwwwwww################", + "......wwwwwwwwww##....##########", + "......wwwwwwwwww##....##########", + ".......wwwwwwwww##......########", + ".......wwwwwwwww##......########", + ".......wwwwwww####~.....########", + ".......wwwwwww####~~....########", + "wwwwwwwwwwww####~~~~....########", + "wwwwwwwwwwww####.~~~....########", + "wwwwwwwwww####.~~~~~..##########", + "wwwwwwwwww####.~~~~...##########", + "wwwwwwww####...~~~..############", + "wwwwwwww####........############", + "##########..........############", + "##########..........############", + "############......##############", + "############......##############", + "############......##############", + "############......##############", + "##############..################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "objects": [ + {"name": "rowan", "kind": "npc", "x": 16, "y": 11, "facing": "north"}, + {"name": "counterpart", "kind": "npc", "x": 17, "y": 11, "facing": "north"}, + {"name": "starly_3", "kind": "npc", "x": 16, "y": 19, "facing": "north"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json new file mode 100644 index 0000000000..4cdef2c0b0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json @@ -0,0 +1,91 @@ +{ + "name": "OreburghCity", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0022.bin, files/fielddata/land_data/land_data_release/narc_0023.bin, files/fielddata/land_data/land_data_release/narc_0024.bin, files/fielddata/land_data/land_data_release/narc_0175.bin; zone_event narc_0044", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "#########################################......#################", + "#########################################...S..#################", + "#########################################......#################", + "#########################################......#################", + "#########################################...####################", + "#########################################...####################", + "#########################################....###################", + "############.#####.######.#.############.....###################", + "###########..#####..#####...############.....###################", + "#########....#####..#####...############.....###################", + "##.....########D######D######D##########.....###################", + "##..S..###..........................####........#.#...##########", + "##..................................####.....S........##########", + "#D..................................####..............##########", + "##..................................####..............####.#####", + "##..................................####..............####.#####", + "##.....###.............#######......#D##..............####.#####", + "##.....##.......####...#######...............#####....####.#####", + "#########.......####.#.#######..............######......#.######", + "#########.......####...#######..............######.....#########", + "#########.......#D####S###D###...............##D##.....#########", + "#########........................................#.....#########", + "#########........................................#.....#########", + "#########........................................#....##########", + "#########........................................#....##########", + "#########........................................#....##########", + "##########.#.#..########.........................#....##########", + "########################.######.############.....#....##########", + "########################.######.###........#.....#....##D#######", + "########################.######.###.#..#...#.....#.........#####", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....###############", + "############################################.....##D############", + "###################################.########.....#...........###", + "###################################.....####.....#...........###", + "###################################.....####.....#...........###", + "###################################....#####.....#...........###", + "#####################################..#.........#...........###", + "#####################################..#..#.#....#....#.#....###", + "#####################################..#..#.#....#....#.#....###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################....#.....................###", + "###################################..###..#.#................###", + "###################################..###..#.#...#.#########.####", + "###################################..###........#.#########.####", + "###################################....#..........#####.....####", + "###################################...............#####.....####", + "#####################################.............##.........###", + "#####################################..####.#.....###.....######", + "#####################################..####.#S....###.....######", + "###########################################.......####.......###", + "############################################.....#####.......###", + "############################################.....#####.....#####", + "######################################################..#..#####", + "################################################################", + "################################################################", + "################################################################" + ], + "points": { + "pokemon_center_door": [47, 20], + "pokemon_center_doorstep": [46, 21], + "gym_door": [26, 20], + "gym_doorstep": [26, 21], + "gate_mouth": [1, 13] + }, + "objects": [ + {"name": "hiker_0", "kind": "npc", "x": 47, "y": 26, "wander": {"x0": 46, "y0": 25, "x1": 48, "y1": 27}}, + {"name": "school_kid_f_1", "kind": "npc", "x": 32, "y": 18, "wander": {"x0": 32, "y0": 16, "x1": 32, "y1": 20}}, + {"name": "pokefan_f_2", "kind": "npc", "x": 45, "y": 38, "wander": {"x0": 45, "y0": 37, "x1": 45, "y1": 39}}, + {"name": "youngster_4", "kind": "npc", "x": 10, "y": 16, "facing": "north"}, + {"name": "worker_15", "kind": "npc", "x": 11, "y": 25}, + {"name": "worker_16", "kind": "npc", "x": 56, "y": 57, "wander": {"x0": 55, "y0": 54, "x1": 57, "y1": 60}}, + {"name": "camper_17", "kind": "npc", "x": 36, "y": 19, "wander": {"x0": 33, "y0": 19, "x1": 39, "y1": 19}}, + {"name": "worker_18", "kind": "npc", "x": 37, "y": 39, "wander": {"x0": 36, "y0": 38, "x1": 38, "y1": 40}}, + {"name": "worker_19", "kind": "npc", "x": 50, "y": 41, "wander": {"x0": 50, "y0": 38, "x1": 50, "y1": 44}}, + {"name": "guitarist_20", "kind": "npc", "x": 23, "y": 13, "wander": {"x0": 22, "y0": 10, "x1": 24, "y1": 16}}, + {"name": "battle_girl_21", "kind": "npc", "x": 36, "y": 23, "wander": {"x0": 36, "y0": 21, "x1": 36, "y1": 25}}, + {"name": "machop_22", "kind": "npc", "x": 55, "y": 56, "wander": {"x0": 53, "y0": 54, "x1": 57, "y1": 58}} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json new file mode 100644 index 0000000000..14c30e35f5 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json @@ -0,0 +1,43 @@ +{ + "name": "OreburghGate", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0418.bin; zone_event narc_0250", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "################################", + "################################", + "################################", + "################################", + "############..#......###########", + "###########..........###########", + "###########........#.###########", + "###########..###################", + "###########..###################", + "###########..###################", + "###########.####################", + "############.###################", + "###########.####################", + "###########..###################", + "###########..###################", + "###########..###################", + "###########..###################", + "###########..###################", + "############.###################", + "###########..###################", + "#####...##...##########...#.####", + "####....##...##########.....####", + "###D........................D###", + "####...#....................####", + "###########..............#.#####", + "############.......#############", + "###########..#.#...#############", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "objects": [ + {"name": "picnicker_0", "kind": "npc", "x": 24, "y": 21, "facing": "south"}, + {"name": "camper_1", "kind": "npc", "x": 17, "y": 25, "facing": "north"}, + {"name": "hiker_10", "kind": "npc", "x": 7, "y": 20, "facing": "south"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json new file mode 100644 index 0000000000..89341d5b3a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json @@ -0,0 +1,50 @@ +{ + "name": "OreburghGym", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0228.bin; zone_event narc_0046", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "################################", + "################################", + "################################", + "#..........#####################", + "#..........#####################", + "#..........#####################", + "#..##.##...#####################", + "#..........#####################", + "#..##.##...#####################", + "#..........#####################", + "#..........#####################", + "###.....#.######################", + "#..........#####################", + "#####.##...#####################", + "#####.##...#####################", + "#..........#####################", + "#..........#####################", + "#..........#####################", + "#..........#####################", + "##.#....########################", + "##.#....########################", + "#..........#####################", + "#..#...#...#####################", + "#..S...S...#####################", + "#....D.....#####################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "points": { + "entrance": [5, 23], + "roark": [5, 3], + "trainer_first_tier": [4, 18], + "trainer_second_tier": [7, 11] + }, + "objects": [ + {"name": "roark_0", "kind": "npc", "x": 5, "y": 3, "facing": "south"}, + {"name": "gym_guide_1", "kind": "npc", "x": 6, "y": 23, "facing": "south"}, + {"name": "youngster_2", "kind": "npc", "x": 4, "y": 18, "facing": "east"}, + {"name": "youngster_3", "kind": "npc", "x": 7, "y": 11, "facing": "west"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json new file mode 100644 index 0000000000..d8ea9a4ff6 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json @@ -0,0 +1,56 @@ +{ + "name": "OreburghMine", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0314.bin; zone_event narc_0197", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "################################", + "###############D################", + "#############.....##############", + "#############.....##############", + "#############.....##############", + "#############.....##############", + "#############.....##############", + "#############...################", + "#############...################", + "#############.....##############", + "#############..#..##############", + "###############...##############", + "#############...################", + "#############.....##############", + "###############...##############", + "########...####..............###", + "######.....##.................##", + "##.#..........................##", + "##....####################....##", + "##vvv##..................#....##", + "##....#..................#....##", + "##.##.#..................#....##", + "##..###..................###..##", + "##..###..................###..##", + "##....#..................#....##", + "##.##.#..................#....##", + "####..####################....##", + "####..####################....##", + "####.............#.#........####", + "######......................####", + "################################", + "################################" + ], + "points": { + "roark": [18, 28], + "corridor_exit_start": [14, 10], + "corridor_top.1": [14, 2], + "corridor_top.2": [15, 2], + "corridor_top.3": [16, 2] + }, + "objects": [ + {"name": "roark", "kind": "npc", "x": 18, "y": 28, "facing": "east"}, + {"name": "item_3", "kind": "item", "x": 4, "y": 28}, + {"name": "item_4", "kind": "item", "x": 26, "y": 24}, + {"name": "worker_5", "kind": "npc", "x": 8, "y": 28, "facing": "north"}, + {"name": "worker_6", "kind": "npc", "x": 26, "y": 20, "facing": "west"}, + {"name": "worker_7", "kind": "npc", "x": 21, "y": 15, "facing": "north"}, + {"name": "machop_8", "kind": "npc", "x": 12, "y": 28, "wander": {"x0": 11, "y0": 28, "x1": 13, "y1": 28}}, + {"name": "machop_9", "kind": "npc", "x": 20, "y": 15}, + {"name": "machop_10", "kind": "npc", "x": 27, "y": 15, "facing": "north"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json new file mode 100644 index 0000000000..7c48de6775 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json @@ -0,0 +1,87 @@ +{ + "name": "RavagedPath", + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_435.bin, res/field/maps/data/map_data_436.bin; events_ravaged_path.json", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "................................", + "................................", + "........................########", + "........................########", + "........................##....##", + "############............##....##", + "############............##....##", + "####...#####............##www.##", + "##...#...############...##www###", + "##..####.############...##www###", + "##..####.#######...#######www###", + "##..####......##...#######www###", + "##.#.###########...##www##www###", + "###.##########.....##wwwwwwwww##", + "###..######.#########wwwwwwwww##", + "###..#####..#########wwwwwwwww##", + "####.#####vv#########www########", + "##...#####..#########www########", + "##..######..#########www###.....", + "##..######..#########www###.....", + "###.######..######wwwwwww##.....", + "##..######..######wwwwwww##.....", + "##.#.#####..######wwwwwww##.....", + "####.#####vv######www######.....", + "####.#......######www######.....", + "####........######www##.........", + "####....wwwwwwwwwwwww##.........", + "..##....wwwwwwwwwwwww##.........", + "..##....wwwwwwwwwwwww##.........", + "..#######www###########.........", + "..#######www###########.........", + "....#####www####................", + "....#####www####................", + "....##wwwwww####................", + "....##wwwwww####................", + "....##wwwwww####................", + "....##.wwww#.###................", + "....##.#....#.##................", + "....##..#.#...#########.........", + "....##....#..##########.........", + "....##.#.#.......#...###########", + "....###.....######...###########", + "....##############....#.......##", + "....##############....#.......##", + "..............####.....#......##", + "..............####...#######D###", + "..............####...###########", + "..............####...####.......", + "..............####...####.......", + "..............####...####.......", + "..............####...####.......", + "..............#####D#####.......", + "..............###########.......", + "..............###########......." + ], + "points": { + "entrance": [19, 50], + "east_end": [29, 44], + "above_exit": [28, 44], + "rocks.1": [11, 36], + "rocks.2": [7, 37], + "rocks.3": [12, 37], + "rocks.4": [8, 38], + "rocks.5": [10, 38], + "rocks.6": [10, 39], + "rocks.7": [13, 39], + "rocks.8": [7, 40], + "rocks.9": [9, 40], + "rocks.10": [17, 40], + "rocks.11": [12, 41], + "rocks.12": [22, 42], + "rocks.13": [22, 43], + "rocks.14": [23, 44], + "before_rocks.1": [21, 42], + "before_rocks.2": [21, 43] + }, + "objects": [ + {"name": "item_27", "kind": "item", "x": 7, "y": 38}, + {"name": "item_28", "kind": "item", "x": 17, "y": 11}, + {"name": "item_29", "kind": "item", "x": 28, "y": 5}, + {"name": "item_30", "kind": "item", "x": 22, "y": 44} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json new file mode 100644 index 0000000000..88f0b99f7e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json @@ -0,0 +1,46 @@ +{ + "name": "Route201", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0005.bin, files/fielddata/land_data/land_data_release/narc_0006.bin; zone_event narc_0327", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "################################################################", + "################################################################", + "################################################################", + "##########################################~~~~~~~~~~~...........", + "##########################################~~~~~~~~~~~..S........", + "##########################################~~~~~~~~~~~...........", + "##########################################~~~~~~~~~~~...........", + "....####..........######..##....##..####..~~~~~~~~~##...........", + "....####..........######..##....##..####..~~~~~~~~~##...........", + "##........####............................~~~~~~~~~##vvvvv######", + "##........####............................~~~~~~~~~##.....######", + "..........................................~~~~~~~~~##.....######", + "vvvv####vvvvvvvvvvvvvvvvvvvvvvvv........S.~~~~~~~~~##.....######", + "....####............~~~~~~~~~~............................######", + "....................~~~~~~~~~~............................######", + "....................~~~~~~~~~~............................######", + "....................~~~~~~~~~~............................######", + "########.....S......##########............................######", + "########............##########............~~~~~~~~~~~~~~~~######", + "##############....############################~~~~~~~~~~~~######", + "##############....############################~~~~~~~~~~~~######", + "##############....##############################################", + "##############....##############################################", + "##############....##############################################", + "##############....##############################################" + ], + "points": { + "border_sign": [55, 4], + "potion_giver": [43, 3], + "potion_giver_talk_from": [44, 3], + "route_201_arrival": [15, 24], + "barry_warning": [15, 18], + "route_201_return": [0, 14], + "rowan_stop": [5, 14], + "route_201_east_end": [63, 5] + }, + "objects": [ + {"name": "pokemon_breeder_m_0", "kind": "npc", "x": 27, "y": 15, "wander": {"x0": 26, "y0": 14, "x1": 28, "y1": 16}}, + {"name": "school_kid_m_9", "kind": "npc", "x": 57, "y": 8, "facing": "west"}, + {"name": "lass_11", "kind": "npc", "x": 46, "y": 16, "wander": {"x0": 44, "y0": 16, "x1": 48, "y1": 16}} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json new file mode 100644 index 0000000000..515e652b45 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json @@ -0,0 +1,68 @@ +{ + "name": "Route202", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0014.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0328", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "###########........#################", + "###########........#################", + "###########........#################", + "###########........#################", + "###~~~~~~........S..~~~~~......#####", + "###~~~~~~...........~~~~~......#####", + "###.~~~~~...........~~~~~......#####", + "###~~~~~~...........~~~~~......#####", + "###~~~~~~...........~~~~~......#####", + "###~~~~~~.....########.........#####", + "#########vvvvv########vvvvvv...~~###", + "#########.....########~~~~~~~~~~~###", + "#######.......########~~~~~~~~~~~###", + "#######...........####~~~~~~~~~~~###", + "###...............####~~~~~~~~~~~###", + "###...............####~~~~~~~~~~~###", + "###............S..####~~~~~~~~~~~###", + "###...............####~~~~~~~~~~~###", + "###...............####..~~~~~~~~~###", + "###~~~~##...............~~~~~~~~~###", + "###~~~~##.................~~~~~~~###", + "###~~~~##....................~~~~###", + "###~~~~##......................#####", + "###~~~~##vvvvv########vvvvvvvvv#####", + "###~~~~##.....########.........#####", + "###~~~~~~......~~~~~~...S......#####", + "###~~~~~~......~~~~~~..........#####", + "###~~~~~~......~~~~~~..........#####", + "###~~~~~~......~~~~~~..........#####", + "###~~~~~~......~~~~~~..........#####", + "#####################..........#####", + "#####################..........#####" + ], + "points": { + "catch_spot": [19, 27], + "save_spot": [30, 24], + "trainer_tristan": [7, 13], + "trainer_natalie": [22, 18], + "trainer_logan": [26, 4], + "exit_jubilife": [15, 0] + }, + "objects": [ + {"name": "youngster_0", "kind": "npc", "x": 7, "y": 13, "facing": "south"}, + {"name": "lass_1", "kind": "npc", "x": 22, "y": 18, "facing": "south"}, + {"name": "youngster_2", "kind": "npc", "x": 26, "y": 4, "facing": "south"}, + {"name": "youngster_7", "kind": "npc", "x": 10, "y": 8, "wander": {"x0": 9, "y0": 8, "x1": 11, "y1": 8}}, + {"name": "item_8", "kind": "item", "x": 3, "y": 6} + ], + "patches": [ + {"x": 15, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 16, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 17, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 18, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 19, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 20, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 15, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 16, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 17, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 18, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 19, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 20, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"x": 21, "y": 30, "glyph": "#", "measured_by": "r254, 2026-11-01"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json new file mode 100644 index 0000000000..88f443c610 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json @@ -0,0 +1,64 @@ +{ + "name": "Route203", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0019.bin; zone_event narc_0329", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "#############################################################", + "#############################################################", + "#############################################################", + "#############################################################", + "#####..............###########..~~~~#########################", + "#####..............###########...~~~..~~~~~~~~~~~~~~#########", + "#####..................#######........~~~~~~~~~~~~~.....#####", + "#####..................#######wwwwww##~~~~~~~~~~~....S..#####", + "#####~~~~##...####.....#......wwwwww##~~~~~~~~~~~.......#####", + "#####~~~~##...####.....#......wwwwww##~~~~~~~~~~~.......D####", + "#####~~~~##...####.....#..S...wwwwww##~~~~~~~~~~~.......#####", + "#####~~~~##...####.....#......wwwwww##~~~~~~~~~~~.......#####", + "#####~~~~##...####.....#....~~~~~~~~##~~~~~~~~~S...~~~..#####", + "#####~~~~##...####vvvvv#...~~...~.~~##~~~~~~~~~....~~~..#####", + "#####~~................#....######~~##.....~~....##~~~..#####", + "#####..................#....######~~##vvvvvvvvvvv##~~~..#####", + "#####....S.............#....~~~..~~~.............~~~~~..#####", + "...........................~~~~...~~.............~~~~~..#####", + "...........................~~.....~~.............~~~~~..#####", + "..........................~~~~.....~##..........~~~~~~..#####", + "..........................~~~~~.~~~~#########################", + "#############################################################", + "#############################################################", + "#############################################################" + ], + "points": { + "gate_exit.1": [55, 9], + "gate_exit.2": [54, 9], + "gate_exit.3": [55, 8], + "gate_exit.4": [55, 10], + "west_line.1": [24, 18], + "west_line.2": [25, 18], + "west_line.3": [26, 18], + "west_line.4": [27, 18], + "west_line.5": [28, 18], + "west_line.6": [29, 18], + "west_line.7": [30, 18], + "west_line.8": [31, 18], + "west_line.9": [32, 18], + "west_line.10": [33, 18], + "west_line.11": [34, 18], + "west_line.12": [35, 18], + "west_line.13": [36, 18], + "west_line.14": [37, 18], + "west_line.15": [38, 18], + "west_line.16": [39, 18], + "west_line.17": [40, 18], + "west_line.18": [41, 18], + "west_line.19": [42, 18] + }, + "objects": [ + {"name": "youngster_1", "kind": "npc", "x": 13, "y": 10, "facing": "west"}, + {"name": "lass_2", "kind": "npc", "x": 43, "y": 17, "facing": "west"}, + {"name": "youngster_3", "kind": "npc", "x": 31, "y": 16, "facing": "south"}, + {"name": "lass_4", "kind": "npc", "x": 49, "y": 8, "facing": "south"}, + {"name": "item_10", "kind": "item", "x": 31, "y": 5}, + {"name": "item_11", "kind": "item", "x": 20, "y": 10}, + {"name": "lass_12", "kind": "npc", "x": 15, "y": 17, "wander": {"x0": 14, "y0": 17, "x1": 16, "y1": 17}} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json new file mode 100644 index 0000000000..65fe1fb8cf --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json @@ -0,0 +1,83 @@ +{ + "name": "Route204North", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0031.bin; zone_event narc_0331", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "########.#...###################", + "########.#...###################", + "####.....#...########.##########", + "##########...#......#.##########", + "#####....#...#......#...........", + "#####....#~~~#......#...######..", + "#####....#~~~###################", + "##########~~~.........##########", + "##........~~~~~.......##########", + "##..######.~~~~..S....##########", + "##..#....#.~~~........##########", + "##..#....#.~~.........##########", + "##########..............########", + "##########..............########", + "##########...####~~~~~~~########", + "##########vvv####~~~~~~~########", + "##########...######~~~~~########", + "##########...######~~~~~########", + "##########...######~~~~~########", + "##########...######~.~~~########", + "##########............~~########", + "##########............##########", + "##########............##########", + "##########...##.......##########", + "##########...##.......##########", + "##########...###################", + "##########...#######.###########", + "##########............##########", + "##########............##########", + "##########............##########", + "##########............##########", + "##########...###################" + ], + "points": { + "cave_exit": [20, 26], + "floaroma_waypoints.1": [20, 27], + "floaroma_waypoints.2": [11, 27], + "floaroma_waypoints.3": [11, 22], + "floaroma_waypoints.4": [19, 22], + "floaroma_waypoints.5": [19, 12], + "floaroma_waypoints.6": [11, 12], + "floaroma_waypoints.7": [11, 5], + "floaroma_path.1": [10, 0], + "floaroma_path.2": [11, 0], + "floaroma_path.3": [12, 0], + "floaroma_path.4": [10, 1], + "floaroma_path.5": [11, 1], + "floaroma_path.6": [12, 1], + "floaroma_path.7": [10, 2], + "floaroma_path.8": [11, 2], + "floaroma_path.9": [12, 2], + "floaroma_path.10": [10, 3], + "floaroma_path.11": [11, 3], + "floaroma_path.12": [12, 3], + "floaroma_path.13": [10, 4], + "floaroma_path.14": [11, 4], + "floaroma_path.15": [12, 4], + "floaroma_path.16": [10, 5], + "floaroma_path.17": [11, 5], + "floaroma_path.18": [12, 5], + "trainer_twin_left": [15, 7], + "trainer_twin_right": [16, 7], + "trainer_taylor": [17, 20], + "trainer_brandon": [20, 12] + }, + "objects": [ + {"name": "bug_catcher_brandon", "kind": "npc", "x": 20, "y": 12}, + {"name": "pokemon_breeder_f_1", "kind": "npc", "x": 17, "y": 20}, + {"name": "twin_2", "kind": "npc", "x": 15, "y": 7, "facing": "south"}, + {"name": "twin_3", "kind": "npc", "x": 16, "y": 7, "facing": "south"}, + {"name": "youngster_4", "kind": "npc", "x": 15, "y": 28, "wander": {"x0": 14, "y0": 28, "x1": 16, "y1": 28}}, + {"name": "item_9", "kind": "item", "x": 2, "y": 10}, + {"name": "ace_trainer_f_10", "kind": "npc", "x": 31, "y": 4, "facing": "west"}, + {"name": "item_11", "kind": "item", "x": 20, "y": 23} + ], + "patches": [ + {"x": 12, "y": 6, "glyph": "#", "measured_by": "r248a, 2026-10-31"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json new file mode 100644 index 0000000000..d70775dce3 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json @@ -0,0 +1,56 @@ +{ + "name": "Route204South", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0021.bin; zone_event narc_0330", "revision": "default branch", "date": "2026-11-01"}, + "tiles": [ + "################################", + "###########D###.################", + "########..S.....################", + "########........################", + "########........################", + "##########...~##################", + "##########...~##################", + "##########..~~##################", + "##########..~~###wwwwwwwww######", + "####~~~~~~~~~~###wwwwwwwww######", + "####~~~~~~~~~~###wwwwwwwww######", + "####~~~~~~~~~~###wwwwwwwww######", + "####~~~~~~~~~~###wwwwwwwww....##", + "####~~~~~~~~~~###wwwwwwwww....##", + "####~~~~~~~~~~#..wwwww##########", + "##~~~~~~~~~~~~#..wwwww##########", + "##~~~~~~~~~~~~#..wwwww##########", + "##~~~~~~~~~~~~S.################", + "##~~~~~.........#.##############", + "##~~~~~.........#.##############", + "##~~~~~.........#.##############", + "##.#########....#.##############", + "##wwwwwwwww#....#......~########", + "##wwwwwwwww#....#wwwww~~########", + "##wwwwwwwww#....#wwwww~~########", + "##wwwwwwwww#....#wwwww~~########", + "##wwwwwwwww#....#wwwww~~########", + "##wwwwwwwww#....#wwwww~~########", + "##..######.#....#..~~~~~########", + "##..######.#....#...~~~~########", + "##########.#....#.......########", + "############....######..########" + ], + "points": { + "below_door": [11, 2], + "jubilife_entry.1": [14, 31], + "jubilife_entry.2": [14, 30], + "jubilife_entry.3": [14, 29], + "trainer_samantha": [11, 8], + "trainer_sarah": [12, 21], + "trainer_tyler": [7, 18] + }, + "objects": [ + {"name": "lass_0", "kind": "npc", "x": 12, "y": 21}, + {"name": "lass_1", "kind": "npc", "x": 11, "y": 8, "facing": "south"}, + {"name": "youngster_2", "kind": "npc", "x": 7, "y": 18}, + {"name": "youngster_3", "kind": "npc", "x": 13, "y": 2, "wander": {"x0": 12, "y0": 2, "x1": 14, "y1": 2}}, + {"name": "item_7", "kind": "item", "x": 2, "y": 28}, + {"name": "item_8", "kind": "item", "x": 29, "y": 12}, + {"name": "item_9", "kind": "item", "x": 17, "y": 18} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json new file mode 100644 index 0000000000..4f7a4e61b4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -0,0 +1,55 @@ +{ + "name": "SandgemTown", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "########################......####", + "########################......####", + "####################..........####", + "####################..........####", + "####################..........####", + "####################..........####", + "####################......########", + "####################......########", + "####################......########", + "####################......########", + "########D##....##D##S....S#D######", + ".....S........................####", + "..............................####", + "..............................####", + "..............................####", + "..............................####", + "######........................####", + "######........................####", + "######.........#####..........####", + "##########.....#####..........####", + "##########.....#####..........####", + "##########.....#####..........####", + "#######D##....S#D###..S.......####", + "######........................####", + "######........................####", + "######........................####", + "######....................########", + "####################......########", + "####################......########", + "####################......########", + "####################......########", + "####################......########" + ], + "points": { + "route_202_entry_stop": [29, 5], + "lab_door": [8, 10], + "pokemon_center_door": [17, 10], + "pokemon_center_sign": [20, 10], + "poke_mart_door": [27, 10], + "front_row_east_end": [29, 11], + "below_sign_gap.1": [21, 11], + "below_sign_gap.2": [22, 11], + "below_sign_gap.3": [23, 11], + "below_sign_gap.4": [24, 11], + "sandgem_arrival": [0, 12], + "dawn_stop": [4, 12] + }, + "objects": [ + {"name": "youngster_0", "kind": "npc", "x": 27, "y": 23, "wander": {"x0": 26, "y0": 22, "x1": 28, "y1": 24}} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json new file mode 100644 index 0000000000..3431befeae --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json @@ -0,0 +1,48 @@ +{ + "name": "TwinleafTown", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0000.bin; zone_event narc_0389", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "############........############", + "#######....#........#....#######", + "#######....#........#....#######", + "############........############", + "######....................######", + "######....................######", + "######....................######", + "######..#####.............######", + "######..#####......####...######", + "######..#####......####...######", + "######..######.....####...######", + "######..#D###S.....#D##...######", + "######....................######", + "######....................######", + "######..........S.........######", + "######....................######", + "######....................######", + "######.............#####..######", + "######...####......#####..######", + "######...####......#####..######", + "######...####.....######..######", + "######...#D##.....S#D###..######", + "######....................######", + "######....................######", + "######....................######", + "######....................######", + "######....................######", + "######......wwwwwwww......######", + "############wwwwwwww############", + "############wwwwwwww############", + "############wwwwwwww############", + "############wwwwwwww############" + ], + "points": { + "house_doorstep": [20, 22], + "barry_doorstep": [9, 12], + "twinleaf_north_exit": [15, 0] + }, + "objects": [ + {"name": "pokemon_breeder_f_0", "kind": "npc", "x": 23, "y": 14, "wander": {"x0": 22, "y0": 14, "x1": 24, "y1": 14}}, + {"name": "collector_1", "kind": "npc", "x": 12, "y": 25}, + {"name": "guitarist_3", "kind": "npc", "x": 12, "y": 5} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json new file mode 100644 index 0000000000..ec50cf46e9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json @@ -0,0 +1,43 @@ +{ + "name": "VerityLakefront", + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0004.bin; zone_event narc_0319", "revision": "default branch", "date": "2026-10-31"}, + "tiles": [ + "....############################", + "....############################", + "....############################", + "....############################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################..##############", + "################..##############", + "################..##############", + "##############.S....<...........", + "##############......<.....####..", + "##############......<.....####..", + "##############......<...........", + "##############......<...........", + "##############......#vvvvv##vvvv", + "################..........##....", + "################................", + "##################..............", + "##################..............", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "points": { + "lakefront_arrival": [31, 23], + "below_lake_entrance": [17, 14], + "lake_entrance": [17, 12] + } +} diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py new file mode 100644 index 0000000000..0bcf886057 --- /dev/null +++ b/devtools/maps/bdsp_maps.py @@ -0,0 +1,555 @@ +"""Writes BDSP AutoStory's maps as JSON, from the Pokemon Diamond decompilation. + +TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonBDSP/Maps) when ready. + +Usage: + python3 devtools/maps/bdsp_maps.py # rewrite every map in OUT + python3 devtools/maps/bdsp_maps.py Route202 # rewrite one + python3 devtools/maps/bdsp_maps.py --check # regenerate, fail on any difference + +Each map is a rectangle of the decompilation's world grid (MAPS below), +decoded tile for tile by devtools/maps/decomp.py from the files cached in +~/.cache/maps/decomp (`python3 -m devtools.maps decomp` fetches missing ones +with `gh api`; this script never fetches, it names the file it lacks). BDSP +keeps Diamond/Pearl's layout, so Diamond is read unless a map says otherwise. +The tables below add what the decompilation doesn't say or BDSP changed: + +- POINTS: named tiles the story walks from and to. A region (a set of + tiles, in order where the order matters) is written as numbered points, + `.1`, `.2`, ...: the shared schema (Pokemon_MapData.h) + has single-tile points only. +- OBJECTS: which of the events file's objects BDSP shows. People hidden by + a story flag are left out, and people who stand still or wander are kept, + unless an entry here says otherwise (`show`, `hide`, `still`, `at`), or + adds someone the console found that Diamond doesn't have. +- WARP_DOORS: warp tiles written 'D' so that no plan steps onto them; the + other warp tiles are written '.', since the story arrives on them. +- PATCHES: tiles measured on the console that differ from Diamond's, with + the run that measured them. The map's tiles stay the decompilation's; the + loader applies the patches. + +The legend is the schema's: '#' wall, '.' open, '~' tall grass, 'w' water, +'^' 'v' '<' '>' ledges hopped the arrow's way, 'D' a door or cave mouth +(walked into) or a warp tile in WARP_DOORS, 'S' a sign or mailbox (read by +facing it; a sign script on a wall too). Items on the ground are objects of +kind "item"; rocks, cut trees, berry soil and steam vents are '#'. + +Rules carried over from the maps' history: terrain from the decomp, people +and BDSP's edits from the console; a route is coded only over tiles a human +or a probe has walked; a map change re-runs every checkpoint that walks it. +Bulbapedia's DP map images have 12 px rows for 16 px columns (3/4 of a tile +per row) and paint cliffs taller than their tiles, so they are for drawing +routes over (`python3 -m devtools.maps overlay`), not for terrain. Scenes' +trigger rectangles (the events files' coord events) have no place in the +schema; Segment00Lines lists those it needs in C++. +""" +import argparse +import json +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from devtools.maps import decomp # noqa: E402 + +OUT = 'SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps' +CACHE = Path.home() / '.cache' / 'maps' / 'decomp' +# When the cache was filled from the decompilations' default branches. +READ = '2026-10-31' + +LEDGES = {'north': '^', 'south': 'v', 'west': '<', 'east': '>'} +SIGN_GFX = ('MAILBOX',) +OBSTACLE_GFX = ('CUT_TREE', 'ROCK_SMASH', 'STRENGTH_BOULDER', 'BERRY_SOIL', 'VENT') +FACING = {'LOOK_NORTH': 'north', 'LOOK_SOUTH': 'south', 'LOOK_WEST': 'west', 'LOOK_EAST': 'east'} + + +# Each map: its header constant, the world rectangle (x0, z0, width, +# height), and the decompilation when not Diamond. Local (x, y) = world +# (x - x0, z - z0). A map that joins another on the world grid keeps its +# rectangle's world corner, so story code can place them side by side. +MAPS = { + # Cells (3..4, 26) from z 839: the image-traced grid's columns and the + # game's rows. Console: the border sign read from (54, 4) facing east, + # row 3 open east of the grass, row 5 to Sandgem without a stop, the + # Potion lady on row 3 (2026-10-28 to 30, CFR "walk"). + 'Route201': {'header': 'ROUTE_201', 'rect': (96, 839, 64, 25)}, + # Cell (5, 25) from x 159. Console: under the south ledge at (22, 24), + # the save spot (30, 24) against the east trees, Natalie's challenge at + # (22, 22), column 30 north to row 4 (r75), the catch spot's walls. + 'Route202': {'header': 'ROUTE_202', 'rect': (159, 800, 36, 32)}, + # Cells (5..6, 23) from x 191: column 0 is Jubilife's east edge. + # Console (r227 hand pass, 2026-10-31): the Gate's warp at column 55, + # the ledge on row 15, the girl at (43, 17), row 18 straight west to + # Jubilife (35 taps). Diamond has four sand rows under the ledge where + # the console counted three (the first tap may only have turned). + 'Route203': {'header': 'ROUTE_203', 'rect': (191, 740, 61, 24)}, + # Cell (5, 21). Console: row 27 open under the cliff, the stairs, + # Taylor's sight at column 17 (human walk, 2026-10-31). Suspects: + # column 23 rows 12..19 blocked (r242a); three open rows under the cave, + # not four (r241a, r243a). + 'Route204North': {'header': 'ROUTE_204_NORTH', 'rect': (160, 672, 32, 32)}, + # Cell (5, 22). Console: north up column 14 stops at the signpost + # (14, 17); column 13 is grass to the cliff (13, 2); Sarah walked up and + # fought on row 21 (r233a, r234a). 01.08 passed once (r235a). + 'Route204South': {'header': 'ROUTE_204_SOUTH', 'rect': (160, 704, 32, 32), 'read': '2026-11-01'}, + # Cell (5, 26). Console (2026-10-29/30): all three doors, five signs, + # the doors' front row east to the trees and north from it, the Lab's + # sign read facing west, the walk south from Route 202 stopping above + # the Mart at (29, 5). + 'SandgemTown': {'header': 'SANDGEM', 'rect': (160, 832, 34, 32)}, + # Cells (4..5, 23..24). Console (2026-10-30/31): the lamps (43, 53) and + # (49, 53), north from (52, 53) to the Center's door, the School's door + # from the Center's doorstep, the east street to Route 203 (r230a), the + # north street, and the 00.05 people on their events-file tiles. + 'JubilifeCity': {'header': 'JUBLIFE', 'rect': (128, 736, 64, 64)}, + # Cells (8..9, 23..24); Platinum's map_data_022/023/175/024 are the + # same terrain. Console (r204 to r215): 20 D-pad taps from the + # Center's doorstep (46, 21) to below the Gym's door. + 'OreburghCity': {'header': 'OREBURGH', 'rect': (256, 736, 64, 64)}, + # The only cell of matrix 003; Platinum identical. + 'OreburghGate': {'header': 'OREBURGH_GATE_1F', 'rect': (0, 0, 32, 32)}, + # The only cell of matrix 113. 01.04 walks it as a record: north up + # column 5 until a trainer stops us. + 'OreburghGym': {'header': 'OREBURGH_GYM', 'rect': (0, 0, 32, 32)}, + # B2F, the coal room: matrix 006. Console (2026-10-28, r99): the + # corridor's rocks zigzag a row at a time, the room's second row passes + # under the worker, Roark a row above the bottom between two rocks; the + # walk north into the hall went up column 14 (the warp is column 15: a + # stick hold drifts, or BDSP's stairs are wider). + 'OreburghMine': {'header': 'OREBURGH_MINE_B2F', 'rect': (0, 0, 32, 32)}, + # Platinum's matrix 051 (Diamond's matrix is not in the cache), rows + # 0..53. Console (2026-10-31, r235b and D-pad probes): in from the south + # door onto (19, 50), up the stairs (18..20, 45..47) to the wall at row + # 39, the corridor three wide to row 41 and open east on rows 42..44, + # the rocks (22, 42), (22, 43), (23, 44) and the Potion (22, 44). Rows + # 0..29 were a hand trace from the DP image before; nothing walks there. + 'RavagedPath': {'header': 'RAVAGED_PATH', 'rect': (0, 0, 32, 54), 'repo': decomp.Platinum.REPO}, + # Cell (5, 20); the cell above carries the same header but is cut off + # from the town. Console: the old couple (2026-10-31 walk, r251a). + 'FloaromaTown': {'header': 'FLOAROMA', 'rect': (160, 640, 32, 32)}, + # Cell (3, 27). The player's house is the south-east one, door + # (20, 21); Barry's the north-west one, door (9, 11) (the interiors say + # so; Diamond's map constants name them the other way round). + 'TwinleafTown': {'header': 'TWINLEAF', 'rect': (96, 864, 32, 32)}, + # Cell (2, 26), of the four the header covers (the others are trees + # and water). The ledges on column 20 (rows 14..18) are hopped west. + 'VerityLakefront': {'header': 'VERITY_LAKEFRONT', 'rect': (64, 832, 32, 32)}, + # Cell (1, 1) of the lake's matrix 101: the shore where the starter + # scene plays. Only this cell is reached on foot. + 'LakeVerity': {'header': 'LAKE_VERITY', 'rect': (32, 32, 32, 32)}, +} + + +def box(x0, y0, x1, y1): + """Every tile of a box, both corners inclusive, row by row.""" + return [(x, y) for y in range(y0, y1 + 1) for x in range(x0, x1 + 1)] + + +# Named tiles; a list is a region, written as numbered points. +POINTS = { + 'Route201': { + # The arrow sign to Sandgem. Console (CFR "walk"): east along row 4 + # stops at its west side and A reads it. + 'border_sign': (55, 4), + # The Poke Mart lady (10 Potions): Diamond spawns her at (44, 3), the + # console had her at (43, 3) and walking west along row 3 stopped at + # (44, 3), facing her (99715d5d6, f823453e9; r135a missed her on row 4). + 'potion_giver': (43, 3), + 'potion_giver_talk_from': (44, 3), + # Segment 00's lines (Segment00Lines). + 'route_201_arrival': (15, 24), + 'barry_warning': (15, 18), + 'route_201_return': (0, 14), + 'rowan_stop': (5, 14), + 'route_201_east_end': (63, 5), + }, + 'Route202': { + # 00.03's save after the catch: the catch patch's bottom row. The + # sign (24, 25) is 5 right and 2 up; south are trees (r253). + 'catch_spot': (19, 27), + # 00.04's save before the trainers, under the south ledge against + # the east trees (r113a..r117a). + 'save_spot': (30, 24), + 'trainer_tristan': (7, 13), + 'trainer_natalie': (22, 18), + 'trainer_logan': (26, 4), + # The middle of the gap to Jubilife, below its 3-wide neck. + 'exit_jubilife': (15, 0), + }, + 'Route203': { + # The warp tile the Gate puts us on, and its open neighbours. + 'gate_exit': [(55, 9), (54, 9), (55, 8), (55, 10)], + # Row 18 between the cliffs: it runs straight west into Jubilife. + 'west_line': box(24, 18, 42, 18), + }, + 'Route204North': { + 'cave_exit': (20, 26), + # The line a human walked on 2026-10-31: out of the cave, west under + # the cliff, up the stairs, east (Taylor), north up column 19, west + # below the flower beds, north between them on column 11 ((12, 6) + # is blocked on the console). + 'floaroma_waypoints': [(20, 27), (11, 27), (11, 22), (19, 22), (19, 12), (11, 12), (11, 5)], + # The path north into Floaroma: walking north from here leaves. + 'floaroma_path': box(10, 0, 12, 5), + 'trainer_twin_left': (15, 7), + 'trainer_twin_right': (16, 7), + 'trainer_taylor': (17, 20), + 'trainer_brandon': (20, 12), + }, + 'Route204South': { + 'below_door': (11, 2), + # Where the walk north from Jubilife may stop, up to two tiles past + # the border (400 ms holds between looks). + 'jubilife_entry': [(14, 31), (14, 30), (14, 29)], + 'trainer_samantha': (11, 8), + 'trainer_sarah': (12, 21), + 'trainer_tyler': (7, 18), + }, + 'SandgemTown': { + # The walk south from Route 202 down the road's east side stops here, + # above the Mart where the road narrows (console, 2026-10-29/30). + 'route_202_entry_stop': (29, 5), + 'lab_door': (8, 10), + 'pokemon_center_door': (17, 10), + # Walking north from row 14 in its column stops below it. + 'pokemon_center_sign': (20, 10), + 'poke_mart_door': (27, 10), + # East along the doors' front row stops here, at the trees (CFR + # "walk", 2026-10-30): a known tile to plan north from. + 'front_row_east_end': (29, 11), + # The front row below the gap between the Center's and the Mart's + # signs: the only way north from that row that passes no door. + 'below_sign_gap': box(21, 11, 24, 11), + 'sandgem_arrival': (0, 12), + 'dawn_stop': (4, 12), + }, + 'JubilifeCity': { + # A doorway (warp tile) stepped onto from (40, 41). + 'trainers_school_door': (40, 40), + # Walked into from (52, 41); eleven taps west from its doorstep put + # us under the School's door (2026-10-30). + 'pokemon_center_door': (52, 40), + 'tv_station_door': (36, 15), + # Talked to from the east (also works from the south). + 'poketch_president': (46, 35), + # His spawn tile; Diamond has him wander a tile either side, the + # console had him a tile east of it. + 'clown_mart': (55, 33), + 'clown_tv_station': (36, 16), + # Talked to from the south; west along row 18 stops beside him. + 'clown_poketch_company': (15, 18), + # A tile west of 00.05's save below the steps, then north: on + # column 46 or 47 a few rows up (CFR "walk", 2026-10-30). + 'up_the_steps': box(46, 58, 47, 60), + # Where Route 203's road enters, rows 21..24 at the east edge. + 'east_entrance': box(61, 21, 63, 24), + # The north road where it leaves the plaza: north from here goes + # up the road to Route 204 and Rowan's scene. + 'north_road': box(44, 16, 48, 20), + }, + 'OreburghCity': { + 'pokemon_center_door': (47, 20), + # The taps say x 46, a column west of the door. + 'pokemon_center_doorstep': (46, 21), + 'gym_door': (26, 20), + 'gym_doorstep': (26, 21), + 'gate_mouth': (1, 13), + }, + 'OreburghGym': { + # Coming in puts us here; the door is below. + 'entrance': (5, 23), + 'roark': (5, 3), + 'trainer_first_tier': (4, 18), + 'trainer_second_tier': (7, 11), + }, + 'OreburghMine': { + 'roark': (18, 28), + 'corridor_exit_start': (14, 10), + # The first open row below the warp tile, where the walk in from + # the hall leaves us. + 'corridor_top': box(14, 2, 16, 2), + }, + 'RavagedPath': { + 'entrance': (19, 50), + 'east_end': (29, 44), + 'above_exit': (28, 44), + # Rock Smash rocks, open once smashed. + 'rocks': [(11, 36), (7, 37), (12, 37), (8, 38), (10, 38), (10, 39), (13, 39), + (7, 40), (9, 40), (17, 40), (12, 41), (22, 42), (22, 43), (23, 44)], + # West of the two rocks on rows 42 and 43. + 'before_rocks': [(21, 42), (21, 43)], + }, + 'FloaromaTown': { + 'route_204_arrival': (11, 29), + 'old_woman': (3, 25), + 'old_man': (2, 25), + 'pokemon_center_door': (16, 26), + }, + 'TwinleafTown': { + 'house_doorstep': (20, 22), + # Barry's scene fires here, below his door. + 'barry_doorstep': (9, 12), + 'twinleaf_north_exit': (15, 0), + }, + 'VerityLakefront': { + 'lakefront_arrival': (31, 23), + 'below_lake_entrance': (17, 14), + # The lake's scene fires here; it is assumed to leave us here too. + 'lake_entrance': (17, 12), + }, +} + + +# Overrides by events-file object index. `show`: a person hidden by a +# story flag who is there when the story walks the map. `hide`: someone +# BDSP doesn't have, or the story never meets. `still`: a wanderer who +# stood still on the console. `at`: where the console found them. `add`: +# people Diamond doesn't have, from the console. +OBJECTS = { + 'Route201': { + # The Potion lady stands a tile off her spawn on the console, and + # her talk is walked to, not planned (POINTS). + 1: {'hide': 'her talk is walked to, not planned'}, + }, + 'Route203': { + # Stands still in Diamond, wanders near the Gate in BDSP (console). + 0: {'hide': 'wanders in BDSP'}, + }, + 'Route204North': { + # Bug Catcher Brandon paces in Diamond from (22, 13); he stopped us + # on row 12 (r246a), and the DP map draws him at (20, 12). + 0: {'at': (20, 12), 'still': 'r246a', 'name': 'bug_catcher_brandon'}, + }, + 'SandgemTown': { + # Stand still in Diamond, wander on the console. + 1: {'hide': 'wanders in BDSP'}, + 2: {'hide': 'wanders in BDSP'}, + }, + 'JubilifeCity': { + # 00.05's story people, hidden before and after it. + 24: {'show': '00.05', 'name': 'poketch_president'}, + 28: {'show': '00.05', 'name': 'clown_tv_station'}, + # Wander in Diamond; stood still on the console (00.05, three runs). + 25: {'show': '00.05', 'still': '00.05, three runs', 'name': 'clown_mart'}, + 26: {'show': '00.05', 'still': '00.05, three runs', 'name': 'clown_poketch_company'}, + }, + 'FloaromaTown': { + # Grunts at the Meadow until the Valley Windworks is cleared, and + # the man with Cyrus's sprite (whether he is there is for the console). + 7: {'show': 'until the Valley Windworks'}, + 8: {'show': 'until the Valley Windworks'}, + 3: {'show': 'not yet checked on the console'}, + 'add': [ + # Not in Diamond's data. Walking north from (3, 29) stopped 3 + # tiles up at the old woman (r251a). + {'name': 'old_woman', 'x': 3, 'y': 25, 'measured_by': 'r251a, 2026-10-31'}, + {'name': 'old_man', 'x': 2, 'y': 25, 'measured_by': 'r251a, 2026-10-31'}, + ], + }, + 'OreburghMine': { + # Hidden once his scene here is over; the story walks to him. + 0: {'show': '01.03', 'name': 'roark'}, + }, + 'LakeVerity': { + # The starter scene's actors, where the walk in ends. + 0: {'show': 'the starter scene', 'name': 'rowan'}, + 1: {'show': 'the starter scene', 'name': 'counterpart'}, + 3: {'show': 'the starter scene'}, + }, +} + + +WARP_DOORS = { + # The Ravaged Path's door: its warp tile is the mouth. + 'Route204South': [(11, 1)], + # The Route 218 gate, and the doorways of the School and the Global + # Terminal: entered, never stood on by a route. + 'JubilifeCity': [(0, 22), (0, 23), (40, 40), (21, 42)], + # The way up to the entrance hall: stepping on it leaves the room. + 'OreburghMine': [(15, 1)], +} + + +PATCHES = { + 'Route202': ( + # BDSP has trees where Diamond's catch patch has its two bottom rows: + # west along row 29 stopped at column 21, beside them. + [(x, y, '#', 'r253, 2026-11-01') for y in (28, 29) for x in range(15, 21)] + # South from the pocket (21, 29), where the catch's save loads, + # was blocked at once. + + [(21, 30, '#', 'r254, 2026-11-01')] + ), + 'Route204North': [ + # Grass in the data, blocked on the console twice. + (12, 6, '#', 'r248a, 2026-10-31'), + ], +} + + +def no_fetch(repo, path): + raise SystemExit(f'{repo}/{path} is not in {CACHE}. Fetch it with `python3 -m devtools.maps decomp ...` first.') + + +def glyph(attr): + behaviour = attr & 0xff + if behaviour in decomp.JUMP: + return LEDGES[decomp.JUMP[behaviour]] + if behaviour in decomp.JUMP_TWICE: + return LEDGES[decomp.JUMP_TWICE[behaviour]] + if behaviour == decomp.DOOR or behaviour in decomp.CAVE_MOUTHS: + return 'D' + if behaviour in decomp.WARP_TILES or behaviour in decomp.WARP_STAIRS: + return 'W' + if behaviour in decomp.WATER: + return 'w' + if attr & decomp.BLOCKED: + return '#' + if behaviour in decomp.TALL_GRASS: + return '~' + return '.' + + +def wander_box(obj, x, y, width, height): + return {'x0': max(0, x - obj.range_x), 'y0': max(0, y - obj.range_z), + 'x1': min(width - 1, x + obj.range_x), 'y1': min(height - 1, y + obj.range_z)} + + +def place_objects(name, events, rect, rows): + """Writes signs and obstacles into `rows`; returns the objects.""" + x0, z0, width, height = rect + overrides = OBJECTS.get(name, {}) + objects = [] + for index, obj in enumerate(events.objects): + x, y = obj.x - x0, obj.z - z0 + if not (0 <= x < width and 0 <= y < height): + continue + override = overrides.get(index, {}) + if obj.gfx in OBSTACLE_GFX: + rows[y][x] = '#' + continue + if obj.gfx == decomp.ITEM: + objects.append({'name': f'item_{index}', 'kind': 'item', 'x': x, 'y': y}) + continue + if obj.hidden and 'show' not in override or 'hide' in override: + continue + if 'SIGN' in obj.gfx or obj.gfx in SIGN_GFX: + rows[y][x] = 'S' + continue + x, y = override.get('at', (x, y)) + entry = {'name': override.get('name', f'{obj.gfx.lower()}_{index}'), 'kind': 'npc', 'x': x, 'y': y} + if obj.movement in FACING: + entry['facing'] = FACING[obj.movement] + if obj.movement.startswith(('WANDER', 'WALK')) and 'still' not in override: + entry['wander'] = wander_box(obj, x, y, width, height) + objects.append(entry) + for added in overrides.get('add', []): + objects.append({'name': added['name'], 'kind': 'npc', 'x': added['x'], 'y': added['y']}) + return objects + + +def decode_map(name): + spec = MAPS[name] + repo = spec.get('repo', decomp.Diamond.REPO) + game = decomp.game_for(repo, CACHE, None, no_fetch) + header = game.header(spec['header']) + matrix = game.matrix(header.matrix_id) + world = decomp.World(game, matrix) + x0, z0, width, height = spec['rect'] + rows = [] + for y in range(height): + row = [] + for x in range(width): + attr = world.attr(x0 + x, z0 + y) + if attr is None: + raise SystemExit(f'{name}: ({x}, {y}) is outside matrix {header.matrix_id}.') + row.append(glyph(attr)) + rows.append(row) + events = game.events(header.events_id) + for sign in events.signs: + x, y = sign.x - x0, sign.z - z0 + if 0 <= x < width and 0 <= y < height and rows[y][x] == '#': + rows[y][x] = 'S' + objects = place_objects(name, events, spec['rect'], rows) + doors = set(WARP_DOORS.get(name, [])) + for y, row in enumerate(rows): + for x, tile in enumerate(row): + if tile == 'W': + row[x] = 'D' if (x, y) in doors else '.' + lands = sorted({world.land_id(x, z) for z in range(z0, z0 + height, decomp.CELL) + for x in range(x0, x0 + width, decomp.CELL)} - {None}) + source = { + 'decomp_file': f'{repo}: ' + ', '.join(game.land_path(land) for land in lands) + + f'; {game.events_name(header.events_id)}', + 'revision': 'default branch', + 'date': spec.get('read', READ), + } + return [''.join(row) for row in rows], objects, source + + +def points_of(name): + points = {} + for point, value in POINTS.get(name, {}).items(): + if isinstance(value, list): + for i, pos in enumerate(value, 1): + points[f'{point}.{i}'] = pos + else: + points[point] = value + return points + + +def map_text(name): + """The map's JSON: one line per row, point, object and patch.""" + tiles, objects, source = decode_map(name) + lines = ['{', f' "name": {json.dumps(name)},', f' "source": {json.dumps(source)},', ' "tiles": ['] + lines += [f' {json.dumps(row)},' for row in tiles] + lines[-1] = lines[-1].rstrip(',') + lines.append(' ]') + + def section(key, items): + if not items: + return + lines[-1] += ',' + lines.append(f' "{key}": ' + ('{' if key == 'points' else '[')) + lines.extend(f' {item},' for item in items) + lines[-1] = lines[-1].rstrip(',') + lines.append(' ' + ('}' if key == 'points' else ']')) + + section('points', [f'{json.dumps(p)}: [{x}, {y}]' for p, (x, y) in points_of(name).items()]) + section('objects', [json.dumps(o) for o in objects]) + section('patches', [json.dumps({'x': x, 'y': y, 'glyph': g, 'measured_by': m}) + for x, y, g, m in PATCHES.get(name, [])]) + lines.append('}') + return '\n'.join(lines) + '\n' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) + parser.add_argument('--out', default=OUT, help='folder of the .json files') + parser.add_argument('--check', action='store_true', help='check the files in --out instead of writing them') + parser.add_argument('maps', nargs='*', help='default: every map in MAPS') + args = parser.parse_args() + names = args.maps or sorted(MAPS) + for name in names: + if name not in MAPS: + parser.error(f'{name}: not in MAPS') + texts = {name: map_text(name) for name in names} + if args.check: + differ = [n for n, text in texts.items() + if not os.path.exists(os.path.join(args.out, n + '.json')) + or open(os.path.join(args.out, n + '.json'), newline='').read() != text] + if not args.maps: + extra = sorted(f[:-5] for f in os.listdir(args.out) if f.endswith('.json') and f[:-5] not in MAPS) + differ += [f'{n} (not in MAPS)' for n in extra] + if differ: + sys.exit(f'Differ from the generator: {", ".join(differ)}. Regenerate them without --check.') + print(f'{len(texts)} maps in {args.out} match the generator.') + return + os.makedirs(args.out, exist_ok=True) + for name, text in texts.items(): + with open(os.path.join(args.out, name + '.json'), 'w', newline='') as file: + file.write(text) + print(f'Wrote {len(texts)} maps to {args.out}.') + + +if __name__ == '__main__': + main() From 3a67d5618e32f69591f23dd4bdb99ae1d51487b0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:20:18 -0800 Subject: [PATCH 05/74] BDSP maps: load the built-in maps, with their points and regions, and test them PokemonBDSP_AutoStory_Maps reads the embedded JSON through the shared MapData loader: story_map(), map_point(), and map_region() for the numbered points a region is written as. The tests load every map, check that points and objects stand where they can, and that the lookups find and refuse what they should. PokemonBDSP::add_tests() is now run by the unit test runner, which never called it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- SerialPrograms/CMakeLists.txt | 2 + .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../Data/PokemonBDSP_AutoStory_Maps.cpp | 77 +++++ .../Data/PokemonBDSP_AutoStory_Maps.h | 54 +++ .../PokemonBDSP_AutoStory_Maps_Tests.cpp | 311 ++++++++++++++++++ .../PokemonBDSP_AutoStory_Maps_Tests.h | 23 ++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 8 files changed, 475 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index d0966df32f..ad0ff7ae70 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -197,6 +197,8 @@ 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) +pa_embed_text_files(SerialProgramsLib Source/PokemonBDSP/Programs/AutoStory/Maps + PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_map_json) # Create binary target diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 46d51dd63e..e72f9ca61f 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -31,6 +31,7 @@ #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" #include "Pokemon/Navigation/Pokemon_Navigation_Tests.h" +#include "PokemonBDSP/PokemonBDSP_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" #include "VideoGames/PokemonLA/PokemonLA_Tests.h" @@ -76,6 +77,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); NintendoSwitch::Typewriter::add_tests_TypewriterTextMapping(ret); + NintendoSwitch::PokemonBDSP::add_tests(ret); NintendoSwitch::PokemonFRLG::add_tests(ret); NintendoSwitch::PokemonRSE::add_tests(ret); NintendoSwitch::PokemonHome::add_tests(ret); diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index b8ff5e26a5..36f4de8f6d 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -5,6 +5,7 @@ */ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -14,6 +15,7 @@ namespace PokemonBDSP{ void add_tests(UnitTestDatabase& database){ + add_tests_AutoStory_Maps(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp new file mode 100644 index 0000000000..65a16564cc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp @@ -0,0 +1,77 @@ +/* BDSP AutoStory - Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonBDSP_AutoStory_Maps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::MapData; +using Pokemon::TilePos; + + +namespace{ + +const std::map>& story_maps_by_name(){ + static const std::map> maps = []{ + std::map> parsed; + for (const auto& [name, json] : bdsp_map_json()){ + MapData map = Pokemon::parse_map(parse_json(json), name + ".json"); + if (map.name != name){ + throw ParseException(std::format("{}.json: name is \"{}\".", name, map.name)); + } + parsed.emplace(name, std::move(map)); + } + return parsed; + }(); + return maps; +} + +} + + +const MapData& story_map(const std::string& name){ + const auto& maps = story_maps_by_name(); + if (auto iter = maps.find(name); iter != maps.end()){ + return iter->second; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No BDSP story map named \"{}\".", name)); +} + +TilePos map_point(const std::string& map, const std::string& point){ + const MapData& data = story_map(map); + if (auto iter = data.points.find(point); iter != data.points.end()){ + return iter->second; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("{} has no point \"{}\".", map, point)); +} + +std::vector map_region(const std::string& map, const std::string& region){ + const MapData& data = story_map(map); + std::vector tiles; + while (true){ + const auto iter = data.points.find(std::format("{}.{}", region, tiles.size() + 1)); + if (iter == data.points.end()){ + break; + } + tiles.push_back(iter->second); + } + if (tiles.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("{} has no region \"{}\".", map, region)); + } + return tiles; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h new file mode 100644 index 0000000000..a4615a47ee --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h @@ -0,0 +1,54 @@ +/* BDSP AutoStory - Maps + * + * From: https://github.com/PokemonAutomation/ + * + * The maps the story walks, as JSON files in the shared map schema + * (Pokemon_MapData.h): PokemonBDSP/Programs/AutoStory/Maps, written by + * devtools/maps/bdsp_maps.py from the Diamond decompilation and built into + * the program by CMake. Each is named as its file ("Route202"). + * + * A map's named tiles are its points. A region, a list of tiles, is the + * points ".1", ".2", ... in order: the schema has + * single-tile points only. + * + * TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonBDSP/Maps) when ready + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Maps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Maps_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// (name, JSON text) of each map in PokemonBDSP/Programs/AutoStory/Maps/, +// built into the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). +const std::vector>& bdsp_map_json(); + +// The map `name`, read from bdsp_map_json() on first use, with its patches +// applied. Throws InternalProgramError for a name it does not have, and +// ParseException if a map does not parse or is not named as its file. +const Pokemon::MapData& story_map(const std::string& name); + +// The point `point` of the map `map`. Throws InternalProgramError for an +// unknown map or point. +Pokemon::TilePos map_point(const std::string& map, const std::string& point); + +// The tiles of the region `region` of the map `map`, in order. Throws +// InternalProgramError for an unknown map, or a region with no tiles. +std::vector map_region(const std::string& map, const std::string& region); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp new file mode 100644 index 0000000000..fa82b08059 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp @@ -0,0 +1,311 @@ +/* BDSP AutoStory Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The built-in story maps (Data/PokemonBDSP_AutoStory_Maps.h): every map + * loads, its points and objects stand where they can, and the lookups + * find what the story code asks for. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_Maps_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::MapData; +using Pokemon::MapObject; +using Pokemon::TileKind; +using Pokemon::TilePos; + +bool is_ground(TileKind tile){ + return tile == TileKind::OPEN || tile == TileKind::TALL_GRASS; +} + +// The person or item that stands still on `pos`, if any. +const MapObject* standing_object(const MapData& map, const TilePos& pos){ + for (const MapObject& object : map.objects){ + if (!object.wander && object.x == pos.x && object.y == pos.y){ + return &object; + } + } + return nullptr; +} + +// "rocks" for "rocks.3", the point's own name otherwise. +std::string region_of(const std::string& point){ + const size_t dot = point.rfind('.'); + if (dot == std::string::npos || dot + 1 == point.size()){ + return point; + } + const bool numbered = std::all_of(point.begin() + dot + 1, point.end(), [](char c){ return '0' <= c && c <= '9'; }); + return numbered ? point.substr(0, dot) : point; +} + + +// Every built-in map parses through the shared loader, named as its file. +class Test_StoryMapsLoad : public UnitTest{ +public: + Test_StoryMapsLoad() + : UnitTest("PokemonBDSP::AutoStory - Maps: the built-in JSON maps load") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + if (bdsp_map_json().empty()){ + return std::string("No built-in maps."); + } + for (const auto& [name, json] : bdsp_map_json()){ + try{ + const MapData& map = story_map(name); + if (map.name != name){ + return std::format("{}.json: story_map() returned \"{}\".", name, map.name); + } + logger.log(std::format( + "{}: {} x {}, {} points, {} objects, {} patches", + name, map.tiles.width, map.tiles.height, map.points.size(), map.objects.size(), map.patches.size() + )); + }catch (Exception& e){ + return std::format("{}: {}: {}", name, e.name(), e.message()); + } + } + return true; + } +}; + + +// What a named point must be on. Points not listed are ground the player +// stands on, with nobody standing there. +enum class PointOn{ + DOOR, + SIGN, + PERSON, // someone stands still there + WALL, // a rock until smashed +}; +struct PointCase{ + std::string map; + std::string point; // a point, or a region for all its tiles + PointOn on; +}; + +const std::vector& point_cases(){ + static const std::vector cases{ + {.map = "Route201", .point = "border_sign", .on = PointOn::SIGN}, + {.map = "Route202", .point = "trainer_tristan", .on = PointOn::PERSON}, + {.map = "Route202", .point = "trainer_natalie", .on = PointOn::PERSON}, + {.map = "Route202", .point = "trainer_logan", .on = PointOn::PERSON}, + {.map = "Route204North", .point = "trainer_twin_left", .on = PointOn::PERSON}, + {.map = "Route204North", .point = "trainer_twin_right", .on = PointOn::PERSON}, + {.map = "Route204North", .point = "trainer_taylor", .on = PointOn::PERSON}, + {.map = "Route204North", .point = "trainer_brandon", .on = PointOn::PERSON}, + {.map = "Route204South", .point = "trainer_samantha", .on = PointOn::PERSON}, + {.map = "Route204South", .point = "trainer_sarah", .on = PointOn::PERSON}, + {.map = "Route204South", .point = "trainer_tyler", .on = PointOn::PERSON}, + {.map = "SandgemTown", .point = "lab_door", .on = PointOn::DOOR}, + {.map = "SandgemTown", .point = "pokemon_center_door", .on = PointOn::DOOR}, + {.map = "SandgemTown", .point = "pokemon_center_sign", .on = PointOn::SIGN}, + {.map = "SandgemTown", .point = "poke_mart_door", .on = PointOn::DOOR}, + {.map = "JubilifeCity", .point = "trainers_school_door", .on = PointOn::DOOR}, + {.map = "JubilifeCity", .point = "pokemon_center_door", .on = PointOn::DOOR}, + {.map = "JubilifeCity", .point = "tv_station_door", .on = PointOn::DOOR}, + {.map = "JubilifeCity", .point = "poketch_president", .on = PointOn::PERSON}, + {.map = "JubilifeCity", .point = "clown_mart", .on = PointOn::PERSON}, + {.map = "JubilifeCity", .point = "clown_tv_station", .on = PointOn::PERSON}, + {.map = "JubilifeCity", .point = "clown_poketch_company", .on = PointOn::PERSON}, + {.map = "OreburghCity", .point = "pokemon_center_door", .on = PointOn::DOOR}, + {.map = "OreburghCity", .point = "gym_door", .on = PointOn::DOOR}, + {.map = "OreburghCity", .point = "gate_mouth", .on = PointOn::DOOR}, + {.map = "OreburghGym", .point = "roark", .on = PointOn::PERSON}, + {.map = "OreburghGym", .point = "trainer_first_tier", .on = PointOn::PERSON}, + {.map = "OreburghGym", .point = "trainer_second_tier", .on = PointOn::PERSON}, + {.map = "OreburghMine", .point = "roark", .on = PointOn::PERSON}, + {.map = "RavagedPath", .point = "rocks", .on = PointOn::WALL}, + {.map = "FloaromaTown", .point = "old_woman", .on = PointOn::PERSON}, + {.map = "FloaromaTown", .point = "old_man", .on = PointOn::PERSON}, + {.map = "FloaromaTown", .point = "pokemon_center_door", .on = PointOn::DOOR}, + }; + return cases; +} + +// An error naming what `pos` should be, or empty when it is. +std::string check_point_on(const MapData& map, const TilePos& pos, PointOn on){ + const TileKind tile = map.tiles.at(pos); + const MapObject* object = standing_object(map, pos); + switch (on){ + case PointOn::DOOR: + return tile == TileKind::DOOR ? "" : "not a door"; + case PointOn::SIGN: + return tile == TileKind::SIGN ? "" : "not a sign"; + case PointOn::PERSON: + return is_ground(tile) && object != nullptr && object->kind == Pokemon::ObjectKind::NPC ? "" : "nobody stands still there"; + case PointOn::WALL: + return tile == TileKind::WALL ? "" : "not a wall"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown PointOn."); +} + +std::string check_ground(const MapData& map, const TilePos& pos){ + if (!is_ground(map.tiles.at(pos))){ + return std::format("'{}', not ground", Pokemon::glyph_of(map.tiles.at(pos))); + } + return standing_object(map, pos) == nullptr ? "" : "someone stands there"; +} + + +// Every point is ground with nobody on it, unless point_cases() says +// otherwise; every numbered region runs from 1 with no gap; every case +// names a point the map has. +class Test_StoryMapPoints : public UnitTest{ +public: + Test_StoryMapPoints() + : UnitTest("PokemonBDSP::AutoStory - Maps: points stand where they can") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + for (const PointCase& item : point_cases()){ + const MapData& map = story_map(item.map); + if (!map.points.contains(item.point) && !map.points.contains(item.point + ".1")){ + return std::format("{}: no point or region \"{}\".", item.map, item.point); + } + } + size_t checked = 0; + for (const auto& [name, json] : bdsp_map_json()){ + const MapData& map = story_map(name); + for (const auto& [point, pos] : map.points){ + const std::string region = region_of(point); + // map_region() counts from 1 and stops at a gap. + if (region != point && std::stoul(point.substr(region.size() + 1)) > map_region(name, region).size()){ + return std::format("{}: {} is not reached counting {}.1, {}.2, ...", name, point, region, region); + } + const auto it = std::ranges::find_if(point_cases(), [&](const PointCase& item){ + return item.map == name && item.point == region; + }); + const std::string error = it == point_cases().end() ? check_ground(map, pos) : check_point_on(map, pos, it->on); + if (!error.empty()){ + return std::format("{}: {} {}: {}.", name, point, Pokemon::to_string(pos), error); + } + checked++; + } + } + logger.log(std::format("{} points checked.", checked)); + return true; + } +}; + + +// Everyone stands on ground, and a wanderer's box holds their tile. +class Test_StoryMapObjects : public UnitTest{ +public: + Test_StoryMapObjects() + : UnitTest("PokemonBDSP::AutoStory - Maps: objects stand on open ground") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + size_t checked = 0; + for (const auto& [name, json] : bdsp_map_json()){ + const MapData& map = story_map(name); + for (const MapObject& object : map.objects){ + const TilePos pos{object.x, object.y}; + if (!is_ground(map.tiles.at(pos))){ + return std::format("{}: {} stands on '{}' at {}.", name, object.name, Pokemon::glyph_of(map.tiles.at(pos)), Pokemon::to_string(pos)); + } + const auto& box = object.wander; + if (box && (pos.x < box->x0 || pos.x > box->x1 || pos.y < box->y0 || pos.y > box->y1)){ + return std::format("{}: {} at {} is outside their wander box.", name, object.name, Pokemon::to_string(pos)); + } + checked++; + } + } + logger.log(std::format("{} objects checked.", checked)); + return true; + } +}; + + +// map_point() and map_region() find what the story asks for, regions in +// order, and throw for what a map does not have. +struct LookupCase{ + std::string name; + std::function()> lookup; + // The tiles, or empty when the lookup must throw InternalProgramError. + std::vector expected; +}; + +class Test_StoryMapLookups : public UnitTest{ +public: + Test_StoryMapLookups() + : UnitTest("PokemonBDSP::AutoStory - Maps: map_point() and map_region()") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + { + .name = "a point", + .lookup = []{ return std::vector{map_point("SandgemTown", "pokemon_center_door")}; }, + .expected = {{17, 10}}, + }, + { + .name = "a region, in order", + .lookup = []{ return map_region("Route204North", "floaroma_waypoints"); }, + .expected = {{20, 27}, {11, 27}, {11, 22}, {19, 22}, {19, 12}, {11, 12}, {11, 5}}, + }, + { + .name = "an unknown map", + .lookup = []{ return std::vector{map_point("Route299", "door")}; }, + .expected = {}, + }, + { + .name = "an unknown point", + .lookup = []{ return std::vector{map_point("SandgemTown", "gym_door")}; }, + .expected = {}, + }, + { + .name = "a point is not a region", + .lookup = []{ return map_region("SandgemTown", "lab_door"); }, + .expected = {}, + }, + }; + for (const LookupCase& item : cases){ + std::vector tiles; + try{ + tiles = item.lookup(); + }catch (InternalProgramError&){ + if (item.expected.empty()){ + continue; + } + return item.name + ": threw InternalProgramError."; + } + if (tiles != item.expected){ + std::string read; + for (const TilePos& pos : tiles){ + read += " " + Pokemon::to_string(pos); + } + return std::format("{}: read{}, expected {} tiles{}.", item.name, read, item.expected.size(), + item.expected.empty() ? " (an InternalProgramError)" : ""); + } + } + return true; + } +}; + +} + + +void add_tests_AutoStory_Maps(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h new file mode 100644 index 0000000000..59905aa331 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h @@ -0,0 +1,23 @@ +/* BDSP AutoStory Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Maps_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Maps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void add_tests_AutoStory_Maps(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index ffc3642a0a..47ad878a18 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1620,6 +1620,10 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/PokemonBDSP_Settings.h Source/PokemonBDSP/PokemonBDSP_Tests.cpp Source/PokemonBDSP/PokemonBDSP_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp From 796dd5627f0803470dd96d57f2dafd6ad502bd19 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:22:46 -0800 Subject: [PATCH 06/74] BDSP maps: the five interiors of 00.01 to 00.03 The player's and Barry's houses (both floors) and Rowan's lab, from pokeplatinum at c6689696d5fb, decomp only and not yet checked on the console: their stairs, doors and the tiles the story talks from, and the doors' warps to Twinleaf's and Sandgem's door points. The map tests check that every warp leads to a point that exists. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Maps/PlayerHouse1F.json | 29 ++++++++++++ .../AutoStory/Maps/PlayerHouse2F.json | 22 +++++++++ .../Programs/AutoStory/Maps/RivalHouse1F.json | 28 ++++++++++++ .../Programs/AutoStory/Maps/RivalHouse2F.json | 25 +++++++++++ .../Programs/AutoStory/Maps/RowansLab.json | 36 +++++++++++++++ .../Programs/AutoStory/Maps/TwinleafTown.json | 4 +- .../PokemonBDSP_AutoStory_Maps_Tests.cpp | 15 ++++++- devtools/maps/bdsp_maps.py | 45 ++++++++++++++++++- 8 files changed, 200 insertions(+), 4 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json new file mode 100644 index 0000000000..7929140ede --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json @@ -0,0 +1,29 @@ +{ + "name": "PlayerHouse1F", + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "tiles": [ + "#############", + "#############", + "#############", + "#SS..S####..#", + "#.....####..#", + "#SSS..SS....#", + "#...........#", + "#...........#", + "#..##.......#", + "##.##......##", + "##....D....##", + "#############" + ], + "points": { + "stairs": [10, 3], + "mom": [7, 8], + "door": [6, 10] + }, + "warps": [ + {"x": 6, "y": 10, "to_map": "TwinleafTown", "to_point": "player_house_door"} + ], + "objects": [ + {"name": "mom_0", "kind": "npc", "x": 7, "y": 8, "facing": "north"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json new file mode 100644 index 0000000000..a33faa27b9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json @@ -0,0 +1,22 @@ +{ + "name": "PlayerHouse2F", + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_187.bin; events_twinleaf_town_player_house_2f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "tiles": [ + "############", + "############", + "############", + "#######S####", + "#S#SSS...###", + "#........###", + "#..........#", + "#..........#", + "#........#.#", + "##.........#", + "##.......#.#", + "############" + ], + "points": { + "stairs": [8, 4], + "start": [4, 6] + } +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json new file mode 100644 index 0000000000..7d1b616c29 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json @@ -0,0 +1,28 @@ +{ + "name": "RivalHouse1F", + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_184.bin; events_twinleaf_town_rival_house_1f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "tiles": [ + "#############", + "#############", + "#############", + "#..#####..###", + "#..####.....#", + "#....##..####", + "#...........#", + "#...........#", + "#.......##..#", + "##......##.##", + "##....D....##", + "#############" + ], + "points": { + "door": [6, 10], + "stairs": [2, 3] + }, + "warps": [ + {"x": 6, "y": 10, "to_map": "TwinleafTown", "to_point": "rival_house_door"} + ], + "objects": [ + {"name": "pokefan_f_0", "kind": "npc", "x": 4, "y": 6} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json new file mode 100644 index 0000000000..d0b03b36e6 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json @@ -0,0 +1,25 @@ +{ + "name": "RivalHouse2F", + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_185.bin; events_twinleaf_town_rival_house_2f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "tiles": [ + "############", + "############", + "############", + "############", + "###...S##S##", + "###........#", + "#..........#", + "#..........#", + "#.#........#", + "#.........##", + "#.#.......##", + "############" + ], + "points": { + "stairs": [3, 4], + "barry_talk": [8, 5] + }, + "objects": [ + {"name": "barry", "kind": "npc", "x": 9, "y": 5, "facing": "north"} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json new file mode 100644 index 0000000000..8faef4e607 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json @@ -0,0 +1,36 @@ +{ + "name": "RowansLab", + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_222.bin; events_sandgem_town_pokemon_research_lab.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "tiles": [ + "######################", + "######################", + "###SSSS####S####.###S#", + "#........#...##......#", + "#.###................#", + "#...................##", + "#.............#....###", + "###........###########", + "###........###########", + "###........###########", + "#............#########", + "##..........##########", + "##..........##########", + "###........###########", + "###........###########", + "###....D...###########", + "######################", + "######################" + ], + "points": { + "door": [7, 15], + "rowan_talk": [7, 6] + }, + "warps": [ + {"x": 7, "y": 15, "to_map": "SandgemTown", "to_point": "lab_door"} + ], + "objects": [ + {"name": "rowan", "kind": "npc", "x": 7, "y": 5, "facing": "south"}, + {"name": "scientist_m_1", "kind": "npc", "x": 3, "y": 12, "wander": {"x0": 1, "y0": 12, "x1": 5, "y1": 12}}, + {"name": "scientist_f_2", "kind": "npc", "x": 10, "y": 12} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json index 3431befeae..ff22e6feba 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json @@ -38,7 +38,9 @@ "points": { "house_doorstep": [20, 22], "barry_doorstep": [9, 12], - "twinleaf_north_exit": [15, 0] + "twinleaf_north_exit": [15, 0], + "player_house_door": [20, 21], + "rival_house_door": [9, 11] }, "objects": [ {"name": "pokemon_breeder_f_0", "kind": "npc", "x": 23, "y": 14, "wander": {"x0": 22, "y0": 14, "x1": 24, "y1": 14}}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp index fa82b08059..0c62adb480 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp @@ -133,6 +133,12 @@ const std::vector& point_cases(){ {.map = "FloaromaTown", .point = "old_woman", .on = PointOn::PERSON}, {.map = "FloaromaTown", .point = "old_man", .on = PointOn::PERSON}, {.map = "FloaromaTown", .point = "pokemon_center_door", .on = PointOn::DOOR}, + {.map = "TwinleafTown", .point = "player_house_door", .on = PointOn::DOOR}, + {.map = "TwinleafTown", .point = "rival_house_door", .on = PointOn::DOOR}, + {.map = "PlayerHouse1F", .point = "mom", .on = PointOn::PERSON}, + {.map = "PlayerHouse1F", .point = "door", .on = PointOn::DOOR}, + {.map = "RivalHouse1F", .point = "door", .on = PointOn::DOOR}, + {.map = "RowansLab", .point = "door", .on = PointOn::DOOR}, }; return cases; } @@ -164,7 +170,7 @@ std::string check_ground(const MapData& map, const TilePos& pos){ // Every point is ground with nobody on it, unless point_cases() says // otherwise; every numbered region runs from 1 with no gap; every case -// names a point the map has. +// names a point the map has; every warp leads to a point that exists. class Test_StoryMapPoints : public UnitTest{ public: Test_StoryMapPoints() @@ -195,6 +201,13 @@ class Test_StoryMapPoints : public UnitTest{ } checked++; } + for (const Pokemon::MapWarp& warp : map.warps){ + try{ + map_point(warp.to_map, warp.to_point); + }catch (InternalProgramError& e){ + return std::format("{}: the warp at {}: {}", name, Pokemon::to_string(TilePos{warp.x, warp.y}), e.message()); + } + } } logger.log(std::format("{} points checked.", checked)); return true; diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py index 0bcf886057..7c4dbf1e72 100644 --- a/devtools/maps/bdsp_maps.py +++ b/devtools/maps/bdsp_maps.py @@ -24,6 +24,7 @@ adds someone the console found that Diamond doesn't have. - WARP_DOORS: warp tiles written 'D' so that no plan steps onto them; the other warp tiles are written '.', since the story arrives on them. +- WARPS: doors that lead to a point of another map in OUT. - PATCHES: tiles measured on the console that differ from Diamond's, with the run that measured them. The map's tiles stay the decompilation's; the loader applies the patches. @@ -63,6 +64,9 @@ FACING = {'LOOK_NORTH': 'north', 'LOOK_SOUTH': 'south', 'LOOK_WEST': 'west', 'LOOK_EAST': 'east'} +# Decoded from pokeplatinum at this revision, not yet checked on the console. +INTERIOR = {'repo': decomp.Platinum.REPO, 'revision': 'c6689696d5fb', 'read': '2026-11-01', 'unverified': True} + # Each map: its header constant, the world rectangle (x0, z0, width, # height), and the decompilation when not Diamond. Local (x, y) = world # (x - x0, z - z0). A map that joins another on the world grid keeps its @@ -137,6 +141,15 @@ # Cell (1, 1) of the lake's matrix 101: the shore where the starter # scene plays. Only this cell is reached on foot. 'LakeVerity': {'header': 'LAKE_VERITY', 'rect': (32, 32, 32, 32)}, + # 00.01 to 00.03's interiors, from pokeplatinum (c6689696d5fb), each + # the only cell of its own matrix: decomp only, not yet checked on the + # console. Mom's warning on the way out is a coord event on the + # player's door tile (6, 10), which the schema has no place for. + 'PlayerHouse1F': {'header': 'TWINLEAF_TOWN_PLAYER_HOUSE_1F', 'rect': (0, 0, 13, 12), **INTERIOR}, + 'PlayerHouse2F': {'header': 'TWINLEAF_TOWN_PLAYER_HOUSE_2F', 'rect': (0, 0, 12, 12), **INTERIOR}, + 'RivalHouse1F': {'header': 'TWINLEAF_TOWN_RIVAL_HOUSE_1F', 'rect': (0, 0, 13, 12), **INTERIOR}, + 'RivalHouse2F': {'header': 'TWINLEAF_TOWN_RIVAL_HOUSE_2F', 'rect': (0, 0, 12, 12), **INTERIOR}, + 'RowansLab': {'header': 'SANDGEM_TOWN_POKEMON_RESEARCH_LAB', 'rect': (0, 0, 22, 18), **INTERIOR}, } @@ -290,6 +303,8 @@ def box(x0, y0, x1, y1): # Barry's scene fires here, below his door. 'barry_doorstep': (9, 12), 'twinleaf_north_exit': (15, 0), + 'player_house_door': (20, 21), + 'rival_house_door': (9, 11), }, 'VerityLakefront': { 'lakefront_arrival': (31, 23), @@ -297,6 +312,14 @@ def box(x0, y0, x1, y1): # The lake's scene fires here; it is assumed to leave us here too. 'lake_entrance': (17, 12), }, + 'PlayerHouse1F': {'stairs': (10, 3), 'mom': (7, 8), 'door': (6, 10)}, + # A new game starts on (4, 6); the TV is the signs at (3, 4) and (4, 4). + 'PlayerHouse2F': {'stairs': (8, 4), 'start': (4, 6)}, + 'RivalHouse1F': {'door': (6, 10), 'stairs': (2, 3)}, + # Barry stands at (9, 5) facing his PC; he is talked to from the west. + 'RivalHouse2F': {'stairs': (3, 4), 'barry_talk': (8, 5)}, + # Rowan is talked to from below, facing north. + 'RowansLab': {'door': (7, 15), 'rowan_talk': (7, 6)}, } @@ -350,6 +373,14 @@ def box(x0, y0, x1, y1): # Hidden once his scene here is over; the story walks to him. 0: {'show': '01.03', 'name': 'roark'}, }, + 'RivalHouse2F': { + # Barry in his room, until he leaves for the lake. + 0: {'show': '00.01', 'name': 'barry'}, + }, + 'RowansLab': { + # Rowan at his desk when the story walks in. + 0: {'show': '00.03', 'name': 'rowan'}, + }, 'LakeVerity': { # The starter scene's actors, where the walk in ends. 0: {'show': 'the starter scene', 'name': 'rowan'}, @@ -370,6 +401,14 @@ def box(x0, y0, x1, y1): } +# Stepping onto (x, y) puts the player at a point of another map. +WARPS = { + 'PlayerHouse1F': [(6, 10, 'TwinleafTown', 'player_house_door')], + 'RivalHouse1F': [(6, 10, 'TwinleafTown', 'rival_house_door')], + 'RowansLab': [(7, 15, 'SandgemTown', 'lab_door')], +} + + PATCHES = { 'Route202': ( # BDSP has trees where Diamond's catch patch has its two bottom rows: @@ -477,10 +516,11 @@ def decode_map(name): row[x] = 'D' if (x, y) in doors else '.' lands = sorted({world.land_id(x, z) for z in range(z0, z0 + height, decomp.CELL) for x in range(x0, x0 + width, decomp.CELL)} - {None}) + unverified = '; decomp only, not checked on the console' if spec.get('unverified') else '' source = { 'decomp_file': f'{repo}: ' + ', '.join(game.land_path(land) for land in lands) - + f'; {game.events_name(header.events_id)}', - 'revision': 'default branch', + + f'; {game.events_name(header.events_id)}{unverified}', + 'revision': spec.get('revision', 'default branch'), 'date': spec.get('read', READ), } return [''.join(row) for row in rows], objects, source @@ -515,6 +555,7 @@ def section(key, items): lines.append(' ' + ('}' if key == 'points' else ']')) section('points', [f'{json.dumps(p)}: [{x}, {y}]' for p, (x, y) in points_of(name).items()]) + section('warps', [json.dumps({'x': x, 'y': y, 'to_map': m, 'to_point': p}) for x, y, m, p in WARPS.get(name, [])]) section('objects', [json.dumps(o) for o in objects]) section('patches', [json.dumps({'x': x, 'y': y, 'glyph': g, 'measured_by': m}) for x, y, g, m in PATCHES.get(name, [])]) From 22aea3340afe1ed4a4efdd12d6e55ba2c825f345 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:37:44 -0800 Subject: [PATCH 07/74] BDSP navigation: the story world and the route planner on the shared MapData StoryWorld joins story maps at world offsets (what Pokemon::MapSet did), with BDSP's step rules on Pokemon::TileKind: ledges hop the arrow's way, water and signs stop, objects standing still block, wanderers don't, and tiles no map covers are off the maps. RoutePlanner is Pokemon_TileGrid's planner moved onto it unchanged in behaviour (walk_to_wall, plan_tile_route, plan_robust_route, sight lines), now in PokemonBDSP; plan_robust_route's search is split into functions under the length limit. Synthetic-map tests for both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Pokemon/Navigation/Pokemon_MapSet.cpp | 102 ---- .../Pokemon/Navigation/Pokemon_MapSet.h | 63 --- .../Pokemon/Navigation/Pokemon_TileGrid.cpp | 503 ------------------ .../Programs/AutoStory/Data/MAPS.md | 45 -- .../PokemonBDSP_AutoStory_FloaromaTown.cpp | 81 --- .../Data/PokemonBDSP_AutoStory_FloaromaTown.h | 36 -- .../PokemonBDSP_AutoStory_JubilifeCity.cpp | 113 ---- .../Data/PokemonBDSP_AutoStory_JubilifeCity.h | 45 -- .../Data/PokemonBDSP_AutoStory_LakeVerity.cpp | 66 --- .../Data/PokemonBDSP_AutoStory_LakeVerity.h | 27 - .../Data/PokemonBDSP_AutoStory_MapGrids.cpp | 115 ---- .../Data/PokemonBDSP_AutoStory_MapGrids.h | 52 -- .../PokemonBDSP_AutoStory_OreburghCity.cpp | 92 ---- .../Data/PokemonBDSP_AutoStory_OreburghCity.h | 37 -- .../PokemonBDSP_AutoStory_OreburghGate.cpp | 51 -- .../Data/PokemonBDSP_AutoStory_OreburghGate.h | 27 - .../PokemonBDSP_AutoStory_OreburghGym.cpp | 61 --- .../Data/PokemonBDSP_AutoStory_OreburghGym.h | 38 -- .../PokemonBDSP_AutoStory_OreburghMine.cpp | 65 --- .../Data/PokemonBDSP_AutoStory_OreburghMine.h | 39 -- .../PokemonBDSP_AutoStory_RavagedPath.cpp | 62 --- .../Data/PokemonBDSP_AutoStory_RavagedPath.h | 47 -- .../Data/PokemonBDSP_AutoStory_Route201.cpp | 82 --- .../Data/PokemonBDSP_AutoStory_Route201.h | 37 -- .../Data/PokemonBDSP_AutoStory_Route202.cpp | 101 ---- .../Data/PokemonBDSP_AutoStory_Route202.h | 49 -- .../Data/PokemonBDSP_AutoStory_Route203.cpp | 78 --- .../Data/PokemonBDSP_AutoStory_Route203.h | 32 -- .../Data/PokemonBDSP_AutoStory_Route204.cpp | 91 ---- .../Data/PokemonBDSP_AutoStory_Route204.h | 43 -- .../PokemonBDSP_AutoStory_Route204South.cpp | 87 --- .../PokemonBDSP_AutoStory_Route204South.h | 44 -- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 434 +++++++++++++++ .../PokemonBDSP_AutoStory_RoutePlanner.h} | 335 +++++------- .../PokemonBDSP_AutoStory_SandgemTown.cpp | 96 ---- .../Data/PokemonBDSP_AutoStory_SandgemTown.h | 49 -- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 232 ++++++++ .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 112 ++++ .../PokemonBDSP_AutoStory_TwinleafTown.cpp | 61 --- .../Data/PokemonBDSP_AutoStory_TwinleafTown.h | 27 - .../PokemonBDSP_AutoStory_VerityLakefront.cpp | 56 -- .../PokemonBDSP_AutoStory_VerityLakefront.h | 27 - .../PokemonBDSP_AutoStory_MapGrid_Tests.cpp | 256 --------- .../PokemonBDSP_AutoStory_MapGrid_Tests.h | 28 - ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 195 +++++++ ...PokemonBDSP_AutoStory_RoutePlanner_Tests.h | 24 + ...PokemonBDSP_AutoStory_StoryWorld_Tests.cpp | 193 +++++++ .../PokemonBDSP_AutoStory_StoryWorld_Tests.h | 24 + 48 files changed, 1358 insertions(+), 3202 deletions(-) delete mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp delete mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h delete mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp rename SerialPrograms/Source/{Pokemon/Navigation/Pokemon_TileGrid.h => PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h} (52%) delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp deleted file mode 100644 index 533dc4f12f..0000000000 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* Map Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Pokemon_MapSet.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -void MapSet::add(std::string name, const TileGrid& grid, const TilePos& offset){ - for (const Placed& placed : m_maps){ - if (placed.name == name){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Map placed twice: " + name); - } - // Map images show a border of trees past their edges, so two maps - // may share blocked tiles, but nothing else. - for (int y = 0; y < grid.height(); y++){ - for (int x = 0; x < grid.width(); x++){ - const TilePos other{offset.x + x - placed.offset.x, offset.y + y - placed.offset.y}; - if (!placed.grid.in_bounds(other)){ - continue; - } - if (grid.at({x, y}) != TileType::BLOCKED || placed.grid.at(other) != TileType::BLOCKED){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Map " + name + " overlaps " + placed.name + " at its tile " + to_string(TilePos{x, y}) + "." - ); - } - } - } - } - m_maps.push_back(Placed{std::move(name), grid, offset}); - - // Rebuild the joined grid. - TilePos low = m_maps[0].offset; - TilePos high = low; - for (const Placed& placed : m_maps){ - low.x = std::min(low.x, placed.offset.x); - low.y = std::min(low.y, placed.offset.y); - high.x = std::max(high.x, placed.offset.x + placed.grid.width()); - high.y = std::max(high.y, placed.offset.y + placed.grid.height()); - } - m_origin = low; - std::vector rows(high.y - low.y, std::string(high.x - low.x, tile_char(TileType::UNKNOWN))); - for (const Placed& placed : m_maps){ - const std::vector map_rows = placed.grid.rows(); - for (size_t y = 0; y < map_rows.size(); y++){ - rows[placed.offset.y - low.y + y].replace(placed.offset.x - low.x, map_rows[y].size(), map_rows[y]); - } - } - m_world.emplace(rows); -} - -const TileGrid& MapSet::world() const{ - if (!m_world){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No maps placed."); - } - return *m_world; -} - -TilePos MapSet::to_world(const std::string& map, const TilePos& local) const{ - for (const Placed& placed : m_maps){ - if (placed.name == map){ - return { - placed.offset.x - m_origin.x + local.x, - placed.offset.y - m_origin.y + local.y, - }; - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown map: " + map); -} - -std::optional MapSet::to_local(const TilePos& world) const{ - for (const Placed& placed : m_maps){ - const TilePos local{ - world.x + m_origin.x - placed.offset.x, - world.y + m_origin.y - placed.offset.y, - }; - if (placed.grid.in_bounds(local)){ - return MapTile{placed.name, local}; - } - } - return std::nullopt; -} - -std::string MapSet::describe(const TilePos& world) const{ - const std::optional local = to_local(world); - if (!local){ - return "world " + to_string(world); - } - return local->map + " " + to_string(local->pos); -} - - - -} -} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h deleted file mode 100644 index 468213c481..0000000000 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapSet.h +++ /dev/null @@ -1,63 +0,0 @@ -/* Map Set - * - * From: https://github.com/PokemonAutomation/ - * - * Several tile grids placed side by side on one world grid, so one plan - * can cross from a route into a town. - */ - -#ifndef PokemonAutomation_Pokemon_MapSet_H -#define PokemonAutomation_Pokemon_MapSet_H - -#include -#include -#include -#include "Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -struct MapTile{ - std::string map; - TilePos pos; -}; - - -class MapSet{ -public: - // Places `grid` with its tile (0,0) at `offset`. Offsets are relative to - // each other and may be negative. Maps may overlap only where both are - // blocked; the map placed first holds those tiles. Throws - // InternalProgramError if the name is taken or the maps conflict. - void add(std::string name, const TileGrid& grid, const TilePos& offset); - - // The maps joined on one grid. Tiles no map covers are UNKNOWN. World - // tile (0,0) is the top-left corner of all the maps together. - const TileGrid& world() const; - - // Throws InternalProgramError for an unknown map name. - TilePos to_world(const std::string& map, const TilePos& local) const; - - // The map that holds a world tile, or nothing between maps. - std::optional to_local(const TilePos& world) const; - - // "Route 201 (45,3)", or the world tile if no map holds it. - std::string describe(const TilePos& world) const; - -private: - struct Placed{ - std::string name; - TileGrid grid; - TilePos offset; - }; - std::vector m_maps; - TilePos m_origin; // offset of world tile (0,0) - std::optional m_world; -}; - - - -} -} -#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp deleted file mode 100644 index e0a70bc8e5..0000000000 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.cpp +++ /dev/null @@ -1,503 +0,0 @@ -/* Tile Grid - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Pokemon_LegPlanner.h" -#include "Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -char tile_char(TileType type){ - switch (type){ - case TileType::BLOCKED: return '#'; - case TileType::WALKABLE: return '.'; - case TileType::TALL_GRASS: return '"'; - case TileType::LEDGE: return 'v'; - case TileType::NPC: return 'N'; - case TileType::SIGN: return 'S'; - case TileType::DOOR: return 'D'; - case TileType::UNKNOWN: return '?'; - } - return '?'; -} - - - - -TileGrid::TileGrid(const std::vector& rows) - : m_width(rows.empty() ? 0 : (int)rows[0].size()) - , m_height((int)rows.size()) -{ - m_tiles.reserve((size_t)m_width * m_height); - for (size_t y = 0; y < rows.size(); y++){ - const std::string& row = rows[y]; - if ((int)row.size() != m_width){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Tile grid row " + std::to_string(y) + " has " + std::to_string(row.size()) + - " tiles, expected " + std::to_string(m_width) + "." - ); - } - for (size_t x = 0; x < row.size(); x++){ - switch (row[x]){ - case '#': m_tiles.push_back(TileType::BLOCKED); break; - case '.': m_tiles.push_back(TileType::WALKABLE); break; - case '"': m_tiles.push_back(TileType::TALL_GRASS); break; - case 'v': m_tiles.push_back(TileType::LEDGE); break; - case 'N': m_tiles.push_back(TileType::NPC); break; - case 'S': m_tiles.push_back(TileType::SIGN); break; - case 'D': m_tiles.push_back(TileType::DOOR); break; - case '?': m_tiles.push_back(TileType::UNKNOWN); break; - default: - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - std::string("Unknown tile '") + row[x] + "' at " + - to_string(TilePos{(int)x, (int)y}) + "." - ); - } - } - } -} - -std::vector TileGrid::rows() const{ - std::vector rows; - for (int y = 0; y < m_height; y++){ - std::string row; - for (int x = 0; x < m_width; x++){ - row += tile_char(at({x, y})); - } - rows.push_back(std::move(row)); - } - return rows; -} - -bool TileGrid::in_bounds(const TilePos& pos) const{ - return 0 <= pos.x && pos.x < m_width && 0 <= pos.y && pos.y < m_height; -} - -TileType TileGrid::at(const TilePos& pos) const{ - if (!in_bounds(pos)){ - return TileType::UNKNOWN; - } - return m_tiles[(size_t)pos.y * m_width + pos.x]; -} - -void TileGrid::set(const TilePos& pos, TileType type){ - if (in_bounds(pos)){ - m_tiles[(size_t)pos.y * m_width + pos.x] = type; - } -} - -bool TileGrid::standable(const TilePos& pos) const{ - const TileType type = at(pos); - return type == TileType::WALKABLE || type == TileType::TALL_GRASS; -} - -std::optional TileGrid::step(const TilePos& from, Direction direction) const{ - const TilePos next = from.next(direction); - if (standable(next)){ - return next; - } - if (at(next) == TileType::LEDGE && direction == Direction::SOUTH){ - const TilePos landing = next.next(direction); - if (standable(landing)){ - return landing; - } - } - return std::nullopt; -} - -bool TileGrid::at_wall(const TilePos& pos, Direction direction) const{ - const TileType next = at(pos.next(direction)); - return next != TileType::DOOR && next != TileType::UNKNOWN && !step(pos, direction).has_value(); -} - - - -WallHit walk_to_wall(const TileGrid& grid, const TilePos& from, Direction direction){ - WallHit hit; - hit.stop = from; - while (true){ - const TilePos before = hit.stop; - const std::optional next = grid.step(before, direction); - if (!next){ - hit.wall = before.next(direction); - hit.anchored = grid.at_wall(before, direction); - return hit; - } - hit.tiles += std::abs(next->x - before.x) + std::abs(next->y - before.y); - hit.stop = *next; - } -} - - - -std::string to_string(const TileLeg& leg){ - return std::string(direction_name(leg.direction)) + " " + std::to_string(leg.tiles) + - (leg.ends_at_wall ? " (to wall)" : " (open)"); -} - - -namespace{ - -// The grid's step rules for the shared leg planner. A ledge hop is one -// press that moves two tiles. -class TileGridModel{ -public: - using State = TilePos; - using StateHash = std::hash; - - TileGridModel(const TileGrid& grid, const TilePlanCosts& costs) - : m_grid(grid) - , m_costs(costs) - {} - - std::optional> press(const State& pos, Direction direction) const{ - const std::optional next = m_grid.step(pos, direction); - if (!next){ - return std::nullopt; - } - Step step; - step.next = *next; - step.facing = direction; - const int tiles = std::abs(next->x - pos.x) + std::abs(next->y - pos.y); - step.extra_cost = m_costs.per_tile * (tiles - 1); - if (m_grid.at(*next) == TileType::TALL_GRASS){ - step.extra_cost += m_costs.per_grass_tile; - } - return step; - } - bool held_at(const State& pos, Direction direction) const{ - return m_grid.at_wall(pos, direction); - } - -private: - const TileGrid& m_grid; - const TilePlanCosts& m_costs; -}; - -} - -std::optional> plan_tile_route( - const TileGrid& grid, - const TilePos& from, const TilePos& to, - const TilePlanCosts& costs -){ - if (!grid.standable(from) || !grid.standable(to)){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Route ends must be standable: " + to_string(from) + " -> " + to_string(to) + "." - ); - } - if (from == to){ - return std::vector(); - } - LegCosts leg_costs; - leg_costs.per_tile = costs.per_tile; - leg_costs.per_turn = costs.per_leg; - leg_costs.per_open_stop = costs.leg_not_at_wall; - const std::optional>> legs = plan_legs( - TileGridModel(grid, costs), from, std::nullopt, - std::function([&](const TilePos& pos){ return pos == to; }), - std::nullopt, leg_costs - ); - if (!legs){ - return std::nullopt; - } - std::vector ret; - for (const Leg& leg : *legs){ - const size_t tiles = std::abs(leg.end.x - leg.start.x) + std::abs(leg.end.y - leg.start.y); - ret.push_back(TileLeg{leg.direction, tiles, leg.to_wall}); - } - return ret; -} - -std::vector sight_tiles(const TileGrid& grid, const TrainerSight& trainer){ - std::vector tiles; - TilePos pos = trainer.pos; - for (int i = 0; i < trainer.range; i++){ - pos = pos.next(trainer.facing); - if (!grid.standable(pos)){ - break; - } - tiles.push_back(pos); - } - return tiles; -} - -std::vector> legs_crossing_sight( - const TileGrid& grid, - const TilePos& from, - const std::vector& legs, - const std::vector& trainers -){ - std::vector> sights; - for (const TrainerSight& trainer : trainers){ - sights.push_back(sight_tiles(grid, trainer)); - } - std::vector> crossings; - TilePos pos = from; - for (const TileLeg& leg : legs){ - const std::vector tiles = trace_legs(grid, pos, {leg}); - std::vector seen_by; - for (size_t t = 0; t < trainers.size(); t++){ - for (size_t i = 1; i < tiles.size(); i++){ - if (std::find(sights[t].begin(), sights[t].end(), tiles[i]) != sights[t].end()){ - seen_by.push_back(trainers[t].name); - break; - } - } - } - crossings.push_back(std::move(seen_by)); - pos = tiles.back(); - } - return crossings; -} - -std::vector trace_legs( - const TileGrid& grid, - const TilePos& from, - const std::vector& legs -){ - std::vector tiles{from}; - for (const TileLeg& leg : legs){ - size_t travelled = 0; - while (travelled < leg.tiles){ - const TilePos pos = tiles.back(); - const std::optional next = grid.step(pos, leg.direction); - if (!next){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Leg " + to_string(leg) + " is stopped at " + to_string(pos) + "." - ); - } - travelled += std::abs(next->x - pos.x) + std::abs(next->y - pos.y); - tiles.push_back(*next); - } - if (travelled != leg.tiles){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Leg " + to_string(leg) + " overshoots on a ledge hop." - ); - } - } - return tiles; -} - - - -std::string to_string(const PlannedLeg& leg){ - std::string out = to_string(leg.leg) + " to"; - for (const TilePos& pos : leg.after){ - out += " " + to_string(pos); - } - return out; -} - -namespace{ - -// Where `from` ends up after `tiles` steps in `direction`, stopping early at -// anything that stops the player. Nothing if a step would leave the map or -// enter a door: the plan cannot tell what happens then. -std::optional step_tiles( - const TileGrid& grid, TilePos from, Direction direction, int tiles, int& grass -){ - int travelled = 0; - while (travelled < tiles){ - const std::optional next = grid.step(from, direction); - if (!next){ - if (!grid.at_wall(from, direction)){ - return std::nullopt; - } - break; - } - travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); - if (grid.at(*next) == TileType::TALL_GRASS){ - grass++; - } - from = *next; - } - return from; -} - -using Spread = std::vector; - -bool spread_less(const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; -} -void normalize(Spread& spread){ - std::sort(spread.begin(), spread.end(), spread_less); - spread.erase(std::unique(spread.begin(), spread.end()), spread.end()); -} -struct SpreadLess{ - bool operator()(const Spread& a, const Spread& b) const{ - return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), spread_less); - } -}; - -} - -std::optional> plan_robust_route( - const TileGrid& grid, - const TilePos& from, const TilePos& to, - const RobustPlanCosts& costs -){ - if (!grid.standable(from) || !grid.standable(to)){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Route ends must be standable: " + to_string(from) + " -> " + to_string(to) + "." - ); - } - return plan_robust_route(grid, std::vector{from}, [&](const TilePos& pos){ return pos == to; }, costs); -} - -std::optional> plan_robust_route( - const TileGrid& grid, - const std::vector& from, const std::function& goal, - const RobustPlanCosts& costs -){ - for (const TilePos& pos : from){ - if (!grid.standable(pos)){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Route starts must be standable: " + to_string(pos) + "." - ); - } - } - // Only the start may be wider than costs.max_spread: every leg must bring - // the player within it. - const size_t max_spread = costs.max_spread; - auto reached = [&](const Spread& spread){ - return std::all_of(spread.begin(), spread.end(), goal); - }; - - struct Node{ - long long cost; - Spread parent; - PlannedLeg leg; - bool done = false; - }; - std::map nodes; - using Entry = std::pair; - auto entry_greater = [](const Entry& a, const Entry& b){ return a.first > b.first; }; - std::priority_queue, decltype(entry_greater)> queue(entry_greater); - - Spread start = from; - normalize(start); - nodes[start] = Node{0, {}, {}}; - queue.emplace(0, start); - - auto relax = [&](const Spread& spread, long long cost, Spread next, PlannedLeg leg){ - normalize(next); - if (next.size() > max_spread || next == spread){ - return; - } - auto iter = nodes.find(next); - if (iter != nodes.end() && iter->second.cost <= cost){ - return; - } - leg.after = next; - nodes[next] = Node{cost, spread, std::move(leg)}; - queue.emplace(cost, std::move(next)); - }; - - size_t searched = 0; - while (!queue.empty()){ - const Entry top = queue.top(); - queue.pop(); - const long long cost = top.first; - const Spread& spread = top.second; - Node& node = nodes[spread]; - if (node.done || node.cost != cost){ - continue; - } - node.done = true; - if (++searched > costs.max_searched){ - return std::nullopt; - } - if (reached(spread)){ - std::vector legs; - for (Spread at = spread; at != start; ){ - const Node& step = nodes[at]; - legs.push_back(step.leg); - at = step.parent; - } - std::reverse(legs.begin(), legs.end()); - return legs; - } - - for (Direction direction : ALL_DIRECTIONS){ - // To the wall: every position walks until stopped. - { - Spread next; - size_t longest = 0; - int grass = 0; - bool ok = true; - for (const TilePos& pos : spread){ - const WallHit hit = walk_to_wall(grid, pos, direction); - if (!hit.anchored){ - ok = false; - break; - } - int leg_grass = 0; - step_tiles(grid, pos, direction, (int)hit.tiles, leg_grass); - grass = std::max(grass, leg_grass); - longest = std::max(longest, hit.tiles); - next.push_back(hit.stop); - } - if (ok && longest > 0){ - const long long step = (long long)costs.per_leg + - (long long)costs.per_tile * longest + (long long)costs.per_grass_tile * grass; - relax(spread, cost + step, std::move(next), PlannedLeg{TileLeg{direction, longest, true}, {}}); - } - } - // Open: about `tiles` tiles, give or take `open_error`. - for (int tiles = 1; tiles <= costs.max_open_tiles; tiles++){ - Spread next; - int grass = 0; - bool ok = true; - for (const TilePos& pos : spread){ - const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; - for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ - int leg_grass = 0; - const std::optional end = step_tiles(grid, pos, direction, n, leg_grass); - if (!end){ - ok = false; - break; - } - grass = std::max(grass, leg_grass); - next.push_back(*end); - } - if (!ok){ - break; - } - } - if (!ok){ - break; - } - const long long step = (long long)costs.per_leg + costs.leg_not_at_wall + - (long long)(costs.per_tile + costs.per_open_tile) * tiles + (long long)costs.per_grass_tile * grass; - relax(spread, cost + step, std::move(next), PlannedLeg{TileLeg{direction, (size_t)tiles, false}, {}}); - } - } - } - - return std::nullopt; -} - - - -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md deleted file mode 100644 index 2c37d39a69..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/MAPS.md +++ /dev/null @@ -1,45 +0,0 @@ -# AutoStory map grids: source and status - -Each map file's header starts with the same three lines, kept current with the code: - -- **Map source**: where the tiles come from. "Decomp" means a decompilation's - collision table (pret/pokediamond `land_data` narc, or pret/pokeplatinum - `map_data_NNN.bin`) with the objects from its events file; BDSP keeps - Diamond/Pearl's layout, and Platinum's few changes show up on the console. "DP image" means a Bulbapedia map image - traced by hand or by colour; those images have 12 px rows for 16 px columns, so - a traced grid has 3/4 of a tile per row and drifts by the map's height - differences (cliffs are painted taller than their tiles). -- **Console checks**: the anchors measured on the Switch (D-pad taps, sign reads, - recorded human walks), with the run or date. -- **Status**: the checkpoints that pass on this exact grid, and the next change. - -| map | source | checkpoints passing | next | -|---|---|---|---| -| Route 201 | decomp (Diamond) | none yet (00.02-00.04 and mart_lady passed on the image grid) | re-run them | -| Route 202 | decomp (Diamond) | none yet (00.04 passed on the image grid) | re-run 00.04; the save-spot legs grew three rows | -| Sandgem Town | decomp (Diamond) | none yet (00.04, 00.05 passed with image rows 0-6) | re-run; the Route 202 entry stop is (29,1) | -| Jubilife City | decomp (Diamond), console NPCs | none yet (00.05, 01.01, 01.06, 01.07 passed on the image grid) | re-run; re-anchor the Mart clown and the steps walk | -| Oreburgh Mine B2F | decomp (Diamond) | none yet (01.02, 01.03 passed 3x on the stretched image grid) | re-run both | -| Route 203 | decomp (Diamond) | none yet (01.06 passed on the image grid) | re-run; the row to Jubilife is 18, four sand rows | -| Route 204 South | decomp | 01.08 (1x) | more passes | -| Ravaged Path | decomp rows 30-53 | 01.09 by hand | program pass | -| Route 204 North | decomp | 01.10 (1x) | probe column 23; (12,6) marked from the console | -| Oreburgh City | decomp (pokediamond) | none yet (01.04, 01.05 run as records) | probe the Center doorstep (x 46 or 47) | -| Oreburgh Gate | decomp (pokediamond) | none yet | | -| Floaroma Town | decomp (pokediamond), the old couple from the console | 01.11 (1x, as a record) | | -| Twinleaf Town | decomp (pokediamond) | none: 00.01 replays recorded stick inputs (#1717); its lines and records are on the grid (Segment00Lines, task #22), tested offline | a new-game run of the lines, then switch 00.01 to them | -| Verity Lakefront | decomp (pokediamond) | none: 00.01 to 00.03 replay recorded stick inputs (#1717); lines and records on the grid, tested offline | the run must say which entrance tile the lake's scene leaves us on | -| Lake Verity | decomp (pokediamond) | none, and no walk: the scene carries us in and the game warps us out | none | -| Oreburgh Gym | decomp (pokediamond) | none: 01.04 walks it as a record (north until a trainer stops us), traced on the grid | a plan on it if the record ever fails | - -Rules: terrain from the decomp, people and Platinum-only edits from the console; -a route is coded only over tiles a human or a probe has walked; a map change -re-runs every checkpoint listed on it. Scenes' trigger rectangles come from the -decomp too (the events files' coord events: Diamond's binaries parsed by hand, -Platinum's JSON readable), listed in `Segment00Lines::scene_triggers()` for -00.01 to 00.03; a line into a scene must step into its rectangle on its last -tile only, which the Segment 00 tests check. The decomp comparison that found the 3/4 -rows is the 2026-10-31 report (`compare.md`, with the decoded grids); the -re-derivation of 2026-10-31 took every grid above from `devtools/maps decomp ---repo pret/pokediamond` and translated each file's named tiles with its -console anchors. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp deleted file mode 100644 index c91f67d5ea..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* BDSP AutoStory - Floaroma Town tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_FloaromaTown.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace FloaromaTown{ - -using namespace Pokemon; - - -// Console: the old couple stands at (2, 25) and (3, 25) ('N'), placed from -// the 2026-10-31 walk; they are not in the DP data (a Camper and a Lass are). -// Map source: the decomp (Diamond land_data 0032 = Platinum map_data_032, -// 2026-10-31) with the objects from its events file. -// Console checks: none yet. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0032: one cell of the -// Sinnoh matrix at column 5, row 20; map_data_032 in pret/pokeplatinum), -// with the objects from its events file (zone_event narc_0404, -// events_floaroma_town.json in Platinum); BDSP keeps Diamond/Pearl's layout. -// Local (x, y) = world (x - 160, z - 640); 32 x 32 tiles. The cell above -// (column 5, row 19, land_data 0033) carries the same map header but is cut -// off from the town (its bottom rows are wall; the town's row 0 is a -// dead-end strip under them), so it is left out. -// The flower field is the west half, columns 0 to 17, rows 2 to 22; -// Diamond's data puts a Camper at (6, 10) and a Lass wandering row 5 in it. -// The old couple BDSP shows there are not in the Diamond/Pearl data: place -// them as 'N' from the console. Exits: Route 204 south through (10..12, -// 30..31) (and the one-tile gap (8, 30..31), which joins a side path on the -// route); Route 205 east at (31, 19..22). Warp tiles the player stands on -// are written as '.': (20, 11), the Flower Shop's entrance, and (2, 1), (3, -// 1) into Floaroma Meadow, where the two Galactic grunts stand ('N' wins -// there) until the Valley Windworks is cleared (flag 447). Objects, from the -// events file: -// door (16, 26) to the Pokemon Center; door (24, 26) to the south-east -// house; -// door (24, 17) to the Poke Mart; its signboard (29, 15); -// door (11, 14) to the middle house; -// Flower Shop entrance (20, 11), its signboard (17, 11) and the two berry -// patches (18, 11) and (22, 11), as '#'; -// map signpost (13, 19); -// Grunt M (2, 1), looks east, and Grunt M (3, 1), looks west, not -// trainers, hidden by flag 447; -// Camper (6, 10), looks around, not a trainer; -// Lass (23, 11), looks west, not a trainer; -// Pokemon Breeder F (19, 21), looks around, not a trainer; -// a man with Cyrus's sprite (11, 26), looks around, not a trainer, hidden -// by flag 449 (Diamond/Pearl only; whether he is there when the story -// arrives is for the console); -// Lass wanders west and east from (10, 5), columns 9 to 11, row 5: off the -// grid; -// School Kid M wanders around (16, 16), columns 15 to 17, rows 15 to 17: -// off the grid. -// No trainers. Platinum differs in one row and one person: its row 30 opens -// columns 8 to 13 where Diamond opens 8 and 10 to 12 (Route 204 North's top -// rows are '########.#...###' in both games, so Diamond's is the border BDSP -// has), and it has a Beauty at (10, 19) looking south instead of the man at -// (11, 26). -const TileGrid& grid(){ - return story_grid("FloaromaTown"); -} - -const TilePos ROUTE_204_ARRIVAL{11, 29}; -const TilePos OLD_WOMAN{3, 25}; -const TilePos OLD_MAN{2, 25}; -const TilePos POKEMON_CENTER_DOOR{16, 26}; - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h deleted file mode 100644 index 43384adc6b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h +++ /dev/null @@ -1,36 +0,0 @@ -/* BDSP AutoStory - Floaroma Town tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see - * the .cpp's header for the cells, the offset and the objects. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_FloaromaTown_H -#define PokemonAutomation_PokemonBDSP_AutoStory_FloaromaTown_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace FloaromaTown{ - - -const Pokemon::TileGrid& grid(); - -// Where 01.10's walk north from Route 204 ends on the town's banner and -// saves (r248a, r251a): the path's middle column, three rows in. -extern const Pokemon::TilePos ROUTE_204_ARRIVAL; -// The old couple in the flower field, placed from the console (2026-10-31 -// hand walk and r251a: eight tiles west of the arrival, then three north -// to the tile below her); not in the DP data. -extern const Pokemon::TilePos OLD_WOMAN; -extern const Pokemon::TilePos OLD_MAN; -extern const Pokemon::TilePos POKEMON_CENTER_DOOR; - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp deleted file mode 100644 index 16089d130c..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* BDSP AutoStory - Jubilife City tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_JubilifeCity.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace JubilifeCity{ - -using namespace Pokemon; - - -// Map source: the decomp (pret/pokediamond land_data narc_0018, 0016, 0017 -// and 0015, 2026-10-31) with the objects from its events file. Platinum -// differs only around the Global Terminal (columns 14..26, rows 30..45). -// Console checks (2026-10-30/31): the lamps (43,53) and (49,53), north from -// (52,53) to the Pokemon Center's door, the School's door from the -// Center's doorstep, the east street to Route 203 (01.06, r230a), the -// north street (01.07), and the four 00.05 people, placed from the -// console on the tiles the events file gives them. -// Status: no checkpoint has run on this grid yet. 00.05, 01.01, 01.06 and -// 01.07 passed on the colour-classified image grid it replaces (48 rows -// for 64) and must be re-run; re-check the Mart clown's tile (he wanders -// 182..184 on row 33 in Diamond) and the hand walk from the steps' top -// east to the house and north to the Center (the decomp has the plaza -// only 171..177 wide on rows 58..59). -// -// Decoded from Pokemon Diamond's collision table: cells (23..24, 4..5) of -// the Sinnoh matrix, with the objects from its events file. Local (x, y) = -// world (x - 128, z - 736); 64 x 64 tiles. The console's measurements on -// the image grid were a column east of its doors; on this grid the lamps, -// the doors and the four people all land where the console put them. -// -// Exits: south, the 3-wide neck (45..47, 61) down to Route 202; east, the -// street (rows 21..24) to Route 203; north, (42..55, 0..1) to Route 204; -// west, the Route 218 gate on rows 22..23 (its warp tiles are 'D'). Doors -// are 'D' tiles walked into from below; the Trainers' School's doorway -// (40,40) and the Global Terminal's (21,42) are warp tiles stepped onto and -// marked 'D' as well, so a plan never steps on them. The main road runs -// from the steps (46..47, 60..62) north between the lamps (43,53), (49,53) -// and on up to the north exit; the doors' row 40 is open between the School -// and the Center (43..49), and the plaza below it is rows 41..52. -// People who stand still, from the events file: the Poketch president -// (46,35) and the clown west of the TV station (36,16), the 00.05 story -// people (hidden by flags before and after); an Ace Trainer (36,25) on the -// north road's west side, a Cashier (26,42), an Expert (44,44), two kids -// (52,46), (54,46) on the plaza and a School Kid (17,55): none of these -// five has been seen on the console yet. The clown by the Mart (55,33) and -// the one by the Poketch Company (15,18) wander three tiles in Diamond but -// stood still on the console (00.05, three runs): on the grid at their -// spawn tiles. Wanderers left off: an Ace Trainer along row 20 (21..23), -// one along row 21 (45..47), a Twin around (33,18), a School Kid on column -// 51 (rows 33..35), a Pokefan around (41,30). Rowan and the grunts at the -// north exit, the Collectors and Dawn are hidden by story flags. -const TileGrid& grid(){ - return story_grid("JubilifeCity"); -} - -// Checked on the console (2026-10-30, CFR "walk"): 00.05's save stands -// below the steps, against the wall just east of them (the banner reads -// Jubilife City). West along that wall does not stop at the steps (it runs -// to the trees); a tile west, then north, climbs them. North up the main -// road from the steps passes the lamps (43,53), (49,53) and does not stop -// before the north exit. From the lamps' row, west stops at the house at -// (37..42, 47..52) and east at the house at (53..57, 49..56); north from -// (52,53) stops in front of the Pokemon Center. The steps are columns -// 45..47 of row 61; the save stands at (48,62) against (48,61), and the -// tile west then north puts us on column 47, a few rows up. On this grid -// east from rows 58..60 stops at column 49 and north from there at the lamp -// (49,53), not the Center: the climb must end on row 57 or above, or BDSP's -// plaza is wider than Diamond's there (re-check on the console). -const std::vector& up_the_steps(){ - static const std::vector tiles{{46, 58}, {47, 58}, {46, 59}, {47, 59}, {46, 60}, {47, 60}}; - return tiles; -} - -// The School's doorway is a warp tile stepped onto from (40,41); the -// Center's door is walked into from (52,41). On the console (2026-10-30) -// eleven one-tile holds west from the Center's doorstep put us under the -// School's door: the doorstep was the tile east of the door's column, as -// story_door_front() allows. -const TilePos TRAINERS_SCHOOL_DOOR{40, 40}; -const TilePos POKEMON_CENTER_DOOR{52, 40}; -const TilePos TV_STATION_DOOR{36, 15}; - -// On the main road, five rows north of the School's and the Center's -// doors' row and six columns west of the Center's door. Talked to from the -// east, facing west (also works from the south). -const TilePos POKETCH_PRESIDENT{46, 35}; -// Below the Poke Mart's planters, where the road meets the plaza: his spawn -// tile; he wanders a tile either side in Diamond, and the console had him -// a tile east of it. -const TilePos CLOWN_MART{55, 33}; -// West of the TV station door, right below it. -const TilePos CLOWN_TV_STATION{36, 16}; -// East of the Poketch Company's sign, a row below it. Talked to from the -// south on the console; from the east a walk west along row 18 stops right -// beside him. -const TilePos CLOWN_POKETCH_COMPANY{15, 18}; - - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h deleted file mode 100644 index 941b89ff77..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h +++ /dev/null @@ -1,45 +0,0 @@ -/* BDSP AutoStory - Jubilife City tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Jubilife City as a tile grid, from the Diamond decompilation's collision - * table, with the places and people of checkpoint 00.05. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_JubilifeCity_H -#define PokemonAutomation_PokemonBDSP_AutoStory_JubilifeCity_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace JubilifeCity{ - - -const Pokemon::TileGrid& grid(); - -// Where we may stand after climbing the steps from where 00.05 starts: -// below them, against the wall just east of them, then a tile west and -// about two tiles north. -const std::vector& up_the_steps(); - -// Doors: walk north from the tile below to enter. -extern const Pokemon::TilePos TRAINERS_SCHOOL_DOOR; -extern const Pokemon::TilePos POKEMON_CENTER_DOOR; -extern const Pokemon::TilePos TV_STATION_DOOR; - -// The Poketch Company president and the three coupon clowns. -extern const Pokemon::TilePos POKETCH_PRESIDENT; -extern const Pokemon::TilePos CLOWN_MART; -extern const Pokemon::TilePos CLOWN_TV_STATION; -extern const Pokemon::TilePos CLOWN_POKETCH_COMPANY; - - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp deleted file mode 100644 index 3198d18e18..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* BDSP AutoStory - Lake Verity tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_LakeVerity.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace LakeVerity{ - -using namespace Pokemon; - - -// Map source: the decomp (Diamond land_data 0512 = Platinum map_data_541, -// 2026-10-31) with the objects from its events file. -// Console checks: none yet. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0512: the cell at column -// 1, row 1 of the lake's own matrix 101, which is 3 x 2 cells; map_data_541 -// of matrix 102 in pret/pokeplatinum), with the objects from its events file -// (zone_event narc_0298, events_lake_verity.json in Platinum); BDSP keeps -// Diamond/Pearl's layout. Local (x, y) = world (x - 32, z - 32) in that -// matrix; 32 x 32 tiles. Only this cell is reachable on foot: the shore -// where the starter scene plays, columns 10 to 25, rows 4 to 22. The lake is -// '#'; the tiles at (0..6, 4..9) are shallow water (puddle, behaviour 0x16), -// walkable in the data but closed in by the lake. The west shore with TM38 -// (cells to the west) needs Surf. -// Entrance: the warp tiles (14, 22) and (15, 22), arrived on from Verity -// Lakefront, written as '.'; walking south off them leaves. The scene's -// actors are hidden-flag objects, drawn where the events file puts them -// because that is where the walk ends: Rowan and the briefcase on (16, 11) -// and the player's counterpart on (17, 11), at the water's edge. Objects, -// from the events file: -// Prof. Rowan (16, 11), looks north, hidden by flag 403; the briefcase on -// the same tile, hidden by flag 404; -// the counterpart (Dawn/Lucas, object "Var 0") (17, 11), looks north, -// hidden by flag 434; -// Starly (16, 19), looks north, hidden by flag 429, drawn as 'N' (a scene -// actor on open ground); -// Starly (25, 11), looks west, hidden by flag 429, perched on a blocked -// tile: stays '#'; -// Barry (15, 22), looks north, hidden by flag 436, on the entrance warp -// tile: '.' wins; -// no one wanders here, and no trainers. -// Platinum differs: it stages its scene elsewhere (Rowan (21, 7), the -// counterpart (22, 6), Mars (23, 6), four Galactic grunts with sight 4 to 6, -// no Starly or Barry), walls off the puddle tiles at (0..6, 4..9) and opens -// a path to the Verity Cavern warp at (0, 0). The shore, columns 10 to 25, -// decodes the same tile for tile. Diamond keeps its Galactic version as a -// separate map (MAP_LAKE_VERITY_GALACTIC), reached from the same Lakefront -// warp tiles. -const TileGrid& grid(){ - return story_grid("LakeVerity"); -} - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h deleted file mode 100644 index a5eb838e8f..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h +++ /dev/null @@ -1,27 +0,0 @@ -/* BDSP AutoStory - Lake Verity tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see - * the .cpp's header for the cells, the offset and the objects. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_LakeVerity_H -#define PokemonAutomation_PokemonBDSP_AutoStory_LakeVerity_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace LakeVerity{ - - -const Pokemon::TileGrid& grid(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp deleted file mode 100644 index 0b7a20d966..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* BDSP AutoStory - Map grids - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "PokemonBDSP_AutoStory_MapGrids.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using Pokemon::MapData; -using Pokemon::TileGrid; -using Pokemon::TileKind; -using Pokemon::TilePos; -using Pokemon::TileType; - - -namespace{ - -std::optional tile_type_of(TileKind kind){ - switch (kind){ - case TileKind::WALL: return TileType::BLOCKED; - case TileKind::OPEN: return TileType::WALKABLE; - case TileKind::TALL_GRASS: return TileType::TALL_GRASS; - case TileKind::LEDGE_SOUTH: return TileType::LEDGE; - case TileKind::DOOR: return TileType::DOOR; - case TileKind::SIGN: return TileType::SIGN; - default: return std::nullopt; - } -} - -} - -TileGrid tile_grid_from_map(const MapData& map){ - std::vector rows; - for (int y = 0; y < map.tiles.height; y++){ - std::string row; - for (int x = 0; x < map.tiles.width; x++){ - const TileKind kind = map.tiles.at(TilePos{x, y}); - const std::optional type = tile_type_of(kind); - if (!type){ - throw ParseException(std::format( - "{}: glyph '{}' at {} has no BDSP tile.", map.name, Pokemon::glyph_of(kind), Pokemon::to_string(TilePos{x, y}) - )); - } - row += Pokemon::tile_char(*type); - } - rows.push_back(std::move(row)); - } - for (const Pokemon::MapObject& object : map.objects){ - if (object.kind != Pokemon::ObjectKind::NPC || object.wander){ - throw ParseException(std::format("{}: object {} is not a person standing still.", map.name, object.name)); - } - rows[object.y][object.x] = Pokemon::tile_char(TileType::NPC); - } - return TileGrid(rows); -} - -std::optional grid_difference(const TileGrid& here, const TileGrid& there){ - if (here.width() != there.width() || here.height() != there.height()){ - return std::format("{} x {} here, {} x {} there", here.width(), here.height(), there.width(), there.height()); - } - for (int y = 0; y < here.height(); y++){ - for (int x = 0; x < here.width(); x++){ - const TilePos pos{x, y}; - if (here.at(pos) != there.at(pos)){ - return std::format( - "{}: '{}' here, '{}' there", - Pokemon::to_string(pos), Pokemon::tile_char(here.at(pos)), Pokemon::tile_char(there.at(pos)) - ); - } - } - } - return std::nullopt; -} - - -namespace{ - -const std::map& story_grids(){ - static const std::map grids = []{ - std::map parsed; - for (const auto& [name, json] : bdsp_map_json()){ - const MapData map = Pokemon::parse_map(parse_json(json), name + ".json"); - if (map.name != name){ - throw ParseException(std::format("{}.json: name is \"{}\".", name, map.name)); - } - parsed.emplace(name, tile_grid_from_map(map)); - } - return parsed; - }(); - return grids; -} - -} - -const TileGrid& story_grid(const std::string& name){ - const std::map& grids = story_grids(); - if (auto iter = grids.find(name); iter != grids.end()){ - return iter->second; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No BDSP story map named \"" + name + "\"."); -} - - - -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h deleted file mode 100644 index 41f0d61d64..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h +++ /dev/null @@ -1,52 +0,0 @@ -/* BDSP AutoStory - Map grids - * - * From: https://github.com/PokemonAutomation/ - * - * The story's maps are JSON files in the shared map schema - * (Pokemon_MapData.h), PokemonBDSP/Programs/AutoStory/Maps, built into the - * program by CMake, read with the shared loader and turned into the tile - * grids the planner walks. Each map's X::grid() returns story_grid("X"). - * - * TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonBDSP/Maps) when ready - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_MapGrids_H -#define PokemonAutomation_PokemonBDSP_AutoStory_MapGrids_H - -#include -#include -#include -#include -#include "Pokemon/Navigation/Pokemon_MapData.h" -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// (name, JSON text) of each map in PokemonBDSP/Programs/AutoStory/Maps/, -// built into the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). -const std::vector>& bdsp_map_json(); - -// A map's tiles as a tile grid: walls, open ground, tall grass, south -// ledges, doors and signs; a standing person ("npc" object) is an NPC tile. -// Throws ParseException, naming the map, for what BDSP's grids have no -// tile for (water, ledges other than south, items, wanderers). -Pokemon::TileGrid tile_grid_from_map(const Pokemon::MapData& map); - -// "(x, y): 'N' here, '.' there", or nothing when the grids are the same -// size and equal cell for cell. -std::optional grid_difference(const Pokemon::TileGrid& here, const Pokemon::TileGrid& there); - -// The grid of the map `name`, read from bdsp_map_json() once. Throws -// InternalProgramError for a name it does not have. -const Pokemon::TileGrid& story_grid(const std::string& name); - - - -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp deleted file mode 100644 index 781af0c643..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* BDSP AutoStory - Oreburgh City tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_OreburghCity.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghCity{ - -using namespace Pokemon; - - -// Map source: the decomp (Diamond land_data 0022, 0023, 0175, 0024 = -// Platinum map_data_022/023/175/024, 2026-10-31) with the objects from -// its events file. -// Console checks: none yet. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0022, 0023, 0175 and -// 0024: four cells of the Sinnoh matrix, columns 8 and 9, rows 23 and 24; -// the same cells are map_data_022, 023, 175 and 024 in pret/pokeplatinum), -// with the objects from its events file (zone_event narc_0044, -// events_oreburgh_city.json in Platinum); BDSP keeps Diamond/Pearl's layout. -// Local (x, y) = world (x - 256, z - 736); 64 x 64 tiles. The town sits on -// the upper rows (10 to 26); row 27 is the cliff, and the stairs down it are -// the road at columns 44 to 48 (rows 27 to 43), which opens into the mine -// yard at row 44. The two one-tile stubs south of the gym, (24, 27..29) and -// (31, 27..29), and the pocket at (35..42, 28..29) are walkable in the data -// but closed off: dead ends, not stairs. -// Exits: Oreburgh Gate west through the cave mouth (1, 13), entered from the -// warp tile (2, 13); Route 207 north up columns 41 to 46 (rows 0 to 9); the -// Mine south over the warp tiles (44..48, 59), walked onto heading south. -// Warp tiles the player stands on are written as '.': (2, 13), (44..48, 59), -// and (49, 11), the Mining Museum's entrance. Objects, from the events file: -// door (26, 20) to the Gym; its signpost (22, 20); -// door (47, 20) to the Pokemon Center; -// door (29, 10) to the Poke Mart; doors (15, 10) and (22, 10) to the -// north-west and north houses; door (17, 20) to the west house; door (37, -// 16) to the middle house; door (56, 28) to the east house; door (51, 36) -// to the south house; -// map signposts (4, 11) and (44, 1); signboards (45, 12) and (45, 56); -// steam vents (9, 26), (11, 26), (13, 26), (60, 52), (60, 53), objects -// that block, as '#'; -// Youngster (10, 16), looks north, not a trainer; -// Worker (11, 25), looks south and west, not a trainer; -// Hiker wanders around (47, 26), columns 46 to 48, rows 25 to 27: off the -// grid; -// School Kid F wanders around (32, 18), column 32, rows 16 to 20: off the -// grid; -// Guitarist wanders around (23, 13), columns 22 to 24, rows 10 to 16: off -// the grid; -// Camper walks back and forth from (36, 19), columns 33 to 39, row 19: off -// the grid; -// Battle Girl wanders around (36, 23), column 36, rows 21 to 25: off the -// grid; -// Pokefan F wanders around (45, 38), column 45, rows 37 to 39: off the -// grid; -// Worker wanders around (37, 39), columns 36 to 38, rows 38 to 40: off the -// grid; -// Worker wanders around (50, 41), column 50, rows 38 to 44: off the grid; -// Worker wanders around (56, 57), columns 55 to 57, rows 54 to 60: off the -// grid; -// Machop wanders around (55, 56), columns 53 to 57, rows 54 to 58: off the -// grid; -// Barry (26, 21), in front of the Gym door, "wander" with no range (hidden -// by flag 410 once the story moves on): off the grid, listed so the route -// knows he may stand there. -// None of the people here is a trainer. Platinum (pret/pokeplatinum) decodes -// the same terrain tile for tile; it adds items on the ground at (35, 37) -// and (39, 38), a Battle Girl at (51, 21), a Machop at (56, 46) and a -// wandering Machop around (35, 45), none of which Diamond has. -const TileGrid& grid(){ - return story_grid("OreburghCity"); -} - -const TilePos POKEMON_CENTER_DOOR{47, 20}; -const TilePos POKEMON_CENTER_DOORSTEP{46, 21}; -const TilePos GYM_DOOR{26, 20}; -const TilePos GYM_DOORSTEP{26, 21}; -const TilePos GATE_MOUTH{1, 13}; - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h deleted file mode 100644 index 7a3f66901b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h +++ /dev/null @@ -1,37 +0,0 @@ -/* BDSP AutoStory - Oreburgh City tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see - * the .cpp's header for the cells, the offset and the objects. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghCity_H -#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghCity_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghCity{ - - -const Pokemon::TileGrid& grid(); - -// Doors are the tiles walked into. The Center's doorstep: the decomp's door -// tile is (47, 20), and 20 D-pad taps west from the doorstep stand under -// the Gym's door (26, 20) on the console (r204 to r215), which puts the -// doorstep at x 46: one of the two is a tile off, a probe decides. -extern const Pokemon::TilePos POKEMON_CENTER_DOOR; -extern const Pokemon::TilePos POKEMON_CENTER_DOORSTEP; -extern const Pokemon::TilePos GYM_DOOR; -extern const Pokemon::TilePos GYM_DOORSTEP; -// The Oreburgh Gate's east mouth, walked into heading west from (2, 13). -extern const Pokemon::TilePos GATE_MOUTH; - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp deleted file mode 100644 index 310728cda5..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* BDSP AutoStory - Oreburgh Gate 1F tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_OreburghGate.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghGate{ - -using namespace Pokemon; - - -// Map source: the decomp (Diamond land_data 0418 = Platinum map_data_441, -// 2026-10-31) with the objects from its events file. -// Console checks: none yet. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0418: one cell, the only -// one of matrix 003, at column 0, row 0; map_data_441 in pret/pokeplatinum), -// with the objects from its events file (zone_event narc_0250, -// events_oreburgh_gate_1f.json in Platinum); BDSP keeps Diamond/Pearl's -// layout. Local (x, y) = world (x - 0, z - 0) in the cave's own matrix; 32 x -// 32 tiles. The cave floor is '.'; the rocks Rock Smash breaks are '#' -// (eight of them, each hidden once smashed). -// Exits: the warp tiles the player stands on are written as '.': (4, 22) -// leaves west to Route 203 and (27, 22) east to Oreburgh City; the cave -// mouths behind them, (3, 22) and (28, 22), are 'D'. (20, 5) is the stairs -// down to B1F (a warp tile too). Objects, from the events file: -// Picnicker Diana (24, 21), looks south, sees 3; -// Camper Curtis (17, 25), looks north, sees 3; -// Hiker (7, 20), looks south, not a trainer (the Rock Smash HM); -// rocks (19, 6), (14, 4), (12, 10), (11, 11), (11, 25), (13, 26), (15, -// 26), (25, 24), as '#'. -// The two trainers face the row-22 corridor from either side: Diana sees -// (24, 22..24) and Curtis (17, 22..24). Platinum decodes this cave -// identically, terrain and objects. -const TileGrid& grid(){ - return story_grid("OreburghGate"); -} - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h deleted file mode 100644 index f0e2984230..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h +++ /dev/null @@ -1,27 +0,0 @@ -/* BDSP AutoStory - Oreburgh Gate tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see - * the .cpp's header for the cells, the offset and the objects. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghGate_H -#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghGate_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghGate{ - - -const Pokemon::TileGrid& grid(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp deleted file mode 100644 index 915bdc1474..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* BDSP AutoStory - Oreburgh Gym tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_OreburghGym.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghGym{ - -using namespace Pokemon; - - -// Map source: the decomp (Diamond land_data 0228, 2026-10-31) with the -// objects from its events file. -// Console checks: none yet. 01.04 walks it as a record (north until a -// trainer stops us), not as a plan. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0228: the only cell of -// matrix 113, at column 0, row 0; MAP_OREBURGH_GYM in -// include/constants/maps.h), with the objects from its events file -// (zone_event narc_0046, events_oreburgh_gym.json in Platinum); BDSP keeps -// Diamond/Pearl's layout. Local (x, y) = world (x - 0, z - 0) in the Gym's -// own matrix; 32 x 32 tiles, of which the floor is columns 1 to 10, rows 3 -// to 24. The tiers' edges and the pillars are '#'. -// Door: (5, 24), walked into heading south to leave; coming in puts us on -// (5, 23). Column 5 runs straight from there to Roark on row 3: the Gym is -// walked north up the middle. Objects, from the events file: -// Roark (5, 3), looks south; -// Gym Guide (6, 23), looks south, beside the entrance; -// Youngster (4, 18), looks east, sees 3: (5..7, 18); -// Youngster (7, 11), looks west, sees 4: (3..6, 11); -// the two wall signs, (3, 23) and (7, 23), read from row 23: 'S'. -// Both trainers see the middle column, so a walk north from the entrance -// is stopped twice before Roark (01.04's record). -const TileGrid& grid(){ - return story_grid("OreburghGym"); -} - -const TilePos ENTRANCE{5, 23}; -const TilePos ROARK{5, 3}; - -std::vector trainer_sights(){ - return { - {"Youngster (first tier)", {4, 18}, Direction::EAST, 3}, - {"Youngster (second tier)", {7, 11}, Direction::WEST, 4}, - }; -} - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h deleted file mode 100644 index 2cb6dc8489..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h +++ /dev/null @@ -1,38 +0,0 @@ -/* BDSP AutoStory - Oreburgh Gym tiles - * - * From: https://github.com/PokemonAutomation/ - * - * The Gym's inside, decoded from the Pokemon Diamond decompilation - * (pret/pokediamond); see the .cpp's header for the cell, the offset and - * the objects. For checkpoint 01.04's walk up to Roark. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghGym_H -#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghGym_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghGym{ - - -const Pokemon::TileGrid& grid(); - -// Where coming in through the door puts us: the tile above it, beside the -// Gym Guide. Roark stands at the top of the same column. -extern const Pokemon::TilePos ENTRANCE; -extern const Pokemon::TilePos ROARK; - -// The two Youngsters, who face the column up the middle from either side: -// walking north from the entrance meets both. -std::vector trainer_sights(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp deleted file mode 100644 index 53e2d1dd6d..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* BDSP AutoStory - Oreburgh Mine tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_OreburghMine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghMine{ - -using namespace Pokemon; - - -// Map source: the decomp (pret/pokediamond land_data narc_0314, matrix 006; -// 2026-10-31) with the objects from its events file; Platinum's -// map_data_337 is the same. -// Console checks (2026-10-28): the corridor's rocks zigzag a row at a time, -// the room's second row passes under the worker on the first, Roark -// stands a row above the bottom row between two rocks; the walk north -// from the corridor's corner reached the entrance hall (r99). -// Status: no checkpoint has run on this grid yet. 01.02 and 01.03 passed -// 3x on the stretched image grid it replaces, which had every row one -// lower, the top corridor a row short, the room's second row blocked -// and no ledge in the west corridor; re-run both. -// -// Decoded from Pokemon Diamond's collision table: the one cell of matrix -// 006, with the objects from its events file. Local (x, y) = world (x, z); -// 32 x 32 tiles. The way up to the entrance hall is the warp tile (15,1), -// marked 'D': stepping onto it leaves the room. The console walked north -// into the hall from column 14 (r99), where this table has the way up only -// at column 15: a stick hold drifts, or BDSP's stairs are wider. -// The corridor from the top (13..17, 2..6) zigzags down to the room's first -// row (15); the room's second row (17) is open from 2 to 29 and passes -// under the worker and his Machop on the first; the coal block fills -// (7..24, 18..25) with the corridors either side; the west corridor has a -// ledge (2..4, 19), crossed southward only; the bottom rows 28..29 run -// under the block. -// Objects, from the events file: Roark (18,28), between two rocks (17,28) -// and (19,28); workers who stand still at (8,28) looking north, (26,20) -// looking west and (21,15) with Machop at (20,15) and (27,15); Poke Balls -// at (4,28) and (26,24), walls until picked up. A Machop wanders along row -// 28, columns 11..13, and is left off the grid. -const TileGrid& grid(){ - return story_grid("OreburghMine"); -} - -// The first open row below the warp tile, where the walk in from the hall -// leaves us (or the row below: the plan's first legs run to walls and meet). -const std::vector& corridor_top(){ - static const std::vector tiles{{14, 2}, {15, 2}, {16, 2}}; - return tiles; -} - -const TilePos ROARK{18, 28}; -const TilePos CORRIDOR_EXIT_START{14, 10}; - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h deleted file mode 100644 index 4dc823b486..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h +++ /dev/null @@ -1,39 +0,0 @@ -/* BDSP AutoStory - Oreburgh Mine tiles - * - * From: https://github.com/PokemonAutomation/ - * - * The Oreburgh Mine's coal room (Bulbapedia's "B2F") as a tile grid, with - * Roark, for checkpoint 01.03. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OreburghMine_H -#define PokemonAutomation_PokemonBDSP_AutoStory_OreburghMine_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace OreburghMine{ - - -const Pokemon::TileGrid& grid(); - -// Where the walk in from the entrance hall leaves us: the top of the rocky -// corridor, the first open row below the warp tile. -const std::vector& corridor_top(); - -// Roark, between two rocks a row above the room's bottom row. Talked to from -// the tile below him, facing north. -extern const Pokemon::TilePos ROARK; -// The corridor's corner a wall-to-wall route ends on, below a straight -// walk north out into the entrance hall. -extern const Pokemon::TilePos CORRIDOR_EXIT_START; - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp deleted file mode 100644 index 500bc58358..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* BDSP AutoStory - Ravaged Path tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_RavagedPath.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace RavagedPath{ - -using namespace Pokemon; - - -// Map source: rows 30 to 53 from the decomp (map_data_435/436, 2026-10-31); -// the rows above from the DP image, unused by any route. -// Console checks: entrance (19,50), the stairs, the three-wide corridor, the -// rocks, the east end and the exit tile (2026-10-31 probes). -// Status: 01.09 reaches the exit by hand; no program pass yet. -// -// Rows 30 to 53 are decoded from Pokemon Platinum's collision table for -// this map (the pret/pokeplatinum decompilation, land data 435/436 of map -// matrix 051) with the objects from its events file; BDSP keeps the layout. -// Water and the items on the ground are '#'; the smashable rocks are '#' -// too and listed in rocks(). Checked on the console 2026-10-31 (r235b and -// D-pad probes): in from the south door onto (19, 50), up the stairs -// (rows 45 to 47, columns 18 to 20) and north to the wall at row 39; the -// corridor is three wide up to row 41 and opens east on rows 42 to 44, -// with the rocks at (22, 42) and (22, 43), the Potion ball at (22, 44) and -// a rock at (23, 44). Rows 0 to 29 are still the hand trace from -// Bulbapedia's Ravaged_Path_DP.png (stretched from 528x672 to 528x864), with -// '?' where the untraced west chambers continue; nothing we walk is there. -const TileGrid& grid(){ - return story_grid("RavagedPath"); -} - -const std::vector& rocks(){ - static const std::vector tiles{ - {11, 36}, {7, 37}, {12, 37}, {8, 38}, {10, 38}, {10, 39}, {13, 39}, - {7, 40}, {9, 40}, {17, 40}, {12, 41}, {22, 42}, {22, 43}, {23, 44}, - }; - return tiles; -} - -const TilePos ENTRANCE{19, 50}; - -const std::vector& before_rocks(){ - static const std::vector tiles{{21, 42}, {21, 43}}; - return tiles; -} - -const TilePos EAST_END{29, 44}; -const TilePos ABOVE_EXIT{28, 44}; - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h deleted file mode 100644 index 4f03dacf39..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h +++ /dev/null @@ -1,47 +0,0 @@ -/* BDSP AutoStory - Ravaged Path tiles - * - * From: https://github.com/PokemonAutomation/ - * - * The Ravaged Path (the cave on Route 204) as a tile grid, for checkpoint - * 01.05: from its south door, where Route 204's south half enters, east - * along its lower corridor to the door out onto Route 204's north half. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RavagedPath_H -#define PokemonAutomation_PokemonBDSP_AutoStory_RavagedPath_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace RavagedPath{ - - -// With every Rock Smash rock in place (blocked). -const Pokemon::TileGrid& grid(); - -// The Rock Smash rocks of the traced part, blocked in grid(). Each breaks -// for good once smashed, so a plan after a smash opens that tile. -const std::vector& rocks(); - -// Where walking in from Route 204's south half leaves us: the tile above the -// south door, at the foot of the room below the stairs. -extern const Pokemon::TilePos ENTRANCE; -// The tiles west of the two rocks across the lower corridor: from either, -// facing east, A offers Rock Smash, and the corridor is open to its east end. -const std::vector& before_rocks(); -// The corridor's east end on its bottom row, where walls stop a walk east -// and south: a route can end here, and nowhere else near the way out. -extern const Pokemon::TilePos EAST_END; -// The tile above the door out onto Route 204's north half, a tile west of -// EAST_END: walk south. -extern const Pokemon::TilePos ABOVE_EXIT; - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp deleted file mode 100644 index 2a79840580..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* BDSP AutoStory - Route 201 tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_Route201.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route201{ - -using namespace Pokemon; - - -// Map source: the decomp (pret/pokediamond land_data narc_0005 and -// narc_0006, 2026-10-31) with the objects from its events file; -// Platinum's map_data_005/006 have the same terrain. -// Console checks: the border sign read from (54,4) facing east, row 3 open -// east of the grass to Sandgem's fence, row 5 to Sandgem without a stop, -// the Potion lady on row 3 (2026-10-28 to 30, CFR "walk"). -// Status: no checkpoint has run on this grid yet. 00.02 to 00.04 and the -// mart_lady checkpoint passed on the image-traced grid it replaces (3/4 -// of a tile per row) and must be re-run. -// -// Decoded from Pokemon Diamond's collision table: cells (26,3) and (26,4) -// of the Sinnoh matrix, with the objects from its events file. Local (x, y) -// = world (x - 96, z - 839); 64 x 25 tiles, rows 0..2 are padding. The -// columns are the ones the image-traced grid had (its anchors matched the -// decomp exactly); the rows are the game's: the image gave 20 rows for 25. -// Sandgem Town's grid joins at column 64, row -3 (its front row is row 4). -// -// Edges: west, rows 6..7 and 11 (Lake Verity, off the map); south, the -// Twinleaf gap (14..17, 21..24); east, rows 3..6, into Sandgem. Ledges: -// row 12 (0..3 and 8..31) and (53..57, 9) in the north-east; both are -// jumped southward only. The north-east grass (42..52, 3..6) is four rows -// deep and its tree stub (51..52) stands on rows 7..12; the middle grass -// (20..29, 13..16) four rows; the south-east grass (42..57, 18) and -// (46..57, 19..20). -// Objects, from the events file: the signs (55,4) to Sandgem (BORDER_SIGN), -// (13,17) to Twinleaf and the Trainer Tips sign (40,12); a School Kid who -// stands at (57,8) looking west (not yet seen on the console). Route 201 -// has no trainers and no items on the ground. Wanderers, left off the grid: -// a Breeder around (27,15), columns 26..28, rows 14..16; a Lass along row -// 16, columns 44..48. The Poke Mart lady, who gives 10 Potions, stands -// still at (44,3) in Diamond's events file and on the console (the user, -// 2026-11-01): left off the grid, since her talk is walked to, not planned -// (r113a..r120a missed her by the walk, not by her moving). Rowan, Barry -// and the briefcase by the lake are hidden by story flags and left off. -const TileGrid& grid(){ - return story_grid("Route201"); -} - - -// The arrow sign to Sandgem Town, world (151,843), on the row of Sandgem's -// doors (its row 7). Checked on the console (2026-10-30, CFR "walk"): a row -// south of the lady's row (row 3), east stops at the sign's west side and A -// reads "Route 201 -> Sandgem Town" (a green box); north from there is one -// row, to row 3. Row 3 runs on east past the sign's north side to the Lab's -// fence. Row 5, the path, runs from the grass's west edge to Sandgem without -// a stop. -const TilePos BORDER_SIGN{55, 4}; -// Her spawn tile in Diamond is (44,3), the east end of the top grass row. -// On the console (by hand, then through the Lab Console; 99715d5d6 and -// f823453e9 on bdsp/new-game-intro-v2) she stood at (43,3), and walking -// west along row 3 from the trees at its east end stopped at (44,3), facing -// her; her lines need one A each, 1.5 s apart. r113a..r120a -// missed her talk walking to her, not because she moved. -// Checked on the console (2026-10-30, CFR "walk"), twice: from the grass's -// west edge on row 5, north stops at the trees 2 rows up, and east from -// there stops at her. r135a missed her walking west along row 4. -const TilePos POTION_GIVER{43, 3}; -const TilePos POTION_GIVER_TALK_FROM{44, 3}; - - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h deleted file mode 100644 index 24481753bf..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h +++ /dev/null @@ -1,37 +0,0 @@ -/* BDSP AutoStory - Route 201 tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Route 201 (Twinleaf Town to Sandgem Town) as a tile grid, from the - * Diamond decompilation's collision table; BDSP keeps DP's tile layout. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route201_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Route201_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route201{ - - -const Pokemon::TileGrid& grid(); - -// The sign by the Sandgem Town border, at the east end of the route. -extern const Pokemon::TilePos BORDER_SIGN; -// The Poke Mart lady, who gives 10 Potions: at the west end of the top -// grass row. Not on the grid: she turns and may wander. -extern const Pokemon::TilePos POTION_GIVER; -// East of her: walking west along her row from the open ground east of the -// grass stops here, facing her. -extern const Pokemon::TilePos POTION_GIVER_TALK_FROM; - - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp deleted file mode 100644 index 9bb6b1a2a3..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* BDSP AutoStory - Route 202 tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_Route202.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route202{ - -using namespace Pokemon; - - -// Map source: the decomp (pret/pokediamond land_data narc_0014, with the -// margins from narc_0006, 0007 and 0173; 2026-10-31) and the objects -// from its events file; Platinum's map_data_014 has the same terrain. -// Console checks: the player under the south ledge at (22,24) beside the -// trees at (21,24), the sign a row below at (24,25), the save spot -// (30,24) against the east trees, Natalie's challenge at (22,22), east -// along the row above the ledge stops at column 30 and column 30 runs -// north to row 4 (r75), the catch spot's walls (2026-10-29/30); trees, -// not grass, at (15..20, 28..29) below the catch patch (r253: west -// along row 29 stopped at column 21, beside the trees); a tree at -// (21, 30), south of the pocket at (21, 29) where the catch's save -// loads (r254: south from there was blocked at once). -// Status: no checkpoint has run on this grid yet. 00.04 passed on the -// image-traced grid it replaces (26 rows for 32) and must be re-run; -// its legs south of the catch spot are three rows longer here. -// -// Decoded from Pokemon Diamond's collision table: cell (25,5) of the Sinnoh -// matrix, with the objects from its events file. Local (x, y) = world -// (x - 159, z - 800); 36 x 32 tiles, the whole cell, so the grid's edges -// are where the game changes its location banner. The columns are the ones -// the image-traced grid had (its ledges, tree pillars and signs matched the -// decomp exactly); the rows are the game's: the image gave 26 rows for 32. -// Sandgem Town's grid starts on the row below row 31, at column 1. -// -// Exits: north, the gap (11..18, 0) to Jubilife City (EXIT_JUBILIFE in its -// middle); south, (21..30, 31) into Sandgem, where the road narrows to -// 25..30 for two rows. Ledges: row 10 (9..13 and -// 22..27) and row 23 (9..13 and 22..30), jumped southward only. The east -// wall is column 33 from row 10 to 20, column 32 on row 21 and column 31 on -// row 22, the row right above the south ledge: east along that row stops at -// column 30 (r75), and column 30 is open north from there to row 4 under -// Logan's row. -// Objects, from the events file: three trainers who stand still, Youngster -// Tristan (7,13), Lass Natalie (22,18) and Youngster Logan (26,4), all -// facing south, with the sight ranges the events give; a Potion ball (3,6), -// a wall until picked up; the signs (17,4) to Jubilife, (15,16) Trainer Tips -// and (24,25) to Sandgem. BDSP has trees where Diamond's catch patch has -// its two bottom rows, (15..20, 28..29): the console's patch is three rows -// between tree rows, as the image-traced grid had it. A Youngster who is not a trainer wanders along row -// 8, columns 9..11, and is left off the grid (the image-traced grid had him -// as a fourth trainer facing east). Dawn's tile (15,27) is hidden by a -// story flag. -const TileGrid& grid(){ - return story_grid("Route202"); -} - - -// Where 00.03's save after the catch stands: the bottom row of the -// tall-grass patch at (15..20, 25..27), world (178,827). On the console the -// sign at (24,25) is 5 columns right and 2 rows up, walking east stops at -// the trees after 11 tiles and north at the trees after 2; south are trees -// (the decomp's two more grass rows are trees in BDSP, r253). -const TilePos CATCH_SPOT{19, 27}; -// Where 00.04 saves once it has Potions, before Route 202's trainers (the -// console's saves from r113a..r117a stand here too): under the south ledge, -// against the east trees, world (189,824). -const TilePos SAVE_SPOT{30, 24}; - -// From the events file: each trainer's tile, facing and sight range. -// Natalie challenged us at (22,22), walking east along the row above the -// ledge (r75), the fourth tile of her sight. -const TilePos TRAINER_TRISTAN{7, 13}; -const TilePos TRAINER_NATALIE{22, 18}; -const TilePos TRAINER_LOGAN{26, 4}; - -const std::vector& trainer_sights(){ - static const std::vector sights{ - {"tristan", TRAINER_TRISTAN, Direction::SOUTH, 5}, - {"natalie", TRAINER_NATALIE, Direction::SOUTH, 4}, - {"logan", TRAINER_LOGAN, Direction::SOUTH, 5}, - }; - return sights; -} - -// The middle of the 8-tile gap at (11..18, 0), world (174,800), below the -// 3-wide neck of Jubilife's south exit (173..175). -const TilePos EXIT_JUBILIFE{15, 0}; - - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h deleted file mode 100644 index cee0a1e49a..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h +++ /dev/null @@ -1,49 +0,0 @@ -/* BDSP AutoStory - Route 202 tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Route 202 (Sandgem Town to Jubilife City) as a tile grid, from the - * Diamond decompilation's collision table; BDSP keeps DP's tile layout. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route202_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Route202_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route202{ - - -const Pokemon::TileGrid& grid(); - -// Where the player stands in the tall grass after the catching tutorial. -extern const Pokemon::TilePos CATCH_SPOT; -// Under the south ledge, against the east trees: where the console's 00.04 -// save stands. Two walls pin it. -extern const Pokemon::TilePos SAVE_SPOT; - -// The three trainers, from the events file: Youngster Tristan in the west -// field, Lass Natalie above the south ledge, Youngster Logan by the east -// grass. All face south. -extern const Pokemon::TilePos TRAINER_TRISTAN; -extern const Pokemon::TilePos TRAINER_NATALIE; -extern const Pokemon::TilePos TRAINER_LOGAN; - -// Their sight lines, in this map's tiles. The story wants these battles. -const std::vector& trainer_sights(); - -// A tile in the gap of the north edge; walking north from it leaves for -// Jubilife City. -extern const Pokemon::TilePos EXIT_JUBILIFE; - - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp deleted file mode 100644 index 642168d015..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* BDSP AutoStory - Route 203 tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_Route203.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route203{ - -using namespace Pokemon; - - -// Map source: the decomp (pret/pokediamond land_data narc_0019 and -// narc_0020, with Jubilife's column 0 from narc_0016; 2026-10-31) and -// the objects from its events file. Platinum adds an X Defense ball at -// (40,14). -// Console checks (r227 hand pass, 2026-10-31): the Gate's warp at column -// 55, the ledge on row 15 (38..48), the beaten girl at column 43 on the -// second sand row, the row below her straight west to Jubilife (35 -// taps, no row change), the blue-haired trainer at the sand's west end. -// Status: no checkpoint has run on this grid yet. 01.06 passed on the -// image-traced grid it replaces (its east stretch corrected on the -// console) and must be re-run: the decomp has four sand rows under the -// ledge where the console counted three (9 taps south from (55,9); the -// decomp has 10 open tiles, so the first tap may only have turned). -// -// Decoded from Pokemon Diamond's collision table: cells (23,6) and (23,7) -// of the Sinnoh matrix, with the objects from its events file. Local -// (x, y) = world (x - 191, z - 740); 61 x 24 tiles. Column 0 is Jubilife's -// east edge. The columns are the ones the image-traced grid had (its gate -// warp, ledge and signs matched the decomp exactly); the rows are the -// game's: the image squeezed the west and middle stretches. -// - West stretch (columns 5..22): the field (5..22, 4..19) with grass at -// 5..8 (8..13), a ledge (18..22, 13), and the road on rows 17..19 that -// runs to Jubilife at column 0. -// - Middle stretch (23..37): the pond (29..34, 7..11) cuts the strip north -// of it, by the Repel ball (31,5), off from the rest: r222g's walk got -// stuck up there. The way through is along the bottom, rows 16..19. -// - East stretch (38..55): the Gate's mouth is (56,9), its warp tile -// (55,9). South from (55,9) is open to row 19. The ledge on row 15 -// (38..48) is crossed southward only. The sand below it is four rows, -// 16..19: the blue-haired trainer (Youngster Dallas, looks south, sees -// 4) at the sand's west end on its first row, the girl (Youngster -// Sebastian in the events file, looks west, sees 5) at (43,17) on its -// second. -// Row 18 runs in one straight line west from the sand to Jubilife; row 17 -// is blocked by the girl and the trainer, row 19 by trees at (36..37, 19). -// Objects, from the events file: trainers who stand still, 'N': Youngster -// Michael (13,10), looks west, sees 2; Dallas (31,16); Sebastian (43,17); -// Lass Madeline (49,8), looks south, sees 5. Items that block their tile -// until picked up, '#': a Poke Ball (20,10) and a Repel (31,5). Signs: to -// Jubilife (9,16), Trainer Tips (26,10) and (47,12), to Oreburgh (53,7); -// Jubilife's own sign to Route 203 stands at (7,16) in its events, not in -// this map's. Left off: a Lass who wanders along row 17 (14..16) and the -// Youngster at (54,16) who stands still in Diamond but wanders in BDSP (the -// blue-haired man near the Gate, on the console); Barry (10,17) is hidden -// by a story flag. -const TileGrid& grid(){ - return story_grid("Route203"); -} - -// The warp tile the Gate puts us on, and its open neighbours. -const std::vector& gate_exit(){ - static const std::vector tiles{{55, 9}, {54, 9}, {55, 8}, {55, 10}}; - return tiles; -} - - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h deleted file mode 100644 index 9bf526197b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h +++ /dev/null @@ -1,32 +0,0 @@ -/* BDSP AutoStory - Route 203 tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Route 203 as a tile grid, for checkpoint 01.06: from the Oreburgh Gate's - * west exit to Jubilife City's east edge. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route203_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Route203_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route203{ - - -const Pokemon::TileGrid& grid(); - -// Where stepping out of the Oreburgh Gate may leave us when Route 203's -// banner shows: the warp tile west of the cave's mouth and its neighbours. -const std::vector& gate_exit(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp deleted file mode 100644 index eee289d1ce..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* BDSP AutoStory - Route 204 tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_Route204.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route204{ - -using namespace Pokemon; - - -// Map source: the decomp (map_data_031, 2026-10-31) with the objects from -// its events file; before that the DP image, 3/4 rows. -// Console checks: row 27 open under the cliff, the stairs, Taylor's sight at -// column 17 (recorded human walk, 2026-10-31). Suspects: column 23 rows -// 12 to 19 blocked on the console (r242a); three open rows under the -// cave, not four (r241a, r243a). -// Status: 01.10 not passed yet; the route is the recorded human line -// (floaroma_waypoints()). -// -// Decoded from Pokemon Platinum's collision table for this map (the -// pret/pokeplatinum decompilation, map_data_031.bin: one cell of the Sinnoh -// matrix, column 5, row 21; local (x, y) = world (x - 160, z - 672)) with -// the objects from its events file; BDSP keeps the layout. Water and the -// items on the ground are '#'. Objects: the Ravaged Path's door, arriving -// on (20, 26); the twins (15, 7) and (16, 7) looking south; Aroma Lady -// Taylor (17, 20) looking south and east; Bug Catcher Brandon walking back -// and forth, on row 12 on the console (r246a), drawn at (20, 12) by the DP -// map, (22, 13) in Platinum's data; the arrow signpost -// (17, 9); a Youngster who is not a trainer wanders rows 27 and 28 below -// the cave, off the grid. The path north into Floaroma is columns 10 to 12 -// at the top. -// The 2026-10-29 hand run went out of the cave, west to the stairs, up them -// into the pocket the ledge (row 15) closes, back down, east and north -// through the tall grass, and west below the flower beds past the twins. -// Before 2026-10-31 this grid was traced from Bulbapedia's DP map image, -// whose rows are 12 px to the columns' 16: every row was 3/4 of a tile. -const TileGrid& north_grid(){ - return story_grid("Route204North"); -} - -const TilePos CAVE_EXIT{20, 26}; - -bool in_floaroma_path(const TilePos& pos){ - return pos.x >= 10 && pos.x <= 12 && pos.y <= 5; -} - -std::vector north_trainer_sights(){ - return { - {"Twins (left)", {15, 7}, Direction::SOUTH, 3}, - {"Twins (right)", {16, 7}, Direction::SOUTH, 4}, - {"Aroma Lady Taylor", {17, 20}, Direction::SOUTH, 4}, - {"Aroma Lady Taylor", {17, 20}, Direction::EAST, 4}, - // Bug Catcher Brandon paces east and west below the flower beds - // and stopped us on row 12 (r246a: "Say, what's your opinion on bug - // Pokemon?"); the DP map draws him at (20, 12), Platinum's data - // has him at (22, 13). The tile is a guess until a shot fixes it. - {"Bug Catcher Brandon", {20, 12}, Direction::WEST, 4}, - {"Bug Catcher Brandon", {20, 12}, Direction::EAST, 4}, - }; -} - -std::vector floaroma_waypoints(){ - // The line a human walked on 2026-10-31 (recorded; drawn over the DP - // map image): a tile south out of the cave's mouth; west along the row - // under the cliff, where the Youngster wanders (he stood a row below - // as we passed; the walker waits for him when he is in the way); north - // up the middle of the stairs; east along the corridor, where Aroma - // Lady Taylor sees us at column 17 and walks over for her battle; north - // up column 19 through the tall grass; west below the flower beds; - // north between the beds. The DP image shows a trainer sprite at - // (20, 12), by the corner where the line turns west: not seen yet on - // the console. The ledge on row 15 closes the stairs' column going - // north, so the line goes round through the grass. - // Column 11 for the last stretch: (12, 6) is blocked on the console - // (r248a, twice), grass in Platinum's data; the detour through (11, 6) - // passed. - return {{20, 27}, {11, 27}, {11, 22}, {19, 22}, {19, 12}, {11, 12}, {11, 5}}; -} - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h deleted file mode 100644 index edd4b29cc0..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h +++ /dev/null @@ -1,43 +0,0 @@ -/* BDSP AutoStory - Route 204 tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Route 204's north half as a tile grid, for checkpoint 01.05: from the - * door out of the Ravaged Path up to the path into Floaroma Town. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route204_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Route204_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route204{ - - -const Pokemon::TileGrid& north_grid(); - -// Where leaving the Ravaged Path puts us: the tile below its door. -extern const Pokemon::TilePos CAVE_EXIT; - -// Whether a tile is in the path north into Floaroma, between the flower -// beds' fences: walking north from here leaves the route. -bool in_floaroma_path(const Pokemon::TilePos& pos); - -// The twins below the right-hand flower bed: a double battle when they see -// us walk past below them. -std::vector north_trainer_sights(); - -// The corners of the line into Floaroma from the cave's exit, as a human -// walked it (2026-10-31): the last is in the path into Floaroma. -std::vector floaroma_waypoints(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp deleted file mode 100644 index 4f022f4dce..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* BDSP AutoStory - Route 204 South tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_Route204South.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route204South{ - -using namespace Pokemon; - - -// Map source: the decomp (map_data_021, 2026-10-31) with the objects from -// its events file. -// Console checks: column 14 stops at the signpost (14,17), column 13 is -// grass to the cliff, Sarah fights on row 21 (r233a, r234a, probes). -// Status: 01.08 passes once (r235a). -// -// Decoded from Pokemon Platinum's collision table for this map (the -// pret/pokeplatinum decompilation, res/field/maps/data/map_data_021.bin: -// 32 x 32 tiles, one cell of the Sinnoh matrix at column 5, row 22), with -// the objects from its events file (events_route_204_south.json); BDSP -// keeps Diamond/Pearl's layout. Local (x, y) = world (x - 160, z - 704). -// Water is '#'. Objects, from the events file: -// door to the Ravaged Path (11, 1); its signboard (10, 2); -// the "204" arrow signpost (14, 17), which stops a walk north up the -// street's column 14 (r233a, r234a); -// Lass Samantha (11, 8), looks south; Lass Sarah (12, 21), looks north -// and east by turns; Youngster Tyler (7, 18), looks west and east; -// items on the ground (17, 18), (29, 12), (2, 28), as '#'; -// a Youngster who is not a trainer wanders west and east along row 2 in -// front of the door: off the grid, the walker waits for him. -// Checked on the console 2026-10-31 (r233a, r234a, probes): north up -// column 14 from Jubilife stops at the signpost (14, 17); column 13 is -// tall grass all the way up and stops at the cliff (13, 2), the door two -// columns west; Sarah walked up and fought us once on row 21. -// Row 31, columns 12 to 15, joins the top of Jubilife's north street: -// walking south there leaves the route. -const TileGrid& grid(){ - return story_grid("Route204South"); -} - -std::vector jubilife_entry(){ - // The walk north looks between 400 ms holds, so it may stop up to two - // tiles past the border. - return {{14, 31}, {14, 30}, {14, 29}}; -} - -const TilePos BELOW_DOOR{11, 2}; - -std::vector trainer_sights(){ - // Sarah turns between north and east; her east line crosses the - // street's columns, so a walk north meets it or not by luck (r233a - // passed, r234a fought). The planner cannot avoid it: she is listed - // so the route knows whom it may meet, with the range that fits. - return { - {"Lass Samantha", {11, 8}, Direction::SOUTH, 4}, - {"Lass Sarah", {12, 21}, Direction::NORTH, 4}, - {"Lass Sarah", {12, 21}, Direction::EAST, 4}, - {"Youngster Tyler", {7, 18}, Direction::EAST, 4}, - {"Youngster Tyler", {7, 18}, Direction::WEST, 4}, - }; -} - -std::vector tiles_to_avoid(){ - std::vector tiles; - for (const TrainerSight& trainer : trainer_sights()){ - if (trainer.name == "Lass Sarah" && trainer.facing == Direction::EAST){ - continue; - } - for (const TilePos& pos : sight_tiles(grid(), trainer)){ - tiles.push_back(pos); - } - } - return tiles; -} - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h deleted file mode 100644 index d03ed47c1b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h +++ /dev/null @@ -1,44 +0,0 @@ -/* BDSP AutoStory - Route 204 South tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Route 204's south half as a tile grid, for checkpoint 01.08: from the top - * of Jubilife City's north street to the door of the Ravaged Path. The - * north half (Route204::north_grid) is reached only through the cave, so - * the two halves are separate maps. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Route204South_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Route204South_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Route204South{ - - -const Pokemon::TileGrid& grid(); - -// Where walking north out of Jubilife's street puts us: its column on the -// route's bottom rows: the walk stops within two tiles of the border. -std::vector jubilife_entry(); - -// The tile below the Ravaged Path's door; walking north from it enters. -extern const Pokemon::TilePos BELOW_DOOR; - -// The trainers whose sight lines a route may cross. -std::vector trainer_sights(); - -// The sight-line tiles a route can keep out of: all but Sarah's east line, -// which crosses the whole street. -std::vector tiles_to_avoid(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp new file mode 100644 index 0000000000..65111d657a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -0,0 +1,434 @@ +/* BDSP AutoStory - Route planner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/Navigation/Pokemon_LegPlanner.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +size_t distance(const TilePos& a, const TilePos& b){ + return std::abs(a.x - b.x) + std::abs(a.y - b.y); +} + +bool tall_grass(const StoryWorld& world, const TilePos& pos){ + return world.tile(pos) == TileKind::TALL_GRASS; +} + +} + + +WallHit walk_to_wall(const StoryWorld& world, const TilePos& from, Direction direction){ + WallHit hit; + hit.stop = from; + while (true){ + const TilePos before = hit.stop; + const std::optional next = world.step(before, direction); + if (!next){ + hit.wall = before.next(direction); + hit.anchored = world.at_wall(before, direction); + return hit; + } + hit.tiles += distance(*next, before); + hit.stop = *next; + } +} + + +std::string to_string(const TileLeg& leg){ + return std::format("{} {}{}", Pokemon::direction_name(leg.direction), leg.tiles, leg.ends_at_wall ? " (to wall)" : " (open)"); +} + + +namespace{ + +// The world's step rules for the shared leg planner. A ledge hop is one +// press that moves two tiles. +class StoryWorldModel{ +public: + using State = TilePos; + using StateHash = std::hash; + + StoryWorldModel(const StoryWorld& world, const TilePlanCosts& costs) + : m_world(world) + , m_costs(costs) + {} + + std::optional> press(const State& pos, Direction direction) const{ + const std::optional next = m_world.step(pos, direction); + if (!next){ + return std::nullopt; + } + Pokemon::Step step; + step.next = *next; + step.facing = direction; + step.extra_cost = m_costs.per_tile * ((int)distance(*next, pos) - 1); + if (tall_grass(m_world, *next)){ + step.extra_cost += m_costs.per_grass_tile; + } + return step; + } + bool held_at(const State& pos, Direction direction) const{ + return m_world.at_wall(pos, direction); + } + +private: + const StoryWorld& m_world; + const TilePlanCosts& m_costs; +}; + +void check_standable(const StoryWorld& world, const TilePos& from, const TilePos& to){ + if (!world.standable(from) || !world.standable(to)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Route ends must be standable: {} -> {}.", Pokemon::to_string(from), Pokemon::to_string(to) + )); + } +} + +} + +std::optional> plan_tile_route( + const StoryWorld& world, + const TilePos& from, const TilePos& to, + const TilePlanCosts& costs +){ + check_standable(world, from, to); + if (from == to){ + return std::vector(); + } + Pokemon::LegCosts leg_costs; + leg_costs.per_tile = costs.per_tile; + leg_costs.per_turn = costs.per_leg; + leg_costs.per_open_stop = costs.leg_not_at_wall; + const auto legs = Pokemon::plan_legs( + StoryWorldModel(world, costs), from, std::nullopt, + std::function([&](const TilePos& pos){ return pos == to; }), + std::nullopt, leg_costs + ); + if (!legs){ + return std::nullopt; + } + std::vector ret; + for (const Pokemon::Leg& leg : *legs){ + ret.push_back(TileLeg{leg.direction, distance(leg.end, leg.start), leg.to_wall}); + } + return ret; +} + +std::vector sight_tiles(const StoryWorld& world, const TrainerSight& trainer){ + std::vector tiles; + TilePos pos = trainer.pos; + for (int i = 0; i < trainer.range; i++){ + pos = pos.next(trainer.facing); + if (!world.standable(pos)){ + break; + } + tiles.push_back(pos); + } + return tiles; +} + +std::vector> legs_crossing_sight( + const StoryWorld& world, + const TilePos& from, + const std::vector& legs, + const std::vector& trainers +){ + std::vector> sights; + for (const TrainerSight& trainer : trainers){ + sights.push_back(sight_tiles(world, trainer)); + } + std::vector> crossings; + TilePos pos = from; + for (const TileLeg& leg : legs){ + const std::vector tiles = trace_legs(world, pos, {leg}); + std::vector seen_by; + for (size_t t = 0; t < trainers.size(); t++){ + const bool seen = std::any_of(tiles.begin() + 1, tiles.end(), [&](const TilePos& tile){ + return std::ranges::find(sights[t], tile) != sights[t].end(); + }); + if (seen){ + seen_by.push_back(trainers[t].name); + } + } + crossings.push_back(std::move(seen_by)); + pos = tiles.back(); + } + return crossings; +} + +std::vector trace_legs( + const StoryWorld& world, + const TilePos& from, + const std::vector& legs +){ + std::vector tiles{from}; + for (const TileLeg& leg : legs){ + size_t travelled = 0; + while (travelled < leg.tiles){ + const TilePos pos = tiles.back(); + const std::optional next = world.step(pos, leg.direction); + if (!next){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Leg {} is stopped at {}.", to_string(leg), Pokemon::to_string(pos) + )); + } + travelled += distance(*next, pos); + tiles.push_back(*next); + } + if (travelled != leg.tiles){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("Leg {} overshoots on a ledge hop.", to_string(leg))); + } + } + return tiles; +} + + +std::string to_string(const PlannedLeg& leg){ + std::string out = to_string(leg.leg) + " to"; + for (const TilePos& pos : leg.after){ + out += " " + Pokemon::to_string(pos); + } + return out; +} + +namespace{ + +// Where `from` ends up after `tiles` steps in `direction`, stopping early at +// anything that stops the player, and how many tall-grass tiles it enters. +// Nothing if a step would leave the maps or enter a door: the plan cannot +// tell what happens then. +struct Stepped{ + TilePos end; + int grass = 0; +}; +std::optional step_tiles(const StoryWorld& world, TilePos from, Direction direction, int tiles){ + Stepped stepped; + int travelled = 0; + while (travelled < tiles){ + const std::optional next = world.step(from, direction); + if (!next){ + if (!world.at_wall(from, direction)){ + return std::nullopt; + } + break; + } + travelled += (int)distance(*next, from); + if (tall_grass(world, *next)){ + stepped.grass++; + } + from = *next; + } + stepped.end = from; + return stepped; +} + +using Spread = std::vector; + +bool spread_less(const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; +} +void normalize(Spread& spread){ + std::sort(spread.begin(), spread.end(), spread_less); + spread.erase(std::unique(spread.begin(), spread.end()), spread.end()); +} +struct SpreadLess{ + bool operator()(const Spread& a, const Spread& b) const{ + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), spread_less); + } +}; + +// A leg out of a spread: where every tile of it ends, and its cost. +struct Expansion{ + long long cost = 0; + Spread next; + TileLeg leg; +}; + +// To the wall: every position walks until stopped. Nothing unless each is +// held at a wall, and one moves. +std::optional to_wall_leg(const StoryWorld& world, const Spread& spread, Direction direction, const RobustPlanCosts& costs){ + Expansion expansion; + size_t longest = 0; + int grass = 0; + for (const TilePos& pos : spread){ + const WallHit hit = walk_to_wall(world, pos, direction); + if (!hit.anchored){ + return std::nullopt; + } + if (const std::optional stepped = step_tiles(world, pos, direction, (int)hit.tiles)){ + grass = std::max(grass, stepped->grass); + } + longest = std::max(longest, hit.tiles); + expansion.next.push_back(hit.stop); + } + if (longest == 0){ + return std::nullopt; + } + expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest + (long long)costs.per_grass_tile * grass; + expansion.leg = TileLeg{direction, longest, true}; + return expansion; +} + +// Open: about `tiles` tiles, give or take the error. Nothing if any +// possible end leaves the maps or enters a door. +std::optional open_leg(const StoryWorld& world, const Spread& spread, Direction direction, int tiles, const RobustPlanCosts& costs){ + Expansion expansion; + int grass = 0; + const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; + for (const TilePos& pos : spread){ + for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ + const std::optional stepped = step_tiles(world, pos, direction, n); + if (!stepped){ + return std::nullopt; + } + grass = std::max(grass, stepped->grass); + expansion.next.push_back(stepped->end); + } + } + expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + + (long long)(costs.per_tile + costs.per_open_tile) * tiles + (long long)costs.per_grass_tile * grass; + expansion.leg = TileLeg{direction, (size_t)tiles, false}; + return expansion; +} + +// Dijkstra over sets of tiles the player may stand on. +class RobustSearch{ +public: + RobustSearch(const StoryWorld& world, const RobustPlanCosts& costs) + : m_world(world) + , m_costs(costs) + {} + + std::optional> run(Spread start, const std::function& goal){ + normalize(start); + m_start = start; + m_nodes[start] = Node{0, {}, {}}; + m_queue.emplace(0, start); + size_t searched = 0; + while (!m_queue.empty()){ + const auto [cost, spread] = m_queue.top(); + m_queue.pop(); + Node& node = m_nodes[spread]; + if (node.done || node.cost != cost){ + continue; + } + node.done = true; + if (++searched > m_costs.max_searched){ + return std::nullopt; + } + if (std::all_of(spread.begin(), spread.end(), goal)){ + return legs_to(spread); + } + expand(spread, cost); + } + return std::nullopt; + } + +private: + struct Node{ + long long cost = 0; + Spread parent; + PlannedLeg leg; + bool done = false; + }; + using Entry = std::pair; + struct EntryGreater{ + bool operator()(const Entry& a, const Entry& b) const{ return a.first > b.first; } + }; + + void expand(const Spread& spread, long long cost){ + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + if (std::optional wall = to_wall_leg(m_world, spread, direction, m_costs)){ + relax(spread, cost, std::move(*wall)); + } + for (int tiles = 1; tiles <= m_costs.max_open_tiles; tiles++){ + std::optional open = open_leg(m_world, spread, direction, tiles, m_costs); + if (!open){ + break; + } + relax(spread, cost, std::move(*open)); + } + } + } + + // Only the start may be wider than costs.max_spread: every leg must + // bring the player within it. + void relax(const Spread& spread, long long cost, Expansion expansion){ + normalize(expansion.next); + if (expansion.next.size() > m_costs.max_spread || expansion.next == spread){ + return; + } + const long long total = cost + expansion.cost; + auto iter = m_nodes.find(expansion.next); + if (iter != m_nodes.end() && iter->second.cost <= total){ + return; + } + m_nodes[expansion.next] = Node{total, spread, PlannedLeg{expansion.leg, expansion.next}}; + m_queue.emplace(total, std::move(expansion.next)); + } + + std::vector legs_to(const Spread& end) const{ + std::vector legs; + for (Spread at = end; at != m_start; ){ + const Node& step = m_nodes.at(at); + legs.push_back(step.leg); + at = step.parent; + } + std::reverse(legs.begin(), legs.end()); + return legs; + } + + const StoryWorld& m_world; + const RobustPlanCosts& m_costs; + Spread m_start; + std::map m_nodes; + std::priority_queue, EntryGreater> m_queue; +}; + +} + +std::optional> plan_robust_route( + const StoryWorld& world, + const TilePos& from, const TilePos& to, + const RobustPlanCosts& costs +){ + check_standable(world, from, to); + return plan_robust_route(world, std::vector{from}, [&](const TilePos& pos){ return pos == to; }, costs); +} + +std::optional> plan_robust_route( + const StoryWorld& world, + const std::vector& from, const std::function& goal, + const RobustPlanCosts& costs +){ + for (const TilePos& pos : from){ + if (!world.standable(pos)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route starts must be standable: " + Pokemon::to_string(pos) + "."); + } + } + return RobustSearch(world, costs).run(from, goal); +} + + + +} +} +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h similarity index 52% rename from SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index c8ae8ba9d9..f5b9d6d730 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_TileGrid.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -1,191 +1,144 @@ -/* Tile Grid - * - * From: https://github.com/PokemonAutomation/ - * - * An overworld map as a grid of tiles, and a planner that turns a walk from - * one tile to another into straight legs. Timed stick holds drift by a tile; - * a leg that ends against a wall does not, because the player stops there - * however long the stick is held. The planner prefers such legs. - */ - -#ifndef PokemonAutomation_Pokemon_TileGrid_H -#define PokemonAutomation_Pokemon_TileGrid_H - -#include -#include -#include -#include -#include -#include "Pokemon_Grid.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// Legend of the ASCII rows a grid is parsed from. -enum class TileType{ - BLOCKED, // '#': trees, walls, items on the ground - WALKABLE, // '.': open ground and paths - TALL_GRASS, // '"': walkable, with wild encounters - LEDGE, // 'v': crossed only southward, hopping to the tile past it - NPC, // 'N': a standing NPC or trainer; blocks like a wall - SIGN, // 'S': a sign; blocks like a wall - DOOR, // 'D': walking into it enters a building - UNKNOWN, // '?': off the map; an exit or ground we have no map of -}; -char tile_char(TileType type); - -class TileGrid{ -public: - // Every row must have the same length and use only the legend's characters. - // Throws InternalProgramError otherwise. - explicit TileGrid(const std::vector& rows); - - // The grid as the ASCII rows it parses from. - std::vector rows() const; - - int width() const{ return m_width; } - int height() const{ return m_height; } - bool in_bounds(const TilePos& pos) const; - - // Out-of-bounds tiles read as UNKNOWN. - TileType at(const TilePos& pos) const; - - // Changes one tile, e.g. to block one found in the way on the console. - // Out-of-bounds tiles are left alone. - void set(const TilePos& pos, TileType type); - - // Whether the player can stand on this tile. - bool standable(const TilePos& pos) const; - - // Where one step from `from` lands, or nothing if the player is stopped. - // A south step onto a ledge hops to the tile past it. - std::optional step(const TilePos& from, Direction direction) const; - - // Whether a step from `pos` is refused by a tile that holds the player - // in place. Doors and unknown tiles are not walls: walking into a door - // enters the building, and unknown ground may be an exit. - bool at_wall(const TilePos& pos, Direction direction) const; - -private: - int m_width = 0; - int m_height = 0; - std::vector m_tiles; -}; - - -// Where the player stops when walking in one direction until stopped. -struct WallHit{ - TilePos stop; - size_t tiles = 0; // tiles travelled; a ledge hop counts 2 - TilePos wall; // the first tile the player could not enter - bool anchored = false; // the player is held at `stop` (see TileGrid::at_wall()) -}; -WallHit walk_to_wall(const TileGrid& grid, const TilePos& from, Direction direction); - - -// A straight run in one direction. -struct TileLeg{ - Direction direction; - size_t tiles = 0; // tiles travelled; a ledge hop counts 2 - bool ends_at_wall = false; // the next tile in `direction` stops the player -}; -std::string to_string(const TileLeg& leg); - -struct TilePlanCosts{ - int per_tile = 1; - int per_grass_tile = 4; // extra for each tall-grass tile entered - int per_leg = 8; - int leg_not_at_wall = 50; // extra for a leg that stops in the open -}; - -// Cheapest legs from `from` to `to`, moving 4 ways, or nothing if `to` -// cannot be reached. Both tiles must be standable. -std::optional> plan_tile_route( - const TileGrid& grid, - const TilePos& from, const TilePos& to, - const TilePlanCosts& costs = TilePlanCosts() -); - -// A trainer sees the tiles in a straight line in front of them, up to -// `range` tiles or the first tile the player cannot stand on. -struct TrainerSight{ - std::string name; - TilePos pos; - Direction facing; - int range = 4; -}; -std::vector sight_tiles(const TileGrid& grid, const TrainerSight& trainer); - -// For each leg, the trainers whose sight line it enters. -std::vector> legs_crossing_sight( - const TileGrid& grid, - const TilePos& from, - const std::vector& legs, - const std::vector& trainers -); - -// The tiles a list of legs visits, starting with `from`. Throws -// InternalProgramError if a leg is stopped before its end. -std::vector trace_legs( - const TileGrid& grid, - const TilePos& from, - const std::vector& legs -); - - -// A leg of a plan that allows for open legs going a tile short or long. A -// leg to a wall is walked until the player stops; an open leg is walked for -// `leg.tiles` tiles' worth of time. `after` lists every tile the player may -// stand on once the leg is done. -struct PlannedLeg{ - TileLeg leg; - std::vector after; -}; -std::string to_string(const PlannedLeg& leg); - -struct RobustPlanCosts : TilePlanCosts{ - // An open leg of n tiles may end open_error + n / open_error_per tiles - // short or long: on the console 7 tiles went 9. - int open_error = 1; - int open_error_per = 5; - // Open legs this many tiles or shorter land exactly: a short hold moves - // whole tiles. 0 keeps every open leg uncertain. - int exact_open_tiles = 0; - // Extra per tile of an open leg: its timing error grows with its length, - // so a short step after a wall beats a long open leg. - int per_open_tile = 0; - int max_open_tiles = 12; // longest open leg to consider - size_t max_spread = 5; // most tiles the player may be on after a leg - // Most sets of possible tiles to search before giving up. The search is - // over sets, not tiles, so it grows far faster than the map: all of - // Jubilife City from six start tiles ran for minutes with no plan - // (r224a, 2026-10-31); 200000 sets took 31 s there, so this gives up - // after about 3. Use town costs in towns (a whole-Jubilife plan then - // takes 1 s) and crop the map to the part a leg needs rather than - // raising this. - size_t max_searched = 20000; -}; - -// Cheapest legs that take the player from any of the tiles in `from` to tiles -// that are all `goal`, even if every open leg ends up to `open_error` tiles -// off: the walls of later legs must bring the possible positions together. -// Legs that would leave the map or enter a door are not used. Nothing if no -// such plan exists, or none is found within `costs.max_searched` sets. -std::optional> plan_robust_route( - const TileGrid& grid, - const std::vector& from, const std::function& goal, - const RobustPlanCosts& costs = RobustPlanCosts() -); -// The same, from one tile to exactly `to`. -std::optional> plan_robust_route( - const TileGrid& grid, - const TilePos& from, const TilePos& to, - const RobustPlanCosts& costs = RobustPlanCosts() -); - - - -} -} -#endif +/* BDSP AutoStory - Route planner + * + * From: https://github.com/PokemonAutomation/ + * + * Turns a walk on the story world from one tile to another into straight + * legs. Timed stick holds drift by a tile; a leg that ends against a wall + * does not, because the player stops there however long the stick is held. + * The planner prefers such legs. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_H + +#include +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Where the player stops when walking in one direction until stopped. +struct WallHit{ + Pokemon::TilePos stop; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + Pokemon::TilePos wall; // the first tile the player could not enter + bool anchored = false; // the player is held at `stop` (see StoryWorld::at_wall()) +}; +WallHit walk_to_wall(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); + + +// A straight run in one direction. +struct TileLeg{ + Pokemon::Direction direction = Pokemon::Direction::NORTH; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + bool ends_at_wall = false; // the next tile in `direction` stops the player +}; +std::string to_string(const TileLeg& leg); + +struct TilePlanCosts{ + int per_tile = 1; + int per_grass_tile = 4; // extra for each tall-grass tile entered + int per_leg = 8; + int leg_not_at_wall = 50; // extra for a leg that stops in the open +}; + +// Cheapest legs from `from` to `to`, moving 4 ways, or nothing if `to` +// cannot be reached. Both tiles must be standable. +std::optional> plan_tile_route( + const StoryWorld& world, + const Pokemon::TilePos& from, const Pokemon::TilePos& to, + const TilePlanCosts& costs = TilePlanCosts() +); + +// A trainer sees the tiles in a straight line in front of them, up to +// `range` tiles or the first tile the player cannot stand on. The maps +// have no sight ranges, so story code lists them. +struct TrainerSight{ + std::string name; + Pokemon::TilePos pos; + Pokemon::Direction facing = Pokemon::Direction::NORTH; + int range = 4; +}; +std::vector sight_tiles(const StoryWorld& world, const TrainerSight& trainer); + +// For each leg, the trainers whose sight line it enters. +std::vector> legs_crossing_sight( + const StoryWorld& world, + const Pokemon::TilePos& from, + const std::vector& legs, + const std::vector& trainers +); + +// The tiles a list of legs visits, starting with `from`. Throws +// InternalProgramError if a leg is stopped before its end. +std::vector trace_legs( + const StoryWorld& world, + const Pokemon::TilePos& from, + const std::vector& legs +); + + +// A leg of a plan that allows for open legs going a tile short or long. A +// leg to a wall is walked until the player stops; an open leg is walked for +// `leg.tiles` tiles' worth of time. `after` lists every tile the player may +// stand on once the leg is done. +struct PlannedLeg{ + TileLeg leg; + std::vector after; +}; +std::string to_string(const PlannedLeg& leg); + +struct RobustPlanCosts : TilePlanCosts{ + // An open leg of n tiles may end open_error + n / open_error_per tiles + // short or long: on the console 7 tiles went 9. + int open_error = 1; + int open_error_per = 5; + // Open legs this many tiles or shorter land exactly: a short hold moves + // whole tiles. 0 keeps every open leg uncertain. + int exact_open_tiles = 0; + // Extra per tile of an open leg: its timing error grows with its length, + // so a short step after a wall beats a long open leg. + int per_open_tile = 0; + int max_open_tiles = 12; // longest open leg to consider + size_t max_spread = 5; // most tiles the player may be on after a leg + // Most sets of possible tiles to search before giving up. The search is + // over sets, not tiles, so it grows far faster than the map: all of + // Jubilife City from six start tiles ran for minutes with no plan + // (r224a, 2026-10-31); 200000 sets took 31 s there, so this gives up + // after about 3. Use town costs in towns (a whole-Jubilife plan then + // takes 1 s) and crop the map to the part a leg needs rather than + // raising this. + size_t max_searched = 20000; +}; + +// Cheapest legs that take the player from any of the tiles in `from` to tiles +// that are all `goal`, even if every open leg ends up to `open_error` tiles +// off: the walls of later legs must bring the possible positions together. +// Legs that would leave the maps or enter a door are not used. Nothing if no +// such plan exists, or none is found within `costs.max_searched` sets. +std::optional> plan_robust_route( + const StoryWorld& world, + const std::vector& from, const std::function& goal, + const RobustPlanCosts& costs = RobustPlanCosts() +); +// The same, from one tile to exactly `to`. +std::optional> plan_robust_route( + const StoryWorld& world, + const Pokemon::TilePos& from, const Pokemon::TilePos& to, + const RobustPlanCosts& costs = RobustPlanCosts() +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp deleted file mode 100644 index 84afae03f1..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* BDSP AutoStory - Sandgem Town tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_SandgemTown.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace SandgemTown{ - -using namespace Pokemon; - - -// Map source: the decomp (pret/pokediamond land_data narc_0007, 2026-10-31) -// with the signs and doors from its events file; Platinum's map_data_007 -// is the same. The rows from the doors down have been the decomp's since -// 2026-10-29; the four rows above the doors were the image's, and the -// grid now starts where the game's map does, four rows higher. -// Console checks: all three doors, five signs, the row below the doors east -// to the trees and north from it, the Lab's sign read facing west, the -// walk south from Route 202 stopping above the Mart (2026-10-29/30). -// Status: no checkpoint has run on this grid yet. 00.04, 00.05 and the -// Sandgem Center and Mart lady checkpoints passed with the image's rows -// above the doors; changed since: every tile is 4 rows lower (the grid -// begins at the map's edge), the road from Route 202 narrows on row 6 -// (the walk south from Route 202 stops at (29,5)), and the gap between -// the Lab's fence and the Center on the doors' row is four wide (11..14). -// Re-run them all. -// -// Decoded from Pokemon Diamond's collision table: cell (26,5) of the Sinnoh -// matrix, with the signs and doors from its events file. Local (x, y) = -// world (x - 160, z - 832); 34 x 32 tiles, the whole cell, so the grid's -// edges are where the game changes its location banner. Route 201 joins at -// column -64, row 7 (its row 4 is this grid's row 11); Route 202's road -// comes down onto row 0 at columns 24..29. -// -// Buildings are blocked; each door is the tile the player walks into, on -// the building's front row (row 10). Top left: Professor Rowan's lab, with a -// fence running west along row 10 to the map edge. Top middle: Pokemon -// Center. Top right: Poke Mart. Exits: west, rows 11..15 (Route 201); north, -// (24..29, 0) (Route 202: the road is 6 wide on rows 0..1, 10 wide on rows -// 2..5 and 6 wide again, columns 20..25, on rows 6..9); south, (20..25, 31) -// (the beach). -// -// The image squeezed the rows below the doors: it put both houses' doors -// three rows too high and the east house's wall where the game has open -// ground; r123a planned a west leg to that wall, ran on past it and entered -// the west house's door going north. The townspeople south of the Mart (a -// youngster and two breeders, who stand still in Diamond at (11,22) and -// (23,20)) wander on the console: not marked. Rowan, Barry and Dawn are -// hidden by story flags. -// -// Checked on the console: walking south from Route 202 along its column 30 -// stops above the Poke Mart, where the road narrows (counted as two rows -// above the signs' row on the image grid; the decomp has the wall at (29,6), -// so the stop is (29,5)), and walking west from there stops at (20,5). The -// lab's sign stands on row 11, in front of the fence: walking west along -// row 11 stops at it. -const TileGrid& grid(){ - return story_grid("SandgemTown"); -} - - -const TilePos ROUTE_202_ENTRY_STOP{29, 5}; -// The lab's door, between its two front windows. -const TilePos LAB_DOOR{8, 10}; -// The Pokemon Center's glass door. -const TilePos POKEMON_CENTER_DOOR{17, 10}; -// On the console, walking south along the road's west edge above it stops -// at (20,9), above it. -const TilePos POKEMON_CENTER_SIGN{20, 10}; -// The Poke Mart's door. -const TilePos POKE_MART_DOOR{27, 10}; -// Walking east along the doors' front row stops here, against the trees. -// Checked on the console (2026-10-30, CFR "walk"): east along row 12 (the -// path under the Lab's sign) from Route 201 stops at (29,12), and north from -// there stops here. From below the Center's sign (20,11), west stops at the -// Lab's sign, which reads facing west; south from there stops at the house -// 4 rows down, and north back at the sign's row; west of the house's north -// side is trees. A 200 ms hold south took one row; 300 ms took one or two. -const TilePos FRONT_ROW_EAST_END{29, 11}; - -std::vector below_sign_gap(){ - return {{21, 11}, {22, 11}, {23, 11}, {24, 11}}; -} - - - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h deleted file mode 100644 index cb5d223828..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h +++ /dev/null @@ -1,49 +0,0 @@ -/* BDSP AutoStory - Sandgem Town tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Sandgem Town as a tile grid, from the Diamond decompilation's collision - * table; BDSP keeps DP's tile layout. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SandgemTown_H -#define PokemonAutomation_PokemonBDSP_AutoStory_SandgemTown_H - -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace SandgemTown{ - - -const Pokemon::TileGrid& grid(); - -// Where the walk south from Route 202 down the road's east side stops, -// above the Poke Mart where the road narrows. -extern const Pokemon::TilePos ROUTE_202_ENTRY_STOP; -extern const Pokemon::TilePos LAB_DOOR; -extern const Pokemon::TilePos POKEMON_CENTER_DOOR; -// The sign east of the Pokemon Center's door. Walking north from row 14 in -// its column stops on the tile below it. -extern const Pokemon::TilePos POKEMON_CENTER_SIGN; -extern const Pokemon::TilePos POKE_MART_DOOR; -// The east end of the row below the Center's and the Mart's doors, at the -// trees: one known tile to plan the way north to Route 202 from. From the -// Mart's door, a tile either side of its column, no plan north is robust. -extern const Pokemon::TilePos FRONT_ROW_EAST_END; -// The doors' front row below the gap between the Center's sign and the -// Mart's, columns 21..24: the only way north from that row that passes no -// door. Walking north from any of them leaves town for Route 202. Walking -// north from anywhere else on the row between columns 18 and 26 stops at a -// sign or a wall; the Center's door is at 17, the Mart's at 27. -std::vector below_sign_gap(); - - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp new file mode 100644 index 0000000000..20012b1bcd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -0,0 +1,232 @@ +/* BDSP AutoStory - Story world + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +// The way a ledge is hopped, or nothing for any other tile. +std::optional ledge_direction(TileKind tile){ + switch (tile){ + case TileKind::LEDGE_NORTH: + return Direction::NORTH; + case TileKind::LEDGE_SOUTH: + return Direction::SOUTH; + case TileKind::LEDGE_WEST: + return Direction::WEST; + case TileKind::LEDGE_EAST: + return Direction::EAST; + case TileKind::WALL: + case TileKind::OPEN: + case TileKind::TALL_GRASS: + case TileKind::WATER: + case TileKind::DOOR: + case TileKind::SIGN: + return std::nullopt; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown TileKind."); +} + +} + + +void StoryWorld::add(std::string name, const Pokemon::MapData& map, const TilePos& offset){ + for (const Placed& placed : m_maps){ + if (placed.name == name){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Map placed twice: " + name); + } + } + Placed placed{std::move(name), map.tiles, {}, offset}; + for (const Pokemon::MapObject& object : map.objects){ + if (!object.wander){ + placed.occupied.push_back({object.x, object.y}); + } + } + check_overlap(placed.name, placed); + m_maps.push_back(std::move(placed)); + rebuild(); +} + +// Map images show a border of trees past their edges, so two maps may +// share walls with nobody on them, but nothing else. +void StoryWorld::check_overlap(const std::string& name, const Placed& map) const{ + const auto free_wall = [](const Placed& placed, const TilePos& pos){ + return placed.tiles.at(pos) == TileKind::WALL && + std::find(placed.occupied.begin(), placed.occupied.end(), pos) == placed.occupied.end(); + }; + for (const Placed& placed : m_maps){ + for (int y = 0; y < map.tiles.height; y++){ + for (int x = 0; x < map.tiles.width; x++){ + const TilePos other{map.offset.x + x - placed.offset.x, map.offset.y + y - placed.offset.y}; + if (placed.tiles.contains(other) && (!free_wall(map, {x, y}) || !free_wall(placed, other))){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Map {} overlaps {} at its tile {}.", name, placed.name, Pokemon::to_string(TilePos{x, y}) + )); + } + } + } + } +} + +void StoryWorld::rebuild(){ + TilePos low = m_maps[0].offset; + TilePos high = low; + for (const Placed& placed : m_maps){ + low.x = std::min(low.x, placed.offset.x); + low.y = std::min(low.y, placed.offset.y); + high.x = std::max(high.x, placed.offset.x + placed.tiles.width); + high.y = std::max(high.y, placed.offset.y + placed.tiles.height); + } + // Block and uncover lists are in world tiles of the old origin. + const TilePos shift{m_origin.x - low.x, m_origin.y - low.y}; + for (std::vector* list : {&m_blocked, &m_uncovered}){ + for (TilePos& pos : *list){ + pos = {pos.x + shift.x, pos.y + shift.y}; + } + } + m_origin = low; + m_cells = Pokemon::Grid{high.x - low.x, high.y - low.y, {}}; + m_cells.cells.resize((size_t)m_cells.width * m_cells.height); + for (auto iter = m_maps.rbegin(); iter != m_maps.rend(); ++iter){ + const TilePos corner{iter->offset.x - low.x, iter->offset.y - low.y}; + for (int y = 0; y < iter->tiles.height; y++){ + for (int x = 0; x < iter->tiles.width; x++){ + m_cells.at({corner.x + x, corner.y + y}) = Cell{true, iter->tiles.at({x, y}), false}; + } + } + for (const TilePos& pos : iter->occupied){ + m_cells.at({corner.x + pos.x, corner.y + pos.y}).occupied = true; + } + } + for (const TilePos& pos : m_blocked){ + if (Cell* blocked = cell(pos)){ + blocked->occupied = true; + } + } + for (const TilePos& pos : m_uncovered){ + if (Cell* uncovered = cell(pos)){ + uncovered->covered = false; + } + } +} + +const StoryWorld::Cell* StoryWorld::cell(const TilePos& pos) const{ + if (!m_cells.contains(pos) || !m_cells.at(pos).covered){ + return nullptr; + } + return &m_cells.at(pos); +} +StoryWorld::Cell* StoryWorld::cell(const TilePos& pos){ + if (!m_cells.contains(pos) || !m_cells.at(pos).covered){ + return nullptr; + } + return &m_cells.at(pos); +} + + +bool StoryWorld::covered(const TilePos& pos) const{ + return cell(pos) != nullptr; +} + +std::optional StoryWorld::tile(const TilePos& pos) const{ + const Cell* found = cell(pos); + if (found == nullptr){ + return std::nullopt; + } + return found->tile; +} + +bool StoryWorld::occupied(const TilePos& pos) const{ + const Cell* found = cell(pos); + return found != nullptr && found->occupied; +} + +bool StoryWorld::standable(const TilePos& pos) const{ + const Cell* found = cell(pos); + return found != nullptr && !found->occupied && + (found->tile == TileKind::OPEN || found->tile == TileKind::TALL_GRASS); +} + +std::optional StoryWorld::step(const TilePos& from, Direction direction) const{ + const TilePos next = from.next(direction); + if (standable(next)){ + return next; + } + const Cell* found = cell(next); + if (found == nullptr || found->occupied || ledge_direction(found->tile) != direction){ + return std::nullopt; + } + const TilePos landing = next.next(direction); + if (standable(landing)){ + return landing; + } + return std::nullopt; +} + +bool StoryWorld::at_wall(const TilePos& pos, Direction direction) const{ + const std::optional next = tile(pos.next(direction)); + return next && *next != TileKind::DOOR && !step(pos, direction).has_value(); +} + +void StoryWorld::block(const TilePos& pos){ + if (Cell* found = cell(pos)){ + found->occupied = true; + m_blocked.push_back(pos); + } +} + +void StoryWorld::uncover(const TilePos& pos){ + if (Cell* found = cell(pos)){ + found->covered = false; + m_uncovered.push_back(pos); + } +} + + +TilePos StoryWorld::to_world(const std::string& map, const TilePos& local) const{ + for (const Placed& placed : m_maps){ + if (placed.name == map){ + return {placed.offset.x - m_origin.x + local.x, placed.offset.y - m_origin.y + local.y}; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown map: " + map); +} + +std::optional StoryWorld::to_local(const TilePos& world) const{ + for (const Placed& placed : m_maps){ + const TilePos local{world.x + m_origin.x - placed.offset.x, world.y + m_origin.y - placed.offset.y}; + if (placed.tiles.contains(local)){ + return MapTile{placed.name, local}; + } + } + return std::nullopt; +} + +std::string StoryWorld::describe(const TilePos& world) const{ + const std::optional local = to_local(world); + if (!local){ + return "world " + Pokemon::to_string(world); + } + return local->map + " " + Pokemon::to_string(local->pos); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h new file mode 100644 index 0000000000..236e1972b2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -0,0 +1,112 @@ +/* BDSP AutoStory - Story world + * + * From: https://github.com/PokemonAutomation/ + * + * Several story maps placed side by side on one world grid, so one plan can + * cross from a route into a town. What the tiles mean for walking in BDSP: + * open ground and tall grass are stood on; a ledge is hopped the arrow's + * way; walls, water and signs stop the player; a door is walked into. A + * person or an item standing still blocks their tile; a wanderer does not + * (the walker waits for them). Tiles no map covers are off the maps: a + * plan may not end there, but walking into one is not a wall, since it may + * be an exit. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A tile of one of the maps, in that map's own coordinates. +struct MapTile{ + std::string map; + Pokemon::TilePos pos; +}; + + +class StoryWorld{ +public: + // Places `map` under `name` with its tile (0,0) at `offset`. Offsets are + // relative to each other and may be negative. Maps may overlap only + // where both are walls with nobody on them; the map placed first holds + // those tiles. Throws InternalProgramError if the name is taken or the + // maps conflict. World tile (0,0) is the top-left corner of all the + // maps together. + void add(std::string name, const Pokemon::MapData& map, const Pokemon::TilePos& offset); + + int width() const{ return m_cells.width; } + int height() const{ return m_cells.height; } + + // Whether a map holds this world tile. + bool covered(const Pokemon::TilePos& pos) const; + // The tile, or nothing off the maps. + std::optional tile(const Pokemon::TilePos& pos) const; + // Whether someone or something stands still on this tile, or it was + // blocked with block(). + bool occupied(const Pokemon::TilePos& pos) const; + + // Whether the player can stand on this tile. + bool standable(const Pokemon::TilePos& pos) const; + // Where one step from `from` lands, or nothing if the player is stopped. + // A step onto a ledge the arrow's way hops to the tile past it. + std::optional step(const Pokemon::TilePos& from, Pokemon::Direction direction) const; + // Whether a step from `pos` is refused by a tile that holds the player + // in place. Doors and tiles off the maps are not walls: walking into a + // door enters the building, and ground off the maps may be an exit. + bool at_wall(const Pokemon::TilePos& pos, Pokemon::Direction direction) const; + + // Blocks a tile found in the way on the console. Tiles off the maps + // are left alone. + void block(const Pokemon::TilePos& pos); + // Takes a tile off the maps: a tile a walk must not cross or stop on + // that the game lets us walk (a trainer's line of sight). + void uncover(const Pokemon::TilePos& pos); + + // Throws InternalProgramError for a map name it does not have. + Pokemon::TilePos to_world(const std::string& map, const Pokemon::TilePos& local) const; + // The map that holds a world tile, or nothing between maps. + std::optional to_local(const Pokemon::TilePos& world) const; + // "Route 201 (45, 3)", or "world (x, y)" if no map holds it. + std::string describe(const Pokemon::TilePos& world) const; + +private: + struct Placed{ + std::string name; + Pokemon::Grid tiles; + std::vector occupied; // local tiles + Pokemon::TilePos offset; + }; + struct Cell{ + bool covered = false; + Pokemon::TileKind tile = Pokemon::TileKind::WALL; + bool occupied = false; + }; + + void check_overlap(const std::string& name, const Placed& map) const; + void rebuild(); + const Cell* cell(const Pokemon::TilePos& pos) const; + Cell* cell(const Pokemon::TilePos& pos); + + std::vector m_maps; + Pokemon::TilePos m_origin; // offset of world tile (0,0) + Pokemon::Grid m_cells; + std::vector m_blocked; // world tiles, kept across add() + std::vector m_uncovered; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp deleted file mode 100644 index b7d0f60bb6..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* BDSP AutoStory - Twinleaf Town tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_TwinleafTown.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace TwinleafTown{ - -using namespace Pokemon; - - -// Map source: the decomp (Diamond land_data 0000 = Platinum map_data_000, -// 2026-10-31) with the objects from its events file. -// Console checks: none yet. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0000: one cell of the -// Sinnoh matrix at column 3, row 27; map_data_000 in pret/pokeplatinum), -// with the objects from its events file (zone_event narc_0389, -// events_twinleaf_town.json in Platinum); BDSP keeps Diamond/Pearl's layout. -// Local (x, y) = world (x - 96, z - 864); 32 x 32 tiles. The pond at the -// bottom, (12..19, 27..31), is water, '#'. The pockets (7..10, 1..2) and -// (21..24, 1..2) are walkable in the data but closed in. -// Exit: Route 201 north through columns 12 to 19 at row 0 (the route's -// bottom rows open the same eight columns). The player's house is the -// south-east one, door (20, 21), and Barry's the north-west one, door (9, -// 11): behind (20, 21) the interior has Mom and the TV, behind (9, 11) only -// Barry's mother, and Platinum's scripts name the mailbox at (18, 21) the -// player's. pret/pokediamond's map constants call them the other way round -// (MAP_TWINLEAF_PLAYER_HOUSE_1F is the house behind (9, 11)); the interiors -// say otherwise. Objects, from the events file: -// door (20, 21), the player's house; its mailbox (18, 21), read like a -// sign, 'S'; -// door (9, 11), Barry's house; its mailbox (13, 11), 'S'; Barry himself -// stands on the door tile at the start (looks south, hidden by flag 402): -// the door keeps its 'D'; -// door (20, 11) to the north-east house; door (10, 21) to the south-west -// house; -// map signpost (16, 14); -// Guitarist (12, 5), looks north, west and east, not a trainer; -// Collector (12, 25), looks around, not a trainer; -// Pokemon Breeder F wanders around (23, 14), columns 22 to 24, row 14: off -// the grid. -// No trainers. Platinum decodes the same terrain and objects; its one extra, -// an arrow signpost at world (109, 856), stands in Route 201's cell. -const TileGrid& grid(){ - return story_grid("TwinleafTown"); -} - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h deleted file mode 100644 index 7e4de02893..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h +++ /dev/null @@ -1,27 +0,0 @@ -/* BDSP AutoStory - Twinleaf Town tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see - * the .cpp's header for the cells, the offset and the objects. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TwinleafTown_H -#define PokemonAutomation_PokemonBDSP_AutoStory_TwinleafTown_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace TwinleafTown{ - - -const Pokemon::TileGrid& grid(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp deleted file mode 100644 index a696281964..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* BDSP AutoStory - Verity Lakefront tiles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_MapGrids.h" -#include "PokemonBDSP_AutoStory_VerityLakefront.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace VerityLakefront{ - -using namespace Pokemon; - - -// Map source: the decomp (Diamond land_data 0004 = Platinum map_data_004, -// 2026-10-31) with the objects from its events file. -// Console checks: none yet. -// Status: no checkpoint passes on this grid yet. -// -// Decoded from Pokemon Diamond's collision table for this map (the -// pret/pokediamond decompilation, -// files/fielddata/land_data/land_data_release/narc_0004: one cell of the -// Sinnoh matrix at column 2, row 26; map_data_004 in pret/pokeplatinum), -// with the objects from its events file (zone_event narc_0319, -// events_verity_lakefront.json in Platinum); BDSP keeps Diamond/Pearl's -// layout. Local (x, y) = world (x - 64, z - 832); 32 x 32 tiles. The map -// header covers four cells (columns 1 and 2, rows 25 and 26); the other -// three are trees and an 8 x 8 patch of shallow water, so only this one is -// kept. The pocket (0..3, 0..3) is that water (puddle, behaviour 0x16), -// closed in. -// Route 201's west edge is this cell's column 31: open on rows 14 to 18 (the -// upper level) and 20 to 23 (the lower), with Route 201's x = 96 at our x = -// 32. From the upper level the way west is over the ledge at column 20 (rows -// 14 to 18, jumped west, shown as a wall), landing on columns 14 to 19; the -// lower level joins it at (16..19, 20). The ledges on row 19, 'v', drop -// south onto the lower level. The lake's entrance is the warp tiles (16, 11) -// and (17, 11), walked onto heading north, written as '.'; their destination -// is Lake Verity, or its Galactic version once that story state is set. -// Objects, from the events file: -// arrow signpost (15, 14), beside the path to the lake; -// Barry (16, 11), looks south, hidden by flag 435, standing on the warp -// tile: '.' wins; -// no one else, and no trainers. -// Platinum decodes the same terrain; it has no Barry object here and calls -// the sign a trainer-tips signpost. -const TileGrid& grid(){ - return story_grid("VerityLakefront"); -} - -} -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h deleted file mode 100644 index 3ededdc534..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h +++ /dev/null @@ -1,27 +0,0 @@ -/* BDSP AutoStory - Verity Lakefront tiles - * - * From: https://github.com/PokemonAutomation/ - * - * Decoded from the Pokemon Diamond decompilation (pret/pokediamond); see - * the .cpp's header for the cells, the offset and the objects. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_VerityLakefront_H -#define PokemonAutomation_PokemonBDSP_AutoStory_VerityLakefront_H - -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace VerityLakefront{ - - -const Pokemon::TileGrid& grid(); - - -} -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp deleted file mode 100644 index a42684c862..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* BDSP AutoStory Map Grid Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "Pokemon/Navigation/Pokemon_MapSet.h" -#include "Pokemon/Navigation/Pokemon_TileGrid.h" -#include "Data/PokemonBDSP_AutoStory_MapGrids.h" -#include "Data/PokemonBDSP_AutoStory_Route202.h" -#include "Data/PokemonBDSP_AutoStory_SandgemTown.h" -#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" -#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" -#include "PokemonBDSP_AutoStory_MapGrid_Tests.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -using Pokemon::Direction; -using Pokemon::MapSet; -using Pokemon::TileGrid; -using Pokemon::TilePos; -using Pokemon::TileType; - -// 00.04's training walks up and down the catch patch, three grass rows -// between tree rows, and needs the walk there to end in its grass: r253 -// and r254 loaded the catch's save in the pocket behind the trees at -// (21, 29), planned from the catch spot instead, and walked up and down -// the lawn east of the grass for three minutes without a battle. -class Test_Route202CatchGrass : public UnitTest{ -public: - Test_Route202CatchGrass() - : UnitTest("PokemonBDSP::AutoStory - Route 202: the catch patch and the walk to it") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - const TileGrid& route = Route202::grid(); - for (int x = 15; x <= 20; x++){ - const Pokemon::WallHit up = Pokemon::walk_to_wall(route, {x, 27}, Direction::NORTH); - const Pokemon::WallHit down = Pokemon::walk_to_wall(route, {x, 25}, Direction::SOUTH); - if (!(up.stop == TilePos{x, 25}) || !(down.stop == TilePos{x, 27})){ - return "Catch patch column " + std::to_string(x) + ": north from row 27 stops at " + - Pokemon::to_string(up.stop) + ", south from row 25 at " + Pokemon::to_string(down.stop) + - "; expected rows 25 and 27, between tree rows."; - } - } - const MapSet& maps = story_maps(); - const std::vector area = story_after_training_area(); - const auto in_grass = [&](const TilePos& pos){ - return maps.world().at(pos) == TileType::TALL_GRASS && std::find(area.begin(), area.end(), pos) != area.end(); - }; - // As walk_route() plans: the route costs, else the default costs. - // From the whole area the catch's save may stand in, and from the - // pocket behind the trees alone, where r252 saved. - const TilePos pocket = maps.to_world(MAP_ROUTE_202, {21, 29}); - const std::vector>> starts{ - {"the catch's save area", story_catch_save_area()}, - {"the pocket behind the trees", {pocket}}, - }; - std::optional> legs; - for (const auto& [name, from] : starts){ - legs = Pokemon::plan_robust_route(maps.world(), from, in_grass, route_plan_costs()); - if (!legs){ - legs = Pokemon::plan_robust_route(maps.world(), from, in_grass, Pokemon::RobustPlanCosts()); - } - if (!legs || legs->empty()){ - return "From " + name + " to the catch grass: no plan."; - } - for (const TilePos& pos : legs->back().after){ - if (!in_grass(pos)){ - return "From " + name + " to the catch grass: the walk may end on " + maps.describe(pos) + ", not in the grass."; - } - } - logger.log("From " + name + " to the catch grass: " + std::to_string(legs->size()) + " legs, ending in the grass."); - } - return true; - } -}; - -// 00.04's way to Sandgem's Pokemon Center ends below the Center's sign, -// walking north into it, then taps west along the doors' row to below the -// door: the row must be open there, the door straight north of where the -// taps end, and nothing else (a sign, the Mart's door) on the way. -class Test_SandgemCenterApproach : public UnitTest{ -public: - Test_SandgemCenterApproach() - : UnitTest("PokemonBDSP::AutoStory - Sandgem Town: below the Center's sign to below its door") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - const TileGrid& town = SandgemTown::grid(); - const TilePos sign = SandgemTown::POKEMON_CENTER_SIGN; - const TilePos door = SandgemTown::POKEMON_CENTER_DOOR; - if (town.at(sign) != TileType::SIGN || town.at(door) != TileType::DOOR || door.y != sign.y || door.x >= sign.x){ - return "The Center's sign " + Pokemon::to_string(sign) + " and door " + Pokemon::to_string(door) + - " are not a sign and a door west of it on one row."; - } - TilePos pos = sign.next(Direction::SOUTH); - for (int tap = 0; tap < sign.x - door.x; tap++){ - const std::optional next = town.step(pos, Direction::WEST); - if (!next){ - return "West from " + Pokemon::to_string(pos) + " is blocked."; - } - if (town.at(next->next(Direction::NORTH)) != TileType::BLOCKED && *next != door.next(Direction::SOUTH)){ - return "Above " + Pokemon::to_string(*next) + " is not the Center's wall."; - } - pos = *next; - } - if (!(pos == door.next(Direction::SOUTH))){ - return "The taps end at " + Pokemon::to_string(pos) + ", not below the door " + Pokemon::to_string(door) + "."; - } - logger.log("Sandgem: below the sign " + Pokemon::to_string(sign.next(Direction::SOUTH)) + ", " + - std::to_string(sign.x - door.x) + " taps west to below the door " + Pokemon::to_string(door) + "."); - return true; - } -}; - -// After training, 00.04 walks from wherever the training left us into -// Sandgem, to where the road stops above the Mart, with the default costs -// (heal_at_sandgem_center()): from the whole area and from each of its -// tiles alone, a plan must exist and end there. -class Test_TrainingToSandgem : public UnitTest{ -public: - Test_TrainingToSandgem() - : UnitTest("PokemonBDSP::AutoStory - Route 202: from every tile of the training area into Sandgem") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - const MapSet& maps = story_maps(); - const TilePos entry = maps.to_world(MAP_SANDGEM_TOWN, SandgemTown::ROUTE_202_ENTRY_STOP); - const std::vector area = story_after_training_area(); - std::vector> starts{area}; - for (const TilePos& pos : area){ - starts.push_back({pos}); - } - for (const std::vector& from : starts){ - const auto legs = Pokemon::plan_robust_route(maps.world(), from, - [&](const TilePos& pos){ return pos == entry; }, Pokemon::RobustPlanCosts()); - const std::string name = from.size() == 1 ? maps.describe(from[0]) : "the whole training area"; - if (!legs || legs->empty()){ - return "From " + name + " into Sandgem: no plan."; - } - if (legs->back().after.size() != 1 || !(legs->back().after[0] == entry)){ - return "From " + name + " into Sandgem: the plan does not end on " + maps.describe(entry) + "."; - } - logger.log("From " + name + " into Sandgem: " + std::to_string(legs->size()) + " legs."); - } - return true; - } -}; - -// The maps (the JSON files built in, bdsp_map_json()) all parse through -// the shared loader into tile grids, each named as its file. -class Test_BuiltInMaps : public UnitTest{ -public: - Test_BuiltInMaps() - : UnitTest("PokemonBDSP::AutoStory - Map grids: the built-in JSON maps load") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - if (bdsp_map_json().empty()){ - return std::string("No built-in maps."); - } - for (const auto& [name, json] : bdsp_map_json()){ - try{ - const TileGrid& grid = story_grid(name); - logger.log(std::format("{}: {} x {}", name, grid.width(), grid.height())); - }catch (Exception& e){ - return std::format("{}: {}: {}", name, e.name(), e.message()); - } - } - return true; - } -}; - -// The JSON glyphs as BDSP tiles: every BDSP tile and a person standing; -// water and a wanderer have none. -struct GlyphCase{ - std::string name; - std::string json; - // The grid's rows, or empty when reading it must throw. - std::vector rows; -}; - -class Test_MapGlyphs : public UnitTest{ -public: - Test_MapGlyphs() - : UnitTest("PokemonBDSP::AutoStory - Map grids: JSON glyphs as tile grids") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::vector cases{ - { - .name = "every BDSP tile, and a person standing", - .json = R"({"name": "T", "source": {"decomp_file": "f", "revision": "r", "date": "d"}, - "tiles": ["#.~", "vDS"], - "objects": [{"name": "npc_1_0", "kind": "npc", "x": 1, "y": 0}]})", - .rows = {"#N\"", "vDS"}, - }, - { - .name = "water has no BDSP tile", - .json = R"({"name": "T", "source": {"decomp_file": "f", "revision": "r", "date": "d"}, "tiles": ["#w"]})", - .rows = {}, - }, - { - .name = "a wanderer has no BDSP tile", - .json = R"({"name": "T", "source": {"decomp_file": "f", "revision": "r", "date": "d"}, "tiles": ["#.."], - "objects": [{"name": "lass", "kind": "npc", "x": 1, "y": 0, "wander": {"x0": 1, "y0": 0, "x1": 2, "y1": 0}}]})", - .rows = {}, - }, - }; - for (const GlyphCase& item : cases){ - std::optional grid; - std::string error; - try{ - grid = tile_grid_from_map(Pokemon::parse_map(parse_json(item.json), item.name)); - }catch (ParseException& e){ - error = e.message(); - } - if (item.rows.empty() != !grid){ - return item.name + (grid ? ": read a grid, expected a ParseException." : ": expected a grid, read: " + error); - } - if (grid){ - if (const std::optional difference = grid_difference(*grid, TileGrid(item.rows))){ - return item.name + ": differs from the expected rows at " + *difference + "."; - } - } - } - return true; - } -}; - -} - - -void add_tests_AutoStory_MapGrids(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); - database.add(); -} - - -} -} -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h deleted file mode 100644 index a7f7250b2b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h +++ /dev/null @@ -1,28 +0,0 @@ -/* BDSP AutoStory Map Grid Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_MapGrid_Tests_H -#define PokemonAutomation_PokemonBDSP_AutoStory_MapGrid_Tests_H - -#include "Common/Cpp/TestRunners/UnitTest.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -// Offline checks of the decomp grids against what the console showed: -// Route 202's catch patch between tree rows and the walks in and out of -// it, and Sandgem's Pokemon Center door, its sign and the row below them. -void add_tests_AutoStory_MapGrids(UnitTestDatabase& database); - - - -} -} -} -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp new file mode 100644 index 0000000000..ea74104879 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -0,0 +1,195 @@ +/* BDSP AutoStory Route Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The route planner (Data/PokemonBDSP_AutoStory_RoutePlanner.h) on small + * synthetic maps: walks to a wall, plans that end on walls, robust plans + * that bring several possible tiles together, and trainers' sight lines. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_RoutePlanner_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::TilePos; + +StoryWorld make_world(const std::vector& rows){ + Pokemon::MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + +std::string describe(const std::vector& legs){ + std::string text; + for (const PlannedLeg& leg : legs){ + text += (text.empty() ? "" : "; ") + to_string(leg); + } + return text; +} + + +struct WallCase{ + std::string name; + std::vector rows; + TilePos from; + Direction direction = Direction::EAST; + TilePos stop; + size_t tiles = 0; + bool anchored = false; +}; + +class Test_WalkToWall : public UnitTest{ +public: + Test_WalkToWall() + : UnitTest("PokemonBDSP::AutoStory - Route planner: walking until stopped") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "to a wall", .rows = {"....#"}, .stop = {3, 0}, .tiles = 3, .anchored = true}, + {.name = "off the map", .rows = {"...."}, .stop = {3, 0}, .tiles = 3, .anchored = false}, + {.name = "into a door", .rows = {"..D"}, .stop = {1, 0}, .tiles = 1, .anchored = false}, + {.name = "over a ledge, which counts 2", .rows = {".", "v", ".", "#"}, .direction = Direction::SOUTH, + .stop = {0, 2}, .tiles = 2, .anchored = true}, + }; + for (const WallCase& item : cases){ + const WallHit hit = walk_to_wall(make_world(item.rows), item.from, item.direction); + if (!(hit.stop == item.stop) || hit.tiles != item.tiles || hit.anchored != item.anchored){ + return std::format("{}: stops at {} after {} tiles, anchored {}; expected {} after {}, anchored {}.", item.name, + Pokemon::to_string(hit.stop), hit.tiles, hit.anchored, Pokemon::to_string(item.stop), item.tiles, item.anchored); + } + } + return true; + } +}; + + +// plan_tile_route() around a pillar: two legs, both to a wall, that trace +// to the goal. +class Test_PlanTileRoute : public UnitTest{ +public: + Test_PlanTileRoute() + : UnitTest("PokemonBDSP::AutoStory - Route planner: legs to walls around a pillar") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld world = make_world({"#####", "#...#", "#.#.#", "#...#", "#####"}); + const std::optional> legs = plan_tile_route(world, {1, 1}, {3, 3}); + if (!legs || legs->size() != 2 || !(*legs)[0].ends_at_wall || !(*legs)[1].ends_at_wall){ + return std::string("Expected two legs, both to a wall."); + } + if (!(trace_legs(world, {1, 1}, *legs).back() == TilePos{3, 3})){ + return std::string("The legs do not end on (3, 3)."); + } + logger.log(std::format("{}, {}", to_string((*legs)[0]), to_string((*legs)[1]))); + const std::optional> none = plan_tile_route(world, {1, 1}, {1, 1}); + if (!none || !none->empty()){ + return std::string("A route to the start is not empty."); + } + return true; + } +}; + + +// plan_robust_route() from one or several tiles to a goal, with the open +// legs' error as the costs give it. +struct RobustCase{ + std::string name; + std::vector from; + TilePos goal; + RobustPlanCosts costs; + // The plan as to_string() writes it, or empty when there is none. + std::string legs; +}; + +class Test_PlanRobustRoute : public UnitTest{ +public: + Test_PlanRobustRoute() + : UnitTest("PokemonBDSP::AutoStory - Route planner: robust plans") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StoryWorld world = make_world({"######", "#....#", "######"}); + RobustPlanCosts exact_step; + exact_step.exact_open_tiles = 1; + const std::vector cases{ + {.name = "two starts meet at the wall", .from = {{1, 1}, {2, 1}}, .goal = {4, 1}, .legs = "east 3 (to wall) to (4, 1)"}, + {.name = "an open stop is never sure", .from = {{1, 1}}, .goal = {3, 1}, .legs = ""}, + {.name = "unless a one-tile step is exact", .from = {{1, 1}}, .goal = {3, 1}, .costs = exact_step, + .legs = "east 3 (to wall) to (4, 1); west 1 (open) to (3, 1)"}, + }; + for (const RobustCase& item : cases){ + const auto legs = plan_robust_route(world, item.from, [&](const TilePos& pos){ return pos == item.goal; }, item.costs); + const std::string read = legs ? describe(*legs) : ""; + if (read != item.legs){ + return std::format("{}: planned \"{}\", expected \"{}\".", item.name, read, item.legs); + } + } + try{ + plan_robust_route(world, TilePos{0, 0}, TilePos{4, 1}); + return std::string("A start on a wall did not throw."); + }catch (InternalProgramError&){} + return true; + } +}; + + +// A trainer's sight stops at the first tile the player cannot stand on, +// and a leg through it is reported; a leg that is stopped throws. +class Test_TrainerSight : public UnitTest{ +public: + Test_TrainerSight() + : UnitTest("PokemonBDSP::AutoStory - Route planner: trainers' sight lines") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StoryWorld world = make_world({".....", ".....", "..#.."}); + const TrainerSight trainer{.name = "lass", .pos = {2, 0}, .facing = Direction::SOUTH, .range = 4}; + if (sight_tiles(world, trainer) != std::vector{{2, 1}}){ + return std::string("The lass's sight is not the one tile above the rock."); + } + const std::vector legs{{Direction::EAST, 4, true}, {Direction::SOUTH, 1, false}}; + const auto crossings = legs_crossing_sight(world, {0, 1}, legs, {trainer}); + if (crossings != std::vector>{{"lass"}, {}}){ + return std::string("Only the first leg crosses the lass's sight."); + } + try{ + trace_legs(world, {0, 1}, {{Direction::SOUTH, 2, false}}); + return std::string("A leg off the map did not throw."); + }catch (InternalProgramError&){} + return true; + } +}; + +} + + +void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h new file mode 100644 index 0000000000..526d0fe601 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Route Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the route planner on synthetic maps. +void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp new file mode 100644 index 0000000000..66e345f140 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -0,0 +1,193 @@ +/* BDSP AutoStory Story World Tests + * + * From: https://github.com/PokemonAutomation/ + * + * StoryWorld on small synthetic maps: what each tile does to a step, maps + * joined at offsets, and tiles blocked or taken off the maps. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_StoryWorld_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::MapData; +using Pokemon::TilePos; + +// A map of these rows, with a person standing still on each `standing` +// tile and one wandering on each `wandering` tile. +MapData make_map( + const std::vector& rows, + const std::vector& standing = {}, + const std::vector& wandering = {} +){ + MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + for (const TilePos& pos : standing){ + map.objects.push_back({.name = "standing", .x = pos.x, .y = pos.y}); + } + for (const TilePos& pos : wandering){ + map.objects.push_back({.name = "wandering", .x = pos.x, .y = pos.y, .wander = Pokemon::WanderBox{pos.x, pos.y, pos.x, pos.y}}); + } + return map; +} + +StoryWorld make_world(const MapData& map){ + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + + +// One step from (1, 1) of a 3 x 3 map whose middle tile (the step's +// target) is `target`, and whether the player is held at a wall there. +struct StepCase{ + std::string name; + std::vector rows; + std::vector standing; + std::vector wandering; + TilePos from; + Direction direction = Direction::NORTH; + std::optional lands; + bool at_wall = false; +}; + +class Test_StoryWorldSteps : public UnitTest{ +public: + Test_StoryWorldSteps() + : UnitTest("PokemonBDSP::AutoStory - Story world: what each tile does to a step") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "open ground", .rows = {".", "."}, .from = {0, 1}, .lands = TilePos{0, 0}}, + {.name = "tall grass", .rows = {"~", "."}, .from = {0, 1}, .lands = TilePos{0, 0}}, + {.name = "a wall", .rows = {"#", "."}, .from = {0, 1}, .at_wall = true}, + {.name = "water", .rows = {"w", "."}, .from = {0, 1}, .at_wall = true}, + {.name = "a sign", .rows = {"S", "."}, .from = {0, 1}, .at_wall = true}, + {.name = "a door is not a wall", .rows = {"D", "."}, .from = {0, 1}}, + {.name = "off the map is not a wall", .rows = {"."}, .from = {0, 0}}, + {.name = "a south ledge hops south", .rows = {".", "v", "."}, .direction = Direction::SOUTH, .lands = TilePos{0, 2}}, + {.name = "a south ledge stops north", .rows = {".", "v", "."}, .from = {0, 2}, .at_wall = true}, + {.name = "a west ledge hops west", .rows = {".<."}, .from = {2, 0}, .direction = Direction::WEST, .lands = TilePos{0, 0}}, + {.name = "a west ledge stops east", .rows = {".<."}, .direction = Direction::EAST, .at_wall = true}, + {.name = "a ledge onto a wall stops", .rows = {".", "v", "#"}, .direction = Direction::SOUTH, .at_wall = true}, + {.name = "a person standing still", .rows = {".", "."}, .standing = {{0, 0}}, .from = {0, 1}, .at_wall = true}, + {.name = "a wanderer does not block", .rows = {".", "."}, .wandering = {{0, 0}}, .from = {0, 1}, .lands = TilePos{0, 0}}, + }; + for (const StepCase& item : cases){ + const StoryWorld world = make_world(make_map(item.rows, item.standing, item.wandering)); + const std::optional lands = world.step(item.from, item.direction); + if (lands != item.lands){ + return std::format("{}: lands on {}, expected {}.", item.name, + lands ? Pokemon::to_string(*lands) : "nothing", item.lands ? Pokemon::to_string(*item.lands) : "nothing"); + } + if (world.at_wall(item.from, item.direction) != item.at_wall){ + return std::format("{}: at_wall() is {}, expected {}.", item.name, !item.at_wall, item.at_wall); + } + } + return true; + } +}; + + +// Two maps joined: tiles of each at their offsets, the gap between them +// off the maps, and a shared wall border allowed where nothing else is. +class Test_StoryWorldJoin : public UnitTest{ +public: + Test_StoryWorldJoin() + : UnitTest("PokemonBDSP::AutoStory - Story world: maps joined at offsets") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryWorld world; + world.add("West", make_map({"##", ".#"}), {0, 0}); + world.add("East", make_map({"#.", "#~"}), {1, -1}); + const std::vector> described{ + {{0, 2}, "West (0, 1)"}, + {{2, 0}, "East (1, 0)"}, + {{1, 1}, "West (1, 0)"}, // the shared wall: the first map holds it + {{2, 2}, "world (2, 2)"}, + }; + for (const auto& [pos, text] : described){ + if (world.describe(pos) != text){ + return std::format("{}: described as \"{}\", expected \"{}\".", Pokemon::to_string(pos), world.describe(pos), text); + } + } + if (world.width() != 3 || world.height() != 3 || world.covered({2, 2}) || !world.standable({2, 1})){ + return std::string("The joined world is not 3 x 3 with East's grass at (2, 1) and nothing at (2, 2)."); + } + if (!(world.to_world("East", {0, 0}) == TilePos{1, 0})){ + return "East (0, 0) is world " + Pokemon::to_string(world.to_world("East", {0, 0})) + ", expected (1, 0)."; + } + try{ + world.add("Overlap", make_map({"."}), {0, 1}); + return std::string("Adding a map over open ground did not throw."); + }catch (InternalProgramError&){} + try{ + world.to_world("North", {0, 0}); + return std::string("to_world() of an unknown map did not throw."); + }catch (InternalProgramError&){} + return true; + } +}; + + +// block() and uncover() change what a tile does, and survive a map added +// later that moves the world's origin. +class Test_StoryWorldBlockUncover : public UnitTest{ +public: + Test_StoryWorldBlockUncover() + : UnitTest("PokemonBDSP::AutoStory - Story world: blocked and uncovered tiles") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryWorld world; + world.add("Road", make_map({"...."}), {0, 0}); + world.block({1, 0}); + world.uncover({2, 0}); + if (world.step({0, 0}, Direction::EAST) || !world.at_wall({0, 0}, Direction::EAST)){ + return std::string("A blocked tile is not a wall."); + } + if (world.covered({2, 0}) || world.at_wall({3, 0}, Direction::WEST)){ + return std::string("An uncovered tile is still on the map, or a wall."); + } + world.add("North", make_map({"#"}), {0, -1}); + const TilePos blocked = world.to_world("Road", {1, 0}); + const TilePos uncovered = world.to_world("Road", {2, 0}); + if (!world.occupied(blocked) || world.covered(uncovered) || !world.standable(world.to_world("Road", {3, 0}))){ + return std::string("Adding a map lost the blocked or uncovered tile."); + } + return true; + } +}; + +} + + +void add_tests_AutoStory_StoryWorld(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h new file mode 100644 index 0000000000..0fee678878 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Story World Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the story world: tile rules, joins, blocked and uncovered tiles. +void add_tests_AutoStory_StoryWorld(UnitTestDatabase& database); + + +} +} +} +#endif From dc74ccb247dc5e47260c5c31e8fc0ae0fd9c5862 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:37:44 -0800 Subject: [PATCH 08/74] BDSP navigation: the story code reads the JSON maps; the per-map grids go StoryMaps, RouteRecords, Segment00Lines and PlanCosts now place story_map()s in StoryWorlds and take their named tiles from map_point()/map_region(). The trainers' sight lists move from the per-map files into StoryMaps. Removed: the per-map Data files, MapGrids, MAPS.md (its rules are in devtools/maps/bdsp_maps.py), the old MapGrid tests, and the generic Pokemon_TileGrid and Pokemon_MapSet. The tests are split by topic: story world, route planner, story maps (with the route records traced on their maps) and Segment 00's lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 8 +- .../Data/PokemonBDSP_AutoStory_PlanCosts.cpp | 1 - .../Data/PokemonBDSP_AutoStory_PlanCosts.h | 10 +- .../PokemonBDSP_AutoStory_RouteRecords.cpp | 376 ++++++------ .../Data/PokemonBDSP_AutoStory_RouteRecords.h | 134 ++--- .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 301 +++++----- .../PokemonBDSP_AutoStory_Segment00Lines.h | 157 +++-- .../Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 555 ++++++++++-------- .../Data/PokemonBDSP_AutoStory_StoryMaps.h | 238 ++++---- .../PokemonBDSP_AutoStory_Segment00_Tests.cpp | 481 +++++++-------- .../PokemonBDSP_AutoStory_Segment00_Tests.h | 4 +- .../PokemonBDSP_AutoStory_StoryMaps_Tests.cpp | 251 ++++++++ .../PokemonBDSP_AutoStory_StoryMaps_Tests.h | 24 + SerialPrograms/cmake/SourceFiles.cmake | 70 +-- 14 files changed, 1424 insertions(+), 1186 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 6f2d10925a..847692b532 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -5,9 +5,11 @@ */ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -18,7 +20,9 @@ namespace PokemonBDSP{ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Maps(database); - add_tests_AutoStory_MapGrids(database); + add_tests_AutoStory_StoryWorld(database); + add_tests_AutoStory_RoutePlanner(database); + add_tests_AutoStory_StoryMaps(database); add_tests_AutoStory_Segment00(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp index 1593266d18..ce7b7bc124 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp @@ -10,7 +10,6 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ -using Pokemon::RobustPlanCosts; RobustPlanCosts route_plan_costs(){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h index 825ef24312..7608e59c9e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h @@ -3,7 +3,7 @@ * From: https://github.com/PokemonAutomation/ * * The costs the story's walks are planned with on the BDSP maps - * (Pokemon::plan_robust_route()), apart from the walker, so the map + * (plan_robust_route()), apart from the walker, so the map * tests plan each walk the way the program does. * */ @@ -11,7 +11,7 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlanCosts_H #define PokemonAutomation_PokemonBDSP_AutoStory_PlanCosts_H -#include "Pokemon/Navigation/Pokemon_TileGrid.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -21,14 +21,14 @@ namespace PokemonBDSP{ // The default: open legs are whole tiles on the D-pad, so they land exactly // at any length; a wall at a leg's end is still worth a little, and each // open tile a little more. -Pokemon::RobustPlanCosts route_plan_costs(); +RobustPlanCosts route_plan_costs(); // Between two corners of a walked line: whole tiles on the D-pad land // exactly, so an open leg costs nothing extra and the straight leg to the // corner beats a run to a wall and a tap back (r244a: "west 10 to the // wall, east 1" through the wandering Youngster lost the count; "west 9" // in taps keeps it). -Pokemon::RobustPlanCosts waypoint_plan_costs(); +RobustPlanCosts waypoint_plan_costs(); // In town: a one-tile step lands exactly, a short open leg a tile either // way, and both cost little more than a leg to a wall, so a plan steps a @@ -36,7 +36,7 @@ Pokemon::RobustPlanCosts waypoint_plan_costs(); // town to end every leg on a wall (Sandgem: 13 legs, r127a and r128b // walked into the Lab and the Mart). Pair it with a check at the end (a // sign read) for the timed legs. -Pokemon::RobustPlanCosts town_plan_costs(); +RobustPlanCosts town_plan_costs(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp index fc0c0b7b61..9736436658 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -1,199 +1,177 @@ -/* BDSP AutoStory - Route records - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_RouteRecords.h" -#include "PokemonBDSP_AutoStory_JubilifeCity.h" -#include "PokemonBDSP_AutoStory_Route201.h" -#include "PokemonBDSP_AutoStory_Route203.h" -#include "PokemonBDSP_AutoStory_Route204.h" -#include "PokemonBDSP_AutoStory_RavagedPath.h" -#include "PokemonBDSP_AutoStory_OreburghCity.h" -#include "PokemonBDSP_AutoStory_OreburghGym.h" -#include "PokemonBDSP_AutoStory_FloaromaTown.h" -#include "PokemonBDSP_AutoStory_SandgemTown.h" -#include "PokemonBDSP_AutoStory_Segment00Lines.h" -#include "PokemonBDSP_AutoStory_TwinleafTown.h" -#include "PokemonBDSP_AutoStory_VerityLakefront.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace RouteRecords{ - -using namespace Pokemon; - -namespace{ -const TileGrid* twinleaf(){ return &TwinleafTown::grid(); } -const TileGrid* route201(){ return &Route201::grid(); } -const TileGrid* lakefront(){ return &VerityLakefront::grid(); } -const TileGrid* sandgem(){ return &SandgemTown::grid(); } -const TileGrid* jubilife(){ return &JubilifeCity::grid(); } -const TileGrid* route203(){ return &Route203::grid(); } -const TileGrid* ravaged_path(){ return &RavagedPath::grid(); } -const TileGrid* route204_north(){ return &Route204::north_grid(); } -const TileGrid* oreburgh_city(){ return &OreburghCity::grid(); } -const TileGrid* oreburgh_gym(){ return &OreburghGym::grid(); } -const TileGrid* floaroma(){ return &FloaromaTown::grid(); } - -// 00.01: the house, Twinleaf, Route 201 and the Lakefront out to the lake. -std::vector checkpoint_0001_records(){ - return { - {"00.01", "The house's doorstep to Barry's door", "Twinleaf Town", twinleaf, true, Segment00Lines::HOUSE_DOORSTEP, { - {Direction::WEST, 7, LegEnd::COUNT, "along row 22 to column 13, clear of the south-west house"}, - {Direction::NORTH, 10, LegEnd::COUNT, "up column 13 to row 12, below Barry's mailbox"}, - {Direction::WEST, 4, LegEnd::COUNT, "onto (9, 12), the one tile that starts Barry's scene: he bursts out of his door"}, - {Direction::NORTH, 1, LegEnd::DOOR, "after the scene, into Barry's house; the stairs, his room and the way back out are replays"}, - }, "Segment00Lines line 1, not walked by the program yet; the Twinleaf grid and the scene's tile from the Diamond decomp (land_data 0000, zone_event 0389)"}, - {"00.01", "Barry's doorstep to Route 201", "Twinleaf Town", twinleaf, true, Segment00Lines::BARRY_DOORSTEP, { - {Direction::EAST, 6, LegEnd::COUNT, "along row 12 to column 15"}, - {Direction::NORTH, 12, LegEnd::COUNT, "up column 15 to (15, 0), the last tile in town; the guitarist's stop on row 3 is inert once Barry has talked upstairs"}, - {Direction::NORTH, 0, LegEnd::BANNER, "on north onto Route 201"}, - }, "Segment00Lines line 2, not walked by the program yet"}, - {"00.01", "Route 201: Barry's tall-grass warning, then west to the Lakefront", "Route 201", route201, true, Segment00Lines::ROUTE_201_ARRIVAL, { - {Direction::NORTH, 6, LegEnd::COUNT, "up the exit path to (15, 18): Barry's warning fires on that row"}, - {Direction::WEST, 3, LegEnd::COUNT, "after the scene, along row 18 to column 12"}, - {Direction::NORTH, 2, LegEnd::COUNT, "to row 16, the lower level's row to the Lakefront"}, - {Direction::WEST, 12, LegEnd::COUNT, "to (0, 16), the route's last tile"}, - {Direction::WEST, 0, LegEnd::BANNER, "on west onto the Verity Lakefront"}, - }, "Segment00Lines lines 2 and 3, not walked by the program yet; traced on Route201::grid(), the decomp's since #111"}, - {"00.01", "Verity Lakefront: to below the lake's entrance", "Verity Lakefront", lakefront, true, Segment00Lines::LAKEFRONT_ARRIVAL, { - {Direction::WEST, 11, LegEnd::COUNT, "along row 23 to column 20"}, - {Direction::NORTH, 2, LegEnd::COUNT, "to row 21"}, - {Direction::WEST, 3, LegEnd::COUNT, "to column 17, the entrance path's east column"}, - {Direction::NORTH, 7, LegEnd::COUNT, "up column 17 to (17, 14), two tiles short of the lake's scene; 00.01 ends here"}, - }, "Segment00Lines line 3, not walked by the program yet"}, - }; -} - -// 00.02 and 00.03: into the lake's scene, and back to Sandgem. -std::vector checkpoints_0002_0003_records(){ - return { - {"00.02", "Into the lake's scene", "Verity Lakefront", lakefront, true, Segment00Lines::BELOW_LAKE_ENTRANCE, { - {Direction::NORTH, 2, LegEnd::COUNT, "onto (17, 12): Barry hears Rowan and the two of us walk into Lake Verity"}, - {Direction::NORTH, 0, LegEnd::SCENE, "the starter, the Starly and the way back out to (17, 12) are the game's; nothing is walked at the lake"}, - }, "starter_nav() presses north twice from where 00.01 ends; Segment00Lines line 3's last two tiles; the scene's tiles from the Diamond decomp (zone_event 0319)"}, - {"00.03", "Verity Lakefront: from the lake's entrance back onto Route 201", "Verity Lakefront", lakefront, true, Segment00Lines::LAKE_ENTRANCE, { - {Direction::SOUTH, 9, LegEnd::COUNT, "down column 17 to row 21"}, - {Direction::EAST, 12, LegEnd::COUNT, "along row 21 to column 29"}, - {Direction::EAST, 0, LegEnd::BANNER, "on east onto Route 201"}, - }, "Segment00Lines line 4, not walked by the program yet; which of the two entrance tiles the scene leaves us on is for the console"}, - {"00.03", "Route 201: Rowan's scene, then east through the grass to Sandgem", "Route 201", route201, true, Segment00Lines::ROUTE_201_RETURN, { - {Direction::EAST, 5, LegEnd::COUNT, "to (5, 14): Rowan and Dawn's scene fires on that column"}, - {Direction::EAST, 12, LegEnd::COUNT, "after the scene, along row 14 to column 17"}, - {Direction::EAST, 12, LegEnd::COUNT, "through the tall grass to column 29; the Breeder wanders rows 14 to 16 there"}, - {Direction::EAST, 12, LegEnd::COUNT, "to column 41"}, - {Direction::NORTH, 7, LegEnd::COUNT, "up column 41 to row 7, beside the north-east grass"}, - {Direction::EAST, 1, LegEnd::COUNT, "into the grass"}, - {Direction::NORTH, 2, LegEnd::COUNT, "to row 5"}, - {Direction::EAST, 10, LegEnd::COUNT, "through the grass to (52, 5), its last tile"}, - {Direction::EAST, 11, LegEnd::COUNT, "to (63, 5), the route's last tile"}, - {Direction::EAST, 0, LegEnd::BANNER, "on east into Sandgem Town"}, - }, "Segment00Lines lines 4 and 5, not walked by the program yet; the grass legs need the wild-battle handling of the replay's walk_through_grass(); traced on Route201::grid()"}, - {"00.03", "Sandgem Town: Dawn at the entrance", "Sandgem Town", sandgem, true, Segment00Lines::SANDGEM_ARRIVAL, { - {Direction::EAST, 4, LegEnd::COUNT, "along row 12 to (4, 12): Dawn's scene, which leads us into Rowan's lab for the Pokedex"}, - {Direction::EAST, 0, LegEnd::SCENE, "the lab is the game's; 00.03 ends in front of Rowan"}, - }, "Segment00Lines line 5, not walked by the program yet; on Sandgem's row 12, where its coord event (zone_event 0396) is"}, - }; -} - -// 01.01 to 01.05: Jubilife to Oreburgh and back out. -std::vector segment01_records_to_oreburgh(){ - return { - {"01.01", "Jubilife Pokemon Center to Barry on Route 203", "Jubilife City", jubilife, true, std::nullopt, { - {Direction::SOUTH, 0, LegEnd::NPC, "out of the Center's door; a girl below it stops us"}, - {Direction::WEST, 4, LegEnd::COUNT, "stick 720 ms: onto the main road", false}, - {Direction::NORTH, 16, LegEnd::COUNT, "stick 3960 ms: up to the street east to Route 203", false}, - {Direction::SOUTH, 2, LegEnd::COUNT, "stick 600 ms: back onto the street", false}, - {Direction::EAST, 0, LegEnd::NPC, "along the street onto Route 203 until Barry stops us; rows retried 0, +1, +1, -3, -1 when a wall comes first"}, - }, "jubilife_to_barry(); stick holds from the console, 2026-10-29, counted in tiles on the image grid's 3/4 rows: recount in taps before giving this record a start tile (task #21)"}, - {"01.02", "Barry to Oreburgh City through the Oreburgh Gate", "Route 203", route203, true, std::nullopt, { - {Direction::EAST, 0, LegEnd::WALL, "along the row Barry stopped us on"}, - {Direction::NORTH, 0, LegEnd::WALL, "to the top wall, then a row south at a time until east goes on (up to ten)"}, - {Direction::EAST, 0, LegEnd::NPC, "to the Hiker"}, - {Direction::EAST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate"}, - {Direction::EAST, 0, LegEnd::TRANSITION, "through the Gate into Oreburgh City"}, - }, "route203_to_oreburgh(); no start tile: Barry stops us on whichever row we came along"}, - {"01.04", "Oreburgh Pokemon Center doorstep to the Gym", "Oreburgh City", oreburgh_city, true, OreburghCity::POKEMON_CENTER_DOORSTEP, { - {Direction::WEST, 20, LegEnd::COUNT, "D-pad taps along the Center's row to below the Gym's door"}, - {Direction::NORTH, 1, LegEnd::DOOR, "into the Gym (the fade)"}, - }, "oreburgh_street_to_gym(); 20 taps measured on the console (r204 to r215, 3 runs on the same tile); the decomp's Center door is at x 47, the taps say the doorstep is x 46"}, - {"01.04", "Inside the Oreburgh Gym", "Oreburgh Gym", oreburgh_gym, true, OreburghGym::ENTRANCE, { - {Direction::NORTH, 0, LegEnd::NPC, "up column 5 from the entrance to Roark on row 3; the Youngsters at (4, 18) and (7, 11) see the column and stop us on rows 18 and 11 on the way"}, - }, "oreburgh_gym_battles(); the Gym's grid from the Diamond decomp (land_data 0228), its trainers and their sight from the events file (zone_event 0046)"}, - {"01.05", "Oreburgh Gym to the Gate and out onto Route 203", "Oreburgh City", oreburgh_city, true, OreburghCity::GYM_DOORSTEP, { - {Direction::EAST, 20, LegEnd::COUNT, "D-pad taps from the Gym's doorstep back to the Center's door"}, - {Direction::WEST, 0, LegEnd::WALL, "to the stairs' cliff"}, - {Direction::NORTH, 0, LegEnd::WALL, "along the cliff"}, - {Direction::EAST, 2, LegEnd::COUNT, "to the stairs' column"}, - {Direction::NORTH, 0, LegEnd::WALL, "up the stairs"}, - {Direction::WEST, 0, LegEnd::WALL, "along the platform"}, - {Direction::SOUTH, 1, LegEnd::COUNT, "onto the Gate's row"}, - {Direction::WEST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate (a row probed when a wall comes first)"}, - {Direction::WEST, 0, LegEnd::BANNER, "through the Gate until Route 203's banner"}, - }, "oreburgh_gym_to_center(), oreburgh_to_route203(); the Center visit between the two taps legs is not a walk"}, - }; -} - -// 01.07 to 01.11: Jubilife north to Floaroma. -std::vector segment01_records_from_jubilife(){ - return { - {"01.07", "Jubilife's east edge to Rowan's scene", "Jubilife City", jubilife, true, std::nullopt, { - {Direction::WEST, 14, LegEnd::COUNT, "stick 2 x 1120 ms along the long road to the crossroads with the north street", false}, - {Direction::NORTH, 0, LegEnd::SCENE, "up the street until Rowan's scene starts (about 6 s); the green-haired man may stand in the way"}, - }, "jubilife_to_rowan(); by hand 2026-10-31 (18 presses), r230b; the stick hold's count was taken on the image grid's 3/4 rows, so no start tile yet"}, - {"01.08", "Jubilife's north street onto Route 204", "Jubilife City", jubilife, true, std::nullopt, { - {Direction::NORTH, 0, LegEnd::BANNER, "up the street until Route 204's banner; the planned walk to the Ravaged Path door follows"}, - }, "jubilife_to_ravaged_path() step 1"}, - {"01.09", "Ravaged Path's east end out onto Route 204 North", "Ravaged Path", ravaged_path, true, RavagedPath::EAST_END, { - {Direction::WEST, 1, LegEnd::COUNT, "onto the tile above the way out"}, - {Direction::SOUTH, 0, LegEnd::TRANSITION, "out of the cave"}, - }, "ravaged_path() exit; the planned legs before it are tested as plans"}, - {"01.10", "Route 204 North's path into Floaroma", "Route 204 North", route204_north, true, TilePos{11, 5}, { - {Direction::NORTH, 0, LegEnd::BANNER, "from (11, 5) until Floaroma Town's banner; the waypoint line before it is tested as plans"}, - }, "route204_to_floaroma(); r248a"}, - {"01.11", "Floaroma's old couple", "Floaroma Town", floaroma, true, FloaromaTown::ROUTE_204_ARRIVAL, { - {Direction::WEST, 8, LegEnd::COUNT, "D-pad taps along the flower field's bottom row"}, - {Direction::NORTH, 0, LegEnd::NPC, "until the old woman stops us (3 tiles on r251a)"}, - {Direction::WEST, 1, LegEnd::COUNT, "below the old man"}, - {Direction::NORTH, 0, LegEnd::NPC, "until the old man stops us (a turn)"}, - }, "floaroma_old_couple(); by hand 2026-10-31 (batches m1 to m9), r251a"}, - }; -} - -} - -// The walks planned on a grid (00.04 and 00.05's walk_route goals, 01.03's -// Mine legs, 01.06's Route 203 and Jubilife legs, 01.08's Route 204 South, -// 01.09's Ravaged Path, 01.10's waypoints) are data already, tested in -// PokemonBDSP_AutoStory_Tests.cpp; these are the rest. -// -// 00.01 to 00.03 (the house, Twinleaf, Route 201, the Lakefront and the -// lake) still replay the stick inputs Butters recorded for #1717 -// (tutorial_part_1_navigation, entry_visible, tutorial_part_2_navigation, -// starter_nav: timed holds, diagonals among them, and "move until -// transition"), off which no tile count can be read. Their records below -// are the same walks as lines on the decomp grids -// (Data/PokemonBDSP_AutoStory_Segment00Lines, task #22), legs the program -// does not walk yet: a new-game run has to confirm where each scene leaves -// the player before Segment_00 switches to them. The house interiors (the -// player's, Barry's) have no grid and stay replays. -const std::vector& all(){ - static const std::vector records = []{ - std::vector all; - for (auto part : {checkpoint_0001_records, checkpoints_0002_0003_records, segment01_records_to_oreburgh, segment01_records_from_jubilife}){ - const std::vector records = part(); - all.insert(all.end(), records.begin(), records.end()); - } - return all; - }(); - return records; -} - - -} -} -} -} +/* BDSP AutoStory - Route records + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_RouteRecords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RouteRecords{ + +using namespace Pokemon; + +namespace{ + +// 00.01: the house, Twinleaf, Route 201 and the Lakefront out to the lake. +std::vector checkpoint_0001_records(){ + return { + {"00.01", "The house's doorstep to Barry's door", "Twinleaf Town", "TwinleafTown", true, map_point("TwinleafTown", "house_doorstep"), { + {Direction::WEST, 7, LegEnd::COUNT, "along row 22 to column 13, clear of the south-west house"}, + {Direction::NORTH, 10, LegEnd::COUNT, "up column 13 to row 12, below Barry's mailbox"}, + {Direction::WEST, 4, LegEnd::COUNT, "onto (9, 12), the one tile that starts Barry's scene: he bursts out of his door"}, + {Direction::NORTH, 1, LegEnd::DOOR, "after the scene, into Barry's house; the stairs, his room and the way back out are replays"}, + }, "Segment00Lines line 1, not walked by the program yet; the Twinleaf grid and the scene's tile from the Diamond decomp (land_data 0000, zone_event 0389)"}, + {"00.01", "Barry's doorstep to Route 201", "Twinleaf Town", "TwinleafTown", true, map_point("TwinleafTown", "barry_doorstep"), { + {Direction::EAST, 6, LegEnd::COUNT, "along row 12 to column 15"}, + {Direction::NORTH, 12, LegEnd::COUNT, "up column 15 to (15, 0), the last tile in town; the guitarist's stop on row 3 is inert once Barry has talked upstairs"}, + {Direction::NORTH, 0, LegEnd::BANNER, "on north onto Route 201"}, + }, "Segment00Lines line 2, not walked by the program yet"}, + {"00.01", "Route 201: Barry's tall-grass warning, then west to the Lakefront", "Route 201", "Route201", true, map_point("Route201", "route_201_arrival"), { + {Direction::NORTH, 6, LegEnd::COUNT, "up the exit path to (15, 18): Barry's warning fires on that row"}, + {Direction::WEST, 3, LegEnd::COUNT, "after the scene, along row 18 to column 12"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 16, the lower level's row to the Lakefront"}, + {Direction::WEST, 12, LegEnd::COUNT, "to (0, 16), the route's last tile"}, + {Direction::WEST, 0, LegEnd::BANNER, "on west onto the Verity Lakefront"}, + }, "Segment00Lines lines 2 and 3, not walked by the program yet; traced on the Route201 map, the decomp's since #111"}, + {"00.01", "Verity Lakefront: to below the lake's entrance", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "lakefront_arrival"), { + {Direction::WEST, 11, LegEnd::COUNT, "along row 23 to column 20"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 21"}, + {Direction::WEST, 3, LegEnd::COUNT, "to column 17, the entrance path's east column"}, + {Direction::NORTH, 7, LegEnd::COUNT, "up column 17 to (17, 14), two tiles short of the lake's scene; 00.01 ends here"}, + }, "Segment00Lines line 3, not walked by the program yet"}, + }; +} + +// 00.02 and 00.03: into the lake's scene, and back to Sandgem. +std::vector checkpoints_0002_0003_records(){ + return { + {"00.02", "Into the lake's scene", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "below_lake_entrance"), { + {Direction::NORTH, 2, LegEnd::COUNT, "onto (17, 12): Barry hears Rowan and the two of us walk into Lake Verity"}, + {Direction::NORTH, 0, LegEnd::SCENE, "the starter, the Starly and the way back out to (17, 12) are the game's; nothing is walked at the lake"}, + }, "starter_nav() presses north twice from where 00.01 ends; Segment00Lines line 3's last two tiles; the scene's tiles from the Diamond decomp (zone_event 0319)"}, + {"00.03", "Verity Lakefront: from the lake's entrance back onto Route 201", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "lake_entrance"), { + {Direction::SOUTH, 9, LegEnd::COUNT, "down column 17 to row 21"}, + {Direction::EAST, 12, LegEnd::COUNT, "along row 21 to column 29"}, + {Direction::EAST, 0, LegEnd::BANNER, "on east onto Route 201"}, + }, "Segment00Lines line 4, not walked by the program yet; which of the two entrance tiles the scene leaves us on is for the console"}, + {"00.03", "Route 201: Rowan's scene, then east through the grass to Sandgem", "Route 201", "Route201", true, map_point("Route201", "route_201_return"), { + {Direction::EAST, 5, LegEnd::COUNT, "to (5, 14): Rowan and Dawn's scene fires on that column"}, + {Direction::EAST, 12, LegEnd::COUNT, "after the scene, along row 14 to column 17"}, + {Direction::EAST, 12, LegEnd::COUNT, "through the tall grass to column 29; the Breeder wanders rows 14 to 16 there"}, + {Direction::EAST, 12, LegEnd::COUNT, "to column 41"}, + {Direction::NORTH, 7, LegEnd::COUNT, "up column 41 to row 7, beside the north-east grass"}, + {Direction::EAST, 1, LegEnd::COUNT, "into the grass"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 5"}, + {Direction::EAST, 10, LegEnd::COUNT, "through the grass to (52, 5), its last tile"}, + {Direction::EAST, 11, LegEnd::COUNT, "to (63, 5), the route's last tile"}, + {Direction::EAST, 0, LegEnd::BANNER, "on east into Sandgem Town"}, + }, "Segment00Lines lines 4 and 5, not walked by the program yet; the grass legs need the wild-battle handling of the replay's walk_through_grass(); traced on the Route201 map"}, + {"00.03", "Sandgem Town: Dawn at the entrance", "Sandgem Town", "SandgemTown", true, map_point("SandgemTown", "sandgem_arrival"), { + {Direction::EAST, 4, LegEnd::COUNT, "along row 12 to (4, 12): Dawn's scene, which leads us into Rowan's lab for the Pokedex"}, + {Direction::EAST, 0, LegEnd::SCENE, "the lab is the game's; 00.03 ends in front of Rowan"}, + }, "Segment00Lines line 5, not walked by the program yet; on Sandgem's row 12, where its coord event (zone_event 0396) is"}, + }; +} + +// 01.01 to 01.05: Jubilife to Oreburgh and back out. +std::vector segment01_records_to_oreburgh(){ + return { + {"01.01", "Jubilife Pokemon Center to Barry on Route 203", "Jubilife City", "JubilifeCity", true, std::nullopt, { + {Direction::SOUTH, 0, LegEnd::NPC, "out of the Center's door; a girl below it stops us"}, + {Direction::WEST, 4, LegEnd::COUNT, "stick 720 ms: onto the main road", false}, + {Direction::NORTH, 16, LegEnd::COUNT, "stick 3960 ms: up to the street east to Route 203", false}, + {Direction::SOUTH, 2, LegEnd::COUNT, "stick 600 ms: back onto the street", false}, + {Direction::EAST, 0, LegEnd::NPC, "along the street onto Route 203 until Barry stops us; rows retried 0, +1, +1, -3, -1 when a wall comes first"}, + }, "jubilife_to_barry(); stick holds from the console, 2026-10-29, counted in tiles on the image grid's 3/4 rows: recount in taps before giving this record a start tile (task #21)"}, + {"01.02", "Barry to Oreburgh City through the Oreburgh Gate", "Route 203", "Route203", true, std::nullopt, { + {Direction::EAST, 0, LegEnd::WALL, "along the row Barry stopped us on"}, + {Direction::NORTH, 0, LegEnd::WALL, "to the top wall, then a row south at a time until east goes on (up to ten)"}, + {Direction::EAST, 0, LegEnd::NPC, "to the Hiker"}, + {Direction::EAST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate"}, + {Direction::EAST, 0, LegEnd::TRANSITION, "through the Gate into Oreburgh City"}, + }, "route203_to_oreburgh(); no start tile: Barry stops us on whichever row we came along"}, + {"01.04", "Oreburgh Pokemon Center doorstep to the Gym", "Oreburgh City", "OreburghCity", true, map_point("OreburghCity", "pokemon_center_doorstep"), { + {Direction::WEST, 20, LegEnd::COUNT, "D-pad taps along the Center's row to below the Gym's door"}, + {Direction::NORTH, 1, LegEnd::DOOR, "into the Gym (the fade)"}, + }, "oreburgh_street_to_gym(); 20 taps measured on the console (r204 to r215, 3 runs on the same tile); the decomp's Center door is at x 47, the taps say the doorstep is x 46"}, + {"01.04", "Inside the Oreburgh Gym", "Oreburgh Gym", "OreburghGym", true, map_point("OreburghGym", "entrance"), { + {Direction::NORTH, 0, LegEnd::NPC, "up column 5 from the entrance to Roark on row 3; the Youngsters at (4, 18) and (7, 11) see the column and stop us on rows 18 and 11 on the way"}, + }, "oreburgh_gym_battles(); the Gym's grid from the Diamond decomp (land_data 0228), its trainers and their sight from the events file (zone_event 0046)"}, + {"01.05", "Oreburgh Gym to the Gate and out onto Route 203", "Oreburgh City", "OreburghCity", true, map_point("OreburghCity", "gym_doorstep"), { + {Direction::EAST, 20, LegEnd::COUNT, "D-pad taps from the Gym's doorstep back to the Center's door"}, + {Direction::WEST, 0, LegEnd::WALL, "to the stairs' cliff"}, + {Direction::NORTH, 0, LegEnd::WALL, "along the cliff"}, + {Direction::EAST, 2, LegEnd::COUNT, "to the stairs' column"}, + {Direction::NORTH, 0, LegEnd::WALL, "up the stairs"}, + {Direction::WEST, 0, LegEnd::WALL, "along the platform"}, + {Direction::SOUTH, 1, LegEnd::COUNT, "onto the Gate's row"}, + {Direction::WEST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate (a row probed when a wall comes first)"}, + {Direction::WEST, 0, LegEnd::BANNER, "through the Gate until Route 203's banner"}, + }, "oreburgh_gym_to_center(), oreburgh_to_route203(); the Center visit between the two taps legs is not a walk"}, + }; +} + +// 01.07 to 01.11: Jubilife north to Floaroma. +std::vector segment01_records_from_jubilife(){ + return { + {"01.07", "Jubilife's east edge to Rowan's scene", "Jubilife City", "JubilifeCity", true, std::nullopt, { + {Direction::WEST, 14, LegEnd::COUNT, "stick 2 x 1120 ms along the long road to the crossroads with the north street", false}, + {Direction::NORTH, 0, LegEnd::SCENE, "up the street until Rowan's scene starts (about 6 s); the green-haired man may stand in the way"}, + }, "jubilife_to_rowan(); by hand 2026-10-31 (18 presses), r230b; the stick hold's count was taken on the image grid's 3/4 rows, so no start tile yet"}, + {"01.08", "Jubilife's north street onto Route 204", "Jubilife City", "JubilifeCity", true, std::nullopt, { + {Direction::NORTH, 0, LegEnd::BANNER, "up the street until Route 204's banner; the planned walk to the Ravaged Path door follows"}, + }, "jubilife_to_ravaged_path() step 1"}, + {"01.09", "Ravaged Path's east end out onto Route 204 North", "Ravaged Path", "RavagedPath", true, map_point("RavagedPath", "east_end"), { + {Direction::WEST, 1, LegEnd::COUNT, "onto the tile above the way out"}, + {Direction::SOUTH, 0, LegEnd::TRANSITION, "out of the cave"}, + }, "ravaged_path() exit; the planned legs before it are tested as plans"}, + {"01.10", "Route 204 North's path into Floaroma", "Route 204 North", "Route204North", true, TilePos{11, 5}, { + {Direction::NORTH, 0, LegEnd::BANNER, "from (11, 5) until Floaroma Town's banner; the waypoint line before it is tested as plans"}, + }, "route204_to_floaroma(); r248a"}, + {"01.11", "Floaroma's old couple", "Floaroma Town", "FloaromaTown", true, map_point("FloaromaTown", "route_204_arrival"), { + {Direction::WEST, 8, LegEnd::COUNT, "D-pad taps along the flower field's bottom row"}, + {Direction::NORTH, 0, LegEnd::NPC, "until the old woman stops us (3 tiles on r251a)"}, + {Direction::WEST, 1, LegEnd::COUNT, "below the old man"}, + {Direction::NORTH, 0, LegEnd::NPC, "until the old man stops us (a turn)"}, + }, "floaroma_old_couple(); by hand 2026-10-31 (batches m1 to m9), r251a"}, + }; +} + +} + +// The walks planned on a grid (00.04 and 00.05's walk_route goals, 01.03's +// Mine legs, 01.06's Route 203 and Jubilife legs, 01.08's Route 204 South, +// 01.09's Ravaged Path, 01.10's waypoints) are data already, tested in +// PokemonBDSP_AutoStory_Tests.cpp; these are the rest. +// +// 00.01 to 00.03 (the house, Twinleaf, Route 201, the Lakefront and the +// lake) still replay the stick inputs Butters recorded for #1717 +// (tutorial_part_1_navigation, entry_visible, tutorial_part_2_navigation, +// starter_nav: timed holds, diagonals among them, and "move until +// transition"), off which no tile count can be read. Their records below +// are the same walks as lines on the decomp grids +// (Data/PokemonBDSP_AutoStory_Segment00Lines, task #22), legs the program +// does not walk yet: a new-game run has to confirm where each scene leaves +// the player before Segment_00 switches to them. The house interiors (the +// player's, Barry's) have no grid and stay replays. +const std::vector& all(){ + static const std::vector records = []{ + std::vector all; + for (auto part : {checkpoint_0001_records, checkpoints_0002_0003_records, segment01_records_to_oreburgh, segment01_records_from_jubilife}){ + const std::vector records = part(); + all.insert(all.end(), records.begin(), records.end()); + } + return all; + }(); + return records; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h index 5fbcc8b09d..3097c7b65b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h @@ -1,67 +1,67 @@ -/* BDSP AutoStory - Route records - * - * From: https://github.com/PokemonAutomation/ - * - * Every walk a checkpoint makes that is not planned on a grid, written - * down as legs: the direction, the count or the thing that ends the leg - * (a wall, a person, a door, a location banner, a map transition, a - * scene). The checkpoints run their own code today; these records say - * what that code does, so a test can trace each leg on the map once the - * map is right, and so the next version can run the record instead. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H -#define PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H - -#include -#include -#include -#include "Pokemon/Navigation/Pokemon_TileGrid.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace RouteRecords{ - - -// What ends a leg. -enum class LegEnd{ - COUNT, // exactly `tiles` tiles (D-pad taps, or a stick hold timed for them) - WALL, // walks until the map stops the player; `tiles` is the expected count, 0 if unknown - NPC, // walks until a person stops the player - DOOR, // walks into a door or cave mouth (a fade) - BANNER, // walks until the next map's location banner shows - TRANSITION, // walks until a map transition (the screen goes dark) - SCENE, // walks until a cutscene takes over -}; - -struct RouteLeg{ - Pokemon::Direction direction; - size_t tiles; - LegEnd end; - std::string note; - // A counted leg walked by D-pad taps (or a leg the map ends) is exact; - // a count from a timed stick hold is an estimate, a tile or two either - // way, until someone counts it on the console in taps. - bool exact = true; -}; - -struct RouteRecord{ - std::string checkpoint; // "01.05" - std::string title; - std::string map; // the map the legs are on ("" when none exists yet) - const Pokemon::TileGrid* (*grid)(); // that map's grid, nullptr when none - bool traceable; // the grid's rows are the game's (decomp or console), so legs can be traced - std::optional start; // where the record starts on that grid - std::vector legs; - std::string source; // the code and the console runs behind it -}; - -const std::vector& all(); - - -} -} -} -} -#endif +/* BDSP AutoStory - Route records + * + * From: https://github.com/PokemonAutomation/ + * + * Every walk a checkpoint makes that is not planned on a grid, written + * down as legs: the direction, the count or the thing that ends the leg + * (a wall, a person, a door, a location banner, a map transition, a + * scene). The checkpoints run their own code today; these records say + * what that code does, so a test can trace each leg on the map once the + * map is right, and so the next version can run the record instead. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RouteRecords{ + + +// What ends a leg. +enum class LegEnd{ + COUNT, // exactly `tiles` tiles (D-pad taps, or a stick hold timed for them) + WALL, // walks until the map stops the player; `tiles` is the expected count, 0 if unknown + NPC, // walks until a person stops the player + DOOR, // walks into a door or cave mouth (a fade) + BANNER, // walks until the next map's location banner shows + TRANSITION, // walks until a map transition (the screen goes dark) + SCENE, // walks until a cutscene takes over +}; + +struct RouteLeg{ + Pokemon::Direction direction; + size_t tiles; + LegEnd end; + std::string note; + // A counted leg walked by D-pad taps (or a leg the map ends) is exact; + // a count from a timed stick hold is an estimate, a tile or two either + // way, until someone counts it on the console in taps. + bool exact = true; +}; + +struct RouteRecord{ + std::string checkpoint; // "01.05" + std::string title; + std::string map; // the map the legs are on + std::string map_file; // that map's JSON map (story_map()) + bool traceable; // the map's tiles are the game's (decomp or console), so legs can be traced + std::optional start; // where the record starts on that map + std::vector legs; + std::string source; // the code and the console runs behind it +}; + +const std::vector& all(); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp index fe4bed1a06..70b9d9bac1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -1,156 +1,145 @@ -/* BDSP AutoStory - Segment 00's walked lines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonBDSP_AutoStory_Route201.h" -#include "PokemonBDSP_AutoStory_SandgemTown.h" -#include "PokemonBDSP_AutoStory_StoryMaps.h" -#include "PokemonBDSP_AutoStory_TwinleafTown.h" -#include "PokemonBDSP_AutoStory_VerityLakefront.h" -#include "PokemonBDSP_AutoStory_Segment00Lines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Segment00Lines{ - -using namespace Pokemon; - - -const char* const MAP_TWINLEAF_TOWN = "Twinleaf Town"; -const char* const MAP_VERITY_LAKEFRONT = "Verity Lakefront"; - - -// Offsets are the decomp's world coordinates of each map's tile (0, 0): -// the Sinnoh matrix's cells are 32 tiles square, the Lakefront is cell -// (column 2, row 26), Route 201 cells (3..4, 26), Twinleaf (3, 27) and -// Sandgem (5, 26). Route201::grid() leaves off the cell's seven wall rows -// at the top, so it starts 7 rows lower; SandgemTown::grid() is its whole -// cell. -const MapSet& segment00_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_TWINLEAF_TOWN, TwinleafTown::grid(), {96, 864}); - maps.add(MAP_ROUTE_201, Route201::grid(), {96, 839}); - maps.add(MAP_VERITY_LAKEFRONT, VerityLakefront::grid(), {64, 832}); - maps.add(MAP_SANDGEM_TOWN, SandgemTown::grid(), {160, 832}); - return maps; - }(); - return maps; -} - - -// From the Diamond decomp's coord events (zone_event narc_0389 Twinleaf, -// 0327 Route 201, 0319 Verity Lakefront, 0396 Sandgem; Lake Verity's -// narc_0298 has none: its scene is the map's own script, run on arrival). -// Each is a rectangle in world tiles with the story variable and value it -// fires at; Platinum's readable events files name the variables and carry -// the same rectangles for Twinleaf and the Lakefront. Listed as local -// tiles of our grids. Not here, having no grid: the player's house's door -// tile (6, 10), where Mom's warning fires on the way out (narc_0392, value -// 1). -const std::vector& scene_triggers(){ - static const std::vector triggers{ - {"Barry's door", MAP_TWINLEAF_TOWN, {9, 12}, 1, 1, - "before Barry has burst out of his house (var 0x40e6 = 0)"}, - {"the guitarist stops us leaving", MAP_TWINLEAF_TOWN, {12, 3}, 8, 1, - "between Barry's door and his talk upstairs (var 0x4070 = 1; 2 after it)"}, - {"Barry's tall-grass warning", MAP_ROUTE_201, {14, 18}, 6, 1, - "the first time north of Twinleaf (var 0x4086 = 0)"}, - {"Route 201's row 19 after the warning", MAP_ROUTE_201, {14, 19}, 6, 1, - "after the warning and before the lake (var 0x4086 = 1); its script is Diamond's binary, not read"}, - {"Rowan and Dawn on the way back", MAP_ROUTE_201, {5, 14}, 1, 3, - "after the lake (var 0x4086 = 2)"}, - {"Barry at the lake's entrance", MAP_VERITY_LAKEFRONT, {16, 12}, 2, 1, - "the first visit (var 0x4082 = 0): he hears Rowan and the two walk into Lake Verity; the same tiles fire again at 3, later in the story"}, - {"Dawn at Sandgem's entrance", MAP_SANDGEM_TOWN, {4, 11}, 1, 5, - "the first time in from Route 201 (var 0x4071 = 0): she leads us to Rowan's lab"}, - }; - return triggers; -} - -bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile){ - return tile.map == trigger.map && - tile.pos.x >= trigger.corner.x && tile.pos.x < trigger.corner.x + trigger.width && - tile.pos.y >= trigger.corner.y && tile.pos.y < trigger.corner.y + trigger.height; -} - - -const TilePos HOUSE_DOORSTEP{20, 22}; -const TilePos BARRY_DOORSTEP{9, 12}; -const TilePos TWINLEAF_NORTH_EXIT{15, 0}; -const TilePos ROUTE_201_ARRIVAL{15, 24}; -const TilePos BARRY_WARNING{15, 18}; -const TilePos LAKEFRONT_ARRIVAL{31, 23}; -const TilePos BELOW_LAKE_ENTRANCE{17, 14}; -const TilePos LAKE_ENTRANCE{17, 12}; -const TilePos ROUTE_201_RETURN{0, 14}; -const TilePos ROWAN_STOP{5, 14}; -const TilePos ROUTE_201_EAST_END{63, 5}; -const TilePos SANDGEM_ARRIVAL{0, 12}; -const TilePos DAWN_STOP{4, 12}; - -// Corners are chosen on the maps' features (a row clear of the houses, -// the exit path, a map's last tile, the tile a scene fires on); where a -// straight run is longer than the planner's 12-tile open leg (the row -// through the Lakefront, the row along Route 201) it is split at the -// twelfth tile. The lower level of Route 201 (rows 13 to 16) is the way -// both to and from the lake: the upper level's ledges only drop onto it. -// Row 16 is used westward and row 14 eastward: on the way out Rowan and -// the counterpart are not yet on (8, 14..15) and Barry is gone from (16, -// 16), but 16 keeps the line one row off the Breeder's range; on the way -// back 14 reaches Rowan's column with the fewest corners. -// -// What a new-game run must confirm before the segment switches to these: -// where each scene leaves the player (Barry's warning and Rowan's scene -// are assumed to leave us on the trigger tile; the lake's scene to warp -// us back onto (17, 12), the right-hand entrance tile, facing south), and -// that the stretches through tall grass are walked with the wild-battle -// handling the replay's walk_through_grass() has, which walk_waypoints() -// does not. -namespace{ -// Corners on each map, and a line from them: parentheses keep the table -// flat enough for the code-health linter's brace limit. -MapTile twinleaf(const TilePos& pos){ return {MAP_TWINLEAF_TOWN, pos}; } -MapTile route201(const TilePos& pos){ return {MAP_ROUTE_201, pos}; } -MapTile lakefront(const TilePos& pos){ return {MAP_VERITY_LAKEFRONT, pos}; } -MapTile sandgem(const TilePos& pos){ return {MAP_SANDGEM_TOWN, pos}; } -WalkedLine walked( - std::string checkpoint, std::string name, std::vector corners, - std::string ends_in, std::vector live_triggers -){ - return {std::move(checkpoint), std::move(name), std::move(corners), std::move(ends_in), std::move(live_triggers)}; -} -} - -const std::vector& lines(){ - static const std::vector lines{ - walked("00.01", "the house's doorstep to Barry's door", { - twinleaf(HOUSE_DOORSTEP), twinleaf({13, 22}), twinleaf({13, 12}), twinleaf(BARRY_DOORSTEP), - }, "Barry's door", {"Barry's door"}), - walked("00.01", "Barry's doorstep to Route 201", { - twinleaf(BARRY_DOORSTEP), twinleaf({15, 12}), twinleaf(TWINLEAF_NORTH_EXIT), route201(BARRY_WARNING), - }, "Barry's tall-grass warning", {"Barry's tall-grass warning"}), - walked("00.01", "Route 201's west half to the lake's entrance", { - route201(BARRY_WARNING), route201({12, 18}), route201({12, 16}), route201({0, 16}), - lakefront({20, 23}), lakefront({20, 21}), lakefront({17, 21}), lakefront(LAKE_ENTRANCE), - }, "Barry at the lake's entrance", {"Barry at the lake's entrance", "Route 201's row 19 after the warning"}), - walked("00.03", "the lake's entrance back to Rowan", { - lakefront(LAKE_ENTRANCE), lakefront({17, 21}), lakefront({29, 21}), route201(ROWAN_STOP), - }, "Rowan and Dawn on the way back", {"Rowan and Dawn on the way back"}), - walked("00.03", "Rowan to Dawn at Sandgem's entrance", { - route201(ROWAN_STOP), route201({17, 14}), route201({29, 14}), route201({41, 14}), - route201({41, 7}), route201({42, 7}), route201({42, 5}), route201({52, 5}), - route201(ROUTE_201_EAST_END), sandgem(DAWN_STOP), - }, "Dawn at Sandgem's entrance", {"Dawn at Sandgem's entrance"}), - }; - return lines; -} - -} -} -} -} +/* BDSP AutoStory - Segment 00's walked lines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP_AutoStory_Segment00Lines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Segment00Lines{ + +using Pokemon::TilePos; + + +const char* const MAP_TWINLEAF_TOWN = "Twinleaf Town"; +const char* const MAP_VERITY_LAKEFRONT = "Verity Lakefront"; + + +// Offsets are the decomp's world coordinates of each map's tile (0, 0): +// the Sinnoh matrix's cells are 32 tiles square, the Lakefront is cell +// (column 2, row 26), Route 201 cells (3..4, 26), Twinleaf (3, 27) and +// Sandgem (5, 26). The Route201 map leaves off the cell's seven wall rows +// at the top, so it starts 7 rows lower; story_map("SandgemTown") is its whole +// cell. +const StoryWorld& segment00_maps(){ + static const StoryWorld maps = []{ + StoryWorld maps; + maps.add(MAP_TWINLEAF_TOWN, story_map("TwinleafTown"), {96, 864}); + maps.add(MAP_ROUTE_201, story_map("Route201"), {96, 839}); + maps.add(MAP_VERITY_LAKEFRONT, story_map("VerityLakefront"), {64, 832}); + maps.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {160, 832}); + return maps; + }(); + return maps; +} + + +// From the Diamond decomp's coord events (zone_event narc_0389 Twinleaf, +// 0327 Route 201, 0319 Verity Lakefront, 0396 Sandgem; Lake Verity's +// narc_0298 has none: its scene is the map's own script, run on arrival). +// Each is a rectangle in world tiles with the story variable and value it +// fires at; Platinum's readable events files name the variables and carry +// the same rectangles for Twinleaf and the Lakefront. Listed as local +// tiles of our grids. Not here, having no grid: the player's house's door +// tile (6, 10), where Mom's warning fires on the way out (narc_0392, value +// 1). +const std::vector& scene_triggers(){ + static const std::vector triggers{ + {"Barry's door", MAP_TWINLEAF_TOWN, {9, 12}, 1, 1, + "before Barry has burst out of his house (var 0x40e6 = 0)"}, + {"the guitarist stops us leaving", MAP_TWINLEAF_TOWN, {12, 3}, 8, 1, + "between Barry's door and his talk upstairs (var 0x4070 = 1; 2 after it)"}, + {"Barry's tall-grass warning", MAP_ROUTE_201, {14, 18}, 6, 1, + "the first time north of Twinleaf (var 0x4086 = 0)"}, + {"Route 201's row 19 after the warning", MAP_ROUTE_201, {14, 19}, 6, 1, + "after the warning and before the lake (var 0x4086 = 1); its script is Diamond's binary, not read"}, + {"Rowan and Dawn on the way back", MAP_ROUTE_201, {5, 14}, 1, 3, + "after the lake (var 0x4086 = 2)"}, + {"Barry at the lake's entrance", MAP_VERITY_LAKEFRONT, {16, 12}, 2, 1, + "the first visit (var 0x4082 = 0): he hears Rowan and the two walk into Lake Verity; the same tiles fire again at 3, later in the story"}, + {"Dawn at Sandgem's entrance", MAP_SANDGEM_TOWN, {4, 11}, 1, 5, + "the first time in from Route 201 (var 0x4071 = 0): she leads us to Rowan's lab"}, + }; + return triggers; +} + +bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile){ + return tile.map == trigger.map && + tile.pos.x >= trigger.corner.x && tile.pos.x < trigger.corner.x + trigger.width && + tile.pos.y >= trigger.corner.y && tile.pos.y < trigger.corner.y + trigger.height; +} + + + +// Corners are chosen on the maps' features (a row clear of the houses, +// the exit path, a map's last tile, the tile a scene fires on); where a +// straight run is longer than the planner's 12-tile open leg (the row +// through the Lakefront, the row along Route 201) it is split at the +// twelfth tile. The lower level of Route 201 (rows 13 to 16) is the way +// both to and from the lake: the upper level's ledges only drop onto it. +// Row 16 is used westward and row 14 eastward: on the way out Rowan and +// the counterpart are not yet on (8, 14..15) and Barry is gone from (16, +// 16), but 16 keeps the line one row off the Breeder's range; on the way +// back 14 reaches Rowan's column with the fewest corners. +// +// What a new-game run must confirm before the segment switches to these: +// where each scene leaves the player (Barry's warning and Rowan's scene +// are assumed to leave us on the trigger tile; the lake's scene to warp +// us back onto (17, 12), the right-hand entrance tile, facing south), and +// that the stretches through tall grass are walked with the wild-battle +// handling the replay's walk_through_grass() has, which walk_waypoints() +// does not. +namespace{ +// Corners on each map, and a line from them: parentheses keep the table +// flat enough for the code-health linter's brace limit. +MapTile twinleaf(const TilePos& pos){ return {MAP_TWINLEAF_TOWN, pos}; } +MapTile route201(const TilePos& pos){ return {MAP_ROUTE_201, pos}; } +MapTile lakefront(const TilePos& pos){ return {MAP_VERITY_LAKEFRONT, pos}; } +MapTile sandgem(const TilePos& pos){ return {MAP_SANDGEM_TOWN, pos}; } +// The same, at a named point of the map. +MapTile twinleaf_point(const char* point){ return twinleaf(map_point("TwinleafTown", point)); } +MapTile route201_point(const char* point){ return route201(map_point("Route201", point)); } +MapTile lakefront_point(const char* point){ return lakefront(map_point("VerityLakefront", point)); } +MapTile sandgem_point(const char* point){ return sandgem(map_point("SandgemTown", point)); } +WalkedLine walked( + std::string checkpoint, std::string name, std::vector corners, + std::string ends_in, std::vector live_triggers +){ + return {std::move(checkpoint), std::move(name), std::move(corners), std::move(ends_in), std::move(live_triggers)}; +} +} + +const std::vector& lines(){ + static const std::vector lines{ + walked("00.01", "the house's doorstep to Barry's door", { + twinleaf_point("house_doorstep"), twinleaf({13, 22}), twinleaf({13, 12}), twinleaf_point("barry_doorstep"), + }, "Barry's door", {"Barry's door"}), + walked("00.01", "Barry's doorstep to Route 201", { + twinleaf_point("barry_doorstep"), twinleaf({15, 12}), twinleaf_point("twinleaf_north_exit"), route201_point("barry_warning"), + }, "Barry's tall-grass warning", {"Barry's tall-grass warning"}), + walked("00.01", "Route 201's west half to the lake's entrance", { + route201_point("barry_warning"), route201({12, 18}), route201({12, 16}), route201({0, 16}), + lakefront({20, 23}), lakefront({20, 21}), lakefront({17, 21}), lakefront_point("lake_entrance"), + }, "Barry at the lake's entrance", {"Barry at the lake's entrance", "Route 201's row 19 after the warning"}), + walked("00.03", "the lake's entrance back to Rowan", { + lakefront_point("lake_entrance"), lakefront({17, 21}), lakefront({29, 21}), route201_point("rowan_stop"), + }, "Rowan and Dawn on the way back", {"Rowan and Dawn on the way back"}), + walked("00.03", "Rowan to Dawn at Sandgem's entrance", { + route201_point("rowan_stop"), route201({17, 14}), route201({29, 14}), route201({41, 14}), + route201({41, 7}), route201({42, 7}), route201({42, 5}), route201({52, 5}), + route201_point("route_201_east_end"), sandgem_point("dawn_stop"), + }, "Dawn at Sandgem's entrance", {"Dawn at Sandgem's entrance"}), + }; + return lines; +} + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h index 8269643c84..940ec31426 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h @@ -1,84 +1,73 @@ -/* BDSP AutoStory - Segment 00's walked lines - * - * From: https://github.com/PokemonAutomation/ - * - * Checkpoints 00.01 to 00.03 (the house, Twinleaf, Route 201, the Verity - * Lakefront, the lake, and back to Sandgem) replay recorded stick holds - * today. These are the same walks as lines on the grids: corner to corner, - * each stretch one straight leg, ending on the tile that starts the next - * scene. The scenes' trigger rectangles come from the Diamond decomp's - * events files, so a test can show each line steps into its scene on its - * last tile and not before. Nothing runs them on the console yet (task - * #22); the segment keeps its replays until a new-game run has checked - * the lines. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H - -#include -#include -#include "Pokemon/Navigation/Pokemon_MapSet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -namespace Segment00Lines{ - - -// Map names in segment00_maps(); Route 201 and Sandgem Town go by -// StoryMaps' MAP_ROUTE_201 and MAP_SANDGEM_TOWN. -extern const char* const MAP_TWINLEAF_TOWN; -extern const char* const MAP_VERITY_LAKEFRONT; - -// Twinleaf Town, Route 201, the Verity Lakefront and Sandgem Town joined on -// one grid at their world offsets from the decomp. Lake Verity is not in -// it: its own matrix, and the scene walks us in and the game warps us out, -// so no line is walked there. -const Pokemon::MapSet& segment00_maps(); - -// A rectangle of tiles that starts a scene when the player steps in while -// the story is in `when`. From the decomp's coord events, as local tiles. -struct SceneTrigger{ - std::string name; - std::string map; - Pokemon::TilePos corner; // north-west tile - int width; - int height; - std::string when; // the story state it fires in -}; -const std::vector& scene_triggers(); -bool trigger_covers(const SceneTrigger& trigger, const Pokemon::MapTile& tile); - -// A line walked corner to corner: every stretch between two corners is one -// straight open leg (whole tiles, as the D-pad walks them). -struct WalkedLine{ - std::string checkpoint; - std::string name; - std::vector corners; // the first is where the line starts - std::string ends_in; // the scene the last corner steps into, "" for none - std::vector live_triggers; // the scenes armed while this line is walked -}; -const std::vector& lines(); - -// Named tiles on the lines, where the route records start and end. -extern const Pokemon::TilePos HOUSE_DOORSTEP; // Twinleaf: below the player's door -extern const Pokemon::TilePos BARRY_DOORSTEP; // Twinleaf: below Barry's door; his scene's tile -extern const Pokemon::TilePos TWINLEAF_NORTH_EXIT; // Twinleaf: the last tile before Route 201 -extern const Pokemon::TilePos ROUTE_201_ARRIVAL; // Route 201: the first tile north of Twinleaf -extern const Pokemon::TilePos BARRY_WARNING; // Route 201: Barry's tall-grass warning -extern const Pokemon::TilePos LAKEFRONT_ARRIVAL; // Lakefront: the first tile west of Route 201 -extern const Pokemon::TilePos BELOW_LAKE_ENTRANCE; // Lakefront: two tiles short of the lake's scene -extern const Pokemon::TilePos LAKE_ENTRANCE; // Lakefront: the lake's scene; where it leaves us -extern const Pokemon::TilePos ROUTE_201_RETURN; // Route 201: the first tile east of the Lakefront -extern const Pokemon::TilePos ROWAN_STOP; // Route 201: Rowan and Dawn's scene -extern const Pokemon::TilePos ROUTE_201_EAST_END; // Route 201: the last tile before Sandgem -extern const Pokemon::TilePos SANDGEM_ARRIVAL; // Sandgem: the first tile east of Route 201 -extern const Pokemon::TilePos DAWN_STOP; // Sandgem: Dawn's scene - - -} -} -} -} -#endif +/* BDSP AutoStory - Segment 00's walked lines + * + * From: https://github.com/PokemonAutomation/ + * + * Checkpoints 00.01 to 00.03 (the house, Twinleaf, Route 201, the Verity + * Lakefront, the lake, and back to Sandgem) replay recorded stick holds + * today. These are the same walks as lines on the maps: corner to corner, + * each stretch one straight leg, ending on the tile that starts the next + * scene. The scenes' trigger rectangles come from the Diamond decomp's + * events files, so a test can show each line steps into its scene on its + * last tile and not before. Nothing runs them on the console yet (task + * #22); the segment keeps its replays until a new-game run has checked + * the lines. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Segment00Lines{ + + +// Map names in segment00_maps(); Route 201 and Sandgem Town go by +// StoryMaps' MAP_ROUTE_201 and MAP_SANDGEM_TOWN. +extern const char* const MAP_TWINLEAF_TOWN; +extern const char* const MAP_VERITY_LAKEFRONT; + +// Twinleaf Town, Route 201, the Verity Lakefront and Sandgem Town joined on +// one grid at their world offsets from the decomp. Lake Verity is not in +// it: its own matrix, and the scene walks us in and the game warps us out, +// so no line is walked there. +const StoryWorld& segment00_maps(); + +// A rectangle of tiles that starts a scene when the player steps in while +// the story is in `when`. From the decomp's coord events, as local tiles. +struct SceneTrigger{ + std::string name; + std::string map; + Pokemon::TilePos corner; // north-west tile + int width; + int height; + std::string when; // the story state it fires in +}; +const std::vector& scene_triggers(); +bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile); + +// A line walked corner to corner: every stretch between two corners is one +// straight open leg (whole tiles, as the D-pad walks them). +struct WalkedLine{ + std::string checkpoint; + std::string name; + std::vector corners; // the first is where the line starts + std::string ends_in; // the scene the last corner steps into, "" for none + std::vector live_triggers; // the scenes armed while this line is walked +}; +const std::vector& lines(); + +// The route records start and end on named points of the maps (Twinleaf +// Town's house_doorstep, Route 201's barry_warning, ...), all on the lines. + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp index 25f7180d5f..6cdb9f95c2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -1,246 +1,309 @@ -/* BDSP AutoStory - Story maps - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_JubilifeCity.h" -#include "PokemonBDSP_AutoStory_OreburghMine.h" -#include "PokemonBDSP_AutoStory_RavagedPath.h" -#include "PokemonBDSP_AutoStory_Route203.h" -#include "PokemonBDSP_AutoStory_Route204.h" -#include "PokemonBDSP_AutoStory_Route204South.h" -#include "PokemonBDSP_AutoStory_OreburghCity.h" -#include "PokemonBDSP_AutoStory_FloaromaTown.h" -#include "PokemonBDSP_AutoStory_Route201.h" -#include "PokemonBDSP_AutoStory_Route202.h" -#include "PokemonBDSP_AutoStory_SandgemTown.h" -#include "PokemonBDSP_AutoStory_StoryMaps.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -const char* const MAP_ROUTE_201 = "Route 201"; -const char* const MAP_SANDGEM_TOWN = "Sandgem Town"; -const char* const MAP_ROUTE_202 = "Route 202"; -const char* const MAP_JUBILIFE_CITY = "Jubilife City"; -const char* const MAP_OREBURGH_MINE = "Oreburgh Mine"; -const char* const MAP_RAVAGED_PATH = "Ravaged Path"; -const char* const MAP_ROUTE_204 = "Route 204"; -const char* const MAP_OREBURGH_CITY = "Oreburgh City"; -const char* const MAP_FLOAROMA_TOWN = "Floaroma Town"; -const char* const MAP_ROUTE_204_SOUTH = "Route 204 South"; -const char* const MAP_ROUTE_203 = "Route 203"; - - -// Offsets are the maps' places in the game's world grid (the decomp's -// cells): Route 201 at world (96,839), Sandgem Town at (160,832), Route 202 -// at (159,800). Route 201's row 4 is Sandgem's row 11, below the doors, and -// Route 202's road comes down off its row 31 onto Sandgem's row 0. -const MapSet& story_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_ROUTE_201, Route201::grid(), {0, 0}); - maps.add(MAP_SANDGEM_TOWN, SandgemTown::grid(), {64, -7}); - maps.add(MAP_ROUTE_202, Route202::grid(), {63, -39}); - return maps; - }(); - return maps; -} - -const MapSet& jubilife_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_JUBILIFE_CITY, JubilifeCity::grid(), {0, 0}); - return maps; - }(); - return maps; -} - -// Planned one map at a time: Route 203 and Jubilife joined ran for minutes -// without a plan (r224a, 2026-10-31). -const MapSet& route203_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_ROUTE_203, Route203::grid(), {0, 0}); - return maps; - }(); - return maps; -} - -bool on_route203_west_line(const TilePos& pos){ - return pos.y == 18 && pos.x >= 24 && pos.x <= 42; -} - -// Columns 42..63, rows 12..25 of the Jubilife grid (world x 170..191, -// z 748..761), as a map of its own: the cut is the map's edge, which no leg -// may cross or stop on, not a wall a plan could walk "to". -namespace{ -const TilePos JUBILIFE_EAST_CORNER{42, 12}; -const int JUBILIFE_EAST_BOTTOM = 25; -} -const MapSet& jubilife_east_maps(){ - static const MapSet maps = []{ - const TileGrid& city = JubilifeCity::grid(); - const TilePos corner = JUBILIFE_EAST_CORNER; - std::vector rows; - for (int y = corner.y; y <= JUBILIFE_EAST_BOTTOM; y++){ - std::string row; - for (int x = corner.x; x < city.width(); x++){ - row += tile_char(city.at({x, y})); - } - rows.push_back(row); - } - MapSet maps; - maps.add(MAP_JUBILIFE_CITY, TileGrid(rows), {0, 0}); - return maps; - }(); - return maps; -} - -// Route 203's road (rows 17..19 of its grid) meets Jubilife's east street, -// rows 21..24 of its grid, at its east edge; the banner shows a tile or two -// in. Both in the corner map's tiles, from the Jubilife grid's. -const std::vector& jubilife_east_entrance(){ - static const std::vector tiles = []{ - std::vector tiles; - for (int y = 21; y <= 24; y++){ - for (int x = 61; x <= 63; x++){ - tiles.push_back({x - JUBILIFE_EAST_CORNER.x, y - JUBILIFE_EAST_CORNER.y}); - } - } - return tiles; - }(); - return tiles; -} - -// The north road where it leaves the plaza, columns 44..48 of rows 16..20. -bool on_jubilife_north_road(const TilePos& pos){ - const int x = pos.x + JUBILIFE_EAST_CORNER.x; - const int y = pos.y + JUBILIFE_EAST_CORNER.y; - return x >= 44 && x <= 48 && y >= 16 && y <= 20; -} - -const MapSet& oreburgh_mine_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_OREBURGH_MINE, OreburghMine::grid(), {0, 0}); - return maps; - }(); - return maps; -} - -MapSet ravaged_path_maps(const std::vector& smashed){ - TileGrid grid = RavagedPath::grid(); - for (const TilePos& rock : smashed){ - grid.set(rock, TileType::WALKABLE); - } - MapSet maps; - maps.add(MAP_RAVAGED_PATH, grid, {0, 0}); - return maps; -} - -const MapSet& oreburgh_city_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_OREBURGH_CITY, OreburghCity::grid(), {0, 0}); - return maps; - }(); - return maps; -} - -const MapSet& floaroma_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_FLOAROMA_TOWN, FloaromaTown::grid(), {0, 0}); - return maps; - }(); - return maps; -} - -const MapSet& route204_north_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_ROUTE_204, Route204::north_grid(), {0, 0}); - return maps; - }(); - return maps; -} - -const MapSet& route204_south_maps(){ - static const MapSet maps = []{ - MapSet maps; - maps.add(MAP_ROUTE_204_SOUTH, Route204South::grid(), {0, 0}); - return maps; - }(); - return maps; -} - -bool story_map_plannable(const std::string& map){ - return map == MAP_ROUTE_201 || map == MAP_ROUTE_202; -} - -bool story_at_jubilife_exit(const TilePos& world){ - const std::optional tile = story_maps().to_local(world); - return tile && tile->map == MAP_ROUTE_202 && tile->pos.y <= 3; -} - -std::vector story_save_spots(){ - const MapSet& maps = story_maps(); - return { - maps.to_world(MAP_ROUTE_202, Route202::CATCH_SPOT), - maps.to_world(MAP_ROUTE_202, Route202::SAVE_SPOT), - }; -} - -std::vector story_door_front(const char* map, const TilePos& door){ - const TilePos below = story_maps().to_world(map, door.next(Direction::SOUTH)); - return {below.next(Direction::WEST), below, below.next(Direction::EAST)}; -} - -std::vector story_catch_save_area(){ - const MapSet& maps = story_maps(); - std::vector area; - for (int y = 25; y <= 29; y++){ - for (int x = 15; x <= 21; x++){ - const TilePos pos = maps.to_world(MAP_ROUTE_202, {x, y}); - if (maps.world().standable(pos)){ - area.push_back(pos); - } - } - } - return area; -} - -std::vector story_after_training_area(){ - const MapSet& maps = story_maps(); - const TilePos catch_spot = maps.to_world(MAP_ROUTE_202, Route202::CATCH_SPOT); - std::vector area; - for (int y = catch_spot.y - 2; y <= catch_spot.y + 2; y++){ - for (int x = catch_spot.x - 1; x <= catch_spot.x + 1; x++){ - // The rows below the catch spot are trees in BDSP. - if (maps.world().standable({x, y})){ - area.push_back({x, y}); - } - } - } - return area; -} - -std::vector story_trainer_sights(){ - std::vector sights = Route202::trainer_sights(); - for (TrainerSight& sight : sights){ - sight.pos = story_maps().to_world(MAP_ROUTE_202, sight.pos); - } - return sights; -} - - - -} -} -} +/* BDSP AutoStory - Story maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StoryMaps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::MapData; +using Pokemon::TilePos; + + +const char* const MAP_ROUTE_201 = "Route 201"; +const char* const MAP_SANDGEM_TOWN = "Sandgem Town"; +const char* const MAP_ROUTE_202 = "Route 202"; +const char* const MAP_JUBILIFE_CITY = "Jubilife City"; +const char* const MAP_OREBURGH_MINE = "Oreburgh Mine"; +const char* const MAP_RAVAGED_PATH = "Ravaged Path"; +const char* const MAP_ROUTE_204 = "Route 204"; +const char* const MAP_OREBURGH_CITY = "Oreburgh City"; +const char* const MAP_FLOAROMA_TOWN = "Floaroma Town"; +const char* const MAP_ROUTE_204_SOUTH = "Route 204 South"; +const char* const MAP_ROUTE_203 = "Route 203"; + + +namespace{ + +// One map on its own. +StoryWorld single(const char* name, const std::string& json_map){ + StoryWorld world; + world.add(name, story_map(json_map), {0, 0}); + return world; +} + +// The tiles of `map` from `corner`, `width` x `height`, and the objects on +// them, as a map of its own. Its points are left out. +MapData crop(const MapData& map, const TilePos& corner, int width, int height){ + MapData cropped; + cropped.name = map.name; + cropped.source = map.source; + cropped.tiles = Pokemon::Grid{width, height, {}}; + for (int y = 0; y < height; y++){ + for (int x = 0; x < width; x++){ + cropped.tiles.cells.push_back(map.tiles.at({corner.x + x, corner.y + y})); + } + } + for (Pokemon::MapObject object : map.objects){ + object.x -= corner.x; + object.y -= corner.y; + if (cropped.tiles.contains({object.x, object.y})){ + cropped.objects.push_back(std::move(object)); + } + } + return cropped; +} + +bool in_region(const std::string& map, const std::string& region, const TilePos& pos){ + const std::vector tiles = map_region(map, region); + return std::find(tiles.begin(), tiles.end(), pos) != tiles.end(); +} + +} + + +// Offsets are the maps' places in the game's world grid (the decomp's +// cells): Route 201 at world (96,839), Sandgem Town at (160,832), Route 202 +// at (159,800). Route 201's row 4 is Sandgem's row 11, below the doors, and +// Route 202's road comes down off its row 31 onto Sandgem's row 0. +const StoryWorld& story_maps(){ + static const StoryWorld maps = []{ + StoryWorld maps; + maps.add(MAP_ROUTE_201, story_map("Route201"), {0, 0}); + maps.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {64, -7}); + maps.add(MAP_ROUTE_202, story_map("Route202"), {63, -39}); + return maps; + }(); + return maps; +} + +const StoryWorld& jubilife_maps(){ + static const StoryWorld maps = single(MAP_JUBILIFE_CITY, "JubilifeCity"); + return maps; +} + +// Planned one map at a time: Route 203 and Jubilife joined ran for minutes +// without a plan (r224a, 2026-10-31). +const StoryWorld& route203_maps(){ + static const StoryWorld maps = single(MAP_ROUTE_203, "Route203"); + return maps; +} + +bool on_route203_west_line(const TilePos& pos){ + return in_region("Route203", "west_line", pos); +} + +// Columns 42..63, rows 12..25 of Jubilife (world x 170..191, z 748..761), +// as a map of its own: the cut is the map's edge, which no leg may cross +// or stop on, not a wall a plan could walk "to". +namespace{ +const TilePos JUBILIFE_EAST_CORNER{42, 12}; +const int JUBILIFE_EAST_BOTTOM = 25; +} +const StoryWorld& jubilife_east_maps(){ + static const StoryWorld maps = []{ + const MapData& city = story_map("JubilifeCity"); + StoryWorld maps; + maps.add(MAP_JUBILIFE_CITY, crop( + city, JUBILIFE_EAST_CORNER, city.tiles.width - JUBILIFE_EAST_CORNER.x, JUBILIFE_EAST_BOTTOM - JUBILIFE_EAST_CORNER.y + 1 + ), {0, 0}); + return maps; + }(); + return maps; +} + +// Route 203's road (rows 17..19 of its map) meets Jubilife's east street, +// rows 21..24 of its map, at its east edge; the banner shows a tile or two +// in. In the corner map's tiles. +const std::vector& jubilife_east_entrance(){ + static const std::vector tiles = []{ + std::vector tiles; + for (const TilePos& pos : map_region("JubilifeCity", "east_entrance")){ + tiles.push_back({pos.x - JUBILIFE_EAST_CORNER.x, pos.y - JUBILIFE_EAST_CORNER.y}); + } + return tiles; + }(); + return tiles; +} + +bool on_jubilife_north_road(const TilePos& pos){ + return in_region("JubilifeCity", "north_road", {pos.x + JUBILIFE_EAST_CORNER.x, pos.y + JUBILIFE_EAST_CORNER.y}); +} + +const StoryWorld& oreburgh_mine_maps(){ + static const StoryWorld maps = single(MAP_OREBURGH_MINE, "OreburghMine"); + return maps; +} + +StoryWorld ravaged_path_maps(const std::vector& smashed){ + MapData map = story_map("RavagedPath"); + for (const TilePos& rock : smashed){ + if (map.tiles.contains(rock)){ + map.tiles.at(rock) = Pokemon::TileKind::OPEN; + } + } + StoryWorld maps; + maps.add(MAP_RAVAGED_PATH, map, {0, 0}); + return maps; +} + +const StoryWorld& oreburgh_city_maps(){ + static const StoryWorld maps = single(MAP_OREBURGH_CITY, "OreburghCity"); + return maps; +} + +const StoryWorld& floaroma_maps(){ + static const StoryWorld maps = single(MAP_FLOAROMA_TOWN, "FloaromaTown"); + return maps; +} + +const StoryWorld& route204_north_maps(){ + static const StoryWorld maps = single(MAP_ROUTE_204, "Route204North"); + return maps; +} + +bool in_floaroma_path(const TilePos& pos){ + return in_region("Route204North", "floaroma_path", pos); +} + +const StoryWorld& route204_south_maps(){ + static const StoryWorld maps = single(MAP_ROUTE_204_SOUTH, "Route204South"); + return maps; +} + +bool story_map_plannable(const std::string& map){ + return map == MAP_ROUTE_201 || map == MAP_ROUTE_202; +} + +bool story_at_jubilife_exit(const TilePos& world){ + const std::optional tile = story_maps().to_local(world); + return tile && tile->map == MAP_ROUTE_202 && tile->pos.y <= 3; +} + +std::vector story_save_spots(){ + const StoryWorld& maps = story_maps(); + return { + maps.to_world(MAP_ROUTE_202, map_point("Route202", "catch_spot")), + maps.to_world(MAP_ROUTE_202, map_point("Route202", "save_spot")), + }; +} + +std::vector story_door_front(const char* map, const TilePos& door){ + const TilePos below = story_maps().to_world(map, door.next(Direction::SOUTH)); + return {below.next(Direction::WEST), below, below.next(Direction::EAST)}; +} + +std::vector story_catch_save_area(){ + const StoryWorld& maps = story_maps(); + std::vector area; + for (int y = 25; y <= 29; y++){ + for (int x = 15; x <= 21; x++){ + const TilePos pos = maps.to_world(MAP_ROUTE_202, {x, y}); + if (maps.standable(pos)){ + area.push_back(pos); + } + } + } + return area; +} + +std::vector story_after_training_area(){ + const StoryWorld& maps = story_maps(); + const TilePos catch_spot = maps.to_world(MAP_ROUTE_202, map_point("Route202", "catch_spot")); + std::vector area; + for (int y = catch_spot.y - 2; y <= catch_spot.y + 2; y++){ + for (int x = catch_spot.x - 1; x <= catch_spot.x + 1; x++){ + // The rows below the catch spot are trees in BDSP. + if (maps.standable({x, y})){ + area.push_back({x, y}); + } + } + } + return area; +} + +std::vector story_trainer_sights(){ + std::vector sights = route202_trainer_sights(); + for (TrainerSight& sight : sights){ + sight.pos = story_maps().to_world(MAP_ROUTE_202, sight.pos); + } + return sights; +} + + +// From the events file: each trainer's tile, facing and sight range. +// Natalie challenged us at (22,22), walking east along the row above the +// ledge (r75), the fourth tile of her sight. +std::vector route202_trainer_sights(){ + return { + {.name = "tristan", .pos = map_point("Route202", "trainer_tristan"), .facing = Direction::SOUTH, .range = 5}, + {.name = "natalie", .pos = map_point("Route202", "trainer_natalie"), .facing = Direction::SOUTH, .range = 4}, + {.name = "logan", .pos = map_point("Route202", "trainer_logan"), .facing = Direction::SOUTH, .range = 5}, + }; +} + +std::vector route204_north_trainer_sights(){ + const auto at = [](const char* point){ return map_point("Route204North", point); }; + return { + {.name = "Twins (left)", .pos = at("trainer_twin_left"), .facing = Direction::SOUTH, .range = 3}, + {.name = "Twins (right)", .pos = at("trainer_twin_right"), .facing = Direction::SOUTH, .range = 4}, + {.name = "Aroma Lady Taylor", .pos = at("trainer_taylor"), .facing = Direction::SOUTH, .range = 4}, + {.name = "Aroma Lady Taylor", .pos = at("trainer_taylor"), .facing = Direction::EAST, .range = 4}, + // Bug Catcher Brandon paces east and west below the flower beds + // and stopped us on row 12 (r246a: "Say, what's your opinion on bug + // Pokemon?"); the DP map draws him at (20, 12), Platinum's data + // has him at (22, 13). The tile is a guess until a shot fixes it. + {.name = "Bug Catcher Brandon", .pos = at("trainer_brandon"), .facing = Direction::WEST, .range = 4}, + {.name = "Bug Catcher Brandon", .pos = at("trainer_brandon"), .facing = Direction::EAST, .range = 4}, + }; +} + +// Sarah turns between north and east; her east line crosses the street's +// columns, so a walk north meets it or not by luck (r233a passed, r234a +// fought). The planner cannot avoid it: she is listed so the route knows +// whom it may meet, with the range that fits. +std::vector route204_south_trainer_sights(){ + const auto at = [](const char* point){ return map_point("Route204South", point); }; + return { + {.name = "Lass Samantha", .pos = at("trainer_samantha"), .facing = Direction::SOUTH, .range = 4}, + {.name = "Lass Sarah", .pos = at("trainer_sarah"), .facing = Direction::NORTH, .range = 4}, + {.name = "Lass Sarah", .pos = at("trainer_sarah"), .facing = Direction::EAST, .range = 4}, + {.name = "Youngster Tyler", .pos = at("trainer_tyler"), .facing = Direction::EAST, .range = 4}, + {.name = "Youngster Tyler", .pos = at("trainer_tyler"), .facing = Direction::WEST, .range = 4}, + }; +} + +// Both see the middle column, so a walk north from the entrance is +// stopped twice before Roark (01.04's record). +std::vector oreburgh_gym_trainer_sights(){ + return { + {.name = "Youngster (first tier)", .pos = map_point("OreburghGym", "trainer_first_tier"), .facing = Direction::EAST, .range = 3}, + {.name = "Youngster (second tier)", .pos = map_point("OreburghGym", "trainer_second_tier"), .facing = Direction::WEST, .range = 4}, + }; +} + +std::vector route204_south_tiles_to_avoid(){ + std::vector tiles; + for (const TrainerSight& trainer : route204_south_trainer_sights()){ + if (trainer.name == "Lass Sarah" && trainer.facing == Direction::EAST){ + continue; + } + for (const TilePos& pos : sight_tiles(route204_south_maps(), trainer)){ + tiles.push_back(pos); + } + } + return tiles; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h index 3e27b3dc7a..4e355d9eff 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h @@ -1,108 +1,130 @@ -/* BDSP AutoStory - Story maps - * - * From: https://github.com/PokemonAutomation/ - * - * The maps the story walks through, joined on one grid. - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H -#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H - -#include "Pokemon/Navigation/Pokemon_MapSet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -extern const char* const MAP_ROUTE_201; -extern const char* const MAP_SANDGEM_TOWN; -extern const char* const MAP_ROUTE_202; -extern const char* const MAP_JUBILIFE_CITY; -extern const char* const MAP_OREBURGH_MINE; -extern const char* const MAP_RAVAGED_PATH; -extern const char* const MAP_ROUTE_204; -extern const char* const MAP_ROUTE_204_SOUTH; -extern const char* const MAP_ROUTE_203; - -// Route 201, Sandgem Town and Route 202. -const Pokemon::MapSet& story_maps(); - -// Jubilife City on its own: 00.05 starts there after Dawn's scene, so it is -// not joined to Route 202. -const Pokemon::MapSet& jubilife_maps(); -// Route 203 on its own (01.06), and whether a tile is on row 18 between the -// two cliffs: row 18 runs straight west from there under the west cliff -// into Jubilife, so the plan ends there (no leg may leave the map) and a -// walk west until Jubilife's banner shows goes on from there. -const Pokemon::MapSet& route203_maps(); -bool on_route203_west_line(const Pokemon::TilePos& pos); -// Jubilife City's north-east corner (01.06), at Jubilife's own tile -// coordinates: the rest of the city is walled off, so the plan searches only -// the part the walk needs. Where Route 203's road enters it, and whether a -// tile is on the north road below the plaza: walking north from there goes -// up the road to Route 204 (and Rowan's scene). -const Pokemon::MapSet& jubilife_east_maps(); -const std::vector& jubilife_east_entrance(); -bool on_jubilife_north_road(const Pokemon::TilePos& pos); -// The Oreburgh Mine's coal room on its own (01.03). -const Pokemon::MapSet& oreburgh_mine_maps(); - -// The Ravaged Path on its own (01.05), with the rocks in `smashed` open. -Pokemon::MapSet ravaged_path_maps(const std::vector& smashed = {}); - -// Route 204's north half on its own (01.05). -const Pokemon::MapSet& route204_north_maps(); - -// Route 204's south half on its own (01.08): it joins the north half only -// through the Ravaged Path, so the two are separate maps. -const Pokemon::MapSet& route204_south_maps(); - -// Oreburgh City alone (01.04, 01.05), and Floaroma Town alone (01.11). -extern const char* const MAP_OREBURGH_CITY; -extern const char* const MAP_FLOAROMA_TOWN; -const Pokemon::MapSet& oreburgh_city_maps(); -const Pokemon::MapSet& floaroma_maps(); - -// Whether a plan may cross this map. Routes are traced from the DP maps and -// their tree walls carried over to BDSP; towns changed more in the remake, so -// a town is crossed by screen-driven legs until the console has confirmed its -// grid. -bool story_map_plannable(const std::string& map); - -// The open rows at the top of Route 202, in world tiles: walking north from -// any of them enters Jubilife City. -bool story_at_jubilife_exit(const Pokemon::TilePos& world); - -// Where the post-catch half of 00.04 may start, in world tiles: the catch -// spot (00.03 saves there after the catch) and the save spot under the -// ledge (00.04 saves there once it has Potions, before Route 202's trainers). -std::vector story_save_spots(); - -// Where 00.04b's save after the catch may stand, in world tiles: wherever -// the catch's walks in the grass ended, the patch (15..20, 25..27) and the -// lawn column east of it, (21, 25..29), down to the pocket behind the tree -// row where r252's catch ended and saved (the save loads there: (21, 29) -// by the screen, the 202 sign 3 columns right and 4 rows up). -std::vector story_catch_save_area(); - -// Where a walk out of the door `door` of `map` may leave us, in world tiles: -// the tile below it and its neighbours either side, since the door opening -// is not lined up with one tile (Jubilife's Center, r85). -std::vector story_door_front(const char* map, const Pokemon::TilePos& door); - -// Where we may stand after training in the catch grass, in world tiles: the -// training walks up and down the catch spot's column, between the tree walls -// north and south of the grass, so a battle may stop us on any of its -// three rows. A column either side allows for where the catch left us. -std::vector story_after_training_area(); - -// Route 202's trainers, in world tiles of story_maps(). -std::vector story_trainer_sights(); - - - -} -} -} -#endif +/* BDSP AutoStory - Story maps + * + * From: https://github.com/PokemonAutomation/ + * + * The maps the story walks through, joined into story worlds, and the + * places and trainers on them that the story's walks need. The tiles and + * named points come from the JSON maps (PokemonBDSP_AutoStory_Maps.h); + * where the maps sit relative to each other, and the trainers' sight + * ranges, the maps do not say, so they are here. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Names of the maps in the story worlds below. Each is placed from the +// JSON map named without spaces ("Route 201" from Route201.json), except +// MAP_ROUTE_204, which is Route204North.json. +extern const char* const MAP_ROUTE_201; +extern const char* const MAP_SANDGEM_TOWN; +extern const char* const MAP_ROUTE_202; +extern const char* const MAP_JUBILIFE_CITY; +extern const char* const MAP_OREBURGH_MINE; +extern const char* const MAP_RAVAGED_PATH; +extern const char* const MAP_ROUTE_204; +extern const char* const MAP_ROUTE_204_SOUTH; +extern const char* const MAP_ROUTE_203; +extern const char* const MAP_OREBURGH_CITY; +extern const char* const MAP_FLOAROMA_TOWN; + +// Route 201, Sandgem Town and Route 202. +const StoryWorld& story_maps(); + +// Jubilife City on its own: 00.05 starts there after Dawn's scene, so it is +// not joined to Route 202. +const StoryWorld& jubilife_maps(); +// Route 203 on its own (01.06), and whether a tile is on row 18 between the +// two cliffs: row 18 runs straight west from there under the west cliff +// into Jubilife, so the plan ends there (no leg may leave the map) and a +// walk west until Jubilife's banner shows goes on from there. +const StoryWorld& route203_maps(); +bool on_route203_west_line(const Pokemon::TilePos& pos); +// Jubilife City's north-east corner (01.06), at its own tile coordinates: +// the rest of the city is walled off, so the plan searches only the part +// the walk needs. Where Route 203's road enters it, and whether a tile is +// on the north road below the plaza: walking north from there goes up the +// road to Route 204 (and Rowan's scene). +const StoryWorld& jubilife_east_maps(); +const std::vector& jubilife_east_entrance(); +bool on_jubilife_north_road(const Pokemon::TilePos& pos); +// The Oreburgh Mine's coal room on its own (01.03). +const StoryWorld& oreburgh_mine_maps(); + +// The Ravaged Path on its own (01.05), with the rocks in `smashed` open. +StoryWorld ravaged_path_maps(const std::vector& smashed = {}); + +// Route 204's north half on its own (01.05), and whether a tile is on the +// path north into Floaroma. +const StoryWorld& route204_north_maps(); +bool in_floaroma_path(const Pokemon::TilePos& pos); + +// Route 204's south half on its own (01.08): it joins the north half only +// through the Ravaged Path, so the two are separate maps. +const StoryWorld& route204_south_maps(); + +// Oreburgh City alone (01.04, 01.05), and Floaroma Town alone (01.11). +const StoryWorld& oreburgh_city_maps(); +const StoryWorld& floaroma_maps(); + +// Whether a plan may cross this map. Towns are crossed by screen-driven +// legs until the console has confirmed their maps. +bool story_map_plannable(const std::string& map); + +// The open rows at the top of Route 202, in world tiles: walking north from +// any of them enters Jubilife City. +bool story_at_jubilife_exit(const Pokemon::TilePos& world); + +// Where the post-catch half of 00.04 may start, in world tiles: the catch +// spot (00.03 saves there after the catch) and the save spot under the +// ledge (00.04 saves there once it has Potions, before Route 202's trainers). +std::vector story_save_spots(); + +// Where 00.04b's save after the catch may stand, in world tiles: wherever +// the catch's walks in the grass ended, the patch (15..20, 25..27) and the +// lawn column east of it, (21, 25..29), down to the pocket behind the tree +// row where r252's catch ended and saved (the save loads there: (21, 29) +// by the screen, the 202 sign 3 columns right and 4 rows up). +std::vector story_catch_save_area(); + +// Where a walk out of the door `door` of `map` may leave us, in world tiles: +// the tile below it and its neighbours either side, since the door opening +// is not lined up with one tile (Jubilife's Center, r85). +std::vector story_door_front(const char* map, const Pokemon::TilePos& door); + +// Where we may stand after training in the catch grass, in world tiles: the +// training walks up and down the catch spot's column, between the tree walls +// north and south of the grass, so a battle may stop us on any of its +// three rows. A column either side allows for where the catch left us. +std::vector story_after_training_area(); + +// Route 202's trainers, in world tiles of story_maps(). +std::vector story_trainer_sights(); + +// The trainers of a map, in its own tiles, with the sight ranges that fit +// the console. A trainer who looks two ways is listed once per way. +std::vector route202_trainer_sights(); +std::vector route204_north_trainer_sights(); +std::vector route204_south_trainer_sights(); +std::vector oreburgh_gym_trainer_sights(); + +// Route 204 South's tiles in the trainers' sight that a walk can avoid: +// all but Sarah's east line, which crosses the street (see the sights). +std::vector route204_south_tiles_to_avoid(); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp index 4f85f52a85..479c1240c2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp @@ -1,266 +1,215 @@ -/* BDSP AutoStory Segment 00 Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/Navigation/Pokemon_MapSet.h" -#include "Pokemon/Navigation/Pokemon_TileGrid.h" -#include "Data/PokemonBDSP_AutoStory_OreburghGym.h" -#include "Data/PokemonBDSP_AutoStory_Segment00Lines.h" -#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" -#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" -#include "PokemonBDSP_AutoStory_Segment00_Tests.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -using Pokemon::Direction; -using Pokemon::MapSet; -using Pokemon::MapTile; -using Pokemon::TileGrid; -using Pokemon::TilePos; -using Pokemon::TileType; -using Segment00Lines::SceneTrigger; -using Segment00Lines::WalkedLine; - -std::string describe(const MapTile& tile){ - return tile.map + " " + Pokemon::to_string(tile.pos); -} - -const SceneTrigger* find_trigger(const std::string& name){ - for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ - if (trigger.name == name){ - return &trigger; - } - } - return nullptr; -} - -// Plans one stretch of a line with the waypoint costs and returns the leg, -// or an error. The stretch must be the one straight leg a human took: to a -// wall or open, as the grid has it, ending exactly on the corner. -struct Stretch{ - Pokemon::TileLeg leg; - std::string error; -}; -Stretch plan_stretch(const MapSet& maps, const TilePos& from, const TilePos& to, const std::string& name){ - const auto plan = Pokemon::plan_robust_route(maps.world(), std::vector{from}, - [&](const TilePos& pos){ return pos == to; }, waypoint_plan_costs()); - if (!plan){ - return {{}, name + ": no plan."}; - } - if (plan->size() != 1){ - std::string text = name + ": " + std::to_string(plan->size()) + " legs, expected the one straight leg:"; - for (const Pokemon::PlannedLeg& leg : *plan){ - text += " " + to_string(leg.leg); - } - return {{}, text}; - } - const Pokemon::PlannedLeg& leg = (*plan)[0]; - if (leg.after.size() != 1 || !(leg.after[0] == to)){ - return {{}, name + ": the leg " + to_string(leg.leg) + " does not end exactly on the corner."}; - } - return {leg.leg, ""}; -} - -// Every tile a line stands on, its start first, as local tiles; logs each -// stretch's leg. Empty with `error` set when a stretch does not plan. -std::vector line_tiles(Logger& logger, const MapSet& maps, const WalkedLine& line, std::string& error){ - const std::string name = line.checkpoint + " " + line.name; - std::vector tiles{line.corners[0]}; - TilePos at = maps.to_world(line.corners[0].map, line.corners[0].pos); - std::string text = name + ": from " + describe(line.corners[0]); - for (size_t i = 1; i < line.corners.size(); i++){ - const MapTile& corner = line.corners[i]; - const TilePos goal = maps.to_world(corner.map, corner.pos); - const Stretch stretch = plan_stretch(maps, at, goal, name + " stretch " + std::to_string(i) + " to " + describe(corner)); - if (!stretch.error.empty()){ - error = stretch.error; - return {}; - } - text += "\n " + to_string(stretch.leg) + " to " + describe(corner); - for (size_t k = 0; k < stretch.leg.tiles; k++){ - at = at.next(stretch.leg.direction); - const std::optional local = maps.to_local(at); - if (!local){ - error = name + ": the line leaves the maps at " + Pokemon::to_string(at) + "."; - return {}; - } - tiles.push_back(*local); - } - } - logger.log(text); - return tiles; -} - -// The last tile steps into the line's scene; no earlier tile is in any -// scene armed while the line is walked (an inert one is only logged). -std::string check_triggers(Logger& logger, const WalkedLine& line, const std::vector& tiles){ - const std::string name = line.checkpoint + " " + line.name; - for (const std::string& live : line.live_triggers){ - if (find_trigger(live) == nullptr){ - return name + ": no scene trigger named \"" + live + "\"."; - } - } - const auto armed = [&](const std::string& trigger){ - return std::ranges::find(line.live_triggers, trigger) != line.live_triggers.end(); - }; - if (!line.ends_in.empty() && !armed(line.ends_in)){ - return name + ": the scene it ends in, \"" + line.ends_in + "\", is not among its live triggers."; - } - for (size_t i = 0; i < tiles.size(); i++){ - for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ - if (!Segment00Lines::trigger_covers(trigger, tiles[i])){ - continue; - } - const bool live = armed(trigger.name); - const bool last = i + 1 == tiles.size(); - logger.log(name + ": tile " + std::to_string(i + 1) + " of " + std::to_string(tiles.size()) + ", " + describe(tiles[i]) + - ", is in \"" + trigger.name + "\" (" + (live ? "armed" : "inert: " + trigger.when) + ")."); - if (live && !(last && trigger.name == line.ends_in)){ - return name + ": steps into the armed scene \"" + trigger.name + "\" at " + describe(tiles[i]) + ", before its end."; - } - } - } - if (!line.ends_in.empty() && !Segment00Lines::trigger_covers(*find_trigger(line.ends_in), tiles.back())){ - return name + ": its last tile " + describe(tiles.back()) + " is not in \"" + line.ends_in + "\"."; - } - return ""; -} - -// The tiles the route records start and end on, each of which must lie on -// one of the lines. -struct NamedTile{ - const char* name; - MapTile tile; -}; -std::vector named_tiles(){ - return { - {"HOUSE_DOORSTEP", {Segment00Lines::MAP_TWINLEAF_TOWN, Segment00Lines::HOUSE_DOORSTEP}}, - {"BARRY_DOORSTEP", {Segment00Lines::MAP_TWINLEAF_TOWN, Segment00Lines::BARRY_DOORSTEP}}, - {"TWINLEAF_NORTH_EXIT", {Segment00Lines::MAP_TWINLEAF_TOWN, Segment00Lines::TWINLEAF_NORTH_EXIT}}, - {"ROUTE_201_ARRIVAL", {MAP_ROUTE_201, Segment00Lines::ROUTE_201_ARRIVAL}}, - {"BARRY_WARNING", {MAP_ROUTE_201, Segment00Lines::BARRY_WARNING}}, - {"LAKEFRONT_ARRIVAL", {Segment00Lines::MAP_VERITY_LAKEFRONT, Segment00Lines::LAKEFRONT_ARRIVAL}}, - {"BELOW_LAKE_ENTRANCE", {Segment00Lines::MAP_VERITY_LAKEFRONT, Segment00Lines::BELOW_LAKE_ENTRANCE}}, - {"LAKE_ENTRANCE", {Segment00Lines::MAP_VERITY_LAKEFRONT, Segment00Lines::LAKE_ENTRANCE}}, - {"ROUTE_201_RETURN", {MAP_ROUTE_201, Segment00Lines::ROUTE_201_RETURN}}, - {"ROWAN_STOP", {MAP_ROUTE_201, Segment00Lines::ROWAN_STOP}}, - {"ROUTE_201_EAST_END", {MAP_ROUTE_201, Segment00Lines::ROUTE_201_EAST_END}}, - {"SANDGEM_ARRIVAL", {MAP_SANDGEM_TOWN, Segment00Lines::SANDGEM_ARRIVAL}}, - {"DAWN_STOP", {MAP_SANDGEM_TOWN, Segment00Lines::DAWN_STOP}}, - }; -} - -// The lines 00.01 to 00.03 would walk (Data/PokemonBDSP_AutoStory_Segment00Lines): -// every stretch plans as one straight leg on the decomp grids, and each -// line enters its scene's trigger rectangle on its last tile only. The -// named tiles the route records start from all lie on the lines. -class Test_Segment00Lines : public UnitTest{ -public: - Test_Segment00Lines() - : UnitTest("PokemonBDSP::AutoStory - Segment 00: the lines into each scene") - {} - - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - const MapSet& maps = Segment00Lines::segment00_maps(); - for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ - if (trigger.width <= 0 || trigger.height <= 0){ - return "Scene trigger \"" + trigger.name + "\" has no tiles."; - } - maps.to_world(trigger.map, trigger.corner); // throws for a map not in the set - } - std::vector walked; - for (const WalkedLine& line : Segment00Lines::lines()){ - if (line.corners.size() < 2){ - return line.checkpoint + " " + line.name + ": a line needs two corners."; - } - std::string error; - const std::vector tiles = line_tiles(logger, maps, line, error); - if (!error.empty()){ - return error; - } - error = check_triggers(logger, line, tiles); - if (!error.empty()){ - return error; - } - walked.insert(walked.end(), tiles.begin(), tiles.end()); - } - for (const NamedTile& tile : named_tiles()){ - const bool on_a_line = std::ranges::any_of(walked, [&](const MapTile& t){ - return t.map == tile.tile.map && t.pos == tile.tile.pos; - }); - if (!on_a_line){ - return std::string(tile.name) + " " + describe(tile.tile) + " is on none of the lines."; - } - } - return true; - } -}; - -// The Oreburgh Gym's inside (Data/PokemonBDSP_AutoStory_OreburghGym): the -// column up from the entrance runs to Roark with nothing in the way but the -// two Youngsters' sight lines, which is what 01.04's "north until a trainer -// stops us" relies on. -class Test_OreburghGymGrid : public UnitTest{ -public: - Test_OreburghGymGrid() - : UnitTest("PokemonBDSP::AutoStory - Oreburgh Gym: the column up to Roark") - {} - - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - const TileGrid& gym = OreburghGym::grid(); - if (!gym.standable(OreburghGym::ENTRANCE)){ - return "The entrance tile is not standable."; - } - if (gym.at(OreburghGym::ENTRANCE.next(Direction::SOUTH)) != TileType::DOOR){ - return "The door is not below the entrance tile."; - } - if (gym.at(OreburghGym::ROARK) != TileType::NPC){ - return "Roark is not on an NPC tile."; - } - const Pokemon::WallHit up = Pokemon::walk_to_wall(gym, OreburghGym::ENTRANCE, Direction::NORTH); - if (!(up.wall == OreburghGym::ROARK)){ - return "North from the entrance stops at " + Pokemon::to_string(up.stop) + ", not in front of Roark."; - } - logger.log("Oreburgh Gym: north from the entrance walks " + std::to_string(up.tiles) + " tiles to Roark."); - for (const Pokemon::TrainerSight& trainer : OreburghGym::trainer_sights()){ - if (gym.at(trainer.pos) != TileType::NPC){ - return trainer.name + " is not on an NPC tile."; - } - const std::vector seen = Pokemon::sight_tiles(gym, trainer); - const bool sees_column = std::ranges::any_of(seen, [&](const TilePos& pos){ - return pos.x == OreburghGym::ENTRANCE.x && pos.y < OreburghGym::ENTRANCE.y && pos.y > OreburghGym::ROARK.y; - }); - if (!sees_column){ - return trainer.name + " does not see the column up to Roark."; - } - std::string text = "Oreburgh Gym: " + trainer.name + " sees"; - for (const TilePos& pos : seen){ - text += " " + Pokemon::to_string(pos); - } - logger.log(text); - } - return true; - } -}; - -} - - -void add_tests_AutoStory_Segment00(UnitTestDatabase& database){ - database.add(); - database.add(); -} - - -} -} -} +/* BDSP AutoStory Segment 00 Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Data/PokemonBDSP_AutoStory_Segment00Lines.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_Segment00_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::TilePos; +using Segment00Lines::SceneTrigger; +using Segment00Lines::WalkedLine; + +std::string describe(const MapTile& tile){ + return tile.map + " " + Pokemon::to_string(tile.pos); +} + +const SceneTrigger* find_trigger(const std::string& name){ + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (trigger.name == name){ + return &trigger; + } + } + return nullptr; +} + +// Plans one stretch of a line with the waypoint costs and returns the leg, +// or an error. The stretch must be the one straight leg a human took: to a +// wall or open, as the grid has it, ending exactly on the corner. +struct Stretch{ + TileLeg leg; + std::string error; +}; +Stretch plan_stretch(const StoryWorld& maps, const TilePos& from, const TilePos& to, const std::string& name){ + const auto plan = plan_robust_route(maps, std::vector{from}, + [&](const TilePos& pos){ return pos == to; }, waypoint_plan_costs()); + if (!plan){ + return {{}, name + ": no plan."}; + } + if (plan->size() != 1){ + std::string text = name + ": " + std::to_string(plan->size()) + " legs, expected the one straight leg:"; + for (const PlannedLeg& leg : *plan){ + text += " " + to_string(leg.leg); + } + return {{}, text}; + } + const PlannedLeg& leg = (*plan)[0]; + if (leg.after.size() != 1 || !(leg.after[0] == to)){ + return {{}, name + ": the leg " + to_string(leg.leg) + " does not end exactly on the corner."}; + } + return {leg.leg, ""}; +} + +// Every tile a line stands on, its start first, as local tiles; logs each +// stretch's leg. Empty with `error` set when a stretch does not plan. +std::vector line_tiles(Logger& logger, const StoryWorld& maps, const WalkedLine& line, std::string& error){ + const std::string name = line.checkpoint + " " + line.name; + std::vector tiles{line.corners[0]}; + TilePos at = maps.to_world(line.corners[0].map, line.corners[0].pos); + std::string text = name + ": from " + describe(line.corners[0]); + for (size_t i = 1; i < line.corners.size(); i++){ + const MapTile& corner = line.corners[i]; + const TilePos goal = maps.to_world(corner.map, corner.pos); + const Stretch stretch = plan_stretch(maps, at, goal, name + " stretch " + std::to_string(i) + " to " + describe(corner)); + if (!stretch.error.empty()){ + error = stretch.error; + return {}; + } + text += "\n " + to_string(stretch.leg) + " to " + describe(corner); + for (size_t k = 0; k < stretch.leg.tiles; k++){ + at = at.next(stretch.leg.direction); + const std::optional local = maps.to_local(at); + if (!local){ + error = name + ": the line leaves the maps at " + Pokemon::to_string(at) + "."; + return {}; + } + tiles.push_back(*local); + } + } + logger.log(text); + return tiles; +} + +// The last tile steps into the line's scene; no earlier tile is in any +// scene armed while the line is walked (an inert one is only logged). +std::string check_triggers(Logger& logger, const WalkedLine& line, const std::vector& tiles){ + const std::string name = line.checkpoint + " " + line.name; + for (const std::string& live : line.live_triggers){ + if (find_trigger(live) == nullptr){ + return name + ": no scene trigger named \"" + live + "\"."; + } + } + const auto armed = [&](const std::string& trigger){ + return std::ranges::find(line.live_triggers, trigger) != line.live_triggers.end(); + }; + if (!line.ends_in.empty() && !armed(line.ends_in)){ + return name + ": the scene it ends in, \"" + line.ends_in + "\", is not among its live triggers."; + } + for (size_t i = 0; i < tiles.size(); i++){ + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (!Segment00Lines::trigger_covers(trigger, tiles[i])){ + continue; + } + const bool live = armed(trigger.name); + const bool last = i + 1 == tiles.size(); + logger.log(name + ": tile " + std::to_string(i + 1) + " of " + std::to_string(tiles.size()) + ", " + describe(tiles[i]) + + ", is in \"" + trigger.name + "\" (" + (live ? "armed" : "inert: " + trigger.when) + ")."); + if (live && !(last && trigger.name == line.ends_in)){ + return name + ": steps into the armed scene \"" + trigger.name + "\" at " + describe(tiles[i]) + ", before its end."; + } + } + } + if (!line.ends_in.empty() && !Segment00Lines::trigger_covers(*find_trigger(line.ends_in), tiles.back())){ + return name + ": its last tile " + describe(tiles.back()) + " is not in \"" + line.ends_in + "\"."; + } + return ""; +} + +// The points the route records start and end on, each of which must lie +// on one of the lines. +struct NamedTile{ + const char* map; // in segment00_maps() + const char* json_map; + const char* point; +}; +std::vector named_tiles(){ + const char* twinleaf = Segment00Lines::MAP_TWINLEAF_TOWN; + const char* lakefront = Segment00Lines::MAP_VERITY_LAKEFRONT; + return { + {.map = twinleaf, .json_map = "TwinleafTown", .point = "house_doorstep"}, + {.map = twinleaf, .json_map = "TwinleafTown", .point = "barry_doorstep"}, + {.map = twinleaf, .json_map = "TwinleafTown", .point = "twinleaf_north_exit"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "route_201_arrival"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "barry_warning"}, + {.map = lakefront, .json_map = "VerityLakefront", .point = "lakefront_arrival"}, + {.map = lakefront, .json_map = "VerityLakefront", .point = "below_lake_entrance"}, + {.map = lakefront, .json_map = "VerityLakefront", .point = "lake_entrance"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "route_201_return"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "rowan_stop"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "route_201_east_end"}, + {.map = MAP_SANDGEM_TOWN, .json_map = "SandgemTown", .point = "sandgem_arrival"}, + {.map = MAP_SANDGEM_TOWN, .json_map = "SandgemTown", .point = "dawn_stop"}, + }; +} + +// The lines 00.01 to 00.03 would walk (Data/PokemonBDSP_AutoStory_Segment00Lines): +// every stretch plans as one straight leg on the decomp maps, and each +// line enters its scene's trigger rectangle on its last tile only. The +// named tiles the route records start from all lie on the lines. +class Test_Segment00Lines : public UnitTest{ +public: + Test_Segment00Lines() + : UnitTest("PokemonBDSP::AutoStory - Segment 00: the lines into each scene") + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld& maps = Segment00Lines::segment00_maps(); + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (trigger.width <= 0 || trigger.height <= 0){ + return "Scene trigger \"" + trigger.name + "\" has no tiles."; + } + maps.to_world(trigger.map, trigger.corner); // throws for a map not in the set + } + std::vector walked; + for (const WalkedLine& line : Segment00Lines::lines()){ + if (line.corners.size() < 2){ + return line.checkpoint + " " + line.name + ": a line needs two corners."; + } + std::string error; + const std::vector tiles = line_tiles(logger, maps, line, error); + if (!error.empty()){ + return error; + } + error = check_triggers(logger, line, tiles); + if (!error.empty()){ + return error; + } + walked.insert(walked.end(), tiles.begin(), tiles.end()); + } + for (const NamedTile& tile : named_tiles()){ + const MapTile named{tile.map, map_point(tile.json_map, tile.point)}; + const bool on_a_line = std::ranges::any_of(walked, [&](const MapTile& t){ + return t.map == named.map && t.pos == named.pos; + }); + if (!on_a_line){ + return std::string(tile.point) + " " + describe(named) + " is on none of the lines."; + } + } + return true; + } +}; + +} + + +void add_tests_AutoStory_Segment00(UnitTestDatabase& database){ + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h index a956b4073c..7e501479e0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h @@ -15,8 +15,8 @@ namespace PokemonBDSP{ -// Offline checks of Segment 00's walked lines against the grids and the -// scenes' trigger rectangles, and of the Oreburgh Gym's inside. +// Offline checks of Segment 00's walked lines against the maps and the +// scenes' trigger rectangles. void add_tests_AutoStory_Segment00(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp new file mode 100644 index 0000000000..36c0bdb348 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -0,0 +1,251 @@ +/* BDSP AutoStory Story Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The story's walks on its maps: Route 202's catch grass and the way into + * Sandgem, Sandgem's Center, the Oreburgh Gym's column, and the route + * records traced on their maps. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "Data/PokemonBDSP_AutoStory_RouteRecords.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP_AutoStory_StoryMaps_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + +StoryWorld alone(const std::string& json_map){ + StoryWorld world; + world.add(json_map, story_map(json_map), {0, 0}); + return world; +} + +// 00.04's training walks up and down the catch patch, three grass rows +// between tree rows, and needs the walk there to end in its grass: r253 +// and r254 loaded the catch's save in the pocket behind the trees at +// (21, 29), planned from the catch spot instead, and walked up and down +// the lawn east of the grass for three minutes without a battle. +class Test_Route202CatchGrass : public UnitTest{ +public: + Test_Route202CatchGrass() + : UnitTest("PokemonBDSP::AutoStory - Route 202: the catch patch and the walk to it") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld route = alone("Route202"); + for (int x = 15; x <= 20; x++){ + const WallHit up = walk_to_wall(route, {x, 27}, Direction::NORTH); + const WallHit down = walk_to_wall(route, {x, 25}, Direction::SOUTH); + if (!(up.stop == TilePos{x, 25}) || !(down.stop == TilePos{x, 27})){ + return std::format("Catch patch column {}: north from row 27 stops at {}, south from row 25 at {}; expected rows 25 and 27, between tree rows.", + x, Pokemon::to_string(up.stop), Pokemon::to_string(down.stop)); + } + } + const StoryWorld& maps = story_maps(); + const std::vector area = story_after_training_area(); + const auto in_grass = [&](const TilePos& pos){ + return maps.tile(pos) == TileKind::TALL_GRASS && std::find(area.begin(), area.end(), pos) != area.end(); + }; + // As walk_route() plans: the route costs, else the default costs. + // From the whole area the catch's save may stand in, and from the + // pocket behind the trees alone, where r252 saved. + const std::vector>> starts{ + {"the catch's save area", story_catch_save_area()}, + {"the pocket behind the trees", {maps.to_world(MAP_ROUTE_202, {21, 29})}}, + }; + for (const auto& [name, from] : starts){ + std::optional> legs = plan_robust_route(maps, from, in_grass, route_plan_costs()); + if (!legs){ + legs = plan_robust_route(maps, from, in_grass, RobustPlanCosts()); + } + if (!legs || legs->empty()){ + return "From " + name + " to the catch grass: no plan."; + } + for (const TilePos& pos : legs->back().after){ + if (!in_grass(pos)){ + return "From " + name + " to the catch grass: the walk may end on " + maps.describe(pos) + ", not in the grass."; + } + } + logger.log(std::format("From {} to the catch grass: {} legs, ending in the grass.", name, legs->size())); + } + return true; + } +}; + +// 00.04's way to Sandgem's Pokemon Center ends below the Center's sign, +// walking north into it, then taps west along the doors' row to below the +// door: the row must be open there, the door straight north of where the +// taps end, and nothing else (a sign, the Mart's door) on the way. +class Test_SandgemCenterApproach : public UnitTest{ +public: + Test_SandgemCenterApproach() + : UnitTest("PokemonBDSP::AutoStory - Sandgem Town: below the Center's sign to below its door") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld town = alone("SandgemTown"); + const TilePos sign = map_point("SandgemTown", "pokemon_center_sign"); + const TilePos door = map_point("SandgemTown", "pokemon_center_door"); + if (town.tile(sign) != TileKind::SIGN || town.tile(door) != TileKind::DOOR || door.y != sign.y || door.x >= sign.x){ + return std::format("The Center's sign {} and door {} are not a sign and a door west of it on one row.", + Pokemon::to_string(sign), Pokemon::to_string(door)); + } + TilePos pos = sign.next(Direction::SOUTH); + for (int tap = 0; tap < sign.x - door.x; tap++){ + const std::optional next = town.step(pos, Direction::WEST); + if (!next){ + return "West from " + Pokemon::to_string(pos) + " is blocked."; + } + if (town.tile(next->next(Direction::NORTH)) != TileKind::WALL && *next != door.next(Direction::SOUTH)){ + return "Above " + Pokemon::to_string(*next) + " is not the Center's wall."; + } + pos = *next; + } + if (!(pos == door.next(Direction::SOUTH))){ + return std::format("The taps end at {}, not below the door {}.", Pokemon::to_string(pos), Pokemon::to_string(door)); + } + logger.log(std::format("Sandgem: below the sign {}, {} taps west to below the door {}.", + Pokemon::to_string(sign.next(Direction::SOUTH)), sign.x - door.x, Pokemon::to_string(door))); + return true; + } +}; + +// After training, 00.04 walks from wherever the training left us into +// Sandgem, to where the road stops above the Mart, with the default costs +// (heal_at_sandgem_center()): from the whole area and from each of its +// tiles alone, a plan must exist and end there. +class Test_TrainingToSandgem : public UnitTest{ +public: + Test_TrainingToSandgem() + : UnitTest("PokemonBDSP::AutoStory - Route 202: from every tile of the training area into Sandgem") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld& maps = story_maps(); + const TilePos entry = maps.to_world(MAP_SANDGEM_TOWN, map_point("SandgemTown", "route_202_entry_stop")); + const std::vector area = story_after_training_area(); + std::vector> starts{area}; + for (const TilePos& pos : area){ + starts.push_back({pos}); + } + for (const std::vector& from : starts){ + const auto legs = plan_robust_route(maps, from, [&](const TilePos& pos){ return pos == entry; }, RobustPlanCosts()); + const std::string name = from.size() == 1 ? maps.describe(from[0]) : "the whole training area"; + if (!legs || legs->empty()){ + return "From " + name + " into Sandgem: no plan."; + } + if (legs->back().after.size() != 1 || !(legs->back().after[0] == entry)){ + return "From " + name + " into Sandgem: the plan does not end on " + maps.describe(entry) + "."; + } + logger.log(std::format("From {} into Sandgem: {} legs.", name, legs->size())); + } + return true; + } +}; + +// The Oreburgh Gym's inside: the column up from the entrance runs to Roark +// with nothing in the way but the two Youngsters' sight lines, which is +// what 01.04's "north until a trainer stops us" relies on. +class Test_OreburghGymColumn : public UnitTest{ +public: + Test_OreburghGymColumn() + : UnitTest("PokemonBDSP::AutoStory - Oreburgh Gym: the column up to Roark") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld gym = alone("OreburghGym"); + const TilePos entrance = map_point("OreburghGym", "entrance"); + const TilePos roark = map_point("OreburghGym", "roark"); + if (!gym.standable(entrance) || gym.tile(entrance.next(Direction::SOUTH)) != TileKind::DOOR){ + return std::string("The entrance tile is not standable above the door."); + } + if (!gym.occupied(roark)){ + return std::string("Nobody stands on Roark's tile."); + } + const WallHit up = walk_to_wall(gym, entrance, Direction::NORTH); + if (!(up.wall == roark)){ + return "North from the entrance stops at " + Pokemon::to_string(up.stop) + ", not in front of Roark."; + } + logger.log(std::format("Oreburgh Gym: north from the entrance walks {} tiles to Roark.", up.tiles)); + for (const TrainerSight& trainer : oreburgh_gym_trainer_sights()){ + if (!gym.occupied(trainer.pos)){ + return trainer.name + " does not stand on their tile."; + } + const std::vector seen = sight_tiles(gym, trainer); + const bool sees_column = std::ranges::any_of(seen, [&](const TilePos& pos){ + return pos.x == entrance.x && pos.y < entrance.y && pos.y > roark.y; + }); + if (!sees_column){ + return trainer.name + " does not see the column up to Roark."; + } + } + return true; + } +}; + +// Each traceable record with a start tile starts on ground, and its legs +// counted in whole tiles trace on its map up to the first leg that ends +// some other way. +class Test_RouteRecords : public UnitTest{ +public: + Test_RouteRecords() + : UnitTest("PokemonBDSP::AutoStory - Route records: counted legs trace on their maps") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + for (const RouteRecords::RouteRecord& record : RouteRecords::all()){ + const std::string name = record.checkpoint + " " + record.title; + const StoryWorld world = alone(record.map_file); + if (!record.traceable || !record.start){ + continue; + } + if (!world.standable(*record.start)){ + return name + ": starts on " + Pokemon::to_string(*record.start) + ", where nobody can stand."; + } + std::vector counted; + for (const RouteRecords::RouteLeg& leg : record.legs){ + if (leg.end != RouteRecords::LegEnd::COUNT || !leg.exact){ + break; + } + counted.push_back({leg.direction, leg.tiles, false}); + } + try{ + const TilePos end = trace_legs(world, *record.start, counted).back(); + logger.log(std::format("{}: {} counted legs to {}.", name, counted.size(), world.describe(end))); + }catch (InternalProgramError& e){ + return name + ": " + e.message(); + } + } + return true; + } +}; + +} + + +void add_tests_AutoStory_StoryMaps(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); + database.add(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h new file mode 100644 index 0000000000..68fb96f3f3 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Story Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the story's walks on its maps: Route 202, Sandgem, the Oreburgh Gym and the route records. +void add_tests_AutoStory_StoryMaps(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 5d63877935..8ed6d5c25d 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1461,8 +1461,6 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_MapData.cpp Source/Pokemon/Navigation/Pokemon_MapData.h Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp - Source/Pokemon/Navigation/Pokemon_MapSet.cpp - Source/Pokemon/Navigation/Pokemon_MapSet.h Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h Source/Pokemon/Navigation/Pokemon_RouteLog.cpp Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -1470,8 +1468,6 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_StoryEvents.cpp Source/Pokemon/Navigation/Pokemon_StoryEvents.h Source/Pokemon/Navigation/Pokemon_StoryEvents_Tests.cpp - Source/Pokemon/Navigation/Pokemon_TileGrid.cpp - Source/Pokemon/Navigation/Pokemon_TileGrid.h Source/Pokemon/Navigation/Pokemon_StorySegments.cpp Source/Pokemon/Navigation/Pokemon_StorySegments.h Source/Pokemon/Navigation/Pokemon_StorySegments_Tests.cpp @@ -1546,52 +1542,6 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Resources/Pokemon_PokemonNames.h Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp Source/Pokemon/Resources/Pokemon_PokemonSlugs.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_JubilifeCity.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghMine.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RavagedPath.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route201.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route202.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route203.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204South.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghCity.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_FloaromaTown.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGate.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TwinleafTown.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_LakeVerity.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_MapGrids.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_VerityLakefront.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_OreburghGym.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Route204.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_SandgemTown.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.cpp - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_MapGrid_Tests.h - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp @@ -1672,8 +1622,28 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/PokemonBDSP_Tests.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp From de7c108c52d2ecaaf2aaa821f28194ded2616ab0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:39:41 -0800 Subject: [PATCH 09/74] BDSP navigation: the walker plans on the story world The walker takes a StoryWorld where it took a Pokemon::MapSet or TileGrid, and the planner's types from PokemonBDSP. Its copy of the world uncovers the tiles to avoid and blocks what it finds in the way, as it set them UNKNOWN and BLOCKED before. Nothing else changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 34 +++++++++---------- .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 21 ++++++------ 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index 8b32093da4..c8382de696 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -58,7 +58,7 @@ void stick_for(Direction direction, double& x, double& y){ // World tiles as tiles of the named maps, for the shared route log // (Pokemon_RouteLog.h); a tile no map holds is a "world" tile. -std::vector route_tiles(const MapSet& maps, const std::vector& tiles){ +std::vector route_tiles(const StoryWorld& maps, const std::vector& tiles){ std::vector out; for (const TilePos& pos : tiles){ const std::optional local = maps.to_local(pos); @@ -67,7 +67,7 @@ std::vector route_tiles(const MapSet& maps, const std::vector& tiles){ +std::string describe(const StoryWorld& maps, const std::vector& tiles){ return Pokemon::describe(route_tiles(maps, tiles)); } @@ -76,11 +76,11 @@ RouteLogLeg route_log_leg(const TileLeg& leg){ .end = leg.ends_at_wall ? RouteLegEnd::WALL : RouteLegEnd::OPEN}; } -PlannedRouteLeg planned_route_leg(const MapSet& maps, const PlannedLeg& leg){ +PlannedRouteLeg planned_route_leg(const StoryWorld& maps, const PlannedLeg& leg){ return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; } -void log_plan(VideoStream& stream, const MapSet& maps, const std::string& label, const std::vector& from, const std::vector& legs){ +void log_plan(VideoStream& stream, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ std::vector logged; for (const PlannedLeg& leg : legs){ logged.push_back(planned_route_leg(maps, leg)); @@ -91,7 +91,7 @@ void log_plan(VideoStream& stream, const MapSet& maps, const std::string& label, // Logs a leg that ended on its planned tiles, and how that is known: an // open leg counts its taps through a wild battle, so its end is assumed; a // leg to a wall is walked again to its wall. -void log_leg_done(VideoStream& stream, const MapSet& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ +void log_leg_done(VideoStream& stream, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); @@ -99,7 +99,7 @@ void log_leg_done(VideoStream& stream, const MapSet& maps, const std::string& la // The tiles the player passes when walking `tiles` tiles from `from`, the // first one after `from` first. Stops early where the player is stopped. -std::vector leg_path(const TileGrid& grid, TilePos from, Direction direction, size_t tiles){ +std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ std::vector path; size_t travelled = 0; while (travelled < tiles){ @@ -139,7 +139,7 @@ bool holding_against_wall(VideoStream& stream, ProControllerContext& context, do } // The map all of `tiles` are on, or empty if they are on several or none. -std::string map_of(const MapSet& maps, const std::vector& tiles){ +std::string map_of(const StoryWorld& maps, const std::vector& tiles){ std::string name; for (const TilePos& pos : tiles){ const std::optional tile = maps.to_local(pos); @@ -154,9 +154,9 @@ std::string map_of(const MapSet& maps, const std::vector& tiles){ } -bool route_wall_readable(const TileGrid& grid, const std::vector& after){ +bool route_wall_readable(const StoryWorld& grid, const std::vector& after){ return std::none_of(after.begin(), after.end(), [&](const TilePos& pos){ - return grid.at(pos) == TileType::TALL_GRASS; + return grid.tile(pos) == TileKind::TALL_GRASS; }); } @@ -245,7 +245,7 @@ bool talk_with_nudges( std::vector walk_route( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const MapSet& maps, + const StoryWorld& maps, std::vector from, const std::function& goal, std::vector& trainers, @@ -258,10 +258,10 @@ std::vector walk_route( // avoid are ground the game lets us walk on (a trainer's line of sight), // so they are off the map, not walls: a leg must not end "at" one, or // the walk would run on through it. - TileGrid grid = maps.world(); + StoryWorld grid = maps; for (const TilePos& pos : avoid){ if (std::find(from.begin(), from.end(), pos) == from.end()){ - grid.set(pos, TileType::UNKNOWN); + grid.uncover(pos); } } // Which way the player faces, once a leg has set it. @@ -415,7 +415,7 @@ std::vector walk_route( } if (stopped.size() == 1){ const TilePos blocker = stopped[0].next(leg.direction); - grid.set(blocker, TileType::BLOCKED); + grid.block(blocker); stream.log("[Route] " + leg_label + ": something the map lacks is at " + maps.describe(blocker) + "; marked it.", COLOR_ORANGE); } @@ -531,7 +531,7 @@ std::vector walk_route( stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); if (stopped.size() == 1){ const TilePos blocker = stopped[0].next(leg.direction); - grid.set(blocker, TileType::BLOCKED); + grid.block(blocker); stream.log("[Route] " + leg_label + ": something the map lacks is at " + maps.describe(blocker) + "; marked it.", COLOR_ORANGE); } @@ -723,7 +723,7 @@ std::vector walk_route( std::vector walk_waypoints( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const MapSet& maps, + const StoryWorld& maps, std::vector from, const std::vector& waypoints, std::vector& trainers, @@ -744,7 +744,7 @@ std::vector walk_waypoints( void talk_to_npc( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const MapSet& maps, + const StoryWorld& maps, std::vector& at, const TilePos& npc, const std::vector& sides, @@ -754,7 +754,7 @@ void talk_to_npc( ){ for (Direction side : sides){ const TilePos stand = npc.next(side); - if (!maps.world().standable(stand)){ + if (!maps.standable(stand)){ continue; } at = walk_route(stream, context, escape, maps, at, [&](const TilePos& pos){ return pos == stand; }, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index b7057b6303..995f341818 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -19,7 +19,8 @@ #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "Pokemon/Navigation/Pokemon_MapSet.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_Walk.h" @@ -89,7 +90,7 @@ constexpr Milliseconds ROUTE_NUDGE_TAP = Milliseconds(50); // Whether a walk to the wall that ends on any of `after` can tell it has // stopped: not in tall grass, whose sway keeps the screen changing at a // wall. Elsewhere, a walk to the wall that stops confirms where it ended. -bool route_wall_readable(const Pokemon::TileGrid& grid, const std::vector& after); +bool route_wall_readable(const StoryWorld& grid, const std::vector& after); // Shows what the route walk is doing in the log and the video overlay. void route_status(VideoStream& stream, const std::string& text); @@ -111,14 +112,14 @@ using RouteTrainerFight = std::function; // after "arriving" on Route 202). std::vector walk_route( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const Pokemon::MapSet& maps, + const StoryWorld& maps, std::vector from, const std::function& goal, - std::vector& trainers, + std::vector& trainers, const RouteTrainerFight& fight, const std::string& label, const std::vector& avoid = {}, - const Pokemon::RobustPlanCosts& costs = route_plan_costs() + const RobustPlanCosts& costs = route_plan_costs() ); // Walks `from` to each of `waypoints` in turn, with walk_route() for every @@ -127,13 +128,13 @@ std::vector walk_route( // trainers and blocks on each stretch (Route 204 North, 2026-10-31). std::vector walk_waypoints( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const Pokemon::MapSet& maps, + const StoryWorld& maps, std::vector from, const std::vector& waypoints, - std::vector& trainers, + std::vector& trainers, const RouteTrainerFight& fight, const std::string& label, - const Pokemon::RobustPlanCosts& costs = waypoint_plan_costs() + const RobustPlanCosts& costs = waypoint_plan_costs() ); // Walks next to the NPC on world tile `npc`, faces them and presses A, trying @@ -143,11 +144,11 @@ std::vector walk_waypoints( // or from a tile a row off, talks to nobody, so each side is tried in turn. void talk_to_npc( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const Pokemon::MapSet& maps, + const StoryWorld& maps, std::vector& at, const Pokemon::TilePos& npc, const std::vector& sides, - std::vector& trainers, + std::vector& trainers, const RouteTrainerFight& fight, const std::string& label ); From e7ead80e03ff48fdebbd658d2db087787fa19a19 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:49:42 -0800 Subject: [PATCH 10/74] BDSP maps: Route 202's training and exit areas as regions catch_save_area, after_training_area, catch_grass and jubilife_exit were computed by the story code from tile loops; they are now regions of Route202, and a map test checks each against the loop it replaces. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Programs/AutoStory/Maps/Route202.json | 75 ++++++++++++++++++- .../PokemonBDSP_AutoStory_Maps_Tests.cpp | 69 +++++++++++++++++ devtools/maps/bdsp_maps.py | 31 ++++---- 3 files changed, 160 insertions(+), 15 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json index 515e652b45..e52d694739 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json @@ -41,7 +41,80 @@ "trainer_tristan": [7, 13], "trainer_natalie": [22, 18], "trainer_logan": [26, 4], - "exit_jubilife": [15, 0] + "exit_jubilife": [15, 0], + "jubilife_exit.1": [11, 0], + "jubilife_exit.2": [12, 0], + "jubilife_exit.3": [13, 0], + "jubilife_exit.4": [14, 0], + "jubilife_exit.5": [15, 0], + "jubilife_exit.6": [16, 0], + "jubilife_exit.7": [17, 0], + "jubilife_exit.8": [18, 0], + "jubilife_exit.9": [11, 1], + "jubilife_exit.10": [12, 1], + "jubilife_exit.11": [13, 1], + "jubilife_exit.12": [14, 1], + "jubilife_exit.13": [15, 1], + "jubilife_exit.14": [16, 1], + "jubilife_exit.15": [17, 1], + "jubilife_exit.16": [18, 1], + "jubilife_exit.17": [11, 2], + "jubilife_exit.18": [12, 2], + "jubilife_exit.19": [13, 2], + "jubilife_exit.20": [14, 2], + "jubilife_exit.21": [15, 2], + "jubilife_exit.22": [16, 2], + "jubilife_exit.23": [17, 2], + "jubilife_exit.24": [18, 2], + "jubilife_exit.25": [11, 3], + "jubilife_exit.26": [12, 3], + "jubilife_exit.27": [13, 3], + "jubilife_exit.28": [14, 3], + "jubilife_exit.29": [15, 3], + "jubilife_exit.30": [16, 3], + "jubilife_exit.31": [17, 3], + "jubilife_exit.32": [18, 3], + "catch_save_area.1": [15, 25], + "catch_save_area.2": [16, 25], + "catch_save_area.3": [17, 25], + "catch_save_area.4": [18, 25], + "catch_save_area.5": [19, 25], + "catch_save_area.6": [20, 25], + "catch_save_area.7": [21, 25], + "catch_save_area.8": [15, 26], + "catch_save_area.9": [16, 26], + "catch_save_area.10": [17, 26], + "catch_save_area.11": [18, 26], + "catch_save_area.12": [19, 26], + "catch_save_area.13": [20, 26], + "catch_save_area.14": [21, 26], + "catch_save_area.15": [15, 27], + "catch_save_area.16": [16, 27], + "catch_save_area.17": [17, 27], + "catch_save_area.18": [18, 27], + "catch_save_area.19": [19, 27], + "catch_save_area.20": [20, 27], + "catch_save_area.21": [21, 27], + "catch_save_area.22": [21, 28], + "catch_save_area.23": [21, 29], + "after_training_area.1": [18, 25], + "after_training_area.2": [19, 25], + "after_training_area.3": [20, 25], + "after_training_area.4": [18, 26], + "after_training_area.5": [19, 26], + "after_training_area.6": [20, 26], + "after_training_area.7": [18, 27], + "after_training_area.8": [19, 27], + "after_training_area.9": [20, 27], + "catch_grass.1": [18, 25], + "catch_grass.2": [19, 25], + "catch_grass.3": [20, 25], + "catch_grass.4": [18, 26], + "catch_grass.5": [19, 26], + "catch_grass.6": [20, 26], + "catch_grass.7": [18, 27], + "catch_grass.8": [19, 27], + "catch_grass.9": [20, 27] }, "objects": [ {"name": "youngster_0", "kind": "npc", "x": 7, "y": 13, "facing": "south"}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp index 0c62adb480..b242068168 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp @@ -243,6 +243,74 @@ class Test_StoryMapObjects : public UnitTest{ }; +// Route 202's regions are the tiles the story code computed before they +// were data: each case is the old helper's loop, over the map's tiles. +struct RegionCase{ + std::string region; + std::function(const MapData& map)> old_helper; +}; + +// The tiles of a box, both corners inclusive, row by row, that someone +// can stand on: ground with nobody standing still there. +std::vector standable_in_box(const MapData& map, const TilePos& low, const TilePos& high){ + std::vector tiles; + for (int y = low.y; y <= high.y; y++){ + for (int x = low.x; x <= high.x; x++){ + if (map.tiles.contains({x, y}) && is_ground(map.tiles.at({x, y})) && standing_object(map, {x, y}) == nullptr){ + tiles.push_back({x, y}); + } + } + } + return tiles; +} + +std::vector after_training_area(const MapData& map){ + const TilePos catch_spot = map_point(map.name, "catch_spot"); + return standable_in_box(map, {catch_spot.x - 1, catch_spot.y - 2}, {catch_spot.x + 1, catch_spot.y + 2}); +} + +class Test_Route202Regions : public UnitTest{ +public: + Test_Route202Regions() + : UnitTest("PokemonBDSP::AutoStory - Maps: Route 202's regions are what the story computed") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const std::vector cases{ + { + .region = "catch_save_area", // story_catch_save_area() + .old_helper = [](const MapData& map){ return standable_in_box(map, {15, 25}, {21, 29}); }, + }, + { + .region = "after_training_area", // story_after_training_area() + .old_helper = after_training_area, + }, + { + .region = "catch_grass", // the story table's catch_grass() + .old_helper = [](const MapData& map){ + std::vector grass = after_training_area(map); + std::erase_if(grass, [&](const TilePos& pos){ return map.tiles.at(pos) != TileKind::TALL_GRASS; }); + return grass; + }, + }, + { + .region = "jubilife_exit", // the story table's jubilife_exit() + .old_helper = [](const MapData& map){ return standable_in_box(map, {0, 0}, {map.tiles.width - 1, 3}); }, + }, + }; + const MapData& map = story_map("Route202"); + for (const RegionCase& item : cases){ + const std::vector region = map_region("Route202", item.region); + const std::vector expected = item.old_helper(map); + if (region != expected){ + return std::format("Route202 {}: {} tiles, the old helper computes {}.", item.region, region.size(), expected.size()); + } + logger.log(std::format("Route202 {}: {} tiles.", item.region, region.size())); + } + return true; + } +}; + + // map_point() and map_region() find what the story asks for, regions in // order, and throw for what a map does not have. struct LookupCase{ @@ -316,6 +384,7 @@ void add_tests_AutoStory_Maps(UnitTestDatabase& database){ database.add(); database.add(); database.add(); + database.add(); } diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py index 7c4dbf1e72..01e01b1ebc 100644 --- a/devtools/maps/bdsp_maps.py +++ b/devtools/maps/bdsp_maps.py @@ -35,14 +35,11 @@ facing it; a sign script on a wall too). Items on the ground are objects of kind "item"; rocks, cut trees, berry soil and steam vents are '#'. -Rules carried over from the maps' history: terrain from the decomp, people -and BDSP's edits from the console; a route is coded only over tiles a human -or a probe has walked; a map change re-runs every checkpoint that walks it. -Bulbapedia's DP map images have 12 px rows for 16 px columns (3/4 of a tile -per row) and paint cliffs taller than their tiles, so they are for drawing -routes over (`python3 -m devtools.maps overlay`), not for terrain. Scenes' -trigger rectangles (the events files' coord events) have no place in the -schema; Segment00Lines lists those it needs in C++. +Rules: terrain from the decomp, people and BDSP's edits from the console; +a route is coded only over tiles a human or a probe has walked; a map change +re-runs every checkpoint that walks it. Bulbapedia's DP images (12 px rows +for 16 px columns, cliffs painted tall) are for drawing routes over, not for +terrain. Scenes' coord events have no place in the schema (Segment00Lines). """ import argparse import json @@ -96,10 +93,8 @@ # (14, 17); column 13 is grass to the cliff (13, 2); Sarah walked up and # fought on row 21 (r233a, r234a). 01.08 passed once (r235a). 'Route204South': {'header': 'ROUTE_204_SOUTH', 'rect': (160, 704, 32, 32), 'read': '2026-11-01'}, - # Cell (5, 26). Console (2026-10-29/30): all three doors, five signs, - # the doors' front row east to the trees and north from it, the Lab's - # sign read facing west, the walk south from Route 202 stopping above - # the Mart at (29, 5). + # Cell (5, 26). Console (2026-10-29/30): the three doors, five signs, + # the doors' front row, the Lab's sign, the stop above the Mart (29, 5). 'SandgemTown': {'header': 'SANDGEM', 'rect': (160, 832, 34, 32)}, # Cells (4..5, 23..24). Console (2026-10-30/31): the lamps (43, 53) and # (49, 53), north from (52, 53) to the Center's door, the School's door @@ -112,8 +107,7 @@ 'OreburghCity': {'header': 'OREBURGH', 'rect': (256, 736, 64, 64)}, # The only cell of matrix 003; Platinum identical. 'OreburghGate': {'header': 'OREBURGH_GATE_1F', 'rect': (0, 0, 32, 32)}, - # The only cell of matrix 113. 01.04 walks it as a record: north up - # column 5 until a trainer stops us. + # The only cell of matrix 113. 01.04 walks north up column 5. 'OreburghGym': {'header': 'OREBURGH_GYM', 'rect': (0, 0, 32, 32)}, # B2F, the coal room: matrix 006. Console (2026-10-28, r99): the # corridor's rocks zigzag a row at a time, the room's second row passes @@ -188,6 +182,15 @@ def box(x0, y0, x1, y1): 'trainer_logan': (26, 4), # The middle of the gap to Jubilife, below its 3-wide neck. 'exit_jubilife': (15, 0), + # The open rows at the top: north from any of them is Jubilife. + 'jubilife_exit': box(11, 0, 18, 3), + # Where 00.04b's save after the catch may stand: the patch and the + # lawn column east of it, down to the pocket where r252 saved. + 'catch_save_area': box(15, 25, 21, 27) + [(21, 28), (21, 29)], + # Where training may leave us (the catch spot's column and one either + # side, between the tree rows), and its grass: all of it. + 'after_training_area': box(18, 25, 20, 27), + 'catch_grass': box(18, 25, 20, 27), }, 'Route203': { # The warp tile the Gate puts us on, and its open neighbours. From c83b4e4f663856d21626849c788a589fd7ae1784 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:51:05 -0800 Subject: [PATCH 11/74] BDSP navigation: slide_to_wall(), and Route 202's areas from the map's regions The planner's walk_to_wall() is now slide_to_wall(), so it no longer shares a name with the walker's walk_to_wall(), which walks on the console. story_catch_save_area() and story_after_training_area() read Route 202's regions instead of looping over its tiles. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 4 +-- .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 2 +- .../Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 36 +++++++------------ ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryMaps_Tests.cpp | 6 ++-- 5 files changed, 20 insertions(+), 30 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index 65111d657a..5952517e28 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -35,7 +35,7 @@ bool tall_grass(const StoryWorld& world, const TilePos& pos){ } -WallHit walk_to_wall(const StoryWorld& world, const TilePos& from, Direction direction){ +WallHit slide_to_wall(const StoryWorld& world, const TilePos& from, Direction direction){ WallHit hit; hit.stop = from; while (true){ @@ -269,7 +269,7 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre size_t longest = 0; int grass = 0; for (const TilePos& pos : spread){ - const WallHit hit = walk_to_wall(world, pos, direction); + const WallHit hit = slide_to_wall(world, pos, direction); if (!hit.anchored){ return std::nullopt; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index f5b9d6d730..9b96713184 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -32,7 +32,7 @@ struct WallHit{ Pokemon::TilePos wall; // the first tile the player could not enter bool anchored = false; // the player is held at `stop` (see StoryWorld::at_wall()) }; -WallHit walk_to_wall(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); +WallHit slide_to_wall(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); // A straight run in one direction. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp index 6cdb9f95c2..c8dc372ab7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -200,33 +200,23 @@ std::vector story_door_front(const char* map, const TilePos& door){ return {below.next(Direction::WEST), below, below.next(Direction::EAST)}; } -std::vector story_catch_save_area(){ - const StoryWorld& maps = story_maps(); - std::vector area; - for (int y = 25; y <= 29; y++){ - for (int x = 15; x <= 21; x++){ - const TilePos pos = maps.to_world(MAP_ROUTE_202, {x, y}); - if (maps.standable(pos)){ - area.push_back(pos); - } - } +namespace{ +// A region of Route 202, in world tiles of story_maps(). +std::vector route202_region(const char* region){ + std::vector tiles; + for (const TilePos& pos : map_region("Route202", region)){ + tiles.push_back(story_maps().to_world(MAP_ROUTE_202, pos)); } - return area; + return tiles; +} +} + +std::vector story_catch_save_area(){ + return route202_region("catch_save_area"); } std::vector story_after_training_area(){ - const StoryWorld& maps = story_maps(); - const TilePos catch_spot = maps.to_world(MAP_ROUTE_202, map_point("Route202", "catch_spot")); - std::vector area; - for (int y = catch_spot.y - 2; y <= catch_spot.y + 2; y++){ - for (int x = catch_spot.x - 1; x <= catch_spot.x + 1; x++){ - // The rows below the catch spot are trees in BDSP. - if (maps.standable({x, y})){ - area.push_back({x, y}); - } - } - } - return area; + return route202_region("after_training_area"); } std::vector story_trainer_sights(){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index ea74104879..fd19365abe 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -74,7 +74,7 @@ class Test_WalkToWall : public UnitTest{ .stop = {0, 2}, .tiles = 2, .anchored = true}, }; for (const WallCase& item : cases){ - const WallHit hit = walk_to_wall(make_world(item.rows), item.from, item.direction); + const WallHit hit = slide_to_wall(make_world(item.rows), item.from, item.direction); if (!(hit.stop == item.stop) || hit.tiles != item.tiles || hit.anchored != item.anchored){ return std::format("{}: stops at {} after {} tiles, anchored {}; expected {} after {}, anchored {}.", item.name, Pokemon::to_string(hit.stop), hit.tiles, hit.anchored, Pokemon::to_string(item.stop), item.tiles, item.anchored); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp index 36c0bdb348..ec79f83bb0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -52,8 +52,8 @@ class Test_Route202CatchGrass : public UnitTest{ virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ const StoryWorld route = alone("Route202"); for (int x = 15; x <= 20; x++){ - const WallHit up = walk_to_wall(route, {x, 27}, Direction::NORTH); - const WallHit down = walk_to_wall(route, {x, 25}, Direction::SOUTH); + const WallHit up = slide_to_wall(route, {x, 27}, Direction::NORTH); + const WallHit down = slide_to_wall(route, {x, 25}, Direction::SOUTH); if (!(up.stop == TilePos{x, 25}) || !(down.stop == TilePos{x, 27})){ return std::format("Catch patch column {}: north from row 27 stops at {}, south from row 25 at {}; expected rows 25 and 27, between tree rows.", x, Pokemon::to_string(up.stop), Pokemon::to_string(down.stop)); @@ -177,7 +177,7 @@ class Test_OreburghGymColumn : public UnitTest{ if (!gym.occupied(roark)){ return std::string("Nobody stands on Roark's tile."); } - const WallHit up = walk_to_wall(gym, entrance, Direction::NORTH); + const WallHit up = slide_to_wall(gym, entrance, Direction::NORTH); if (!(up.wall == roark)){ return "North from the entrance stops at " + Pokemon::to_string(up.stop) + ", not in front of Roark."; } From 090783ff36b77480405b1596311f6044d8371a1e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 13:52:15 -0800 Subject: [PATCH 12/74] BDSP navigation: the walker calls the planner's slide_to_wall() Follows the rename in #127; the walker's own walk_to_wall() is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index c8382de696..bb3a012840 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -342,7 +342,7 @@ std::vector walk_route( // the time walked, put it on our map and plan again from there. size_t nearest = SIZE_MAX; for (const TilePos& pos : from){ - nearest = std::min(nearest, walk_to_wall(grid, pos, leg.direction).tiles); + nearest = std::min(nearest, slide_to_wall(grid, pos, leg.direction).tiles); } auto tiles_moved = [&](const WalkResult& walk){ const Milliseconds moving = walk.walked - ROUTE_START_DELAY - From 45a2eaf736788f2b4a910cfa53bb736520f6e39c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:20:08 -0800 Subject: [PATCH 13/74] BDSP maps: the loader takes names as string_view GCC -Werror=dangling-reference flagged story_map("Route202") bound to a reference: with a const std::string& parameter, the temporary string looks like what the result refers to. string_view arguments are not flagged; callers are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp | 8 ++++---- .../Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h | 9 ++++++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp index 65a16564cc..065b53300a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp @@ -38,7 +38,7 @@ const std::map>& story_maps_by_name(){ } -const MapData& story_map(const std::string& name){ +const MapData& story_map(std::string_view name){ const auto& maps = story_maps_by_name(); if (auto iter = maps.find(name); iter != maps.end()){ return iter->second; @@ -46,15 +46,15 @@ const MapData& story_map(const std::string& name){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No BDSP story map named \"{}\".", name)); } -TilePos map_point(const std::string& map, const std::string& point){ +TilePos map_point(std::string_view map, std::string_view point){ const MapData& data = story_map(map); - if (auto iter = data.points.find(point); iter != data.points.end()){ + if (auto iter = data.points.find(std::string(point)); iter != data.points.end()){ return iter->second; } throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("{} has no point \"{}\".", map, point)); } -std::vector map_region(const std::string& map, const std::string& region){ +std::vector map_region(std::string_view map, std::string_view region){ const MapData& data = story_map(map); std::vector tiles; while (true){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h index a4615a47ee..e6e3a96bef 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h @@ -19,6 +19,7 @@ #define PokemonAutomation_PokemonBDSP_AutoStory_Maps_H #include +#include #include #include #include "Pokemon/Navigation/Pokemon_Grid.h" @@ -36,15 +37,17 @@ const std::vector>& bdsp_map_json(); // The map `name`, read from bdsp_map_json() on first use, with its patches // applied. Throws InternalProgramError for a name it does not have, and // ParseException if a map does not parse or is not named as its file. -const Pokemon::MapData& story_map(const std::string& name); +// The name is a string_view so that a temporary string argument is not +// mistaken (by GCC's -Wdangling-reference) for what the result refers to. +const Pokemon::MapData& story_map(std::string_view name); // The point `point` of the map `map`. Throws InternalProgramError for an // unknown map or point. -Pokemon::TilePos map_point(const std::string& map, const std::string& point); +Pokemon::TilePos map_point(std::string_view map, std::string_view point); // The tiles of the region `region` of the map `map`, in order. Throws // InternalProgramError for an unknown map, or a region with no tiles. -std::vector map_region(const std::string& map, const std::string& region); +std::vector map_region(std::string_view map, std::string_view region); From fd2202ddd66369a7e2052dec4847662ac25f6c4b Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:35:52 -0800 Subject: [PATCH 14/74] BDSP navigation tests: name every field, or give it a default Windows clang -Werror,-Wmissing-designated-field-initializers rejected test rows that left fields out. The rows' optional fields now have default member initializers, and the MapObjects built in the story world tests name all their fields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- ...okemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 6 +++--- .../PokemonBDSP_AutoStory_StoryWorld_Tests.cpp | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index fd19365abe..15a8111056 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -53,9 +53,9 @@ std::string describe(const std::vector& legs){ struct WallCase{ std::string name; std::vector rows; - TilePos from; + TilePos from = {}; Direction direction = Direction::EAST; - TilePos stop; + TilePos stop = {}; size_t tiles = 0; bool anchored = false; }; @@ -117,7 +117,7 @@ struct RobustCase{ std::string name; std::vector from; TilePos goal; - RobustPlanCosts costs; + RobustPlanCosts costs = {}; // The plan as to_string() writes it, or empty when there is none. std::string legs; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp index 66e345f140..e409fcceb3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -43,10 +43,16 @@ MapData make_map( } } for (const TilePos& pos : standing){ - map.objects.push_back({.name = "standing", .x = pos.x, .y = pos.y}); + map.objects.push_back({ + .name = "standing", .kind = Pokemon::ObjectKind::NPC, .x = pos.x, .y = pos.y, + .facing = std::nullopt, .wander = std::nullopt, + }); } for (const TilePos& pos : wandering){ - map.objects.push_back({.name = "wandering", .x = pos.x, .y = pos.y, .wander = Pokemon::WanderBox{pos.x, pos.y, pos.x, pos.y}}); + map.objects.push_back({ + .name = "wandering", .kind = Pokemon::ObjectKind::NPC, .x = pos.x, .y = pos.y, + .facing = std::nullopt, .wander = Pokemon::WanderBox{pos.x, pos.y, pos.x, pos.y}, + }); } return map; } @@ -63,11 +69,11 @@ StoryWorld make_world(const MapData& map){ struct StepCase{ std::string name; std::vector rows; - std::vector standing; - std::vector wandering; - TilePos from; + std::vector standing = {}; + std::vector wandering = {}; + TilePos from = {}; Direction direction = Direction::NORTH; - std::optional lands; + std::optional lands = std::nullopt; bool at_wall = false; }; From 282212e5acf136d557493a5f631f671b1a846dab Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:37:47 -0800 Subject: [PATCH 15/74] BDSP navigation: change grid cells with Pokemon::cell_at() #122 made Grid's at() read-only and added cell_at() for writes; the story world and the Ravaged Path's smashed rocks follow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 2 +- .../AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp index c8dc372ab7..02ab715514 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -146,7 +146,7 @@ StoryWorld ravaged_path_maps(const std::vector& smashed){ MapData map = story_map("RavagedPath"); for (const TilePos& rock : smashed){ if (map.tiles.contains(rock)){ - map.tiles.at(rock) = Pokemon::TileKind::OPEN; + Pokemon::cell_at(map.tiles, rock) = Pokemon::TileKind::OPEN; } } StoryWorld maps; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index 20012b1bcd..1786780d6c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -106,11 +106,11 @@ void StoryWorld::rebuild(){ const TilePos corner{iter->offset.x - low.x, iter->offset.y - low.y}; for (int y = 0; y < iter->tiles.height; y++){ for (int x = 0; x < iter->tiles.width; x++){ - m_cells.at({corner.x + x, corner.y + y}) = Cell{true, iter->tiles.at({x, y}), false}; + Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, iter->tiles.at({x, y}), false}; } } for (const TilePos& pos : iter->occupied){ - m_cells.at({corner.x + pos.x, corner.y + pos.y}).occupied = true; + Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}).occupied = true; } } for (const TilePos& pos : m_blocked){ @@ -135,7 +135,7 @@ StoryWorld::Cell* StoryWorld::cell(const TilePos& pos){ if (!m_cells.contains(pos) || !m_cells.at(pos).covered){ return nullptr; } - return &m_cells.at(pos); + return &Pokemon::cell_at(m_cells, pos); } From b798ef3ec1299055ae508abf5f8d596971b69623 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:40:14 -0800 Subject: [PATCH 16/74] BDSP navigation: StoryWorld keeps seven methods; walking rules are free functions Code health: StoryWorld had 14 public methods, and its overlap check and rebuild nested five deep. covered(), standable(), step(), at_wall() and describe() now take the world as their first argument and read it through tile() and occupied(); width() and height() are gone. The overlap check and the painting of a map are split out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 20 +-- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 125 ++++++++++-------- .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 40 +++--- .../PokemonBDSP_AutoStory_StoryMaps_Tests.cpp | 14 +- ...PokemonBDSP_AutoStory_StoryWorld_Tests.cpp | 16 +-- 5 files changed, 115 insertions(+), 100 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index 5952517e28..d836670c06 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -40,10 +40,10 @@ WallHit slide_to_wall(const StoryWorld& world, const TilePos& from, Direction di hit.stop = from; while (true){ const TilePos before = hit.stop; - const std::optional next = world.step(before, direction); + const std::optional next = step(world, before, direction); if (!next){ hit.wall = before.next(direction); - hit.anchored = world.at_wall(before, direction); + hit.anchored = at_wall(world, before, direction); return hit; } hit.tiles += distance(*next, before); @@ -72,7 +72,7 @@ class StoryWorldModel{ {} std::optional> press(const State& pos, Direction direction) const{ - const std::optional next = m_world.step(pos, direction); + const std::optional next = step(m_world, pos, direction); if (!next){ return std::nullopt; } @@ -86,7 +86,7 @@ class StoryWorldModel{ return step; } bool held_at(const State& pos, Direction direction) const{ - return m_world.at_wall(pos, direction); + return at_wall(m_world, pos, direction); } private: @@ -95,7 +95,7 @@ class StoryWorldModel{ }; void check_standable(const StoryWorld& world, const TilePos& from, const TilePos& to){ - if (!world.standable(from) || !world.standable(to)){ + if (!standable(world, from) || !standable(world, to)){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( "Route ends must be standable: {} -> {}.", Pokemon::to_string(from), Pokemon::to_string(to) )); @@ -137,7 +137,7 @@ std::vector sight_tiles(const StoryWorld& world, const TrainerSight& tr TilePos pos = trainer.pos; for (int i = 0; i < trainer.range; i++){ pos = pos.next(trainer.facing); - if (!world.standable(pos)){ + if (!standable(world, pos)){ break; } tiles.push_back(pos); @@ -184,7 +184,7 @@ std::vector trace_legs( size_t travelled = 0; while (travelled < leg.tiles){ const TilePos pos = tiles.back(); - const std::optional next = world.step(pos, leg.direction); + const std::optional next = step(world, pos, leg.direction); if (!next){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( "Leg {} is stopped at {}.", to_string(leg), Pokemon::to_string(pos) @@ -223,9 +223,9 @@ std::optional step_tiles(const StoryWorld& world, TilePos from, Directi Stepped stepped; int travelled = 0; while (travelled < tiles){ - const std::optional next = world.step(from, direction); + const std::optional next = step(world, from, direction); if (!next){ - if (!world.at_wall(from, direction)){ + if (!at_wall(world, from, direction)){ return std::nullopt; } break; @@ -420,7 +420,7 @@ std::optional> plan_robust_route( const RobustPlanCosts& costs ){ for (const TilePos& pos : from){ - if (!world.standable(pos)){ + if (!standable(world, pos)){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route starts must be standable: " + Pokemon::to_string(pos) + "."); } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index 1786780d6c..656c684217 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -57,30 +57,37 @@ void StoryWorld::add(std::string name, const Pokemon::MapData& map, const TilePo placed.occupied.push_back({object.x, object.y}); } } - check_overlap(placed.name, placed); + check_overlap(placed); m_maps.push_back(std::move(placed)); rebuild(); } // Map images show a border of trees past their edges, so two maps may // share walls with nobody on them, but nothing else. -void StoryWorld::check_overlap(const std::string& name, const Placed& map) const{ - const auto free_wall = [](const Placed& placed, const TilePos& pos){ - return placed.tiles.at(pos) == TileKind::WALL && - std::find(placed.occupied.begin(), placed.occupied.end(), pos) == placed.occupied.end(); +std::optional StoryWorld::conflict(const Placed& map, const Placed& placed){ + const auto free_wall = [](const Placed& in, const TilePos& pos){ + return in.tiles.at(pos) == TileKind::WALL && + std::find(in.occupied.begin(), in.occupied.end(), pos) == in.occupied.end(); }; - for (const Placed& placed : m_maps){ - for (int y = 0; y < map.tiles.height; y++){ - for (int x = 0; x < map.tiles.width; x++){ - const TilePos other{map.offset.x + x - placed.offset.x, map.offset.y + y - placed.offset.y}; - if (placed.tiles.contains(other) && (!free_wall(map, {x, y}) || !free_wall(placed, other))){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( - "Map {} overlaps {} at its tile {}.", name, placed.name, Pokemon::to_string(TilePos{x, y}) - )); - } + for (int y = 0; y < map.tiles.height; y++){ + for (int x = 0; x < map.tiles.width; x++){ + const TilePos other{map.offset.x + x - placed.offset.x, map.offset.y + y - placed.offset.y}; + if (placed.tiles.contains(other) && (!free_wall(map, {x, y}) || !free_wall(placed, other))){ + return TilePos{x, y}; } } } + return std::nullopt; +} + +void StoryWorld::check_overlap(const Placed& map) const{ + for (const Placed& placed : m_maps){ + if (const std::optional at = conflict(map, placed)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Map {} overlaps {} at its tile {}.", map.name, placed.name, Pokemon::to_string(*at) + )); + } + } } void StoryWorld::rebuild(){ @@ -103,15 +110,7 @@ void StoryWorld::rebuild(){ m_cells = Pokemon::Grid{high.x - low.x, high.y - low.y, {}}; m_cells.cells.resize((size_t)m_cells.width * m_cells.height); for (auto iter = m_maps.rbegin(); iter != m_maps.rend(); ++iter){ - const TilePos corner{iter->offset.x - low.x, iter->offset.y - low.y}; - for (int y = 0; y < iter->tiles.height; y++){ - for (int x = 0; x < iter->tiles.width; x++){ - Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, iter->tiles.at({x, y}), false}; - } - } - for (const TilePos& pos : iter->occupied){ - Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}).occupied = true; - } + paint(*iter, {iter->offset.x - low.x, iter->offset.y - low.y}); } for (const TilePos& pos : m_blocked){ if (Cell* blocked = cell(pos)){ @@ -125,6 +124,17 @@ void StoryWorld::rebuild(){ } } +void StoryWorld::paint(const Placed& placed, const TilePos& corner){ + for (int y = 0; y < placed.tiles.height; y++){ + for (int x = 0; x < placed.tiles.width; x++){ + Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, placed.tiles.at({x, y}), false}; + } + } + for (const TilePos& pos : placed.occupied){ + Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}).occupied = true; + } +} + const StoryWorld::Cell* StoryWorld::cell(const TilePos& pos) const{ if (!m_cells.contains(pos) || !m_cells.at(pos).covered){ return nullptr; @@ -139,10 +149,6 @@ StoryWorld::Cell* StoryWorld::cell(const TilePos& pos){ } -bool StoryWorld::covered(const TilePos& pos) const{ - return cell(pos) != nullptr; -} - std::optional StoryWorld::tile(const TilePos& pos) const{ const Cell* found = cell(pos); if (found == nullptr){ @@ -156,33 +162,6 @@ bool StoryWorld::occupied(const TilePos& pos) const{ return found != nullptr && found->occupied; } -bool StoryWorld::standable(const TilePos& pos) const{ - const Cell* found = cell(pos); - return found != nullptr && !found->occupied && - (found->tile == TileKind::OPEN || found->tile == TileKind::TALL_GRASS); -} - -std::optional StoryWorld::step(const TilePos& from, Direction direction) const{ - const TilePos next = from.next(direction); - if (standable(next)){ - return next; - } - const Cell* found = cell(next); - if (found == nullptr || found->occupied || ledge_direction(found->tile) != direction){ - return std::nullopt; - } - const TilePos landing = next.next(direction); - if (standable(landing)){ - return landing; - } - return std::nullopt; -} - -bool StoryWorld::at_wall(const TilePos& pos, Direction direction) const{ - const std::optional next = tile(pos.next(direction)); - return next && *next != TileKind::DOOR && !step(pos, direction).has_value(); -} - void StoryWorld::block(const TilePos& pos){ if (Cell* found = cell(pos)){ found->occupied = true; @@ -217,10 +196,42 @@ std::optional StoryWorld::to_local(const TilePos& world) const{ return std::nullopt; } -std::string StoryWorld::describe(const TilePos& world) const{ - const std::optional local = to_local(world); + + +bool covered(const StoryWorld& world, const TilePos& pos){ + return world.tile(pos).has_value(); +} + +bool standable(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.tile(pos); + return tile && (*tile == TileKind::OPEN || *tile == TileKind::TALL_GRASS) && !world.occupied(pos); +} + +std::optional step(const StoryWorld& world, const TilePos& from, Direction direction){ + const TilePos next = from.next(direction); + if (standable(world, next)){ + return next; + } + const std::optional tile = world.tile(next); + if (!tile || world.occupied(next) || ledge_direction(*tile) != direction){ + return std::nullopt; + } + const TilePos landing = next.next(direction); + if (standable(world, landing)){ + return landing; + } + return std::nullopt; +} + +bool at_wall(const StoryWorld& world, const TilePos& pos, Direction direction){ + const std::optional next = world.tile(pos.next(direction)); + return next && *next != TileKind::DOOR && !step(world, pos, direction).has_value(); +} + +std::string describe(const StoryWorld& world, const TilePos& pos){ + const std::optional local = world.to_local(pos); if (!local){ - return "world " + Pokemon::to_string(world); + return "world " + Pokemon::to_string(pos); } return local->map + " " + Pokemon::to_string(local->pos); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index 236e1972b2..1953009657 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -44,27 +44,12 @@ class StoryWorld{ // maps together. void add(std::string name, const Pokemon::MapData& map, const Pokemon::TilePos& offset); - int width() const{ return m_cells.width; } - int height() const{ return m_cells.height; } - - // Whether a map holds this world tile. - bool covered(const Pokemon::TilePos& pos) const; // The tile, or nothing off the maps. std::optional tile(const Pokemon::TilePos& pos) const; // Whether someone or something stands still on this tile, or it was // blocked with block(). bool occupied(const Pokemon::TilePos& pos) const; - // Whether the player can stand on this tile. - bool standable(const Pokemon::TilePos& pos) const; - // Where one step from `from` lands, or nothing if the player is stopped. - // A step onto a ledge the arrow's way hops to the tile past it. - std::optional step(const Pokemon::TilePos& from, Pokemon::Direction direction) const; - // Whether a step from `pos` is refused by a tile that holds the player - // in place. Doors and tiles off the maps are not walls: walking into a - // door enters the building, and ground off the maps may be an exit. - bool at_wall(const Pokemon::TilePos& pos, Pokemon::Direction direction) const; - // Blocks a tile found in the way on the console. Tiles off the maps // are left alone. void block(const Pokemon::TilePos& pos); @@ -76,8 +61,6 @@ class StoryWorld{ Pokemon::TilePos to_world(const std::string& map, const Pokemon::TilePos& local) const; // The map that holds a world tile, or nothing between maps. std::optional to_local(const Pokemon::TilePos& world) const; - // "Route 201 (45, 3)", or "world (x, y)" if no map holds it. - std::string describe(const Pokemon::TilePos& world) const; private: struct Placed{ @@ -92,8 +75,12 @@ class StoryWorld{ bool occupied = false; }; - void check_overlap(const std::string& name, const Placed& map) const; + void check_overlap(const Placed& map) const; + // The first tile of `map` that `placed` holds as anything but a wall + // with nobody on it, or nothing. + static std::optional conflict(const Placed& map, const Placed& placed); void rebuild(); + void paint(const Placed& placed, const Pokemon::TilePos& corner); const Cell* cell(const Pokemon::TilePos& pos) const; Cell* cell(const Pokemon::TilePos& pos); @@ -105,6 +92,23 @@ class StoryWorld{ }; +// The rules of walking on a story world, from its tiles. + +// Whether a map holds this world tile. +bool covered(const StoryWorld& world, const Pokemon::TilePos& pos); +// Whether the player can stand on this tile. +bool standable(const StoryWorld& world, const Pokemon::TilePos& pos); +// Where one step from `from` lands, or nothing if the player is stopped. +// A step onto a ledge the arrow's way hops to the tile past it. +std::optional step(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); +// Whether a step from `pos` is refused by a tile that holds the player +// in place. Doors and tiles off the maps are not walls: walking into a +// door enters the building, and ground off the maps may be an exit. +bool at_wall(const StoryWorld& world, const Pokemon::TilePos& pos, Pokemon::Direction direction); +// "Route 201 (45, 3)", or "world (x, y)" if no map holds it. +std::string describe(const StoryWorld& world, const Pokemon::TilePos& pos); + + } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp index ec79f83bb0..3c6d8487cb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -81,7 +81,7 @@ class Test_Route202CatchGrass : public UnitTest{ } for (const TilePos& pos : legs->back().after){ if (!in_grass(pos)){ - return "From " + name + " to the catch grass: the walk may end on " + maps.describe(pos) + ", not in the grass."; + return "From " + name + " to the catch grass: the walk may end on " + describe(maps, pos) + ", not in the grass."; } } logger.log(std::format("From {} to the catch grass: {} legs, ending in the grass.", name, legs->size())); @@ -109,7 +109,7 @@ class Test_SandgemCenterApproach : public UnitTest{ } TilePos pos = sign.next(Direction::SOUTH); for (int tap = 0; tap < sign.x - door.x; tap++){ - const std::optional next = town.step(pos, Direction::WEST); + const std::optional next = step(town, pos, Direction::WEST); if (!next){ return "West from " + Pokemon::to_string(pos) + " is blocked."; } @@ -146,12 +146,12 @@ class Test_TrainingToSandgem : public UnitTest{ } for (const std::vector& from : starts){ const auto legs = plan_robust_route(maps, from, [&](const TilePos& pos){ return pos == entry; }, RobustPlanCosts()); - const std::string name = from.size() == 1 ? maps.describe(from[0]) : "the whole training area"; + const std::string name = from.size() == 1 ? describe(maps, from[0]) : "the whole training area"; if (!legs || legs->empty()){ return "From " + name + " into Sandgem: no plan."; } if (legs->back().after.size() != 1 || !(legs->back().after[0] == entry)){ - return "From " + name + " into Sandgem: the plan does not end on " + maps.describe(entry) + "."; + return "From " + name + " into Sandgem: the plan does not end on " + describe(maps, entry) + "."; } logger.log(std::format("From {} into Sandgem: {} legs.", name, legs->size())); } @@ -171,7 +171,7 @@ class Test_OreburghGymColumn : public UnitTest{ const StoryWorld gym = alone("OreburghGym"); const TilePos entrance = map_point("OreburghGym", "entrance"); const TilePos roark = map_point("OreburghGym", "roark"); - if (!gym.standable(entrance) || gym.tile(entrance.next(Direction::SOUTH)) != TileKind::DOOR){ + if (!standable(gym, entrance) || gym.tile(entrance.next(Direction::SOUTH)) != TileKind::DOOR){ return std::string("The entrance tile is not standable above the door."); } if (!gym.occupied(roark)){ @@ -213,7 +213,7 @@ class Test_RouteRecords : public UnitTest{ if (!record.traceable || !record.start){ continue; } - if (!world.standable(*record.start)){ + if (!standable(world, *record.start)){ return name + ": starts on " + Pokemon::to_string(*record.start) + ", where nobody can stand."; } std::vector counted; @@ -225,7 +225,7 @@ class Test_RouteRecords : public UnitTest{ } try{ const TilePos end = trace_legs(world, *record.start, counted).back(); - logger.log(std::format("{}: {} counted legs to {}.", name, counted.size(), world.describe(end))); + logger.log(std::format("{}: {} counted legs to {}.", name, counted.size(), describe(world, end))); }catch (InternalProgramError& e){ return name + ": " + e.message(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp index e409fcceb3..3fd80e93b8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -101,12 +101,12 @@ class Test_StoryWorldSteps : public UnitTest{ }; for (const StepCase& item : cases){ const StoryWorld world = make_world(make_map(item.rows, item.standing, item.wandering)); - const std::optional lands = world.step(item.from, item.direction); + const std::optional lands = step(world, item.from, item.direction); if (lands != item.lands){ return std::format("{}: lands on {}, expected {}.", item.name, lands ? Pokemon::to_string(*lands) : "nothing", item.lands ? Pokemon::to_string(*item.lands) : "nothing"); } - if (world.at_wall(item.from, item.direction) != item.at_wall){ + if (at_wall(world, item.from, item.direction) != item.at_wall){ return std::format("{}: at_wall() is {}, expected {}.", item.name, !item.at_wall, item.at_wall); } } @@ -133,11 +133,11 @@ class Test_StoryWorldJoin : public UnitTest{ {{2, 2}, "world (2, 2)"}, }; for (const auto& [pos, text] : described){ - if (world.describe(pos) != text){ - return std::format("{}: described as \"{}\", expected \"{}\".", Pokemon::to_string(pos), world.describe(pos), text); + if (describe(world, pos) != text){ + return std::format("{}: described as \"{}\", expected \"{}\".", Pokemon::to_string(pos), describe(world, pos), text); } } - if (world.width() != 3 || world.height() != 3 || world.covered({2, 2}) || !world.standable({2, 1})){ + if (!covered(world, {0, 2}) || covered(world, {3, 0}) || covered(world, {0, 3}) || covered(world, {2, 2}) || !standable(world, {2, 1})){ return std::string("The joined world is not 3 x 3 with East's grass at (2, 1) and nothing at (2, 2)."); } if (!(world.to_world("East", {0, 0}) == TilePos{1, 0})){ @@ -168,16 +168,16 @@ class Test_StoryWorldBlockUncover : public UnitTest{ world.add("Road", make_map({"...."}), {0, 0}); world.block({1, 0}); world.uncover({2, 0}); - if (world.step({0, 0}, Direction::EAST) || !world.at_wall({0, 0}, Direction::EAST)){ + if (step(world, {0, 0}, Direction::EAST) || !at_wall(world, {0, 0}, Direction::EAST)){ return std::string("A blocked tile is not a wall."); } - if (world.covered({2, 0}) || world.at_wall({3, 0}, Direction::WEST)){ + if (covered(world, {2, 0}) || at_wall(world, {3, 0}, Direction::WEST)){ return std::string("An uncovered tile is still on the map, or a wall."); } world.add("North", make_map({"#"}), {0, -1}); const TilePos blocked = world.to_world("Road", {1, 0}); const TilePos uncovered = world.to_world("Road", {2, 0}); - if (!world.occupied(blocked) || world.covered(uncovered) || !world.standable(world.to_world("Road", {3, 0}))){ + if (!world.occupied(blocked) || covered(world, uncovered) || !standable(world, world.to_world("Road", {3, 0}))){ return std::string("Adding a map lost the blocked or uncovered tile."); } return true; From d5046f2663f6caa3fcd0db56bb2f870af1309a41 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:41:24 -0800 Subject: [PATCH 17/74] BDSP navigation: the walker calls the story world's free functions Follows #127: standable(), step() and describe() take the world first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index bb3a012840..7cb39ac94b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -103,7 +103,7 @@ std::vector leg_path(const StoryWorld& grid, TilePos from, Direction di std::vector path; size_t travelled = 0; while (travelled < tiles){ - const std::optional next = grid.step(from, direction); + const std::optional next = step(grid, from, direction); if (!next){ break; } @@ -417,7 +417,7 @@ std::vector walk_route( const TilePos blocker = stopped[0].next(leg.direction); grid.block(blocker); stream.log("[Route] " + leg_label + ": something the map lacks is at " + - maps.describe(blocker) + "; marked it.", COLOR_ORANGE); + describe(maps, blocker) + "; marked it.", COLOR_ORANGE); } stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), "stopped early after about " + std::to_string(walked_tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); @@ -533,7 +533,7 @@ std::vector walk_route( const TilePos blocker = stopped[0].next(leg.direction); grid.block(blocker); stream.log("[Route] " + leg_label + ": something the map lacks is at " + - maps.describe(blocker) + "; marked it.", COLOR_ORANGE); + describe(maps, blocker) + "; marked it.", COLOR_ORANGE); } stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), "blocked after " + std::to_string(moved) + " of " + std::to_string(leg.tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); @@ -736,7 +736,7 @@ std::vector walk_waypoints( from = walk_route(stream, context, escape, maps, from, [&](const TilePos& pos){ return pos == goal; }, trainers, fight, - label + " (" + std::to_string(i + 1) + "/" + std::to_string(waypoints.size()) + ", to " + maps.describe(goal) + ")", + label + " (" + std::to_string(i + 1) + "/" + std::to_string(waypoints.size()) + ", to " + describe(maps, goal) + ")", {}, costs); } return from; @@ -754,7 +754,7 @@ void talk_to_npc( ){ for (Direction side : sides){ const TilePos stand = npc.next(side); - if (!maps.standable(stand)){ + if (!standable(maps, stand)){ continue; } at = walk_route(stream, context, escape, maps, at, [&](const TilePos& pos){ return pos == stand; }, @@ -769,13 +769,13 @@ void talk_to_npc( context.wait_for_all_requests(); ShortDialogWatcher dialog(COLOR_CYAN); if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, label + ": talking from " + maps.describe(stand) + "."); + route_status(stream, label + ": talking from " + describe(maps, stand) + "."); return; } - route_status(stream, label + ": nobody answered from " + maps.describe(stand) + "; trying another side."); + route_status(stream, label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); } OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": no side of " + maps.describe(npc) + " started a dialogue.", stream); + label + ": no side of " + describe(maps, npc) + " started a dialogue.", stream); } void finish_dialogue( From 6daf60615b1c16999a8c80f42ef9f92d7591c204 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:45:05 -0800 Subject: [PATCH 18/74] BDSP walker: formatting the code-health check asks for namespace X{ with no space, and if bodies on their own lines. No code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_OverworldDetector.cpp | 6 +++--- .../PokemonBDSP_AutoStory_OverworldDetector.h | 6 +++--- .../Utils/PokemonBDSP_AutoStory_Indoors.cpp | 16 ++++++++++++---- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp index 3e4e0f41ca..d9e759ec3a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp @@ -14,9 +14,9 @@ using namespace std::chrono_literals; -namespace PokemonAutomation { -namespace NintendoSwitch { -namespace PokemonBDSP { +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ // --------------------------------------------------------------------------- diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h index 4741325711..cf3d1ea2b6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h @@ -31,9 +31,9 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" -namespace PokemonAutomation { -namespace NintendoSwitch { -namespace PokemonBDSP { +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ // Static (single-frame) version — use when you already have a frame. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp index 8819372066..12baf6710f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp @@ -41,10 +41,18 @@ bool indoors(const ImageViewRGB32& screen){ count++; warm += pixel.red() > 150 && pixel.red() > pixel.blue() + 70 && pixel.green() > pixel.blue() + 20; const bool dark = pixel.red() + pixel.green() + pixel.blue() < 60; - if (y < strip_h){ add_pixel(top, dark); } - if (y >= height - strip_h){ add_pixel(bottom, dark); } - if (x < strip_w){ add_pixel(left, dark); } - if (x >= width - strip_w){ add_pixel(right, dark); } + if (y < strip_h){ + add_pixel(top, dark); + } + if (y >= height - strip_h){ + add_pixel(bottom, dark); + } + if (x < strip_w){ + add_pixel(left, dark); + } + if (x >= width - strip_w){ + add_pixel(right, dark); + } } } if (count == 0 || warm * 4 <= count){ From 91dfd2e39fd4463c02eeaf10a97b1105e8c9e1a4 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:45:20 -0800 Subject: [PATCH 19/74] BDSP walker: the story language behind a getter and a setter Code health rejects the non-const extern g_story_language. The program sets the language once before the story runs, so it now calls set_story_language(), and readers call story_language(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_Location.cpp | 17 +++++++++++++++-- .../Utils/PokemonBDSP_AutoStory_Location.h | 14 ++++++++------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp index ecf90056c7..6b63b5cf71 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -58,10 +58,23 @@ std::string normalize_location_name(const std::string& text){ return out; } -Language g_story_language = Language::English; +namespace{ +Language& story_language_setting(){ + static Language language = Language::English; + return language; +} +} + +Language story_language(){ + return story_language_setting(); +} + +void set_story_language(Language language){ + story_language_setting() = language; +} bool story_reads_text(){ - return story_reads_text(g_story_language); + return story_reads_text(story_language()); } bool story_reads_text(Language language){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h index 4294ede6eb..24bdc2ecc0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h @@ -24,12 +24,14 @@ namespace PokemonBDSP{ std::string normalize_location_name(const std::string& text); // The game's language, for the reads that still use text (item names, the -// location banner, a sign's or talk's first box), set from the program's -// options (StoryRunOptions). story_reads_text() says whether those reads -// have a model and dictionary for it (English only, so far); when not, -// callers use language-free checks: the banner's box showing, a sign's box -// opening, the first row of a Bag pocket. -extern Language g_story_language; +// location banner, a sign's or talk's first box), set once from the +// program's options (StoryRunOptions) before the story runs; English until +// then. story_reads_text() says whether those reads have a model and +// dictionary for it (English only, so far); when not, callers use +// language-free checks: the banner's box showing, a sign's box opening, the +// first row of a Bag pocket. +Language story_language(); +void set_story_language(Language language); bool story_reads_text(); bool story_reads_text(Language language); From 2bb2fb97f89cf72bd37e813a2fcfd8ac4640b668 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:47:51 -0800 Subject: [PATCH 20/74] BDSP walker: walks take a JoystickPosition, and options instead of bools Code health: walk_until() took 8 parameters, walk_until_dpad() 9 with a defaulted bool, walk_expecting() 9, and walk_until_impl() 12 with four bools over 126 lines. Every walk now takes the stick as one JoystickPosition. walk_until_dpad() takes DpadWalkOptions (arrived, and a DpadPace for B held) and walk_expecting() a WalkExpectation (the stop, and arrived). The walk loop is a WalkUntil class in the .cpp, with what it presses and how battles end it as enums. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 24 +- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 378 +++++++++++------- .../Utils/PokemonBDSP_AutoStory_Walk.h | 59 ++- 3 files changed, 284 insertions(+), 177 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index 7cb39ac94b..129795d797 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -327,7 +327,7 @@ std::vector walk_route( // Long enough to reach the wall from the farthest tile, with room // for a slow start; past the wall the player stands still. const Milliseconds limit = ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; - result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); // A wild battle may end the walk early. Walking to a wall again // ends in the same place, so finish the leg. const bool interrupted = result.wild_battles > 0; @@ -335,7 +335,7 @@ std::vector walk_route( (result.stop == WalkStop::LIMIT || result.stop == WalkStop::BLOCKED); again++ ){ stream.log("[Route] " + leg_label + ": a wild battle on the way; walking to the wall again."); - result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); } // A wall well before the nearest one the map has: something the // map does not know is in the way. Work out where we stopped from @@ -366,7 +366,7 @@ std::vector walk_route( pbf_press_dpad(context, dpad, 160ms, 640ms); } context.wait_for_all_requests(); - result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); walked_tiles += tiles_moved(result); } // Someone walking about may stand in the way for a moment: wait @@ -378,7 +378,7 @@ std::vector walk_route( " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); pbf_wait(context, 2500ms); context.wait_for_all_requests(); - result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label, watch_banner, true); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); walked_tiles += tiles_moved(result); } // Any stop short of the wall's distance: someone who stays put @@ -433,7 +433,7 @@ std::vector walk_route( // grass a stop reads, so walk on: a player still moving is // not where the plan has him. if (!interrupted && result.stop == WalkStop::LIMIT && route_wall_readable(grid, planned.after)){ - const WalkResult check = walk_until_dpad(stream, context, escape, x, y, 2000ms, leg_label + ": at the wall?", nullptr, true); + const WalkResult check = walk_until_dpad(stream, context, escape, {x, y}, 2000ms, leg_label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); if (check.stop == WalkStop::DIALOG){ // A trainer who saw us froze the walk (the "!") until // its time ran out, then walked over (r241a: Aroma Lady @@ -446,7 +446,7 @@ std::vector walk_route( // guess the tile: a leg to a wall ends at its wall however // far it got. Walk on to it. stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - result = walk_until_dpad(stream, context, escape, x, y, limit, leg_label + ": on to the wall", watch_banner, true); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); } if (check.stop != WalkStop::BLOCKED && !(check.stop == WalkStop::LIMIT && holding_against_wall(stream, context, x, y, leg_label + ": at the wall?")) @@ -478,7 +478,7 @@ std::vector walk_route( } } if (leg.tiles > turn_moved){ - result = walk_tiles_dpad(stream, context, escape, x, y, leg.tiles - turn_moved, leg_label); + result = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - turn_moved, leg_label); }else{ result = WalkResult{WalkStop::LIMIT, 0ms, 0}; } @@ -505,7 +505,7 @@ std::vector walk_route( std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); pbf_wait(context, 2500ms); context.wait_for_all_requests(); - const WalkResult rest = walk_tiles_dpad(stream, context, escape, x, y, leg.tiles - moved, leg_label + ": the rest"); + const WalkResult rest = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - moved, leg_label + ": the rest"); moved = std::min(leg.tiles, moved + taps_moved(rest)); result.stop = rest.stop; result.walked += rest.walked; @@ -627,7 +627,7 @@ std::vector walk_route( const Milliseconds limit = ROUTE_START_DELAY + ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(stream, context, escape, x, y, limit, leg_label + ": on to the wall", watch_banner, true); + walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); from = planned.after; log_leg_done(stream, maps, label, planned, 0); continue; @@ -669,7 +669,7 @@ std::vector walk_route( const Milliseconds limit = ROUTE_START_DELAY + ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(stream, context, escape, x, y, limit, leg_label + ": on to the wall", watch_banner, true); + walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); from = planned.after; log_leg_done(stream, maps, label, planned, 0); continue; @@ -829,7 +829,7 @@ void enter_door_north(VideoStream& stream, ProControllerContext& context, const // one more. const Direction steps[] = {Direction::EAST, Direction::WEST, Direction::WEST}; for (size_t attempt = 0; attempt <= 3; attempt++){ - const WalkResult walk = walk_until(stream, context, escape, 0, 1, 2500ms, label); + const WalkResult walk = walk_until(stream, context, escape, {0, 1}, 2500ms, label); if (walk.stop == WalkStop::TRANSITION){ context.wait_for(1500ms); return; @@ -900,7 +900,7 @@ void leave_door_south(VideoStream& stream, ProControllerContext& context, const }; bool out = false; for (size_t tries = 0; tries < 5 && !out; tries++){ - const WalkResult walk = walk_until(stream, context, escape, 0, -1, 6000ms, label, out_of_door); + const WalkResult walk = walk_until(stream, context, escape, {0, -1}, 6000ms, label, out_of_door); if (walk.stop == WalkStop::DIALOG){ pbf_mash_button(context, BUTTON_B, 2000ms); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index eb0ec4ce02..5cdc90dc3e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -163,182 +163,273 @@ class WalkProbeSampler : public VisualInferenceCallback{ namespace{ -WalkResult walk_until_impl( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - const std::function& arrived, - bool wild, bool dpad, bool run, bool taps = false -); -} - -WalkResult walk_until( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - const std::function& arrived -){ - return walk_until_impl(stream, context, escape, x, y, limit, label, arrived, true, false, false); -} - -WalkResult walk_until_dpad( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - const std::function& arrived, - bool run -){ - return walk_until_impl(stream, context, escape, x, y, limit, label, arrived, true, true, run); -} -WalkResult walk_tiles_dpad( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, size_t tiles, const std::string& label -){ - return walk_until_impl(stream, context, escape, x, y, 800ms * tiles, label, nullptr, true, true, false, true); -} +// What a walk presses. +enum class WalkInput{ + STICK, + DPAD, + DPAD_RUN, // the D-pad with B held + TAPS, // a D-pad tap a tile, 800 ms each +}; +// What a battle that starts on the way is. +enum class WildPolicy{ + RUN_FROM, // a wild battle: run, and walk on + STOP_AT, // no wild Pokemon here: a trainer's, so the walk stops with DIALOG +}; -WalkResult walk_until_no_wild( - VideoStream& stream, ProControllerContext& context, - double x, double y, Milliseconds limit, const std::string& label -){ - // With no wild Pokemon any battle is a trainer's, and the walk stops at - // it (DIALOG) without running. - const WildBattleEscape no_wild = [](VideoStream& stream, ProControllerContext&){ - throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "walk_until_no_wild() ran from a battle."); - }; - return walk_until_impl(stream, context, no_wild, x, y, limit, label, nullptr, false, false, false); -} +struct WalkSpec{ + JoystickPosition stick; + Milliseconds limit = 0ms; + std::string label; + WalkArrived arrived = nullptr; + WalkInput input = WalkInput::STICK; + WildPolicy wild = WildPolicy::RUN_FROM; +}; -namespace{ -WalkResult walk_until_impl( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - const std::function& arrived, - bool wild, bool dpad, bool run, bool taps -){ - // A tile a tap: 160 ms held, the rest released, so each chunk is one tile. - const Milliseconds CHUNK = taps ? 800ms : 400ms; - const DpadPosition dpad_direction = x < 0 ? DPAD_LEFT : x > 0 ? DPAD_RIGHT : y > 0 ? DPAD_UP : DPAD_DOWN; - WalkResult result{WalkStop::LIMIT, 0ms, 0}; - size_t unchanged = 0; - // The largest change a chunk of this walk made: a step. A bump into an - // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old - // woman), over the fixed line of 16, so "still" is also anything under - // 40% of the walk's own steps. - double largest = 0; +// What a chunk of the walk decided: stop with `stop`, walk the next chunk, +// or (after the watchers) look at how the screen changed. +enum class ChunkNext{ + STOP, + NEXT_CHUNK, + LOOK, +}; +struct ChunkVerdict{ + ChunkNext next = ChunkNext::LOOK; + WalkStop stop = WalkStop::LIMIT; +}; - context.wait_for_all_requests(); - VideoSnapshot before = snapshot_or_fail(stream, label); - auto finish = [&](WalkStop stop){ - result.stop = stop; - if (wild && (stop == WalkStop::LIMIT || stop == WalkStop::BLOCKED) && - run_from_late_encounter(stream, context, escape, label) - ){ - result.wild_battles++; - } - stream.log("[Walk] " + label + ": " + walk_stop_name(stop) + " after " + - std::to_string(result.walked.count()) + "ms, " + - std::to_string(result.wild_battles) + " wild battle(s)."); - return result; - }; +// walk_until() and its variants: holds the input a chunk at a time, and +// after each chunk reads the watchers, then the screen. +class WalkUntil{ +public: + WalkUntil(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const WalkSpec& spec) + : m_stream(stream) + , m_context(context) + , m_escape(escape) + , m_spec(spec) + , m_dpad(spec.stick.x < 0 ? DPAD_LEFT : spec.stick.x > 0 ? DPAD_RIGHT : spec.stick.y > 0 ? DPAD_UP : DPAD_DOWN) + {} - while (true){ - if (arrived && arrived(*before.frame)){ - return finish(WalkStop::ARRIVED); - } - if (result.walked >= limit){ - return finish(WalkStop::LIMIT); + WalkResult run(){ + // A tile a tap: 160 ms held, the rest released, so each chunk is one tile. + const Milliseconds CHUNK = m_spec.input == WalkInput::TAPS ? 800ms : 400ms; + m_context.wait_for_all_requests(); + m_before = snapshot_or_fail(m_stream, m_spec.label); + while (true){ + if (m_spec.arrived && m_spec.arrived(*m_before.frame)){ + return finish(WalkStop::ARRIVED); + } + if (m_result.walked >= m_spec.limit){ + return finish(WalkStop::LIMIT); + } + const Milliseconds chunk = std::min(CHUNK, m_spec.limit - m_result.walked); + const int ret = hold(chunk); + m_result.walked += chunk; + ChunkVerdict verdict = after_watchers(ret); + if (verdict.next == ChunkNext::LOOK){ + verdict = look(); + } + if (verdict.next == ChunkNext::STOP){ + return finish(verdict.stop); + } } - const Milliseconds chunk = std::min(CHUNK, limit - result.walked); + } +private: + int hold(Milliseconds chunk){ WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); BlackScreenWatcher black(COLOR_RED); BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); ShortDialogWatcher dialog(COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); - const int ret = run_until( - stream, context, + return run_until( + m_stream, m_context, [&](ProControllerContext& context){ - if (taps){ - pbf_press_dpad(context, dpad_direction, 160ms, chunk - 160ms); - }else if (dpad && run){ - ssf_press_button(context, BUTTON_B, 0ms, chunk, 0ms); - ssf_press_dpad(context, dpad_direction, chunk, chunk, 0ms); - }else if (dpad){ - pbf_press_dpad(context, dpad_direction, chunk, 0ms); - }else{ - pbf_move_left_joystick(context, {x, y}, chunk, 0ms); - } + press(context, chunk); }, {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} ); - result.walked += chunk; + } + + void press(ProControllerContext& context, Milliseconds chunk) const{ + switch (m_spec.input){ + case WalkInput::TAPS: + pbf_press_dpad(context, m_dpad, 160ms, chunk - 160ms); + return; + case WalkInput::DPAD_RUN: + ssf_press_button(context, BUTTON_B, 0ms, chunk, 0ms); + ssf_press_dpad(context, m_dpad, chunk, chunk, 0ms); + return; + case WalkInput::DPAD: + pbf_press_dpad(context, m_dpad, chunk, 0ms); + return; + case WalkInput::STICK: + pbf_move_left_joystick(context, m_spec.stick, chunk, 0ms); + return; + } + } + // The watchers: 0 the encounter flash, 1 black, 2 the battle menu, 3 a + // dialogue, 4 the battle's text box. + ChunkVerdict after_watchers(int ret){ bool battle = ret == 0 || ret == 2 || ret == 4; if (ret == 1){ - battle = black_screen_was_battle(stream, context); + battle = black_screen_was_battle(m_stream, m_context); if (!battle){ - return finish(WalkStop::TRANSITION); + return {ChunkNext::STOP, WalkStop::TRANSITION}; } } - if (battle && !wild){ - stream.log("[Walk] " + label + ": a battle started; a trainer's here."); - return finish(WalkStop::DIALOG); + if (battle && m_spec.wild == WildPolicy::STOP_AT){ + m_stream.log("[Walk] " + m_spec.label + ": a battle started; a trainer's here."); + return {ChunkNext::STOP, WalkStop::DIALOG}; } if (battle){ - result.wild_battles++; - stream.log("[Walk] " + label + ": wild battle; running."); - escape(stream, context); - context.wait_for_all_requests(); - before = snapshot_or_fail(stream, label); - unchanged = 0; - continue; + escape_battle("wild battle; running."); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } if (ret == 3){ - return finish(WalkStop::DIALOG); + return {ChunkNext::STOP, WalkStop::DIALOG}; } + return {ChunkNext::LOOK, WalkStop::LIMIT}; + } - context.wait_for_all_requests(); - VideoSnapshot after = snapshot_or_fail(stream, label); - const double change = walk_screen_change(*before.frame, *after.frame); - stream.log("[Walk] " + label + ": " + std::to_string(result.walked.count()) + + ChunkVerdict look(){ + m_context.wait_for_all_requests(); + VideoSnapshot after = snapshot_or_fail(m_stream, m_spec.label); + const double change = walk_screen_change(*m_before.frame, *after.frame); + m_stream.log("[Walk] " + m_spec.label + ": " + std::to_string(m_result.walked.count()) + "ms, screen change " + std::to_string(change) + "."); - if (change > WALK_SCENE_CHANGE && !wild && battle_follows(stream, context)){ - stream.log("[Walk] " + label + ": a battle started; a trainer's here."); - return finish(WalkStop::DIALOG); + if (change > WALK_SCENE_CHANGE && m_spec.wild == WildPolicy::STOP_AT && battle_follows(m_stream, m_context)){ + m_stream.log("[Walk] " + m_spec.label + ": a battle started; a trainer's here."); + return {ChunkNext::STOP, WalkStop::DIALOG}; } - if (change > WALK_SCENE_CHANGE && battle_follows(stream, context)){ - result.wild_battles++; - stream.log("[Walk] " + label + ": wild battle (leaf opening); running."); - escape(stream, context); - context.wait_for_all_requests(); - before = snapshot_or_fail(stream, label); - unchanged = 0; - continue; + if (change > WALK_SCENE_CHANGE && battle_follows(m_stream, m_context)){ + escape_battle("wild battle (leaf opening); running."); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } // Two still chunks in a row, so one dropped frame does not stop us. A // frame exactly the same is a stalled video or a game hitch, not a wall: // standing at a wall still animates. if (change == 0){ - before = std::move(after); - continue; + m_before = std::move(after); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } - largest = std::max(largest, change); - const double line = taps ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * largest) : WALK_BLOCKED_CHANGE; - const bool still = change < line; + const bool still = still_chunk(change); if (!still){ - result.moved_chunks++; + m_result.moved_chunks++; + } + m_unchanged = still ? m_unchanged + 1 : 0; + if (m_unchanged >= 2){ + return {ChunkNext::STOP, WalkStop::BLOCKED}; } - unchanged = still ? unchanged + 1 : 0; - if (unchanged >= 2){ - return finish(WalkStop::BLOCKED); + m_before = std::move(after); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; + } + + // The largest change a chunk of this walk made is a step. A bump into an + // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old + // woman), over the fixed line of 16, so for taps "still" is also + // anything under 40% of the walk's own steps. + bool still_chunk(double change){ + m_largest = std::max(m_largest, change); + const double line = m_spec.input == WalkInput::TAPS + ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * m_largest) + : WALK_BLOCKED_CHANGE; + return change < line; + } + + void escape_battle(const std::string& what){ + m_result.wild_battles++; + m_stream.log("[Walk] " + m_spec.label + ": " + what); + m_escape(m_stream, m_context); + m_context.wait_for_all_requests(); + m_before = snapshot_or_fail(m_stream, m_spec.label); + m_unchanged = 0; + } + + WalkResult finish(WalkStop stop){ + m_result.stop = stop; + if (m_spec.wild == WildPolicy::RUN_FROM && (stop == WalkStop::LIMIT || stop == WalkStop::BLOCKED) && + run_from_late_encounter(m_stream, m_context, m_escape, m_spec.label) + ){ + m_result.wild_battles++; } - before = std::move(after); + m_stream.log("[Walk] " + m_spec.label + ": " + walk_stop_name(stop) + " after " + + std::to_string(m_result.walked.count()) + "ms, " + + std::to_string(m_result.wild_battles) + " wild battle(s)."); + return m_result; } + + VideoStream& m_stream; + ProControllerContext& m_context; + const WildBattleEscape& m_escape; + const WalkSpec& m_spec; + const DpadPosition m_dpad; + WalkResult m_result{WalkStop::LIMIT, 0ms, 0}; + VideoSnapshot m_before; + size_t m_unchanged = 0; + double m_largest = 0; +}; + +WalkResult walk_until_spec( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const WalkSpec& spec +){ + return WalkUntil(stream, context, escape, spec).run(); } + +} + +WalkResult walk_until( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkArrived& arrived +){ + return walk_until_spec(stream, context, escape, { + .stick = stick, .limit = limit, .label = label, .arrived = arrived, + .input = WalkInput::STICK, .wild = WildPolicy::RUN_FROM, + }); +} + +WalkResult walk_until_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const DpadWalkOptions& options +){ + return walk_until_spec(stream, context, escape, { + .stick = stick, .limit = limit, .label = label, .arrived = options.arrived, + .input = options.pace == DpadPace::RUN ? WalkInput::DPAD_RUN : WalkInput::DPAD, + .wild = WildPolicy::RUN_FROM, + }); +} + +WalkResult walk_tiles_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, size_t tiles, const std::string& label +){ + return walk_until_spec(stream, context, escape, { + .stick = stick, .limit = 800ms * tiles, .label = label, .arrived = nullptr, + .input = WalkInput::TAPS, .wild = WildPolicy::RUN_FROM, + }); +} + +WalkResult walk_until_no_wild( + VideoStream& stream, ProControllerContext& context, + JoystickPosition stick, Milliseconds limit, const std::string& label +){ + // With no wild Pokemon any battle is a trainer's, and the walk stops at + // it (DIALOG) without running. + const WildBattleEscape no_wild = [](VideoStream& stream, ProControllerContext&){ + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "walk_until_no_wild() ran from a battle."); + }; + return walk_until_spec(stream, context, no_wild, { + .stick = stick, .limit = limit, .label = label, .arrived = nullptr, + .input = WalkInput::STICK, .wild = WildPolicy::STOP_AT, + }); } WalkResult walk_for( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds duration, const std::string& label + JoystickPosition stick, Milliseconds duration, const std::string& label ){ WalkResult result{WalkStop::LIMIT, duration, 0}; context.wait_for_all_requests(); @@ -350,7 +441,7 @@ WalkResult walk_for( const int ret = run_until( stream, context, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, {x, y}, duration, 0ms); + pbf_move_left_joystick(context, stick, duration, 0ms); }, {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} ); @@ -382,11 +473,11 @@ WalkResult walk_for( WalkResult walk_to_talk( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label + JoystickPosition stick, Milliseconds limit, const std::string& label ){ WalkResult total{WalkStop::LIMIT, 0ms, 0}; while (total.walked < limit){ - const WalkResult step = walk_until(stream, context, escape, x, y, + const WalkResult step = walk_until(stream, context, escape, stick, std::min(400ms, limit - total.walked), label); total.walked += step.walked; total.wild_battles += step.wild_battles; @@ -414,7 +505,7 @@ WalkResult walk_to_talk( WalkProbe probe_walk( VideoStream& stream, ProControllerContext& context, - double x, double y, Milliseconds limit, + JoystickPosition stick, Milliseconds limit, double moving_change, const std::string& label ){ WalkProbe result; @@ -423,7 +514,7 @@ WalkProbe probe_walk( run_until( stream, context, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, {x, y}, limit, 0ms); + pbf_move_left_joystick(context, stick, limit, 0ms); }, {{sampler}} ); @@ -435,9 +526,9 @@ WalkProbe probe_walk( WalkResult walk_to_wall( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label + JoystickPosition stick, Milliseconds limit, const std::string& label ){ - const WalkResult result = walk_until(stream, context, escape, x, y, limit, label); + const WalkResult result = walk_until(stream, context, escape, stick, limit, label); if (result.stop == WalkStop::DIALOG || result.stop == WalkStop::TRANSITION){ OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, label + ": " + walk_stop_name(result.stop) + " instead of a wall.", stream); @@ -450,14 +541,13 @@ WalkResult walk_to_wall( WalkResult walk_expecting( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - WalkStop expected, - const std::function& arrived + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkExpectation& expected ){ - const WalkResult result = walk_until(stream, context, escape, x, y, limit, label, arrived); - if (result.stop != expected){ + const WalkResult result = walk_until(stream, context, escape, stick, limit, label, expected.arrived); + if (result.stop != expected.stop){ OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": expected " + walk_stop_name(expected) + ", got " + + label + ": expected " + walk_stop_name(expected.stop) + ", got " + walk_stop_name(result.stop) + ".", stream); } return result; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index 15622b26f4..9beb976f6e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -16,6 +16,7 @@ #include "Common/Cpp/Time.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Tools/VideoStream.h" +#include "Controllers/Joystick.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" namespace PokemonAutomation{ @@ -37,6 +38,9 @@ enum class WalkStop{ }; const char* walk_stop_name(WalkStop stop); +// Whether the walk has arrived, from the screen after each chunk. +using WalkArrived = std::function; + struct WalkResult{ WalkStop stop; Milliseconds walked; @@ -48,26 +52,35 @@ struct WalkResult{ size_t moved_chunks = 0; }; -// Holds the left stick at (x, y) until one of the WalkStop events. Wild battles on +// Holds the left stick at `stick` until one of the WalkStop events. Wild battles on // the way are run from, and walking resumes. Does not throw for any WalkStop; the // caller decides which ones are expected. WalkResult walk_until( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - const std::function& arrived = nullptr + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkArrived& arrived = nullptr ); +// How walk_until_dpad() presses: RUN holds B too, twice as fast and as +// tile-true. +enum class DpadPace{ + WALK, + RUN, +}; +struct DpadWalkOptions{ + WalkArrived arrived = nullptr; + DpadPace pace = DpadPace::WALK; +}; + // walk_until() on the D-pad, for a straight walk along a row or a column -// ((x, y) is one of the four directions). The D-pad moves whole tiles and +// (`stick` is one of the four directions). The D-pad moves whole tiles and // keeps to the row: the stick drifts off it, catches tree corners and slides // a row on stairs (Route 203, r226a and r227b; by hand the D-pad went -// through the same places). With `run`, B is held too: twice as fast, and -// as tile-true. +// through the same places). WalkResult walk_until_dpad( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - const std::function& arrived = nullptr, - bool run = false + JoystickPosition stick, Milliseconds limit, const std::string& label, + const DpadWalkOptions& options = {} ); // A set number of whole tiles on the D-pad, a tap a tile (a tap moves @@ -76,7 +89,7 @@ WalkResult walk_until_dpad( // LIMIT after `tiles` taps, or BLOCKED when two taps in a row move nothing. WalkResult walk_tiles_dpad( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, size_t tiles, const std::string& label + JoystickPosition stick, size_t tiles, const std::string& label ); // walk_until() where there are no wild Pokemon (a gym, a building): any @@ -85,25 +98,29 @@ WalkResult walk_tiles_dpad( // (r206d tried to run from the second Oreburgh Gym trainer). WalkResult walk_until_no_wild( VideoStream& stream, ProControllerContext& context, - double x, double y, Milliseconds limit, const std::string& label + JoystickPosition stick, Milliseconds limit, const std::string& label ); -// Holds the left stick at (x, y) for `duration` in one go, for a walk of a +// Holds the left stick at `stick` for `duration` in one go, for a walk of a // set length: walk_until() checks the screen between short holds, and each // break can cost a step. Stops early for a dialog or a transition. A wild // battle is run from and ends the walk with `wild_battles` 1, at a place the // caller cannot know. WalkResult walk_for( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds duration, const std::string& label + JoystickPosition stick, Milliseconds duration, const std::string& label ); -// walk_until() that requires `expected`. Fails with the screenshot otherwise. +// The stop walk_expecting() requires, and what counts as arrived. +struct WalkExpectation{ + WalkStop stop = WalkStop::ARRIVED; + WalkArrived arrived = nullptr; +}; +// walk_until() that requires `expected.stop`. Fails with the screenshot otherwise. WalkResult walk_expecting( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label, - WalkStop expected, - const std::function& arrived = nullptr + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkExpectation& expected ); // After a move that may have walked onto an encounter tile (a tap in a cave @@ -119,7 +136,7 @@ bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, // next gate. Fails on a dialog or a transition: we are not where we think. WalkResult walk_to_wall( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label + JoystickPosition stick, Milliseconds limit, const std::string& label ); // Walks toward someone to talk to: after each short stretch, presses A and stops @@ -127,7 +144,7 @@ WalkResult walk_to_wall( // BLOCKED, e.g. in tall grass, whose sway keeps the screen changing. WalkResult walk_to_talk( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - double x, double y, Milliseconds limit, const std::string& label + JoystickPosition stick, Milliseconds limit, const std::string& label ); // How much the screen changed between two frames, 0 for identical. Walking scrolls @@ -145,7 +162,7 @@ constexpr double WALK_SCENE_CHANGE = 120.0; // One straight walk timed finely, to check a map against the game: holds the -// stick at (x, y) and samples the screen every 100ms until the view has been +// stick at `stick` and samples the screen every 100ms until the view has been // still for 800ms or `limit` runs out. Times count from the start of the hold. // A sample moved if it changed by at least `moving_change`: still is 4 to 7, // walking 16 to 85. Handles no battles or dialogs: use it on open ground, @@ -161,7 +178,7 @@ struct WalkProbe{ }; WalkProbe probe_walk( VideoStream& stream, ProControllerContext& context, - double x, double y, Milliseconds limit, + JoystickPosition stick, Milliseconds limit, double moving_change, const std::string& label ); From b678b4a377d8ba20276422d7822baf7bff959e25 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:49:09 -0800 Subject: [PATCH 21/74] BDSP walker: walk_route() and its helpers move to PlannedRoute RouteWalk.cpp was 926 lines, and splitting walk_route() into functions would take it past the 1000-line limit. walk_route(), walk_waypoints(), talk_to_npc(), RouteTrainerFight and the route-log helpers they use move unchanged to PokemonBDSP_AutoStory_PlannedRoute.{h,cpp}. RouteWalk exposes route_ms_per_tile() and route_stick() for them. Review with: git diff --color-moved HEAD~1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 670 ++++++++++++++++++ .../PokemonBDSP_AutoStory_PlannedRoute.h | 92 +++ .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 664 +---------------- .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 72 +- SerialPrograms/cmake/SourceFiles.cmake | 2 + 5 files changed, 789 insertions(+), 711 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp new file mode 100644 index 0000000000..5d80952053 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -0,0 +1,670 @@ +/* BDSP AutoStory - Planned Route + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_PlannedRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using namespace Pokemon; + + +namespace{ + +// World tiles as tiles of the named maps, for the shared route log +// (Pokemon_RouteLog.h); a tile no map holds is a "world" tile. +std::vector route_tiles(const StoryWorld& maps, const std::vector& tiles){ + std::vector out; + for (const TilePos& pos : tiles){ + const std::optional local = maps.to_local(pos); + out.push_back(local ? RouteTile{local->map, local->pos} : RouteTile{"world", pos}); + } + return out; +} + +std::string describe(const StoryWorld& maps, const std::vector& tiles){ + return Pokemon::describe(route_tiles(maps, tiles)); +} + +RouteLogLeg route_log_leg(const TileLeg& leg){ + return {.action = RouteLegAction::WALK, .direction = leg.direction, .tiles = leg.tiles, + .end = leg.ends_at_wall ? RouteLegEnd::WALL : RouteLegEnd::OPEN}; +} + +PlannedRouteLeg planned_route_leg(const StoryWorld& maps, const PlannedLeg& leg){ + return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; +} + +void log_plan(VideoStream& stream, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ + std::vector logged; + for (const PlannedLeg& leg : legs){ + logged.push_back(planned_route_leg(maps, leg)); + } + stream.log(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged)); +} + +// Logs a leg that ended on its planned tiles, and how that is known: an +// open leg counts its taps through a wild battle, so its end is assumed; a +// leg to a wall is walked again to its wall. +void log_leg_done(VideoStream& stream, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ + const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; + stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), + assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); +} + +// The tiles the player passes when walking `tiles` tiles from `from`, the +// first one after `from` first. Stops early where the player is stopped. +std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ + std::vector path; + size_t travelled = 0; + while (travelled < tiles){ + const std::optional next = step(grid, from, direction); + if (!next){ + break; + } + travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); + from = *next; + path.push_back(from); + } + return path; +} + +// Holding toward a wall with people or Pokemon moving beside us never reads +// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking +// scrolls the view far more (35 to 90). True if holding toward (x, y) for +// 1.6 s changes the screen less than walking would: we stand at a wall. +bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ + constexpr double WALKING_CHANGE = 25.0; + context.wait_for_all_requests(); + VideoSnapshot before = stream.video().snapshot(); + double most = 0; + for (size_t chunk = 0; chunk < 4 && before; chunk++){ + pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); + context.wait_for_all_requests(); + VideoSnapshot after = stream.video().snapshot(); + if (!after){ + return false; + } + most = std::max(most, walk_screen_change(*before.frame, *after.frame)); + before = std::move(after); + } + stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + + (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); + return before && most < WALKING_CHANGE; +} + +// The map all of `tiles` are on, or empty if they are on several or none. +std::string map_of(const StoryWorld& maps, const std::vector& tiles){ + std::string name; + for (const TilePos& pos : tiles){ + const std::optional tile = maps.to_local(pos); + if (!tile || (!name.empty() && tile->map != name)){ + return ""; + } + name = tile->map; + } + return name; +} + +} + + +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, + std::vector from, + const std::function& goal, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const std::vector& avoid, + const RobustPlanCosts& costs +){ + // Our own copy, so things found in the way can be added to it. Tiles to + // avoid are ground the game lets us walk on (a trainer's line of sight), + // so they are off the map, not walls: a leg must not end "at" one, or + // the walk would run on through it. + StoryWorld grid = maps; + for (const TilePos& pos : avoid){ + if (std::find(from.begin(), from.end(), pos) == from.end()){ + grid.uncover(pos); + } + } + // Which way the player faces, once a leg has set it. + std::optional facing; + // Every banner read on the way, to check the map we arrive on against. + const std::string map_start = map_of(maps, from); + std::vector all_banners; + for (size_t plans = 0; plans < 8; plans++){ + std::optional> legs = plan_robust_route(grid, from, goal, costs); + if (!legs){ + // From a few possible tiles the exact-open-leg costs found no + // plan where the default ones did (r240a, three tiles on Route + // 204's row 27); the default plan is longer but sound. + stream.log("[Route] " + label + ": no plan with the route costs from " + describe(maps, from) + + "; trying the default costs.", COLOR_ORANGE); + legs = plan_robust_route(grid, from, goal, RobustPlanCosts()); + } + if (!legs){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": no plan from " + describe(maps, from) + ".", stream); + } + route_status(stream, label + ": " + std::to_string(legs->size()) + " legs planned"); + log_plan(stream, maps, label, from, *legs); + + bool replanned = false; + size_t leg_number = 0; + for (const PlannedLeg& planned : *legs){ + const TileLeg& leg = planned.leg; + leg_number++; + route_status(stream, route_leg_line(leg_number, legs->size(), planned_route_leg(maps, planned))); + const double x = route_stick(leg.direction).x; + const double y = route_stick(leg.direction).y; + const std::string leg_label = label + ": " + to_string(leg); + + // Note the location banners the walk passes, to check map changes. + // A wild battle or a second walk to the wall may follow the + // banner: any banner seen during the leg counts. + const std::string map_before = map_of(maps, from); + const std::string map_after = map_of(maps, planned.after); + std::vector banners; + auto banner_ok = [&]{ + return std::any_of(banners.begin(), banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_after); + }); + }; + auto watch_banner = [&](const ImageViewRGB32& screen){ + if (banners.empty() || (!map_after.empty() && !banner_ok() && banners.size() < 8)){ + const std::string read = read_location_banner(screen); + if (!read.empty() && (banners.empty() || banners.back() != read)){ + banners.push_back(read); + } + } + return false; + }; + + WalkResult result; + // Tiles the first tap of an open leg moved (see below). + size_t turn_moved = 0; + if (leg.ends_at_wall){ + // Run (B held) on the D-pad: a leg to a wall ends at the wall + // however fast we get there, and the D-pad keeps to the row. + const Milliseconds per_tile = route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; + // Long enough to reach the wall from the farthest tile, with room + // for a slow start; past the wall the player stands still. + const Milliseconds limit = ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); + // A wild battle may end the walk early. Walking to a wall again + // ends in the same place, so finish the leg. + const bool interrupted = result.wild_battles > 0; + for (size_t again = 0; again < 3 && result.wild_battles > 0 && + (result.stop == WalkStop::LIMIT || result.stop == WalkStop::BLOCKED); again++ + ){ + stream.log("[Route] " + leg_label + ": a wild battle on the way; walking to the wall again."); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); + } + // A wall well before the nearest one the map has: something the + // map does not know is in the way. Work out where we stopped from + // the time walked, put it on our map and plan again from there. + size_t nearest = SIZE_MAX; + for (const TilePos& pos : from){ + nearest = std::min(nearest, slide_to_wall(grid, pos, leg.direction).tiles); + } + auto tiles_moved = [&](const WalkResult& walk){ + const Milliseconds moving = walk.walked - ROUTE_START_DELAY - + (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); + return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); + }; + size_t walked_tiles = tiles_moved(result); + // A stick walk can catch a corner when we stand part of a tile + // off centre, where a D-pad tap, which moves whole tiles, gets + // through: on Route 203's stairs the walk west stopped nine + // times in a row and two taps crossed (r225a, 2026-10-31). + // Tap twice, then walk on to the wall. + if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ + const DpadPosition dpad = + leg.direction == Direction::NORTH ? DPAD_UP : + leg.direction == Direction::SOUTH ? DPAD_DOWN : + leg.direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; + stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); + for (size_t tap = 0; tap < 2; tap++){ + pbf_press_dpad(context, dpad, 160ms, 640ms); + } + context.wait_for_all_requests(); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); + walked_tiles += tiles_moved(result); + } + // Someone walking about may stand in the way for a moment: wait + // and walk to the wall again before calling it an obstacle. + for (size_t again = 0; !interrupted && again < 2 && + result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++ + ){ + stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); + walked_tiles += tiles_moved(result); + } + // Any stop short of the wall's distance: someone who stays put + // is talked to, and the leg is planned again from where we are. + // Within the time count's slack this may be the wall itself, + // where A does nothing and the new plan walks no further (r239a: + // a wanderer 3 tiles short passed as "about 8 of 10", and every + // later leg was off by those tiles). + if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ + // Someone who stays put: talk to them. A trainer we walked up + // to from the side starts the battle this way. + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + { + ShortDialogWatcher dialog(COLOR_YELLOW); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, leg_label + ": someone is in the way; talking to them."); + fight("someone in the way"); + } + } + std::vector stopped; + for (const TilePos& pos : from){ + const std::vector path = leg_path(grid, pos, leg.direction, SIZE_MAX); + for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ + stopped.push_back(k == 0 ? pos : path[k - 1]); + } + } + std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": stopped early, and no tile fits.", stream); + } + if (stopped.size() == 1){ + const TilePos blocker = stopped[0].next(leg.direction); + grid.block(blocker); + stream.log("[Route] " + leg_label + ": something the map lacks is at " + + describe(maps, blocker) + "; marked it.", COLOR_ORANGE); + } + stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), + "stopped early after about " + std::to_string(walked_tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); + facing = leg.direction; + from = stopped; + replanned = true; + break; + } + // A leg to the wall that ran out of time is not at its wall: + // the open leg before it stopped short, and it ran along + // another row (r127a went west along Sandgem's row 13 for row + // 14, and the next leg north walked into the lab). Out of tall + // grass a stop reads, so walk on: a player still moving is + // not where the plan has him. + if (!interrupted && result.stop == WalkStop::LIMIT && route_wall_readable(grid, planned.after)){ + const WalkResult check = walk_until_dpad(stream, context, escape, {x, y}, 2000ms, leg_label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); + if (check.stop == WalkStop::DIALOG){ + // A trainer who saw us froze the walk (the "!") until + // its time ran out, then walked over (r241a: Aroma Lady + // Taylor's line crosses Route 204's corridor). Battle, + // then plan again from where a sight line crosses the leg. + route_status(stream, leg_label + ": a trainer stopped us on the way; battling."); + fight("a trainer on the way"); + // Where they saw us from is not reliable (BDSP's trainers + // stand a few tiles from Platinum's, r242a), so do not + // guess the tile: a leg to a wall ends at its wall however + // far it got. Walk on to it. + stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); + result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); + } + if (check.stop != WalkStop::BLOCKED && + !(check.stop == WalkStop::LIMIT && holding_against_wall(stream, context, x, y, leg_label + ": at the wall?")) + ){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": ran out of time short of the wall, and walking on gets " + + walk_stop_name(check.stop) + ": not where the plan has us.", stream); + } + } + }else{ + // Whole tiles on the D-pad, a tap each: a tap moves exactly + // one tile, while a stick hold timed for three moved one in + // the Ravaged Path (r235b) and the belief drifted four rows. + // The first tap of a leg was meant to turn, but a 160 ms + // D-pad tap turns and steps whichever way the player faced + // (r248a: all seven did; r246a: "south 1" out of the cave + // went two tiles, onto the Youngster's row), so the tap is + // measured like any other and a step counts for the leg. + if (facing != leg.direction){ + const DpadPosition dpad = x < 0 ? DPAD_LEFT : x > 0 ? DPAD_RIGHT : y > 0 ? DPAD_UP : DPAD_DOWN; + context.wait_for_all_requests(); + VideoSnapshot before = stream.video().snapshot(); + pbf_press_dpad(context, dpad, 160ms, 700ms); + context.wait_for_all_requests(); + VideoSnapshot after = stream.video().snapshot(); + if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ + turn_moved = 1; + stream.log("[Route] " + leg_label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); + } + } + if (leg.tiles > turn_moved){ + result = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - turn_moved, leg_label); + }else{ + result = WalkResult{WalkStop::LIMIT, 0ms, 0}; + } + // A wild battle starts once the step onto the grass is done, + // so the taps still count; the walk went on after it. + if (result.wild_battles > 0){ + stream.log("[Route] " + leg_label + ": " + std::to_string(result.wild_battles) + + " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); + } + // Taps that moved nothing: someone stands in the way (the + // Youngster below the Ravaged Path wanders across the row + // under the cliff, r239a, r240a). Two still taps end the walk, + // so the tiles moved are the taps less those two. Wait for + // them to move on and tap the rest; someone who stays is + // talked to, put on the map, and the leg planned again from + // the tile we stand on, which the taps give exactly. + auto taps_moved = [](const WalkResult& walk){ return walk.moved_chunks; }; + size_t moved = std::min(leg.tiles, taps_moved(result) + turn_moved); + // One wait: a wanderer in the way steps off in a few seconds; + // anything still there after that is talked to (r246a lost + // 20 s per block on three waits). + for (size_t again = 0; again < 1 && result.stop == WalkStop::BLOCKED && moved < leg.tiles; again++){ + stream.log("[Route] " + leg_label + ": blocked after " + std::to_string(moved) + " of " + + std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + const WalkResult rest = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - moved, leg_label + ": the rest"); + moved = std::min(leg.tiles, moved + taps_moved(rest)); + result.stop = rest.stop; + result.walked += rest.walked; + result.wild_battles += rest.wild_battles; + } + if (result.stop == WalkStop::BLOCKED && moved < leg.tiles){ + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + { + ShortDialogWatcher dialog(COLOR_YELLOW); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, leg_label + ": someone is in the way; talking to them."); + fight("someone in the way"); + } + } + std::vector stopped; + for (const TilePos& pos : from){ + const std::vector path = leg_path(grid, pos, leg.direction, moved); + stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); + } + std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); + if (stopped.size() == 1){ + const TilePos blocker = stopped[0].next(leg.direction); + grid.block(blocker); + stream.log("[Route] " + leg_label + ": something the map lacks is at " + + describe(maps, blocker) + "; marked it.", COLOR_ORANGE); + } + stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), + "blocked after " + std::to_string(moved) + " of " + std::to_string(leg.tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); + facing = leg.direction; + from = stopped; + replanned = true; + break; + } + } + facing = leg.direction; + { + context.wait_for_all_requests(); + if (VideoSnapshot screen = stream.video().snapshot()){ + watch_banner(*screen.frame); + } + } + std::string banner_text; + for (const std::string& read : banners){ + banner_text += (banner_text.empty() ? "\"" : ", \"") + read + "\""; + } + all_banners.insert(all_banners.end(), banners.begin(), banners.end()); + // Entering another map shows its name; a missing or wrong name means + // the walk did not end where the plan says. From tiles on several + // maps (a leg not confirmed) the banner may already have shown. + if (!map_before.empty() && !map_after.empty() && map_after != map_before && !banner_ok()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": expected to enter " + map_after + ", but the location banner read " + + (banner_text.empty() ? "nothing" : banner_text) + ".", stream); + } + if (!banner_text.empty()){ + stream.log("[Route] " + leg_label + ": location banner " + banner_text + "."); + } + // Where each leg ended, to compare with the plan after a run. + if (VideoSnapshot screen = stream.video().snapshot()){ + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; + Filesystem::create_directories(Filesystem::Path(folder)); + screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(leg_label) + ".png"); + } + if (result.stop == WalkStop::TRANSITION){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": unexpected transition.", stream); + } + // A trainer who sees us freezes the player and walks over; the + // dialogue may open after the walk has ended. + const std::vector> paths = [&]{ + std::vector> out; + for (const TilePos& pos : from){ + out.push_back(leg_path(grid, pos, leg.direction, + leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); + } + return out; + }(); + std::vector watching; + for (size_t t = 0; t < trainers.size(); t++){ + const std::vector sight = sight_tiles(grid, trainers[t]); + for (const std::vector& path : paths){ + if (std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ + return std::find(sight.begin(), sight.end(), pos) != sight.end(); + })){ + watching.push_back(t); + break; + } + } + } + bool talking = result.stop == WalkStop::DIALOG; + if (!talking){ + ShortDialogWatcher dialog(COLOR_YELLOW); + const Milliseconds wait = watching.empty() ? 500ms : 4000ms; + talking = wait_until(stream, context, wait, {{dialog}}) == 0; + } + if (!talking){ + from = planned.after; + log_leg_done(stream, maps, label, planned, result.wild_battles); + continue; + } + + if (watching.empty()){ + // A trainer the map does not have. Fight, then plan again from + // anywhere the leg could have stopped. + std::vector anywhere = from; + for (const std::vector& path : paths){ + anywhere.insert(anywhere.end(), path.begin(), path.end()); + } + std::sort(anywhere.begin(), anywhere.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + anywhere.erase(std::unique(anywhere.begin(), anywhere.end()), anywhere.end()); + route_status(stream, label + ": a trainer the map lacks stopped us; fighting."); + fight("unknown trainer"); + if (leg.ends_at_wall){ + const Milliseconds limit = ROUTE_START_DELAY + + route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; + stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); + walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); + from = planned.after; + log_leg_done(stream, maps, label, planned, 0); + continue; + } + from = anywhere; + replanned = true; + break; + } + // Each possible start tile was stopped on the first tile of its path + // inside a watching trainer's sight. + const TrainerSight trainer = trainers[watching[0]]; + std::vector stopped; + for (const std::vector& path : paths){ + for (const TilePos& pos : path){ + bool seen = false; + for (size_t t : watching){ + const std::vector sight = sight_tiles(grid, trainers[t]); + seen |= std::find(sight.begin(), sight.end(), pos) != sight.end(); + } + if (seen){ + stopped.push_back(pos); + break; + } + } + } + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + leg_label + ": " + trainer.name + " talked, but no path enters their sight.", stream); + } + stream.log(ROUTE_LOG_TAG + route_trainer_line(label, trainer.name, route_tiles(maps, stopped))); + route_status(stream, "Fighting " + trainer.name + "."); + fight(trainer.name); + trainers.erase(trainers.begin() + watching[0]); + // Their sight line only says roughly where: BDSP's trainers stand a + // few tiles from Platinum's (r242a). A leg to a wall ends at its + // wall however far it got: walk on to it and carry on. An open leg + // counts its taps: the step that brought us into sight was complete. + if (leg.ends_at_wall){ + const Milliseconds limit = ROUTE_START_DELAY + + route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; + stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); + walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); + from = planned.after; + log_leg_done(stream, maps, label, planned, 0); + continue; + } + // Only the taps that moved count: the trainer freezes the player + // on the tile they saw, and the taps pressed while they walk over + // move nobody (r248a: "4 taps" were 2 steps; the belief of two + // tiles then cost a 12-tile run to a wall and 5 back). + const size_t taps = std::min(leg.tiles, result.moved_chunks + turn_moved); + std::vector by_taps; + for (const TilePos& pos : from){ + const std::vector path = leg_path(grid, pos, leg.direction, leg.tiles); + const size_t k = std::min(taps, path.size()); + by_taps.push_back(k == 0 ? pos : path[k - 1]); + } + std::sort(by_taps.begin(), by_taps.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + by_taps.erase(std::unique(by_taps.begin(), by_taps.end()), by_taps.end()); + stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), + std::to_string(taps) + " taps before the battle", route_tiles(maps, by_taps)), COLOR_ORANGE); + from = by_taps; + replanned = true; + break; + } + if (!replanned){ + // Legs whose ends span two maps skip the per-leg check; the walk + // as a whole must still have seen the banner of the map it ends on. + const std::string map_end = map_of(maps, from); + const bool changed_map = !map_start.empty() && !map_end.empty() && map_end != map_start; + if (changed_map && std::none_of(all_banners.begin(), all_banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_end); + })){ + std::string seen; + for (const std::string& read : all_banners){ + seen += (seen.empty() ? "\"" : ", \"") + read + "\""; + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": arrived at " + describe(maps, from) + " on the map, but " + map_end + + "'s location banner never showed (read " + (seen.empty() ? "nothing" : seen) + ").", stream); + } + stream.log(ROUTE_LOG_TAG + route_arrived_line(label, route_tiles(maps, from))); + return from; + } + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": too many plans.", stream); +} + + + +std::vector walk_waypoints( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, + std::vector from, + const std::vector& waypoints, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const RobustPlanCosts& costs +){ + for (size_t i = 0; i < waypoints.size(); i++){ + const TilePos goal = waypoints[i]; + from = walk_route(stream, context, escape, maps, from, + [&](const TilePos& pos){ return pos == goal; }, + trainers, fight, + label + " (" + std::to_string(i + 1) + "/" + std::to_string(waypoints.size()) + ", to " + describe(maps, goal) + ")", + {}, costs); + } + return from; +} + +void talk_to_npc( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, + std::vector& at, + const TilePos& npc, + const std::vector& sides, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label +){ + for (Direction side : sides){ + const TilePos stand = npc.next(side); + if (!standable(maps, stand)){ + continue; + } + at = walk_route(stream, context, escape, maps, at, [&](const TilePos& pos){ return pos == stand; }, + trainers, fight, label); + // Face the NPC: the opposite of the side we stand on. + const Direction face = + side == Direction::NORTH ? Direction::SOUTH : + side == Direction::SOUTH ? Direction::NORTH : + side == Direction::EAST ? Direction::WEST : Direction::EAST; + route_turn(stream, context, face); + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, label + ": talking from " + describe(maps, stand) + "."); + return; + } + route_status(stream, label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": no side of " + describe(maps, npc) + " started a dialogue.", stream); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h new file mode 100644 index 0000000000..6950867b70 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -0,0 +1,92 @@ +/* BDSP AutoStory - Planned Route + * + * From: https://github.com/PokemonAutomation/ + * + * Walks a plan made on the story maps: legs to a wall are held until the + * player stops, open legs are tapped a tile at a time. Tracks every tile + * the player may be on, and plans again after something stops the walk. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_H +#define PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_H + +#include +#include +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Called when a trainer's dialogue has opened, or when someone standing in +// the way was talked to. Fights the battle if one starts, and returns to the +// overworld either way. +using RouteTrainerFight = std::function; + +// Walks from any of the world tiles `from` of `maps` until every tile the +// player may be on is `goal`, and returns those tiles. Trainers in +// `trainers` who see the player are fought with `fight` and taken off the +// list. Tiles in `avoid` (where someone wanders) are planned as walls. +// Fails with a screenshot +// on a transition, a dialogue no trainer explains, a wild battle during an +// open leg, or when no plan exists. A walk from one map to another must see +// the second map's location banner on the way: a walk whose legs all ended +// on walls can still end in the wrong place (r124a saved in Sandgem Town +// after "arriving" on Route 202). +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, + std::vector from, + const std::function& goal, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const std::vector& avoid = {}, + const RobustPlanCosts& costs = route_plan_costs() +); + +// Walks `from` to each of `waypoints` in turn, with walk_route() for every +// stretch, and returns where the last one ended. The corners of a line a +// human walked, so the plan is that line, with the walker's handling of +// trainers and blocks on each stretch (Route 204 North, 2026-10-31). +std::vector walk_waypoints( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, + std::vector from, + const std::vector& waypoints, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label, + const RobustPlanCosts& costs = waypoint_plan_costs() +); + +// Walks next to the NPC on world tile `npc`, faces them and presses A, trying +// the sides in `sides` (the side of the NPC to stand on) in order until a +// dialogue opens. `at` is where the player may be, and is updated. Fails with +// a screenshot if no side starts a dialogue. A press from a diagonal tile, +// or from a tile a row off, talks to nobody, so each side is tried in turn. +void talk_to_npc( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, + std::vector& at, + const Pokemon::TilePos& npc, + const std::vector& sides, + std::vector& trainers, + const RouteTrainerFight& fight, + const std::string& label +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index 129795d797..d7d6367e9c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -39,118 +39,24 @@ bool across(Direction direction){ return direction == Direction::EAST || direction == Direction::WEST; } -Milliseconds ms_per_tile(Direction direction){ - return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; -} - -// The left stick for a direction. Row 0 is the top of a map, and the stick's -// y is positive upward. -void stick_for(Direction direction, double& x, double& y){ - x = 0; - y = 0; - switch (direction){ - case Direction::NORTH: y = 1; break; - case Direction::EAST: x = 1; break; - case Direction::SOUTH: y = -1; break; - case Direction::WEST: x = -1; break; - } -} - -// World tiles as tiles of the named maps, for the shared route log -// (Pokemon_RouteLog.h); a tile no map holds is a "world" tile. -std::vector route_tiles(const StoryWorld& maps, const std::vector& tiles){ - std::vector out; - for (const TilePos& pos : tiles){ - const std::optional local = maps.to_local(pos); - out.push_back(local ? RouteTile{local->map, local->pos} : RouteTile{"world", pos}); - } - return out; -} - -std::string describe(const StoryWorld& maps, const std::vector& tiles){ - return Pokemon::describe(route_tiles(maps, tiles)); -} - -RouteLogLeg route_log_leg(const TileLeg& leg){ - return {.action = RouteLegAction::WALK, .direction = leg.direction, .tiles = leg.tiles, - .end = leg.ends_at_wall ? RouteLegEnd::WALL : RouteLegEnd::OPEN}; -} - -PlannedRouteLeg planned_route_leg(const StoryWorld& maps, const PlannedLeg& leg){ - return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; -} - -void log_plan(VideoStream& stream, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ - std::vector logged; - for (const PlannedLeg& leg : legs){ - logged.push_back(planned_route_leg(maps, leg)); - } - stream.log(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged)); } -// Logs a leg that ended on its planned tiles, and how that is known: an -// open leg counts its taps through a wild battle, so its end is assumed; a -// leg to a wall is walked again to its wall. -void log_leg_done(VideoStream& stream, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ - const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; - stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), - assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); -} - -// The tiles the player passes when walking `tiles` tiles from `from`, the -// first one after `from` first. Stops early where the player is stopped. -std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ - std::vector path; - size_t travelled = 0; - while (travelled < tiles){ - const std::optional next = step(grid, from, direction); - if (!next){ - break; - } - travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); - from = *next; - path.push_back(from); - } - return path; -} - -// Holding toward a wall with people or Pokemon moving beside us never reads -// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking -// scrolls the view far more (35 to 90). True if holding toward (x, y) for -// 1.6 s changes the screen less than walking would: we stand at a wall. -bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ - constexpr double WALKING_CHANGE = 25.0; - context.wait_for_all_requests(); - VideoSnapshot before = stream.video().snapshot(); - double most = 0; - for (size_t chunk = 0; chunk < 4 && before; chunk++){ - pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); - context.wait_for_all_requests(); - VideoSnapshot after = stream.video().snapshot(); - if (!after){ - return false; - } - most = std::max(most, walk_screen_change(*before.frame, *after.frame)); - before = std::move(after); - } - stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + - (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); - return before && most < WALKING_CHANGE; +Milliseconds route_ms_per_tile(Direction direction){ + return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; } -// The map all of `tiles` are on, or empty if they are on several or none. -std::string map_of(const StoryWorld& maps, const std::vector& tiles){ - std::string name; - for (const TilePos& pos : tiles){ - const std::optional tile = maps.to_local(pos); - if (!tile || (!name.empty() && tile->map != name)){ - return ""; - } - name = tile->map; +JoystickPosition route_stick(Direction direction){ + switch (direction){ + case Direction::NORTH: + return {0, 1}; + case Direction::EAST: + return {1, 0}; + case Direction::SOUTH: + return {0, -1}; + case Direction::WEST: + return {-1, 0}; } - return name; -} - + return {0, 0}; } @@ -166,15 +72,13 @@ void route_status(VideoStream& stream, const std::string& text){ } Milliseconds route_open_hold(Direction direction, size_t tiles){ - const Milliseconds step = ms_per_tile(direction); + const Milliseconds step = route_ms_per_tile(direction); return step * tiles - step / 2; } void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ - double x, y; - stick_for(direction, x, y); stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); - pbf_move_left_joystick(context, {x, y}, ROUTE_TURN_TAP, 300ms); + pbf_move_left_joystick(context, route_stick(direction), ROUTE_TURN_TAP, 300ms); context.wait_for_all_requests(); } @@ -209,9 +113,7 @@ bool talk_with_nudges( for (int offset : {0, -1, 1, -2, 2}){ const Direction side = offset < at ? minus : plus; for (; at != offset; at += offset < at ? -1 : 1){ - double x, y; - stick_for(side, x, y); - pbf_move_left_joystick(context, {x, y}, ROUTE_NUDGE_TAP, 300ms); + pbf_move_left_joystick(context, route_stick(side), ROUTE_NUDGE_TAP, 300ms); } if (offset != 0){ route_turn(stream, context, facing); @@ -243,540 +145,6 @@ bool talk_with_nudges( return false; } -std::vector walk_route( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::function& goal, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const std::vector& avoid, - const RobustPlanCosts& costs -){ - // Our own copy, so things found in the way can be added to it. Tiles to - // avoid are ground the game lets us walk on (a trainer's line of sight), - // so they are off the map, not walls: a leg must not end "at" one, or - // the walk would run on through it. - StoryWorld grid = maps; - for (const TilePos& pos : avoid){ - if (std::find(from.begin(), from.end(), pos) == from.end()){ - grid.uncover(pos); - } - } - // Which way the player faces, once a leg has set it. - std::optional facing; - // Every banner read on the way, to check the map we arrive on against. - const std::string map_start = map_of(maps, from); - std::vector all_banners; - for (size_t plans = 0; plans < 8; plans++){ - std::optional> legs = plan_robust_route(grid, from, goal, costs); - if (!legs){ - // From a few possible tiles the exact-open-leg costs found no - // plan where the default ones did (r240a, three tiles on Route - // 204's row 27); the default plan is longer but sound. - stream.log("[Route] " + label + ": no plan with the route costs from " + describe(maps, from) + - "; trying the default costs.", COLOR_ORANGE); - legs = plan_robust_route(grid, from, goal, RobustPlanCosts()); - } - if (!legs){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": no plan from " + describe(maps, from) + ".", stream); - } - route_status(stream, label + ": " + std::to_string(legs->size()) + " legs planned"); - log_plan(stream, maps, label, from, *legs); - - bool replanned = false; - size_t leg_number = 0; - for (const PlannedLeg& planned : *legs){ - const TileLeg& leg = planned.leg; - leg_number++; - route_status(stream, route_leg_line(leg_number, legs->size(), planned_route_leg(maps, planned))); - double x, y; - stick_for(leg.direction, x, y); - const std::string leg_label = label + ": " + to_string(leg); - - // Note the location banners the walk passes, to check map changes. - // A wild battle or a second walk to the wall may follow the - // banner: any banner seen during the leg counts. - const std::string map_before = map_of(maps, from); - const std::string map_after = map_of(maps, planned.after); - std::vector banners; - auto banner_ok = [&]{ - return std::any_of(banners.begin(), banners.end(), [&](const std::string& read){ - return location_banner_matches(read, map_after); - }); - }; - auto watch_banner = [&](const ImageViewRGB32& screen){ - if (banners.empty() || (!map_after.empty() && !banner_ok() && banners.size() < 8)){ - const std::string read = read_location_banner(screen); - if (!read.empty() && (banners.empty() || banners.back() != read)){ - banners.push_back(read); - } - } - return false; - }; - - WalkResult result; - // Tiles the first tap of an open leg moved (see below). - size_t turn_moved = 0; - if (leg.ends_at_wall){ - // Run (B held) on the D-pad: a leg to a wall ends at the wall - // however fast we get there, and the D-pad keeps to the row. - const Milliseconds per_tile = ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; - // Long enough to reach the wall from the farthest tile, with room - // for a slow start; past the wall the player stands still. - const Milliseconds limit = ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - // A wild battle may end the walk early. Walking to a wall again - // ends in the same place, so finish the leg. - const bool interrupted = result.wild_battles > 0; - for (size_t again = 0; again < 3 && result.wild_battles > 0 && - (result.stop == WalkStop::LIMIT || result.stop == WalkStop::BLOCKED); again++ - ){ - stream.log("[Route] " + leg_label + ": a wild battle on the way; walking to the wall again."); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - } - // A wall well before the nearest one the map has: something the - // map does not know is in the way. Work out where we stopped from - // the time walked, put it on our map and plan again from there. - size_t nearest = SIZE_MAX; - for (const TilePos& pos : from){ - nearest = std::min(nearest, slide_to_wall(grid, pos, leg.direction).tiles); - } - auto tiles_moved = [&](const WalkResult& walk){ - const Milliseconds moving = walk.walked - ROUTE_START_DELAY - - (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); - return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); - }; - size_t walked_tiles = tiles_moved(result); - // A stick walk can catch a corner when we stand part of a tile - // off centre, where a D-pad tap, which moves whole tiles, gets - // through: on Route 203's stairs the walk west stopped nine - // times in a row and two taps crossed (r225a, 2026-10-31). - // Tap twice, then walk on to the wall. - if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ - const DpadPosition dpad = - leg.direction == Direction::NORTH ? DPAD_UP : - leg.direction == Direction::SOUTH ? DPAD_DOWN : - leg.direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; - stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); - for (size_t tap = 0; tap < 2; tap++){ - pbf_press_dpad(context, dpad, 160ms, 640ms); - } - context.wait_for_all_requests(); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - walked_tiles += tiles_moved(result); - } - // Someone walking about may stand in the way for a moment: wait - // and walk to the wall again before calling it an obstacle. - for (size_t again = 0; !interrupted && again < 2 && - result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++ - ){ - stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - walked_tiles += tiles_moved(result); - } - // Any stop short of the wall's distance: someone who stays put - // is talked to, and the leg is planned again from where we are. - // Within the time count's slack this may be the wall itself, - // where A does nothing and the new plan walks no further (r239a: - // a wanderer 3 tiles short passed as "about 8 of 10", and every - // later leg was off by those tiles). - if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ - // Someone who stays put: talk to them. A trainer we walked up - // to from the side starts the battle this way. - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - { - ShortDialogWatcher dialog(COLOR_YELLOW); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, leg_label + ": someone is in the way; talking to them."); - fight("someone in the way"); - } - } - std::vector stopped; - for (const TilePos& pos : from){ - const std::vector path = leg_path(grid, pos, leg.direction, SIZE_MAX); - for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ - stopped.push_back(k == 0 ? pos : path[k - 1]); - } - } - std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); - if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": stopped early, and no tile fits.", stream); - } - if (stopped.size() == 1){ - const TilePos blocker = stopped[0].next(leg.direction); - grid.block(blocker); - stream.log("[Route] " + leg_label + ": something the map lacks is at " + - describe(maps, blocker) + "; marked it.", COLOR_ORANGE); - } - stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), - "stopped early after about " + std::to_string(walked_tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); - facing = leg.direction; - from = stopped; - replanned = true; - break; - } - // A leg to the wall that ran out of time is not at its wall: - // the open leg before it stopped short, and it ran along - // another row (r127a went west along Sandgem's row 13 for row - // 14, and the next leg north walked into the lab). Out of tall - // grass a stop reads, so walk on: a player still moving is - // not where the plan has him. - if (!interrupted && result.stop == WalkStop::LIMIT && route_wall_readable(grid, planned.after)){ - const WalkResult check = walk_until_dpad(stream, context, escape, {x, y}, 2000ms, leg_label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); - if (check.stop == WalkStop::DIALOG){ - // A trainer who saw us froze the walk (the "!") until - // its time ran out, then walked over (r241a: Aroma Lady - // Taylor's line crosses Route 204's corridor). Battle, - // then plan again from where a sight line crosses the leg. - route_status(stream, leg_label + ": a trainer stopped us on the way; battling."); - fight("a trainer on the way"); - // Where they saw us from is not reliable (BDSP's trainers - // stand a few tiles from Platinum's, r242a), so do not - // guess the tile: a leg to a wall ends at its wall however - // far it got. Walk on to it. - stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); - } - if (check.stop != WalkStop::BLOCKED && - !(check.stop == WalkStop::LIMIT && holding_against_wall(stream, context, x, y, leg_label + ": at the wall?")) - ){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": ran out of time short of the wall, and walking on gets " + - walk_stop_name(check.stop) + ": not where the plan has us.", stream); - } - } - }else{ - // Whole tiles on the D-pad, a tap each: a tap moves exactly - // one tile, while a stick hold timed for three moved one in - // the Ravaged Path (r235b) and the belief drifted four rows. - // The first tap of a leg was meant to turn, but a 160 ms - // D-pad tap turns and steps whichever way the player faced - // (r248a: all seven did; r246a: "south 1" out of the cave - // went two tiles, onto the Youngster's row), so the tap is - // measured like any other and a step counts for the leg. - if (facing != leg.direction){ - const DpadPosition dpad = x < 0 ? DPAD_LEFT : x > 0 ? DPAD_RIGHT : y > 0 ? DPAD_UP : DPAD_DOWN; - context.wait_for_all_requests(); - VideoSnapshot before = stream.video().snapshot(); - pbf_press_dpad(context, dpad, 160ms, 700ms); - context.wait_for_all_requests(); - VideoSnapshot after = stream.video().snapshot(); - if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ - turn_moved = 1; - stream.log("[Route] " + leg_label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); - } - } - if (leg.tiles > turn_moved){ - result = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - turn_moved, leg_label); - }else{ - result = WalkResult{WalkStop::LIMIT, 0ms, 0}; - } - // A wild battle starts once the step onto the grass is done, - // so the taps still count; the walk went on after it. - if (result.wild_battles > 0){ - stream.log("[Route] " + leg_label + ": " + std::to_string(result.wild_battles) + - " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); - } - // Taps that moved nothing: someone stands in the way (the - // Youngster below the Ravaged Path wanders across the row - // under the cliff, r239a, r240a). Two still taps end the walk, - // so the tiles moved are the taps less those two. Wait for - // them to move on and tap the rest; someone who stays is - // talked to, put on the map, and the leg planned again from - // the tile we stand on, which the taps give exactly. - auto taps_moved = [](const WalkResult& walk){ return walk.moved_chunks; }; - size_t moved = std::min(leg.tiles, taps_moved(result) + turn_moved); - // One wait: a wanderer in the way steps off in a few seconds; - // anything still there after that is talked to (r246a lost - // 20 s per block on three waits). - for (size_t again = 0; again < 1 && result.stop == WalkStop::BLOCKED && moved < leg.tiles; again++){ - stream.log("[Route] " + leg_label + ": blocked after " + std::to_string(moved) + " of " + - std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - const WalkResult rest = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - moved, leg_label + ": the rest"); - moved = std::min(leg.tiles, moved + taps_moved(rest)); - result.stop = rest.stop; - result.walked += rest.walked; - result.wild_battles += rest.wild_battles; - } - if (result.stop == WalkStop::BLOCKED && moved < leg.tiles){ - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - { - ShortDialogWatcher dialog(COLOR_YELLOW); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, leg_label + ": someone is in the way; talking to them."); - fight("someone in the way"); - } - } - std::vector stopped; - for (const TilePos& pos : from){ - const std::vector path = leg_path(grid, pos, leg.direction, moved); - stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); - } - std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); - if (stopped.size() == 1){ - const TilePos blocker = stopped[0].next(leg.direction); - grid.block(blocker); - stream.log("[Route] " + leg_label + ": something the map lacks is at " + - describe(maps, blocker) + "; marked it.", COLOR_ORANGE); - } - stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), - "blocked after " + std::to_string(moved) + " of " + std::to_string(leg.tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); - facing = leg.direction; - from = stopped; - replanned = true; - break; - } - } - facing = leg.direction; - { - context.wait_for_all_requests(); - if (VideoSnapshot screen = stream.video().snapshot()){ - watch_banner(*screen.frame); - } - } - std::string banner_text; - for (const std::string& read : banners){ - banner_text += (banner_text.empty() ? "\"" : ", \"") + read + "\""; - } - all_banners.insert(all_banners.end(), banners.begin(), banners.end()); - // Entering another map shows its name; a missing or wrong name means - // the walk did not end where the plan says. From tiles on several - // maps (a leg not confirmed) the banner may already have shown. - if (!map_before.empty() && !map_after.empty() && map_after != map_before && !banner_ok()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": expected to enter " + map_after + ", but the location banner read " + - (banner_text.empty() ? "nothing" : banner_text) + ".", stream); - } - if (!banner_text.empty()){ - stream.log("[Route] " + leg_label + ": location banner " + banner_text + "."); - } - // Where each leg ended, to compare with the plan after a run. - if (VideoSnapshot screen = stream.video().snapshot()){ - const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; - Filesystem::create_directories(Filesystem::Path(folder)); - screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(leg_label) + ".png"); - } - if (result.stop == WalkStop::TRANSITION){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": unexpected transition.", stream); - } - // A trainer who sees us freezes the player and walks over; the - // dialogue may open after the walk has ended. - const std::vector> paths = [&]{ - std::vector> out; - for (const TilePos& pos : from){ - out.push_back(leg_path(grid, pos, leg.direction, - leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); - } - return out; - }(); - std::vector watching; - for (size_t t = 0; t < trainers.size(); t++){ - const std::vector sight = sight_tiles(grid, trainers[t]); - for (const std::vector& path : paths){ - if (std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ - return std::find(sight.begin(), sight.end(), pos) != sight.end(); - })){ - watching.push_back(t); - break; - } - } - } - bool talking = result.stop == WalkStop::DIALOG; - if (!talking){ - ShortDialogWatcher dialog(COLOR_YELLOW); - const Milliseconds wait = watching.empty() ? 500ms : 4000ms; - talking = wait_until(stream, context, wait, {{dialog}}) == 0; - } - if (!talking){ - from = planned.after; - log_leg_done(stream, maps, label, planned, result.wild_battles); - continue; - } - - if (watching.empty()){ - // A trainer the map does not have. Fight, then plan again from - // anywhere the leg could have stopped. - std::vector anywhere = from; - for (const std::vector& path : paths){ - anywhere.insert(anywhere.end(), path.begin(), path.end()); - } - std::sort(anywhere.begin(), anywhere.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - anywhere.erase(std::unique(anywhere.begin(), anywhere.end()), anywhere.end()); - route_status(stream, label + ": a trainer the map lacks stopped us; fighting."); - fight("unknown trainer"); - if (leg.ends_at_wall){ - const Milliseconds limit = ROUTE_START_DELAY + - ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; - stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); - from = planned.after; - log_leg_done(stream, maps, label, planned, 0); - continue; - } - from = anywhere; - replanned = true; - break; - } - // Each possible start tile was stopped on the first tile of its path - // inside a watching trainer's sight. - const TrainerSight trainer = trainers[watching[0]]; - std::vector stopped; - for (const std::vector& path : paths){ - for (const TilePos& pos : path){ - bool seen = false; - for (size_t t : watching){ - const std::vector sight = sight_tiles(grid, trainers[t]); - seen |= std::find(sight.begin(), sight.end(), pos) != sight.end(); - } - if (seen){ - stopped.push_back(pos); - break; - } - } - } - if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": " + trainer.name + " talked, but no path enters their sight.", stream); - } - stream.log(ROUTE_LOG_TAG + route_trainer_line(label, trainer.name, route_tiles(maps, stopped))); - route_status(stream, "Fighting " + trainer.name + "."); - fight(trainer.name); - trainers.erase(trainers.begin() + watching[0]); - // Their sight line only says roughly where: BDSP's trainers stand a - // few tiles from Platinum's (r242a). A leg to a wall ends at its - // wall however far it got: walk on to it and carry on. An open leg - // counts its taps: the step that brought us into sight was complete. - if (leg.ends_at_wall){ - const Milliseconds limit = ROUTE_START_DELAY + - ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; - stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); - from = planned.after; - log_leg_done(stream, maps, label, planned, 0); - continue; - } - // Only the taps that moved count: the trainer freezes the player - // on the tile they saw, and the taps pressed while they walk over - // move nobody (r248a: "4 taps" were 2 steps; the belief of two - // tiles then cost a 12-tile run to a wall and 5 back). - const size_t taps = std::min(leg.tiles, result.moved_chunks + turn_moved); - std::vector by_taps; - for (const TilePos& pos : from){ - const std::vector path = leg_path(grid, pos, leg.direction, leg.tiles); - const size_t k = std::min(taps, path.size()); - by_taps.push_back(k == 0 ? pos : path[k - 1]); - } - std::sort(by_taps.begin(), by_taps.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - by_taps.erase(std::unique(by_taps.begin(), by_taps.end()), by_taps.end()); - stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), - std::to_string(taps) + " taps before the battle", route_tiles(maps, by_taps)), COLOR_ORANGE); - from = by_taps; - replanned = true; - break; - } - if (!replanned){ - // Legs whose ends span two maps skip the per-leg check; the walk - // as a whole must still have seen the banner of the map it ends on. - const std::string map_end = map_of(maps, from); - const bool changed_map = !map_start.empty() && !map_end.empty() && map_end != map_start; - if (changed_map && std::none_of(all_banners.begin(), all_banners.end(), [&](const std::string& read){ - return location_banner_matches(read, map_end); - })){ - std::string seen; - for (const std::string& read : all_banners){ - seen += (seen.empty() ? "\"" : ", \"") + read + "\""; - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": arrived at " + describe(maps, from) + " on the map, but " + map_end + - "'s location banner never showed (read " + (seen.empty() ? "nothing" : seen) + ").", stream); - } - stream.log(ROUTE_LOG_TAG + route_arrived_line(label, route_tiles(maps, from))); - return from; - } - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": too many plans.", stream); -} - - - -std::vector walk_waypoints( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::vector& waypoints, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const RobustPlanCosts& costs -){ - for (size_t i = 0; i < waypoints.size(); i++){ - const TilePos goal = waypoints[i]; - from = walk_route(stream, context, escape, maps, from, - [&](const TilePos& pos){ return pos == goal; }, - trainers, fight, - label + " (" + std::to_string(i + 1) + "/" + std::to_string(waypoints.size()) + ", to " + describe(maps, goal) + ")", - {}, costs); - } - return from; -} - -void talk_to_npc( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector& at, - const TilePos& npc, - const std::vector& sides, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label -){ - for (Direction side : sides){ - const TilePos stand = npc.next(side); - if (!standable(maps, stand)){ - continue; - } - at = walk_route(stream, context, escape, maps, at, [&](const TilePos& pos){ return pos == stand; }, - trainers, fight, label); - // Face the NPC: the opposite of the side we stand on. - const Direction face = - side == Direction::NORTH ? Direction::SOUTH : - side == Direction::SOUTH ? Direction::NORTH : - side == Direction::EAST ? Direction::WEST : Direction::EAST; - route_turn(stream, context, face); - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - context.wait_for_all_requests(); - ShortDialogWatcher dialog(COLOR_CYAN); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, label + ": talking from " + describe(maps, stand) + "."); - return; - } - route_status(stream, label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": no side of " + describe(maps, npc) + " started a dialogue.", stream); -} void finish_dialogue( VideoStream& stream, ProControllerContext& context, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index 995f341818..6654a93379 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -2,9 +2,9 @@ * * From: https://github.com/PokemonAutomation/ * - * Walks a plan made on the story maps: legs to a wall are held until the - * player stops, open legs for their length in time. Tracks every tile the - * player may be on, and plans again after a trainer stops the walk. + * What walking on the story maps is made of: walking times per tile, the + * stick for a direction, turning, talking to someone next to us, finishing + * a dialogue, and going through doors. PlannedRoute walks whole plans. * */ @@ -19,9 +19,7 @@ #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_Walk.h" namespace PokemonAutomation{ @@ -41,6 +39,12 @@ constexpr Milliseconds ROUTE_START_DELAY = Milliseconds(250); // short by two tiles. 1 until running is measured to work. constexpr int ROUTE_RUN_SPEEDUP = 1; +// Walking time per tile in `direction`. +Milliseconds route_ms_per_tile(Pokemon::Direction direction); +// The left stick for a direction. Row 0 is the top of a map, and the +// stick's y is positive upward. +JoystickPosition route_stick(Pokemon::Direction direction); + // How long to hold the stick for an open leg of `tiles` tiles, for a player // already facing that way: a step once started is always finished, so stop // half a tile early. On the console a 1290ms hold west went 9 tiles and an @@ -95,64 +99,6 @@ bool route_wall_readable(const StoryWorld& grid, const std::vector; - -// Walks from any of the world tiles `from` of `maps` until every tile the -// player may be on is `goal`, and returns those tiles. Trainers in -// `trainers` who see the player are fought with `fight` and taken off the -// list. Tiles in `avoid` (where someone wanders) are planned as walls. -// Fails with a screenshot -// on a transition, a dialogue no trainer explains, a wild battle during an -// open leg, or when no plan exists. A walk from one map to another must see -// the second map's location banner on the way: a walk whose legs all ended -// on walls can still end in the wrong place (r124a saved in Sandgem Town -// after "arriving" on Route 202). -std::vector walk_route( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::function& goal, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const std::vector& avoid = {}, - const RobustPlanCosts& costs = route_plan_costs() -); - -// Walks `from` to each of `waypoints` in turn, with walk_route() for every -// stretch, and returns where the last one ended. The corners of a line a -// human walked, so the plan is that line, with the walker's handling of -// trainers and blocks on each stretch (Route 204 North, 2026-10-31). -std::vector walk_waypoints( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::vector& waypoints, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const RobustPlanCosts& costs = waypoint_plan_costs() -); - -// Walks next to the NPC on world tile `npc`, faces them and presses A, trying -// the sides in `sides` (the side of the NPC to stand on) in order until a -// dialogue opens. `at` is where the player may be, and is updated. Fails with -// a screenshot if no side starts a dialogue. A press from a diagonal tile, -// or from a tile a row off, talks to nobody, so each side is tried in turn. -void talk_to_npc( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector& at, - const Pokemon::TilePos& npc, - const std::vector& sides, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label -); - // Finishes a dialogue that has opened, however many lines it has: presses // `button` while a dialogue box shows, and returns once the overworld has // shown with no box for 1.5 s (the box blinks off between lines and during diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 6647e962b6..4c4e69c4f8 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1657,6 +1657,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp From 6a24b565fcce07886e813d4ff500daf6fe19725c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:51:40 -0800 Subject: [PATCH 22/74] BDSP walker: walk_route() as a RouteWalker with one function per decision Code health: walk_route() was 475 lines nested 7 deep with 11 parameters, walk_waypoints() and talk_to_npc() had 10. walk_route() is now a RouteWalker class: planning, a leg to a wall, an open leg, the banner check, the trainers after a leg and each replan are their own functions, with the same steps in the same order. The trainers and their fight go together in RouteTrainers; where a walk goes is a RouteWalkPlan, WaypointWalkPlan or NpcTalk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 1107 +++++++++-------- .../PokemonBDSP_AutoStory_PlannedRoute.h | 95 +- 2 files changed, 673 insertions(+), 529 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 5d80952053..c9c56096bc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Common/Cpp/PrettyPrint.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/GlobalAutoPaths.h" @@ -128,522 +129,650 @@ std::string map_of(const StoryWorld& maps, const std::vector& tiles){ } -std::vector walk_route( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::function& goal, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const std::vector& avoid, - const RobustPlanCosts& costs -){ - // Our own copy, so things found in the way can be added to it. Tiles to - // avoid are ground the game lets us walk on (a trainer's line of sight), - // so they are off the map, not walls: a leg must not end "at" one, or - // the walk would run on through it. - StoryWorld grid = maps; - for (const TilePos& pos : avoid){ - if (std::find(from.begin(), from.end(), pos) == from.end()){ - grid.uncover(pos); +namespace{ + +// Sorted by row, then column, without repeats. +std::vector sorted_unique(std::vector tiles){ + std::sort(tiles.begin(), tiles.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + tiles.erase(std::unique(tiles.begin(), tiles.end()), tiles.end()); + return tiles; +} + +std::string quoted_list(const std::vector& reads){ + std::string text; + for (const std::string& read : reads){ + text += (text.empty() ? "\"" : ", \"") + read + "\""; + } + return text; +} + +// Long enough to reach the wall from the farthest tile, with room for a +// slow start; past the wall the player stands still. +Milliseconds wall_limit(const TileLeg& leg){ + const Milliseconds per_tile = route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; + return ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; +} + +// Tiles a walk to the wall moved, from the time it walked. +size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ + const Milliseconds moving = walk.walked - ROUTE_START_DELAY - + (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); + return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); +} + +// Whether a leg's walk goes on to the next leg or the route plans again. +enum class LegNext{ + NEXT_LEG, + REPLAN, +}; + +// One planned leg as it is walked: where it goes, and the location +// banners read on the way. +struct LegWalk{ + const PlannedLeg& planned; + std::string label; + JoystickPosition stick; + std::string map_before; + std::string map_after; + std::vector banners = {}; + WalkResult result{WalkStop::LIMIT, 0ms, 0}; + // Tiles the first tap of an open leg moved (see open_leg()). + size_t turn_moved = 0; + + const TileLeg& leg() const{ + return planned.leg; + } + bool banner_ok() const{ + return std::any_of(banners.begin(), banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_after); + }); + } + // Notes the location banners the walk passes, to check map changes. A + // wild battle or a second walk to the wall may follow the banner: any + // banner seen during the leg counts. + bool watch_banner(const ImageViewRGB32& screen){ + if (banners.empty() || (!map_after.empty() && !banner_ok() && banners.size() < 8)){ + const std::string read = read_location_banner(screen); + if (!read.empty() && (banners.empty() || banners.back() != read)){ + banners.push_back(read); + } } + return false; + } + DpadWalkOptions run_watching(){ + return {.arrived = [this](const ImageViewRGB32& screen){ return watch_banner(screen); }, .pace = DpadPace::RUN}; } +}; + +// walk_route(): plans, walks each leg, and plans again from where the walk +// turned out to be when something stopped it. +class RouteWalker{ +public: + RouteWalker( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, RouteTrainers& trainers, const RouteWalkPlan& plan + ) + : m_stream(stream) + , m_context(context) + , m_escape(escape) + , m_maps(maps) + , m_grid(maps) + , m_trainers(trainers) + , m_plan(plan) + {} + + std::vector run(std::vector from); + +private: + std::vector plan_legs() const; + LegNext walk_leg(const PlannedLeg& planned, size_t number, size_t count); + std::vector arrive() const; + + // Legs to a wall. + LegNext wall_leg(LegWalk& walk); + size_t unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest); + LegNext stopped_short_of_wall(LegWalk& walk, size_t walked_tiles); + void check_at_wall(LegWalk& walk); + void on_to_wall(LegWalk& walk); + + // Open legs, tapped. + LegNext open_leg(LegWalk& walk); + void turn_tap(LegWalk& walk); + LegNext blocked_open_leg(LegWalk& walk, size_t moved); + + // After each leg. + void check_banners(LegWalk& walk); + LegNext after_leg(LegWalk& walk); + std::vector watching_trainers(const std::vector>& paths) const; + LegNext unknown_trainer(LegWalk& walk, const std::vector>& paths); + LegNext known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching); + + void talk_to_blocker(const std::string& leg_label); + LegNext replan_from(const LegWalk& walk, std::vector stopped, const std::string& why); + void mark_blocker(const LegWalk& walk, const std::vector& stopped); + + VideoStream& m_stream; + ProControllerContext& m_context; + const WildBattleEscape& m_escape; + const StoryWorld& m_maps; + // Our own copy, so things found in the way can be added to it. + StoryWorld m_grid; + RouteTrainers& m_trainers; + const RouteWalkPlan& m_plan; + std::vector m_from; // Which way the player faces, once a leg has set it. - std::optional facing; + std::optional m_facing; // Every banner read on the way, to check the map we arrive on against. - const std::string map_start = map_of(maps, from); - std::vector all_banners; + std::vector m_all_banners; + std::string m_map_start; +}; + +std::vector RouteWalker::run(std::vector from){ + // Tiles to avoid are ground the game lets us walk on (a trainer's line + // of sight), so they are off the map, not walls: a leg must not end + // "at" one, or the walk would run on through it. + for (const TilePos& pos : m_plan.avoid){ + if (std::find(from.begin(), from.end(), pos) == from.end()){ + m_grid.uncover(pos); + } + } + m_from = std::move(from); + m_map_start = map_of(m_maps, m_from); for (size_t plans = 0; plans < 8; plans++){ - std::optional> legs = plan_robust_route(grid, from, goal, costs); - if (!legs){ - // From a few possible tiles the exact-open-leg costs found no - // plan where the default ones did (r240a, three tiles on Route - // 204's row 27); the default plan is longer but sound. - stream.log("[Route] " + label + ": no plan with the route costs from " + describe(maps, from) + - "; trying the default costs.", COLOR_ORANGE); - legs = plan_robust_route(grid, from, goal, RobustPlanCosts()); + const std::vector legs = plan_legs(); + route_status(m_stream, m_plan.label + ": " + std::to_string(legs.size()) + " legs planned"); + log_plan(m_stream, m_maps, m_plan.label, m_from, legs); + bool replanned = false; + for (size_t number = 1; number <= legs.size() && !replanned; number++){ + replanned = walk_leg(legs[number - 1], number, legs.size()) == LegNext::REPLAN; } - if (!legs){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": no plan from " + describe(maps, from) + ".", stream); + if (!replanned){ + return arrive(); } - route_status(stream, label + ": " + std::to_string(legs->size()) + " legs planned"); - log_plan(stream, maps, label, from, *legs); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + m_plan.label + ": too many plans.", m_stream); +} - bool replanned = false; - size_t leg_number = 0; - for (const PlannedLeg& planned : *legs){ - const TileLeg& leg = planned.leg; - leg_number++; - route_status(stream, route_leg_line(leg_number, legs->size(), planned_route_leg(maps, planned))); - const double x = route_stick(leg.direction).x; - const double y = route_stick(leg.direction).y; - const std::string leg_label = label + ": " + to_string(leg); - - // Note the location banners the walk passes, to check map changes. - // A wild battle or a second walk to the wall may follow the - // banner: any banner seen during the leg counts. - const std::string map_before = map_of(maps, from); - const std::string map_after = map_of(maps, planned.after); - std::vector banners; - auto banner_ok = [&]{ - return std::any_of(banners.begin(), banners.end(), [&](const std::string& read){ - return location_banner_matches(read, map_after); - }); - }; - auto watch_banner = [&](const ImageViewRGB32& screen){ - if (banners.empty() || (!map_after.empty() && !banner_ok() && banners.size() < 8)){ - const std::string read = read_location_banner(screen); - if (!read.empty() && (banners.empty() || banners.back() != read)){ - banners.push_back(read); - } - } - return false; - }; - - WalkResult result; - // Tiles the first tap of an open leg moved (see below). - size_t turn_moved = 0; - if (leg.ends_at_wall){ - // Run (B held) on the D-pad: a leg to a wall ends at the wall - // however fast we get there, and the D-pad keeps to the row. - const Milliseconds per_tile = route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; - // Long enough to reach the wall from the farthest tile, with room - // for a slow start; past the wall the player stands still. - const Milliseconds limit = ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - // A wild battle may end the walk early. Walking to a wall again - // ends in the same place, so finish the leg. - const bool interrupted = result.wild_battles > 0; - for (size_t again = 0; again < 3 && result.wild_battles > 0 && - (result.stop == WalkStop::LIMIT || result.stop == WalkStop::BLOCKED); again++ - ){ - stream.log("[Route] " + leg_label + ": a wild battle on the way; walking to the wall again."); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - } - // A wall well before the nearest one the map has: something the - // map does not know is in the way. Work out where we stopped from - // the time walked, put it on our map and plan again from there. - size_t nearest = SIZE_MAX; - for (const TilePos& pos : from){ - nearest = std::min(nearest, slide_to_wall(grid, pos, leg.direction).tiles); - } - auto tiles_moved = [&](const WalkResult& walk){ - const Milliseconds moving = walk.walked - ROUTE_START_DELAY - - (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); - return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); - }; - size_t walked_tiles = tiles_moved(result); - // A stick walk can catch a corner when we stand part of a tile - // off centre, where a D-pad tap, which moves whole tiles, gets - // through: on Route 203's stairs the walk west stopped nine - // times in a row and two taps crossed (r225a, 2026-10-31). - // Tap twice, then walk on to the wall. - if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ - const DpadPosition dpad = - leg.direction == Direction::NORTH ? DPAD_UP : - leg.direction == Direction::SOUTH ? DPAD_DOWN : - leg.direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; - stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); - for (size_t tap = 0; tap < 2; tap++){ - pbf_press_dpad(context, dpad, 160ms, 640ms); - } - context.wait_for_all_requests(); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - walked_tiles += tiles_moved(result); - } - // Someone walking about may stand in the way for a moment: wait - // and walk to the wall again before calling it an obstacle. - for (size_t again = 0; !interrupted && again < 2 && - result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++ - ){ - stream.log("[Route] " + leg_label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label, {.arrived = watch_banner, .pace = DpadPace::RUN}); - walked_tiles += tiles_moved(result); - } - // Any stop short of the wall's distance: someone who stays put - // is talked to, and the leg is planned again from where we are. - // Within the time count's slack this may be the wall itself, - // where A does nothing and the new plan walks no further (r239a: - // a wanderer 3 tiles short passed as "about 8 of 10", and every - // later leg was off by those tiles). - if (!interrupted && result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ - // Someone who stays put: talk to them. A trainer we walked up - // to from the side starts the battle this way. - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - { - ShortDialogWatcher dialog(COLOR_YELLOW); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, leg_label + ": someone is in the way; talking to them."); - fight("someone in the way"); - } - } - std::vector stopped; - for (const TilePos& pos : from){ - const std::vector path = leg_path(grid, pos, leg.direction, SIZE_MAX); - for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ - stopped.push_back(k == 0 ? pos : path[k - 1]); - } - } - std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); - if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": stopped early, and no tile fits.", stream); - } - if (stopped.size() == 1){ - const TilePos blocker = stopped[0].next(leg.direction); - grid.block(blocker); - stream.log("[Route] " + leg_label + ": something the map lacks is at " + - describe(maps, blocker) + "; marked it.", COLOR_ORANGE); - } - stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), - "stopped early after about " + std::to_string(walked_tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); - facing = leg.direction; - from = stopped; - replanned = true; - break; - } - // A leg to the wall that ran out of time is not at its wall: - // the open leg before it stopped short, and it ran along - // another row (r127a went west along Sandgem's row 13 for row - // 14, and the next leg north walked into the lab). Out of tall - // grass a stop reads, so walk on: a player still moving is - // not where the plan has him. - if (!interrupted && result.stop == WalkStop::LIMIT && route_wall_readable(grid, planned.after)){ - const WalkResult check = walk_until_dpad(stream, context, escape, {x, y}, 2000ms, leg_label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); - if (check.stop == WalkStop::DIALOG){ - // A trainer who saw us froze the walk (the "!") until - // its time ran out, then walked over (r241a: Aroma Lady - // Taylor's line crosses Route 204's corridor). Battle, - // then plan again from where a sight line crosses the leg. - route_status(stream, leg_label + ": a trainer stopped us on the way; battling."); - fight("a trainer on the way"); - // Where they saw us from is not reliable (BDSP's trainers - // stand a few tiles from Platinum's, r242a), so do not - // guess the tile: a leg to a wall ends at its wall however - // far it got. Walk on to it. - stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - result = walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); - } - if (check.stop != WalkStop::BLOCKED && - !(check.stop == WalkStop::LIMIT && holding_against_wall(stream, context, x, y, leg_label + ": at the wall?")) - ){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": ran out of time short of the wall, and walking on gets " + - walk_stop_name(check.stop) + ": not where the plan has us.", stream); - } - } - }else{ - // Whole tiles on the D-pad, a tap each: a tap moves exactly - // one tile, while a stick hold timed for three moved one in - // the Ravaged Path (r235b) and the belief drifted four rows. - // The first tap of a leg was meant to turn, but a 160 ms - // D-pad tap turns and steps whichever way the player faced - // (r248a: all seven did; r246a: "south 1" out of the cave - // went two tiles, onto the Youngster's row), so the tap is - // measured like any other and a step counts for the leg. - if (facing != leg.direction){ - const DpadPosition dpad = x < 0 ? DPAD_LEFT : x > 0 ? DPAD_RIGHT : y > 0 ? DPAD_UP : DPAD_DOWN; - context.wait_for_all_requests(); - VideoSnapshot before = stream.video().snapshot(); - pbf_press_dpad(context, dpad, 160ms, 700ms); - context.wait_for_all_requests(); - VideoSnapshot after = stream.video().snapshot(); - if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ - turn_moved = 1; - stream.log("[Route] " + leg_label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); - } - } - if (leg.tiles > turn_moved){ - result = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - turn_moved, leg_label); - }else{ - result = WalkResult{WalkStop::LIMIT, 0ms, 0}; - } - // A wild battle starts once the step onto the grass is done, - // so the taps still count; the walk went on after it. - if (result.wild_battles > 0){ - stream.log("[Route] " + leg_label + ": " + std::to_string(result.wild_battles) + - " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); - } - // Taps that moved nothing: someone stands in the way (the - // Youngster below the Ravaged Path wanders across the row - // under the cliff, r239a, r240a). Two still taps end the walk, - // so the tiles moved are the taps less those two. Wait for - // them to move on and tap the rest; someone who stays is - // talked to, put on the map, and the leg planned again from - // the tile we stand on, which the taps give exactly. - auto taps_moved = [](const WalkResult& walk){ return walk.moved_chunks; }; - size_t moved = std::min(leg.tiles, taps_moved(result) + turn_moved); - // One wait: a wanderer in the way steps off in a few seconds; - // anything still there after that is talked to (r246a lost - // 20 s per block on three waits). - for (size_t again = 0; again < 1 && result.stop == WalkStop::BLOCKED && moved < leg.tiles; again++){ - stream.log("[Route] " + leg_label + ": blocked after " + std::to_string(moved) + " of " + - std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - const WalkResult rest = walk_tiles_dpad(stream, context, escape, {x, y}, leg.tiles - moved, leg_label + ": the rest"); - moved = std::min(leg.tiles, moved + taps_moved(rest)); - result.stop = rest.stop; - result.walked += rest.walked; - result.wild_battles += rest.wild_battles; - } - if (result.stop == WalkStop::BLOCKED && moved < leg.tiles){ - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - { - ShortDialogWatcher dialog(COLOR_YELLOW); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, leg_label + ": someone is in the way; talking to them."); - fight("someone in the way"); - } - } - std::vector stopped; - for (const TilePos& pos : from){ - const std::vector path = leg_path(grid, pos, leg.direction, moved); - stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); - } - std::sort(stopped.begin(), stopped.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - stopped.erase(std::unique(stopped.begin(), stopped.end()), stopped.end()); - if (stopped.size() == 1){ - const TilePos blocker = stopped[0].next(leg.direction); - grid.block(blocker); - stream.log("[Route] " + leg_label + ": something the map lacks is at " + - describe(maps, blocker) + "; marked it.", COLOR_ORANGE); - } - stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), - "blocked after " + std::to_string(moved) + " of " + std::to_string(leg.tiles) + " tiles", route_tiles(maps, stopped)), COLOR_ORANGE); - facing = leg.direction; - from = stopped; - replanned = true; - break; - } - } - facing = leg.direction; - { - context.wait_for_all_requests(); - if (VideoSnapshot screen = stream.video().snapshot()){ - watch_banner(*screen.frame); - } - } - std::string banner_text; - for (const std::string& read : banners){ - banner_text += (banner_text.empty() ? "\"" : ", \"") + read + "\""; - } - all_banners.insert(all_banners.end(), banners.begin(), banners.end()); - // Entering another map shows its name; a missing or wrong name means - // the walk did not end where the plan says. From tiles on several - // maps (a leg not confirmed) the banner may already have shown. - if (!map_before.empty() && !map_after.empty() && map_after != map_before && !banner_ok()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": expected to enter " + map_after + ", but the location banner read " + - (banner_text.empty() ? "nothing" : banner_text) + ".", stream); - } - if (!banner_text.empty()){ - stream.log("[Route] " + leg_label + ": location banner " + banner_text + "."); - } - // Where each leg ended, to compare with the plan after a run. - if (VideoSnapshot screen = stream.video().snapshot()){ - const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; - Filesystem::create_directories(Filesystem::Path(folder)); - screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(leg_label) + ".png"); - } - if (result.stop == WalkStop::TRANSITION){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": unexpected transition.", stream); - } - // A trainer who sees us freezes the player and walks over; the - // dialogue may open after the walk has ended. - const std::vector> paths = [&]{ - std::vector> out; - for (const TilePos& pos : from){ - out.push_back(leg_path(grid, pos, leg.direction, - leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); - } - return out; - }(); - std::vector watching; - for (size_t t = 0; t < trainers.size(); t++){ - const std::vector sight = sight_tiles(grid, trainers[t]); - for (const std::vector& path : paths){ - if (std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ - return std::find(sight.begin(), sight.end(), pos) != sight.end(); - })){ - watching.push_back(t); - break; - } - } - } - bool talking = result.stop == WalkStop::DIALOG; - if (!talking){ - ShortDialogWatcher dialog(COLOR_YELLOW); - const Milliseconds wait = watching.empty() ? 500ms : 4000ms; - talking = wait_until(stream, context, wait, {{dialog}}) == 0; - } - if (!talking){ - from = planned.after; - log_leg_done(stream, maps, label, planned, result.wild_battles); - continue; - } +std::vector RouteWalker::plan_legs() const{ + std::optional> legs = plan_robust_route(m_grid, m_from, m_plan.goal, m_plan.costs); + if (!legs){ + // From a few possible tiles the exact-open-leg costs found no + // plan where the default ones did (r240a, three tiles on Route + // 204's row 27); the default plan is longer but sound. + m_stream.log("[Route] " + m_plan.label + ": no plan with the route costs from " + describe(m_maps, m_from) + + "; trying the default costs.", COLOR_ORANGE); + legs = plan_robust_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); + } + if (!legs){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + m_plan.label + ": no plan from " + describe(m_maps, m_from) + ".", m_stream); + } + return std::move(*legs); +} - if (watching.empty()){ - // A trainer the map does not have. Fight, then plan again from - // anywhere the leg could have stopped. - std::vector anywhere = from; - for (const std::vector& path : paths){ - anywhere.insert(anywhere.end(), path.begin(), path.end()); - } - std::sort(anywhere.begin(), anywhere.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - anywhere.erase(std::unique(anywhere.begin(), anywhere.end()), anywhere.end()); - route_status(stream, label + ": a trainer the map lacks stopped us; fighting."); - fight("unknown trainer"); - if (leg.ends_at_wall){ - const Milliseconds limit = ROUTE_START_DELAY + - route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; - stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); - from = planned.after; - log_leg_done(stream, maps, label, planned, 0); - continue; - } - from = anywhere; - replanned = true; - break; - } - // Each possible start tile was stopped on the first tile of its path - // inside a watching trainer's sight. - const TrainerSight trainer = trainers[watching[0]]; - std::vector stopped; - for (const std::vector& path : paths){ - for (const TilePos& pos : path){ - bool seen = false; - for (size_t t : watching){ - const std::vector sight = sight_tiles(grid, trainers[t]); - seen |= std::find(sight.begin(), sight.end(), pos) != sight.end(); - } - if (seen){ - stopped.push_back(pos); - break; - } - } - } - if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - leg_label + ": " + trainer.name + " talked, but no path enters their sight.", stream); - } - stream.log(ROUTE_LOG_TAG + route_trainer_line(label, trainer.name, route_tiles(maps, stopped))); - route_status(stream, "Fighting " + trainer.name + "."); - fight(trainer.name); - trainers.erase(trainers.begin() + watching[0]); - // Their sight line only says roughly where: BDSP's trainers stand a - // few tiles from Platinum's (r242a). A leg to a wall ends at its - // wall however far it got: walk on to it and carry on. An open leg - // counts its taps: the step that brought us into sight was complete. - if (leg.ends_at_wall){ - const Milliseconds limit = ROUTE_START_DELAY + - route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP * leg.tiles * 5 / 4 + 1000ms; - stream.log("[Route] " + leg_label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(stream, context, escape, {x, y}, limit, leg_label + ": on to the wall", {.arrived = watch_banner, .pace = DpadPace::RUN}); - from = planned.after; - log_leg_done(stream, maps, label, planned, 0); - continue; - } - // Only the taps that moved count: the trainer freezes the player - // on the tile they saw, and the taps pressed while they walk over - // move nobody (r248a: "4 taps" were 2 steps; the belief of two - // tiles then cost a 12-tile run to a wall and 5 back). - const size_t taps = std::min(leg.tiles, result.moved_chunks + turn_moved); - std::vector by_taps; - for (const TilePos& pos : from){ - const std::vector path = leg_path(grid, pos, leg.direction, leg.tiles); - const size_t k = std::min(taps, path.size()); - by_taps.push_back(k == 0 ? pos : path[k - 1]); - } - std::sort(by_taps.begin(), by_taps.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; +LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t count){ + route_status(m_stream, route_leg_line(number, count, planned_route_leg(m_maps, planned))); + LegWalk walk{ + .planned = planned, + .label = m_plan.label + ": " + to_string(planned.leg), + .stick = route_stick(planned.leg.direction), + .map_before = map_of(m_maps, m_from), + .map_after = map_of(m_maps, planned.after), + }; + const LegNext next = planned.leg.ends_at_wall ? wall_leg(walk) : open_leg(walk); + if (next == LegNext::REPLAN){ + return next; + } + m_facing = planned.leg.direction; + check_banners(walk); + if (walk.result.stop == WalkStop::TRANSITION){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": unexpected transition.", m_stream); + } + return after_leg(walk); +} + +// Legs whose ends span two maps skip the per-leg check; the walk as a +// whole must still have seen the banner of the map it ends on. +std::vector RouteWalker::arrive() const{ + const std::string map_end = map_of(m_maps, m_from); + const bool changed_map = !m_map_start.empty() && !map_end.empty() && map_end != m_map_start; + const bool seen = std::any_of(m_all_banners.begin(), m_all_banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_end); + }); + if (changed_map && !seen){ + const std::string reads = quoted_list(m_all_banners); + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + m_plan.label + ": arrived at " + describe(m_maps, m_from) + " on the map, but " + map_end + + "'s location banner never showed (read " + (reads.empty() ? "nothing" : reads) + ").", m_stream); + } + m_stream.log(ROUTE_LOG_TAG + route_arrived_line(m_plan.label, route_tiles(m_maps, m_from))); + return m_from; +} + + +// Run (B held) on the D-pad: a leg to a wall ends at the wall however fast +// we get there, and the D-pad keeps to the row. +LegNext RouteWalker::wall_leg(LegWalk& walk){ + const TileLeg& leg = walk.leg(); + const Milliseconds limit = wall_limit(leg); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + // A wild battle may end the walk early. Walking to a wall again ends in + // the same place, so finish the leg. + const bool interrupted = walk.result.wild_battles > 0; + for (size_t again = 0; again < 3 && walk.result.wild_battles > 0 && + (walk.result.stop == WalkStop::LIMIT || walk.result.stop == WalkStop::BLOCKED); again++ + ){ + m_stream.log("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again."); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + } + if (interrupted){ + return LegNext::NEXT_LEG; + } + // A wall well before the nearest one the map has: something the map + // does not know is in the way. Work out where we stopped from the time + // walked, put it on our map and plan again from there. + size_t nearest = SIZE_MAX; + for (const TilePos& pos : m_from){ + nearest = std::min(nearest, slide_to_wall(m_grid, pos, leg.direction).tiles); + } + size_t walked_tiles = tiles_moved(walk.result, route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP); + walked_tiles = unstick_wall_leg(walk, walked_tiles, nearest); + // Any stop short of the wall's distance: someone who stays put is + // talked to, and the leg is planned again from where we are. Within the + // time count's slack this may be the wall itself, where A does nothing + // and the new plan walks no further (r239a: a wanderer 3 tiles short + // passed as "about 8 of 10", and every later leg was off by those tiles). + if (walk.result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ + return stopped_short_of_wall(walk, walked_tiles); + } + // A leg to the wall that ran out of time is not at its wall: the open + // leg before it stopped short, and it ran along another row (r127a went + // west along Sandgem's row 13 for row 14, and the next leg north walked + // into the lab). Out of tall grass a stop reads, so walk on: a player + // still moving is not where the plan has him. + if (walk.result.stop == WalkStop::LIMIT && route_wall_readable(m_grid, walk.planned.after)){ + check_at_wall(walk); + } + return LegNext::NEXT_LEG; +} + +// A walk to the wall that stopped well short of it: tap through a corner, +// then wait for someone in the way. Returns the tiles walked by then. +size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest){ + const Milliseconds per_tile = route_ms_per_tile(walk.leg().direction) / ROUTE_RUN_SPEEDUP; + const Milliseconds limit = wall_limit(walk.leg()); + // A stick walk can catch a corner when we stand part of a tile off + // centre, where a D-pad tap, which moves whole tiles, gets through: on + // Route 203's stairs the walk west stopped nine times in a row and two + // taps crossed (r225a, 2026-10-31). Tap twice, then walk on to the wall. + if (walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ + const Direction direction = walk.leg().direction; + const DpadPosition dpad = + direction == Direction::NORTH ? DPAD_UP : + direction == Direction::SOUTH ? DPAD_DOWN : + direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; + m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); + for (size_t tap = 0; tap < 2; tap++){ + pbf_press_dpad(m_context, dpad, 160ms, 640ms); + } + m_context.wait_for_all_requests(); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + walked_tiles += tiles_moved(walk.result, per_tile); + } + // Someone walking about may stand in the way for a moment: wait and + // walk to the wall again before calling it an obstacle. + for (size_t again = 0; again < 2 && walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++){ + m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(m_context, 2500ms); + m_context.wait_for_all_requests(); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + walked_tiles += tiles_moved(walk.result, per_tile); + } + return walked_tiles; +} + +LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ + // Someone who stays put: talk to them. A trainer we walked up to from + // the side starts the battle this way. + talk_to_blocker(walk.label); + std::vector stopped; + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.leg().direction, SIZE_MAX); + for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ + stopped.push_back(k == 0 ? pos : path[k - 1]); + } + } + stopped = sorted_unique(std::move(stopped)); + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": stopped early, and no tile fits.", m_stream); + } + mark_blocker(walk, stopped); + return replan_from(walk, std::move(stopped), "stopped early after about " + std::to_string(walked_tiles) + " tiles"); +} + +void RouteWalker::check_at_wall(LegWalk& walk){ + const WalkResult check = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, 2000ms, + walk.label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); + if (check.stop == WalkStop::DIALOG){ + // A trainer who saw us froze the walk (the "!") until its time ran + // out, then walked over (r241a: Aroma Lady Taylor's line crosses + // Route 204's corridor). Battle, then walk on to the wall: where + // they saw us from is not reliable (BDSP's trainers stand a few + // tiles from Platinum's, r242a), and a leg to a wall ends at its + // wall however far it got. + route_status(m_stream, walk.label + ": a trainer stopped us on the way; battling."); + m_trainers.fight("a trainer on the way"); + m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.leg()), + walk.label + ": on to the wall", walk.run_watching()); + } + if (check.stop != WalkStop::BLOCKED && + !(check.stop == WalkStop::LIMIT && holding_against_wall(m_stream, m_context, walk.stick.x, walk.stick.y, walk.label + ": at the wall?")) + ){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": ran out of time short of the wall, and walking on gets " + + walk_stop_name(check.stop) + ": not where the plan has us.", m_stream); + } +} + +// After a battle on a leg to a wall: a leg to a wall ends at its wall +// however far it got, so walk on to it and carry on. +void RouteWalker::on_to_wall(LegWalk& walk){ + m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); + walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.leg()), + walk.label + ": on to the wall", walk.run_watching()); + m_from = walk.planned.after; + log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, 0); +} + + +// Whole tiles on the D-pad, a tap each: a tap moves exactly one tile, while +// a stick hold timed for three moved one in the Ravaged Path (r235b) and the +// belief drifted four rows. +LegNext RouteWalker::open_leg(LegWalk& walk){ + const TileLeg& leg = walk.leg(); + if (m_facing != leg.direction){ + turn_tap(walk); + } + if (leg.tiles > walk.turn_moved){ + walk.result = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - walk.turn_moved, walk.label); + } + // A wild battle starts once the step onto the grass is done, so the + // taps still count; the walk went on after it. + if (walk.result.wild_battles > 0){ + m_stream.log("[Route] " + walk.label + ": " + std::to_string(walk.result.wild_battles) + + " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); + } + // Taps that moved nothing: someone stands in the way (the Youngster + // below the Ravaged Path wanders across the row under the cliff, r239a, + // r240a). Two still taps end the walk, so the tiles moved are the taps + // less those two. Wait once for them to move on and tap the rest (r246a + // lost 20 s per block on three waits); someone who stays is talked to, + // put on the map, and the leg planned again from the tile we stand on, + // which the taps give exactly. + size_t moved = std::min(leg.tiles, walk.result.moved_chunks + walk.turn_moved); + if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ + m_stream.log("[Route] " + walk.label + ": blocked after " + std::to_string(moved) + " of " + + std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(m_context, 2500ms); + m_context.wait_for_all_requests(); + const WalkResult rest = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - moved, walk.label + ": the rest"); + moved = std::min(leg.tiles, moved + rest.moved_chunks); + walk.result.stop = rest.stop; + walk.result.walked += rest.walked; + walk.result.wild_battles += rest.wild_battles; + } + if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ + return blocked_open_leg(walk, moved); + } + return LegNext::NEXT_LEG; +} + +// The first tap of a leg was meant to turn, but a 160 ms D-pad tap turns +// and steps whichever way the player faced (r248a: all seven did; r246a: +// "south 1" out of the cave went two tiles, onto the Youngster's row), so +// the tap is measured like any other and a step counts for the leg. +void RouteWalker::turn_tap(LegWalk& walk){ + const DpadPosition dpad = walk.stick.x < 0 ? DPAD_LEFT : walk.stick.x > 0 ? DPAD_RIGHT : walk.stick.y > 0 ? DPAD_UP : DPAD_DOWN; + m_context.wait_for_all_requests(); + VideoSnapshot before = m_stream.video().snapshot(); + pbf_press_dpad(m_context, dpad, 160ms, 700ms); + m_context.wait_for_all_requests(); + VideoSnapshot after = m_stream.video().snapshot(); + if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ + walk.turn_moved = 1; + m_stream.log("[Route] " + walk.label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); + } +} + +LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ + talk_to_blocker(walk.label); + std::vector stopped; + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.leg().direction, moved); + stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); + } + stopped = sorted_unique(std::move(stopped)); + mark_blocker(walk, stopped); + return replan_from(walk, std::move(stopped), + "blocked after " + std::to_string(moved) + " of " + std::to_string(walk.leg().tiles) + " tiles"); +} + + +// Entering another map shows its name; a missing or wrong name means the +// walk did not end where the plan says. From tiles on several maps (a leg +// not confirmed) the banner may already have shown. +void RouteWalker::check_banners(LegWalk& walk){ + m_context.wait_for_all_requests(); + if (VideoSnapshot screen = m_stream.video().snapshot()){ + walk.watch_banner(*screen.frame); + } + const std::string banner_text = quoted_list(walk.banners); + m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); + if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !walk.banner_ok()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + + (banner_text.empty() ? "nothing" : banner_text) + ".", m_stream); + } + if (!banner_text.empty()){ + m_stream.log("[Route] " + walk.label + ": location banner " + banner_text + "."); + } + // Where each leg ended, to compare with the plan after a run. + if (VideoSnapshot screen = m_stream.video().snapshot()){ + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; + Filesystem::create_directories(Filesystem::Path(folder)); + screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(walk.label) + ".png"); + } +} + +// A trainer who sees us freezes the player and walks over; the dialogue +// may open after the walk has ended. +LegNext RouteWalker::after_leg(LegWalk& walk){ + const TileLeg& leg = walk.leg(); + std::vector> paths; + for (const TilePos& pos : m_from){ + paths.push_back(leg_path(m_grid, pos, leg.direction, leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); + } + const std::vector watching = watching_trainers(paths); + bool talking = walk.result.stop == WalkStop::DIALOG; + if (!talking){ + ShortDialogWatcher dialog(COLOR_YELLOW); + const Milliseconds wait = watching.empty() ? 500ms : 4000ms; + talking = wait_until(m_stream, m_context, wait, {{dialog}}) == 0; + } + if (!talking){ + m_from = walk.planned.after; + log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); + return LegNext::NEXT_LEG; + } + if (watching.empty()){ + return unknown_trainer(walk, paths); + } + return known_trainer(walk, paths, watching); +} + +// The trainers whose sight one of the leg's possible paths enters. +std::vector RouteWalker::watching_trainers(const std::vector>& paths) const{ + std::vector watching; + for (size_t t = 0; t < m_trainers.sights.size(); t++){ + const std::vector sight = sight_tiles(m_grid, m_trainers.sights[t]); + const bool seen = std::any_of(paths.begin(), paths.end(), [&](const std::vector& path){ + return std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ + return std::find(sight.begin(), sight.end(), pos) != sight.end(); }); - by_taps.erase(std::unique(by_taps.begin(), by_taps.end()), by_taps.end()); - stream.log(ROUTE_LOG_TAG + route_replan_line(label, route_log_leg(leg), - std::to_string(taps) + " taps before the battle", route_tiles(maps, by_taps)), COLOR_ORANGE); - from = by_taps; - replanned = true; - break; + }); + if (seen){ + watching.push_back(t); } - if (!replanned){ - // Legs whose ends span two maps skip the per-leg check; the walk - // as a whole must still have seen the banner of the map it ends on. - const std::string map_end = map_of(maps, from); - const bool changed_map = !map_start.empty() && !map_end.empty() && map_end != map_start; - if (changed_map && std::none_of(all_banners.begin(), all_banners.end(), [&](const std::string& read){ - return location_banner_matches(read, map_end); - })){ - std::string seen; - for (const std::string& read : all_banners){ - seen += (seen.empty() ? "\"" : ", \"") + read + "\""; - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": arrived at " + describe(maps, from) + " on the map, but " + map_end + - "'s location banner never showed (read " + (seen.empty() ? "nothing" : seen) + ").", stream); - } - stream.log(ROUTE_LOG_TAG + route_arrived_line(label, route_tiles(maps, from))); - return from; + } + return watching; +} + +// A trainer the map does not have. Fight, then plan again from anywhere +// the leg could have stopped. +LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ + std::vector anywhere = m_from; + for (const std::vector& path : paths){ + anywhere.insert(anywhere.end(), path.begin(), path.end()); + } + anywhere = sorted_unique(std::move(anywhere)); + route_status(m_stream, m_plan.label + ": a trainer the map lacks stopped us; fighting."); + m_trainers.fight("unknown trainer"); + if (walk.leg().ends_at_wall){ + on_to_wall(walk); + return LegNext::NEXT_LEG; + } + m_from = std::move(anywhere); + return LegNext::REPLAN; +} + +LegNext RouteWalker::known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching){ + // Each possible start tile was stopped on the first tile of its path + // inside a watching trainer's sight. + const TrainerSight trainer = m_trainers.sights[watching[0]]; + std::vector stopped; + for (const std::vector& path : paths){ + const auto first_seen = std::find_if(path.begin(), path.end(), [&](const TilePos& pos){ + return std::any_of(watching.begin(), watching.end(), [&](size_t t){ + const std::vector sight = sight_tiles(m_grid, m_trainers.sights[t]); + return std::find(sight.begin(), sight.end(), pos) != sight.end(); + }); + }); + if (first_seen != path.end()){ + stopped.push_back(*first_seen); } } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": too many plans.", stream); + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": " + trainer.name + " talked, but no path enters their sight.", m_stream); + } + m_stream.log(ROUTE_LOG_TAG + route_trainer_line(m_plan.label, trainer.name, route_tiles(m_maps, stopped))); + route_status(m_stream, "Fighting " + trainer.name + "."); + m_trainers.fight(trainer.name); + m_trainers.sights.erase(m_trainers.sights.begin() + watching[0]); + // Their sight line only says roughly where: BDSP's trainers stand a few + // tiles from Platinum's (r242a). A leg to a wall walks on to its wall. + if (walk.leg().ends_at_wall){ + on_to_wall(walk); + return LegNext::NEXT_LEG; + } + // An open leg counts only the taps that moved: the trainer freezes the + // player on the tile they saw, and the taps pressed while they walk + // over move nobody (r248a: "4 taps" were 2 steps; the belief of two + // tiles then cost a 12-tile run to a wall and 5 back). + const size_t taps = std::min(walk.leg().tiles, walk.result.moved_chunks + walk.turn_moved); + std::vector by_taps; + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.leg().direction, walk.leg().tiles); + const size_t k = std::min(taps, path.size()); + by_taps.push_back(k == 0 ? pos : path[k - 1]); + } + return replan_from(walk, sorted_unique(std::move(by_taps)), std::to_string(taps) + " taps before the battle"); +} + + +// Presses A at whoever stopped the walk; a trainer we walked up to from +// the side starts the battle this way. +void RouteWalker::talk_to_blocker(const std::string& leg_label){ + pbf_press_button(m_context, BUTTON_A, 80ms, 200ms); + ShortDialogWatcher dialog(COLOR_YELLOW); + if (wait_until(m_stream, m_context, 2000ms, {{dialog}}) == 0){ + route_status(m_stream, leg_label + ": someone is in the way; talking to them."); + m_trainers.fight("someone in the way"); + } +} + +// One tile we may stand on: what stopped us is on the next tile, and goes +// on our map. +void RouteWalker::mark_blocker(const LegWalk& walk, const std::vector& stopped){ + if (stopped.size() != 1){ + return; + } + const TilePos blocker = stopped[0].next(walk.leg().direction); + m_grid.block(blocker); + m_stream.log("[Route] " + walk.label + ": something the map lacks is at " + + describe(m_maps, blocker) + "; marked it.", COLOR_ORANGE); +} + +LegNext RouteWalker::replan_from(const LegWalk& walk, std::vector stopped, const std::string& why){ + m_stream.log(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.leg()), why, route_tiles(m_maps, stopped)), COLOR_ORANGE); + m_facing = walk.leg().direction; + m_from = std::move(stopped); + return LegNext::REPLAN; +} + } +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan +){ + return RouteWalker(stream, context, escape, maps, trainers, plan).run(std::move(from)); +} std::vector walk_waypoints( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::vector& waypoints, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const RobustPlanCosts& costs + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const WaypointWalkPlan& plan ){ - for (size_t i = 0; i < waypoints.size(); i++){ - const TilePos goal = waypoints[i]; - from = walk_route(stream, context, escape, maps, from, - [&](const TilePos& pos){ return pos == goal; }, - trainers, fight, - label + " (" + std::to_string(i + 1) + "/" + std::to_string(waypoints.size()) + ", to " + describe(maps, goal) + ")", - {}, costs); + for (size_t i = 0; i < plan.waypoints.size(); i++){ + const TilePos goal = plan.waypoints[i]; + from = walk_route(stream, context, escape, maps, from, trainers, { + .goal = [goal](const TilePos& pos){ return pos == goal; }, + .label = plan.label + " (" + std::to_string(i + 1) + "/" + std::to_string(plan.waypoints.size()) + + ", to " + describe(maps, goal) + ")", + .avoid = {}, + .costs = plan.costs, + }); } return from; } void talk_to_npc( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector& at, - const TilePos& npc, - const std::vector& sides, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label + const StoryWorld& maps, std::vector& at, + RouteTrainers& trainers, const NpcTalk& talk ){ - for (Direction side : sides){ - const TilePos stand = npc.next(side); + for (Direction side : talk.sides){ + const TilePos stand = talk.npc.next(side); if (!standable(maps, stand)){ continue; } - at = walk_route(stream, context, escape, maps, at, [&](const TilePos& pos){ return pos == stand; }, - trainers, fight, label); + at = walk_route(stream, context, escape, maps, at, trainers, { + .goal = [stand](const TilePos& pos){ return pos == stand; }, + .label = talk.label, + .avoid = {}, + .costs = route_plan_costs(), + }); // Face the NPC: the opposite of the side we stand on. const Direction face = side == Direction::NORTH ? Direction::SOUTH : @@ -654,13 +783,13 @@ void talk_to_npc( context.wait_for_all_requests(); ShortDialogWatcher dialog(COLOR_CYAN); if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, label + ": talking from " + describe(maps, stand) + "."); + route_status(stream, talk.label + ": talking from " + describe(maps, stand) + "."); return; } - route_status(stream, label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); + route_status(stream, talk.label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); } OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": no side of " + describe(maps, npc) + " started a dialogue.", stream); + talk.label + ": no side of " + describe(maps, talk.npc) + " started a dialogue.", stream); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 6950867b70..e6d38f1b5f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -31,57 +31,72 @@ namespace PokemonBDSP{ // overworld either way. using RouteTrainerFight = std::function; +// The trainers a route walk may meet, and how to fight them. A trainer who +// is fought is taken off `sights`. +struct RouteTrainers{ + std::vector sights; + RouteTrainerFight fight; +}; + +// Where walk_route() goes: until every tile the player may be on is +// `goal`. Tiles in `avoid` (where someone wanders, a trainer's sight) are +// planned as off the map. +struct RouteWalkPlan{ + std::function goal; + std::string label; + std::vector avoid = {}; + RobustPlanCosts costs = route_plan_costs(); +}; + // Walks from any of the world tiles `from` of `maps` until every tile the -// player may be on is `goal`, and returns those tiles. Trainers in -// `trainers` who see the player are fought with `fight` and taken off the -// list. Tiles in `avoid` (where someone wanders) are planned as walls. -// Fails with a screenshot -// on a transition, a dialogue no trainer explains, a wild battle during an -// open leg, or when no plan exists. A walk from one map to another must see -// the second map's location banner on the way: a walk whose legs all ended -// on walls can still end in the wrong place (r124a saved in Sandgem Town -// after "arriving" on Route 202). +// player may be on is `plan.goal`, and returns those tiles. Trainers who +// see the player are fought and taken off `trainers`. Fails with a +// screenshot on a transition, a dialogue no trainer explains, or when no +// plan exists. A walk from one map to another must see the second map's +// location banner on the way: a walk whose legs all ended on walls can +// still end in the wrong place (r124a saved in Sandgem Town after +// "arriving" on Route 202). std::vector walk_route( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::function& goal, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const std::vector& avoid = {}, - const RobustPlanCosts& costs = route_plan_costs() + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan ); -// Walks `from` to each of `waypoints` in turn, with walk_route() for every -// stretch, and returns where the last one ended. The corners of a line a -// human walked, so the plan is that line, with the walker's handling of -// trainers and blocks on each stretch (Route 204 North, 2026-10-31). +// The corners of a line a human walked, and the costs to plan each +// stretch with. +struct WaypointWalkPlan{ + std::vector waypoints; + std::string label; + RobustPlanCosts costs = waypoint_plan_costs(); +}; + +// Walks `from` to each of `plan.waypoints` in turn, with walk_route() for +// every stretch, and returns where the last one ended: the plan is the +// line, with the walker's handling of trainers and blocks on each stretch +// (Route 204 North, 2026-10-31). std::vector walk_waypoints( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector from, - const std::vector& waypoints, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label, - const RobustPlanCosts& costs = waypoint_plan_costs() + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const WaypointWalkPlan& plan ); -// Walks next to the NPC on world tile `npc`, faces them and presses A, trying -// the sides in `sides` (the side of the NPC to stand on) in order until a -// dialogue opens. `at` is where the player may be, and is updated. Fails with -// a screenshot if no side starts a dialogue. A press from a diagonal tile, -// or from a tile a row off, talks to nobody, so each side is tried in turn. +// Whom talk_to_npc() talks to: the NPC on world tile `npc`, from the sides +// in `sides` (the side of the NPC to stand on), in order. +struct NpcTalk{ + Pokemon::TilePos npc; + std::vector sides; + std::string label; +}; + +// Walks next to `talk.npc`, faces them and presses A, trying each side +// until a dialogue opens. `at` is where the player may be, and is updated. +// Fails with a screenshot if no side starts a dialogue. A press from a +// diagonal tile, or from a tile a row off, talks to nobody, so each side is +// tried in turn. void talk_to_npc( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, - std::vector& at, - const Pokemon::TilePos& npc, - const std::vector& sides, - std::vector& trainers, - const RouteTrainerFight& fight, - const std::string& label + const StoryWorld& maps, std::vector& at, + RouteTrainers& trainers, const NpcTalk& talk ); From c459094be13bbc202983d666a50ba00223af1e24 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:53:01 -0800 Subject: [PATCH 23/74] BDSP walker: the transition watchers take only what their callers set Code health: WhiteScreenWatcher and BlackScreenFlashWatcher had 8 parameters. Every caller used the default thresholds and durations, so WhiteScreenWatcher takes the colour, box, finder type and duration, and WhiteScreenOverWatcher the colour and box; the values are the old defaults. BlackScreenFlashWatcher had no callers and is removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_TransitionWatchers.cpp | 12 ++---- .../PokemonBDSP_TransitionWatchers.h | 38 ++++--------------- 2 files changed, 10 insertions(+), 40 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp index 3655b5244d..d774df0ddd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp @@ -1,15 +1,9 @@ #include "PokemonBDSP_TransitionWatchers.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ -WhiteScreenOverWatcher::WhiteScreenOverWatcher( - Color color, const ImageFloatBox& box, - double min_rgb_sum, - double max_stddev_sum, - std::chrono::milliseconds hold_duration, - std::chrono::milliseconds release_duration -) +WhiteScreenOverWatcher::WhiteScreenOverWatcher(Color color, const ImageFloatBox& box) : VisualInferenceCallback("WhiteScreenOverWatcher") - , m_on(color, box, min_rgb_sum, max_stddev_sum, WhiteScreenWatcher::FinderType::PRESENT, hold_duration) - , m_off(color, box, min_rgb_sum, max_stddev_sum, WhiteScreenWatcher::FinderType::GONE, release_duration) + , m_on(color, box, WhiteScreenWatcher::FinderType::PRESENT, std::chrono::milliseconds(100)) + , m_off(color, box, WhiteScreenWatcher::FinderType::GONE, std::chrono::milliseconds(100)) {} void WhiteScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ m_on.make_overlays(items); diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h index ce5a34d2cb..8b40e51455 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h @@ -2,44 +2,20 @@ #include "CommonTools/VisualDetectors/BlackScreenDetector.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ // AutoStory-specific transition handling; shared watchers retain upstream behavior. +// A white screen (RGB sum over 500, stddev sum under 10) in `box`, +// present or gone for `duration`. class WhiteScreenWatcher : public DetectorToFinder{ public: - WhiteScreenWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double min_rgb_sum = 500, - double max_stddev_sum = 10, - FinderType finder_type = FinderType::PRESENT, - std::chrono::milliseconds duration = std::chrono::milliseconds(100) - ) - : DetectorToFinder("WhiteScreenWatcher", finder_type, duration, color, box, min_rgb_sum, max_stddev_sum) - {} -}; - -class BlackScreenFlashWatcher : public BlackScreenOverWatcher{ -public: - BlackScreenFlashWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(20), - std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) - ) - : BlackScreenOverWatcher(color, box, max_rgb_sum, max_stddev_sum, hold_duration, release_duration) + WhiteScreenWatcher(Color color, const ImageFloatBox& box, FinderType finder_type, std::chrono::milliseconds duration) + : DetectorToFinder("WhiteScreenWatcher", finder_type, duration, color, box, 500, 10) {} }; +// The screen in `box` went white for 100 ms, then stopped being white for +// 100 ms: an encounter's flash. class WhiteScreenOverWatcher : public VisualInferenceCallback{ public: - WhiteScreenOverWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double min_rgb_sum = 500, - double max_stddev_sum = 10, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(100), - std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) - ); + WhiteScreenOverWatcher(Color color, const ImageFloatBox& box); bool white_is_over(const ImageViewRGB32& frame); From 352c9fc2b4d3512b681406ef175e47f076099847 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 14:53:01 -0800 Subject: [PATCH 24/74] BDSP walker: LegWalk is a plain struct Code health asks for public data without methods: the banner checks and the run options are free functions of a LegWalk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 96 +++++++++---------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index c9c56096bc..f4ed4a1bb1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -180,31 +180,31 @@ struct LegWalk{ WalkResult result{WalkStop::LIMIT, 0ms, 0}; // Tiles the first tap of an open leg moved (see open_leg()). size_t turn_moved = 0; +}; - const TileLeg& leg() const{ - return planned.leg; - } - bool banner_ok() const{ - return std::any_of(banners.begin(), banners.end(), [&](const std::string& read){ - return location_banner_matches(read, map_after); - }); - } - // Notes the location banners the walk passes, to check map changes. A - // wild battle or a second walk to the wall may follow the banner: any - // banner seen during the leg counts. - bool watch_banner(const ImageViewRGB32& screen){ - if (banners.empty() || (!map_after.empty() && !banner_ok() && banners.size() < 8)){ - const std::string read = read_location_banner(screen); - if (!read.empty() && (banners.empty() || banners.back() != read)){ - banners.push_back(read); - } +bool banner_ok(const LegWalk& walk){ + return std::any_of(walk.banners.begin(), walk.banners.end(), [&](const std::string& read){ + return location_banner_matches(read, walk.map_after); + }); +} + +// Notes the location banners the walk passes, to check map changes. A wild +// battle or a second walk to the wall may follow the banner: any banner +// seen during the leg counts. +bool watch_banner(LegWalk& walk, const ImageViewRGB32& screen){ + if (walk.banners.empty() || (!walk.map_after.empty() && !banner_ok(walk) && walk.banners.size() < 8)){ + const std::string read = read_location_banner(screen); + if (!read.empty() && (walk.banners.empty() || walk.banners.back() != read)){ + walk.banners.push_back(read); } - return false; - } - DpadWalkOptions run_watching(){ - return {.arrived = [this](const ImageViewRGB32& screen){ return watch_banner(screen); }, .pace = DpadPace::RUN}; } -}; + return false; +} + +// Running on the D-pad, reading the banners on the way. +DpadWalkOptions run_watching(LegWalk& walk){ + return {.arrived = [&walk](const ImageViewRGB32& screen){ return watch_banner(walk, screen); }, .pace = DpadPace::RUN}; +} // walk_route(): plans, walks each leg, and plans again from where the walk // turned out to be when something stopped it. @@ -357,9 +357,9 @@ std::vector RouteWalker::arrive() const{ // Run (B held) on the D-pad: a leg to a wall ends at the wall however fast // we get there, and the D-pad keeps to the row. LegNext RouteWalker::wall_leg(LegWalk& walk){ - const TileLeg& leg = walk.leg(); + const TileLeg& leg = walk.planned.leg; const Milliseconds limit = wall_limit(leg); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); // A wild battle may end the walk early. Walking to a wall again ends in // the same place, so finish the leg. const bool interrupted = walk.result.wild_battles > 0; @@ -367,7 +367,7 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ (walk.result.stop == WalkStop::LIMIT || walk.result.stop == WalkStop::BLOCKED); again++ ){ m_stream.log("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again."); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); } if (interrupted){ return LegNext::NEXT_LEG; @@ -403,14 +403,14 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ // A walk to the wall that stopped well short of it: tap through a corner, // then wait for someone in the way. Returns the tiles walked by then. size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest){ - const Milliseconds per_tile = route_ms_per_tile(walk.leg().direction) / ROUTE_RUN_SPEEDUP; - const Milliseconds limit = wall_limit(walk.leg()); + const Milliseconds per_tile = route_ms_per_tile(walk.planned.leg.direction) / ROUTE_RUN_SPEEDUP; + const Milliseconds limit = wall_limit(walk.planned.leg); // A stick walk can catch a corner when we stand part of a tile off // centre, where a D-pad tap, which moves whole tiles, gets through: on // Route 203's stairs the walk west stopped nine times in a row and two // taps crossed (r225a, 2026-10-31). Tap twice, then walk on to the wall. if (walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ - const Direction direction = walk.leg().direction; + const Direction direction = walk.planned.leg.direction; const DpadPosition dpad = direction == Direction::NORTH ? DPAD_UP : direction == Direction::SOUTH ? DPAD_DOWN : @@ -421,7 +421,7 @@ size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t pbf_press_dpad(m_context, dpad, 160ms, 640ms); } m_context.wait_for_all_requests(); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); walked_tiles += tiles_moved(walk.result, per_tile); } // Someone walking about may stand in the way for a moment: wait and @@ -431,7 +431,7 @@ size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); pbf_wait(m_context, 2500ms); m_context.wait_for_all_requests(); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, walk.run_watching()); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); walked_tiles += tiles_moved(walk.result, per_tile); } return walked_tiles; @@ -443,7 +443,7 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ talk_to_blocker(walk.label); std::vector stopped; for (const TilePos& pos : m_from){ - const std::vector path = leg_path(m_grid, pos, walk.leg().direction, SIZE_MAX); + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, SIZE_MAX); for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ stopped.push_back(k == 0 ? pos : path[k - 1]); } @@ -470,8 +470,8 @@ void RouteWalker::check_at_wall(LegWalk& walk){ route_status(m_stream, walk.label + ": a trainer stopped us on the way; battling."); m_trainers.fight("a trainer on the way"); m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.leg()), - walk.label + ": on to the wall", walk.run_watching()); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), + walk.label + ": on to the wall", run_watching(walk)); } if (check.stop != WalkStop::BLOCKED && !(check.stop == WalkStop::LIMIT && holding_against_wall(m_stream, m_context, walk.stick.x, walk.stick.y, walk.label + ": at the wall?")) @@ -486,8 +486,8 @@ void RouteWalker::check_at_wall(LegWalk& walk){ // however far it got, so walk on to it and carry on. void RouteWalker::on_to_wall(LegWalk& walk){ m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.leg()), - walk.label + ": on to the wall", walk.run_watching()); + walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), + walk.label + ": on to the wall", run_watching(walk)); m_from = walk.planned.after; log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, 0); } @@ -497,7 +497,7 @@ void RouteWalker::on_to_wall(LegWalk& walk){ // a stick hold timed for three moved one in the Ravaged Path (r235b) and the // belief drifted four rows. LegNext RouteWalker::open_leg(LegWalk& walk){ - const TileLeg& leg = walk.leg(); + const TileLeg& leg = walk.planned.leg; if (m_facing != leg.direction){ turn_tap(walk); } @@ -556,13 +556,13 @@ LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ talk_to_blocker(walk.label); std::vector stopped; for (const TilePos& pos : m_from){ - const std::vector path = leg_path(m_grid, pos, walk.leg().direction, moved); + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, moved); stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); } stopped = sorted_unique(std::move(stopped)); mark_blocker(walk, stopped); return replan_from(walk, std::move(stopped), - "blocked after " + std::to_string(moved) + " of " + std::to_string(walk.leg().tiles) + " tiles"); + "blocked after " + std::to_string(moved) + " of " + std::to_string(walk.planned.leg.tiles) + " tiles"); } @@ -572,11 +572,11 @@ LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ void RouteWalker::check_banners(LegWalk& walk){ m_context.wait_for_all_requests(); if (VideoSnapshot screen = m_stream.video().snapshot()){ - walk.watch_banner(*screen.frame); + watch_banner(walk, *screen.frame); } const std::string banner_text = quoted_list(walk.banners); m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); - if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !walk.banner_ok()){ + if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + (banner_text.empty() ? "nothing" : banner_text) + ".", m_stream); @@ -595,7 +595,7 @@ void RouteWalker::check_banners(LegWalk& walk){ // A trainer who sees us freezes the player and walks over; the dialogue // may open after the walk has ended. LegNext RouteWalker::after_leg(LegWalk& walk){ - const TileLeg& leg = walk.leg(); + const TileLeg& leg = walk.planned.leg; std::vector> paths; for (const TilePos& pos : m_from){ paths.push_back(leg_path(m_grid, pos, leg.direction, leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); @@ -645,7 +645,7 @@ LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector by_taps; for (const TilePos& pos : m_from){ - const std::vector path = leg_path(m_grid, pos, walk.leg().direction, walk.leg().tiles); + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, walk.planned.leg.tiles); const size_t k = std::min(taps, path.size()); by_taps.push_back(k == 0 ? pos : path[k - 1]); } @@ -715,15 +715,15 @@ void RouteWalker::mark_blocker(const LegWalk& walk, const std::vector& if (stopped.size() != 1){ return; } - const TilePos blocker = stopped[0].next(walk.leg().direction); + const TilePos blocker = stopped[0].next(walk.planned.leg.direction); m_grid.block(blocker); m_stream.log("[Route] " + walk.label + ": something the map lacks is at " + describe(m_maps, blocker) + "; marked it.", COLOR_ORANGE); } LegNext RouteWalker::replan_from(const LegWalk& walk, std::vector stopped, const std::string& why){ - m_stream.log(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.leg()), why, route_tiles(m_maps, stopped)), COLOR_ORANGE); - m_facing = walk.leg().direction; + m_stream.log(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.planned.leg), why, route_tiles(m_maps, stopped)), COLOR_ORANGE); + m_facing = walk.planned.leg.direction; m_from = std::move(stopped); return LegNext::REPLAN; } From aeb36c8aa633440b24f31185a0b7b9e477974145 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 15:23:06 -0800 Subject: [PATCH 25/74] BDSP walker: credit #1717 for the pieces adapted from it The transition watchers, the overworld detector and Walk.cpp's BattleDialogWatcher come from PokemonAutomation/Arduino-Source#1717 by Developer-Butters; their headers now say so. The transition watchers get the repo's header block, include guard and one namespace per line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_TransitionWatchers.cpp | 19 ++++++++++++-- .../PokemonBDSP_TransitionWatchers.h | 25 ++++++++++++++++--- ...okemonBDSP_AutoStory_OverworldDetector.cpp | 1 + .../PokemonBDSP_AutoStory_OverworldDetector.h | 2 ++ .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 2 ++ 5 files changed, 44 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp index d774df0ddd..3cf98c2e72 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp @@ -1,5 +1,17 @@ +/* BDSP Transition Watchers + * + * From: https://github.com/PokemonAutomation/ + * + * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. + */ + #include "PokemonBDSP_TransitionWatchers.h" -namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + WhiteScreenOverWatcher::WhiteScreenOverWatcher(Color color, const ImageFloatBox& box) : VisualInferenceCallback("WhiteScreenOverWatcher") , m_on(color, box, WhiteScreenWatcher::FinderType::PRESENT, std::chrono::milliseconds(100)) @@ -27,4 +39,7 @@ bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ return m_white_is_over.load(std::memory_order_acquire); } -}}} + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h index 8b40e51455..9091f99fb0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h @@ -1,6 +1,20 @@ -#pragma once +/* BDSP Transition Watchers + * + * From: https://github.com/PokemonAutomation/ + * + * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. + */ + +#ifndef PokemonAutomation_PokemonBDSP_TransitionWatchers_H +#define PokemonAutomation_PokemonBDSP_TransitionWatchers_H + #include "CommonTools/VisualDetectors/BlackScreenDetector.h" -namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + // AutoStory-specific transition handling; shared watchers retain upstream behavior. // A white screen (RGB sum over 500, stddev sum under 10) in `box`, // present or gone for `duration`. @@ -29,4 +43,9 @@ class WhiteScreenOverWatcher : public VisualInferenceCallback{ bool m_has_been_white = false; std::atomic m_white_is_over = false; }; -}}} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp index d9e759ec3a..855d3bbeae 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp @@ -2,6 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * + * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. */ #include "CommonFramework/ImageTools/ImageStats.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h index cf3d1ea2b6..f33988fcc3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h @@ -2,6 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * + * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. + * * Detects that the player is in the free-roaming overworld state: * no dialog box, no battle menu, and no in-game menu open. * diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index 5cdc90dc3e..0f5d15fc9f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -2,6 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * + * BattleDialogWatcher adapted from PokemonAutomation/Arduino-Source#1717 by + * Developer-Butters. */ #include From b585b8c6eaed812df5acd36a55ac4d8cd09fdf6c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 15:24:38 -0800 Subject: [PATCH 26/74] BDSP navigation: Segment 00 tests header in CRLF Like every other .h in the repo; line endings only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_Segment00_Tests.h | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h index 7e501479e0..1471536bd4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h @@ -1,27 +1,27 @@ -/* BDSP AutoStory Segment 00 Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H - -#include "Common/Cpp/TestRunners/UnitTest.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -// Offline checks of Segment 00's walked lines against the maps and the -// scenes' trigger rectangles. -void add_tests_AutoStory_Segment00(UnitTestDatabase& database); - - - -} -} -} -#endif +/* BDSP AutoStory Segment 00 Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Offline checks of Segment 00's walked lines against the maps and the +// scenes' trigger rectangles. +void add_tests_AutoStory_Segment00(UnitTestDatabase& database); + + + +} +} +} +#endif From ba95847e16eda3ec725997b9ff90f01b8d426347 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 15:24:44 -0800 Subject: [PATCH 27/74] BDSP walker: new files in CRLF #129's new .cpp and .h files were LF; they are CRLF like the rest of the repo. Line endings only: git diff --ignore-cr-at-eol shows nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- ...okemonBDSP_AutoStory_OverworldDetector.cpp | 272 +-- .../PokemonBDSP_AutoStory_OverworldDetector.h | 200 +-- .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 450 ++--- .../PokemonBDSP_AutoStory_Walk_Tests.h | 54 +- .../Utils/PokemonBDSP_AutoStory_Indoors.cpp | 136 +- .../Utils/PokemonBDSP_AutoStory_Indoors.h | 66 +- .../Utils/PokemonBDSP_AutoStory_Location.cpp | 296 +-- .../Utils/PokemonBDSP_AutoStory_Location.h | 134 +- .../PokemonBDSP_AutoStory_OverlayLog.cpp | 84 +- .../Utils/PokemonBDSP_AutoStory_OverlayLog.h | 54 +- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 1598 ++++++++--------- .../PokemonBDSP_AutoStory_PlannedRoute.h | 214 +-- .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 588 +++--- .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 300 ++-- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 1122 ++++++------ .../Utils/PokemonBDSP_AutoStory_Walk.h | 378 ++-- 16 files changed, 2973 insertions(+), 2973 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp index 855d3bbeae..6b250862fd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp @@ -1,136 +1,136 @@ -/* BDSP AutoStory - Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/Images/SolidColorTest.h" - -#include "PokemonBDSP_AutoStory_OverworldDetector.h" - -using namespace std::chrono_literals; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// --------------------------------------------------------------------------- -// OverworldDetector -// --------------------------------------------------------------------------- - -OverworldDetector::OverworldDetector(Color color) - : m_color(color) - , m_battle_menu(BattleType::STANDARD, color){ -} - -void OverworldDetector::make_overlays(VideoOverlaySet& items) const { - m_dialog.make_overlays(items); - m_battle_menu.make_overlays(items); - m_menu.make_overlays(items); -} - -bool OverworldDetector::detect(const ImageViewRGB32& screen){ - // We are in the overworld when none of the overlay screens are present. - if (m_dialog.detect(screen)){ - return false; - } - if (m_battle_menu.detect(screen)){ - return false; - } - if (m_menu.detect(screen)){ - return false; - } - return true; -} - - -// --------------------------------------------------------------------------- -// OverworldWatcher -// --------------------------------------------------------------------------- - -OverworldWatcher::OverworldWatcher(Color color) - : OverworldDetector(color) - , VisualInferenceCallback("OverworldWatcher"){ -} - -void OverworldWatcher::make_overlays(VideoOverlaySet& items) const { - OverworldDetector::make_overlays(items); -} - -bool OverworldWatcher::process_frame(const ImageViewRGB32& frame, WallClock /*timestamp*/){ - return detect(frame); -} - - -// --------------------------------------------------------------------------- -// PoketchButtonDetector -// --------------------------------------------------------------------------- - -PoketchButtonDetector::PoketchButtonDetector(Color color) - : m_color(color) - , m_button(0.968, 0.170, 0.022, 0.120){ -} - -void PoketchButtonDetector::make_overlays(VideoOverlaySet& items) const { - items.add(m_color, m_button); -} - -bool PoketchButtonDetector::detect(const ImageViewRGB32& screen){ - ImageStats stats = image_stats(extract_box_reference(screen, m_button)); - // The button is a glossy red with a highlight, so allow a wide stddev. - return is_solid(stats, {0.74, 0.10, 0.16}, 0.12, 80); -} - -PoketchButtonWatcher::PoketchButtonWatcher(Color color) - : PoketchButtonDetector(color) - , VisualInferenceCallback("PoketchButtonWatcher"){ -} - -void PoketchButtonWatcher::make_overlays(VideoOverlaySet& items) const { - PoketchButtonDetector::make_overlays(items); -} - -bool PoketchButtonWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ - return detect(frame); -} - - -static bool look_for_poketch_button(VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - PoketchButtonWatcher watcher; - return wait_until(stream, context, 2s, {{watcher}}) == 0; -} - -bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context){ - for (size_t attempt = 0; attempt < 3; attempt++){ - if (look_for_poketch_button(stream, context)){ - return true; - } - stream.log("[AutoStory] Poketch button not found. Attempt " + std::to_string(attempt + 1) + " of 3.", - COLOR_ORANGE); - - if (attempt == 0){ - // Most likely hidden: one tap shows it. - pbf_press_button(context, BUTTON_R, 205ms, 0ms); - }else{ - // Long press hides it, then a tap shows it at the normal size. - pbf_press_button(context, BUTTON_R, 1548ms, 0ms); - pbf_wait(context, 1418ms); - pbf_press_button(context, BUTTON_R, 143ms, 0ms); - } - } - - // Check the result of the last press sequence. - return look_for_poketch_button(stream, context); -} - - -} -} -} +/* BDSP AutoStory - Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/Images/SolidColorTest.h" + +#include "PokemonBDSP_AutoStory_OverworldDetector.h" + +using namespace std::chrono_literals; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// --------------------------------------------------------------------------- +// OverworldDetector +// --------------------------------------------------------------------------- + +OverworldDetector::OverworldDetector(Color color) + : m_color(color) + , m_battle_menu(BattleType::STANDARD, color){ +} + +void OverworldDetector::make_overlays(VideoOverlaySet& items) const { + m_dialog.make_overlays(items); + m_battle_menu.make_overlays(items); + m_menu.make_overlays(items); +} + +bool OverworldDetector::detect(const ImageViewRGB32& screen){ + // We are in the overworld when none of the overlay screens are present. + if (m_dialog.detect(screen)){ + return false; + } + if (m_battle_menu.detect(screen)){ + return false; + } + if (m_menu.detect(screen)){ + return false; + } + return true; +} + + +// --------------------------------------------------------------------------- +// OverworldWatcher +// --------------------------------------------------------------------------- + +OverworldWatcher::OverworldWatcher(Color color) + : OverworldDetector(color) + , VisualInferenceCallback("OverworldWatcher"){ +} + +void OverworldWatcher::make_overlays(VideoOverlaySet& items) const { + OverworldDetector::make_overlays(items); +} + +bool OverworldWatcher::process_frame(const ImageViewRGB32& frame, WallClock /*timestamp*/){ + return detect(frame); +} + + +// --------------------------------------------------------------------------- +// PoketchButtonDetector +// --------------------------------------------------------------------------- + +PoketchButtonDetector::PoketchButtonDetector(Color color) + : m_color(color) + , m_button(0.968, 0.170, 0.022, 0.120){ +} + +void PoketchButtonDetector::make_overlays(VideoOverlaySet& items) const { + items.add(m_color, m_button); +} + +bool PoketchButtonDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats = image_stats(extract_box_reference(screen, m_button)); + // The button is a glossy red with a highlight, so allow a wide stddev. + return is_solid(stats, {0.74, 0.10, 0.16}, 0.12, 80); +} + +PoketchButtonWatcher::PoketchButtonWatcher(Color color) + : PoketchButtonDetector(color) + , VisualInferenceCallback("PoketchButtonWatcher"){ +} + +void PoketchButtonWatcher::make_overlays(VideoOverlaySet& items) const { + PoketchButtonDetector::make_overlays(items); +} + +bool PoketchButtonWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ + return detect(frame); +} + + +static bool look_for_poketch_button(VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + PoketchButtonWatcher watcher; + return wait_until(stream, context, 2s, {{watcher}}) == 0; +} + +bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context){ + for (size_t attempt = 0; attempt < 3; attempt++){ + if (look_for_poketch_button(stream, context)){ + return true; + } + stream.log("[AutoStory] Poketch button not found. Attempt " + std::to_string(attempt + 1) + " of 3.", + COLOR_ORANGE); + + if (attempt == 0){ + // Most likely hidden: one tap shows it. + pbf_press_button(context, BUTTON_R, 205ms, 0ms); + }else{ + // Long press hides it, then a tap shows it at the normal size. + pbf_press_button(context, BUTTON_R, 1548ms, 0ms); + pbf_wait(context, 1418ms); + pbf_press_button(context, BUTTON_R, 143ms, 0ms); + } + } + + // Check the result of the last press sequence. + return look_for_poketch_button(stream, context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h index f33988fcc3..ce36eb5f86 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h @@ -1,100 +1,100 @@ -/* BDSP AutoStory - Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. - * - * Detects that the player is in the free-roaming overworld state: - * no dialog box, no battle menu, and no in-game menu open. - * - * BDSP does not ship a standalone OverworldDetector in PokemonBDSP/Inference/, - * so this composite detector is defined here for AutoStory use. - * - * Reuses: - * - ShortDialogDetector (PokemonBDSP_DialogDetector.h) — absence required - * - BattleMenuDetector (PokemonBDSP_BattleMenuDetector.h) — absence required - * - MenuDetector (PokemonBDSP_MenuDetector.h) — absence required - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OverworldDetector_H -#define PokemonAutomation_PokemonBDSP_AutoStory_OverworldDetector_H - -#include "Common/Cpp/Color.h" - -#include "CommonFramework/Tools/VideoStream.h" - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" - -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Static (single-frame) version — use when you already have a frame. -class OverworldDetector : public StaticScreenDetector { -public: - OverworldDetector(Color color = COLOR_CYAN); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Returns true when none of: short dialog, battle menu, or in-game menu - // are present on the given frame. - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ShortDialogDetector m_dialog; - BattleMenuDetector m_battle_menu; - MenuDetector m_menu; -}; - - -// Watcher (callback) version — use with run_until<> or wait_until(). -class OverworldWatcher : public OverworldDetector, public VisualInferenceCallback { -public: - OverworldWatcher(Color color = COLOR_CYAN); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - -// Detects the big red button on the right edge of the Poketch overlay. -// Present only while the Poketch is shown at its normal size. -class PoketchButtonDetector : public StaticScreenDetector { -public: - PoketchButtonDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_button; -}; - -class PoketchButtonWatcher : public PoketchButtonDetector, public VisualInferenceCallback { -public: - PoketchButtonWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - -// Tries up to 3 times to get the Poketch button on screen using R presses. -// Returns true if the button was seen. -bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context); - - -} -} -} -#endif +/* BDSP AutoStory - Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. + * + * Detects that the player is in the free-roaming overworld state: + * no dialog box, no battle menu, and no in-game menu open. + * + * BDSP does not ship a standalone OverworldDetector in PokemonBDSP/Inference/, + * so this composite detector is defined here for AutoStory use. + * + * Reuses: + * - ShortDialogDetector (PokemonBDSP_DialogDetector.h) — absence required + * - BattleMenuDetector (PokemonBDSP_BattleMenuDetector.h) — absence required + * - MenuDetector (PokemonBDSP_MenuDetector.h) — absence required + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OverworldDetector_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OverworldDetector_H + +#include "Common/Cpp/Color.h" + +#include "CommonFramework/Tools/VideoStream.h" + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" + +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Static (single-frame) version — use when you already have a frame. +class OverworldDetector : public StaticScreenDetector { +public: + OverworldDetector(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Returns true when none of: short dialog, battle menu, or in-game menu + // are present on the given frame. + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ShortDialogDetector m_dialog; + BattleMenuDetector m_battle_menu; + MenuDetector m_menu; +}; + + +// Watcher (callback) version — use with run_until<> or wait_until(). +class OverworldWatcher : public OverworldDetector, public VisualInferenceCallback { +public: + OverworldWatcher(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + +// Detects the big red button on the right edge of the Poketch overlay. +// Present only while the Poketch is shown at its normal size. +class PoketchButtonDetector : public StaticScreenDetector { +public: + PoketchButtonDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_button; +}; + +class PoketchButtonWatcher : public PoketchButtonDetector, public VisualInferenceCallback { +public: + PoketchButtonWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + +// Tries up to 3 times to get the Poketch button on screen using R presses. +// Returns true if the button was seen. +bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index cb6ab3bb54..9357b6cee2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -1,225 +1,225 @@ -/* BDSP AutoStory Walk Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Filesystem/Filesystem.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "CommonFramework/GlobalAutoPaths.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "Utils/PokemonBDSP_AutoStory_Indoors.h" -#include "Utils/PokemonBDSP_AutoStory_Location.h" -#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_Walk_Tests.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -// indoors() decides when leave_door_south() is out: r257 walked on south -// past Sandgem's road into a house after leaving the Center, because the -// evening tint made the outside as warm as a room. Synthetic screens: the -// evening outside (warm all over), a room (warm, black along the bottom), -// a fade (black all over), and warm with a thin dark edge (a shadow). -struct IndoorsCase{ - std::string name; - uint32_t fill; - double dark_bottom; // how much of the screen's height, from the bottom, is black - bool indoors; -}; - -class Test_IndoorsAnyLight : public UnitTest{ -public: - Test_IndoorsAnyLight() - : UnitTest("PokemonBDSP::AutoStory - indoors() under the evening tint") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::vector cases{ - {.name = "evening outside, orange all over", .fill = 0xffe0a040, .dark_bottom = 0, .indoors = false}, - {.name = "a room: orange, black below its floor", .fill = 0xffe0a040, .dark_bottom = 0.10, .indoors = true}, - {.name = "a fade: black all over", .fill = 0xff000000, .dark_bottom = 0, .indoors = false}, - {.name = "orange with a thin shadow at the bottom", .fill = 0xffe0a040, .dark_bottom = 0.01, .indoors = false}, - {.name = "daytime grass", .fill = 0xff60b040, .dark_bottom = 0.10, .indoors = false}, - }; - for (const IndoorsCase& item : cases){ - ImageRGB32 screen(1920, 1080); - const size_t dark_from = (size_t)(1080 * (1 - item.dark_bottom)); - for (size_t y = 0; y < 1080; y++){ - for (size_t x = 0; x < 1920; x++){ - screen.pixel(x, y) = y >= dark_from ? 0xff000000 : item.fill; - } - } - if (indoors(screen) != item.indoors){ - return item.name + (item.indoors ? ": read as outside." : ": read as inside."); - } - } - return true; - } -}; - -// door_fade_look(): out of a door is a dark look, then a bright one that is -// not a room. r259 turned round in Sandgem's lit Center, read "not a room" -// once at full brightness, and walked east inside it as if outside. -struct DoorLook{ - double brightness; - bool room; -}; -struct DoorCase{ - std::string name; - std::vector looks; - // The look (1-based) that reads out, or 0 for none. - size_t out_at; -}; - -class Test_DoorFade : public UnitTest{ -public: - Test_DoorFade() - : UnitTest("PokemonBDSP::AutoStory - out of a door needs its fade") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const std::vector cases{ - {.name = "r259: a bright look in the Center that misses the room", .looks = {{458, true}, {440, false}, {457, true}}, .out_at = 0}, - {.name = "the fade, then the town", .looks = {{458, true}, {300, true}, {60, false}, {310, false}}, .out_at = 4}, - {.name = "the fade, then the room again", .looks = {{458, true}, {60, false}, {420, true}}, .out_at = 0}, - {.name = "the fade, still dim", .looks = {{60, false}, {150, false}, {320, false}}, .out_at = 3}, - }; - for (const DoorCase& item : cases){ - DoorFadeWatch watch; - size_t out_at = 0; - for (size_t i = 0; i < item.looks.size() && out_at == 0; i++){ - if (door_fade_look(watch, item.looks[i].brightness, item.looks[i].room)){ - out_at = i + 1; - } - } - if (out_at != item.out_at){ - return item.name + ": out at look " + std::to_string(out_at) + ", expected " + std::to_string(item.out_at) + "."; - } - } - return true; - } -}; - - -class Test_LocationBanner : public UnitTest{ -public: - Test_LocationBanner() - : UnitTest("PokemonBDSP::AutoStory - location banner match") - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - struct Case{ - const char* read; - const char* expected; - bool match; - }; - const Case cases[] = { - {"sandgemtown", "Sandgem Town", true}, - {"andgemltown", "Sandgem Town", true}, // r109's OCR - {"Route 202", "Route 202", true}, - {"route2o2", "Route 202", false}, // a digit read as a letter is not trusted - {"route201", "Route 202", false}, - {"jubilifecity", "Sandgem Town", false}, - {"twinleaftown", "Sandgem Town", false}, - {"", "Sandgem Town", false}, - }; - for (const Case& c : cases){ - if (location_banner_matches(c.read, c.expected) != c.match){ - return std::string("Banner \"") + c.read + "\" for " + c.expected + - (c.match ? " should match." : " should not match."); - } - } - return true; - } -}; - - -class Test_Indoors : public UnitTest{ -public: - Test_Indoors() - : UnitTest("PokemonBDSP::AutoStory - indoors") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - struct Case{ const char* file; bool inside; }; - const Case cases[] = { - {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", true}, - {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c4.png", true}, - {"PokemonBDSP/AutoStory/JubilifeCenterInsideUpper-20261030-r151a.png", true}, - {"PokemonBDSP/AutoStory/SandgemCenterInside-20261030-053555.png", true}, - {"PokemonBDSP/AutoStory/JubilifeSchoolInside-20261030.png", true}, - {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", false}, - {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep-20261030.png", false}, - {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep2-20261030.png", false}, - {"PokemonBDSP/AutoStory/JubilifeCenterFrontDoor-20261030-q2.png", false}, - {"PokemonBDSP/AutoStory/SandgemCenterBelowSign-20261030-053527.png", false}, - {"PokemonBDSP/AutoStory/SandgemMartDoorUpRight-20261030-023443.png", false}, - }; - for (const Case& c : cases){ - const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; - if (!Filesystem::is_regular_file(path)){ - return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); - } - const bool inside = indoors(ImageRGB32(path)); - logger.log(std::string(c.file) + ": " + (inside ? "indoors" : "outside")); - if (inside != c.inside){ - return std::string(c.file) + ": expected " + (c.inside ? "indoors" : "outside") + "."; - } - } - return true; - } -}; - - -class Test_LocationBannerShowing : public UnitTest{ -public: - Test_LocationBannerShowing() - : UnitTest("PokemonBDSP::AutoStory - location banner showing") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - struct Case{ const char* file; bool banner; }; - const Case cases[] = { - {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", true}, - {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep-20261030.png", true}, - {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", false}, - {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c4.png", false}, - {"PokemonBDSP/AutoStory/JubilifeCenterInsideUpper-20261030-r151a.png", false}, - {"PokemonBDSP/AutoStory/JubilifeCenterFrontDoor-20261030-q2.png", false}, - }; - for (const Case& c : cases){ - const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; - if (!Filesystem::is_regular_file(path)){ - return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); - } - const bool banner = location_banner_showing(ImageRGB32(path)); - logger.log(std::string(c.file) + ": banner " + (banner ? "shows" : "none")); - if (banner != c.banner){ - return std::string(c.file) + ": expected " + (c.banner ? "a banner" : "no banner") + "."; - } - } - return true; - } -}; - - -} - - -void add_tests_AutoStory_Walk(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); - database.add(); -} - - - -} -} -} +/* BDSP AutoStory Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Utils/PokemonBDSP_AutoStory_Indoors.h" +#include "Utils/PokemonBDSP_AutoStory_Location.h" +#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_Walk_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// indoors() decides when leave_door_south() is out: r257 walked on south +// past Sandgem's road into a house after leaving the Center, because the +// evening tint made the outside as warm as a room. Synthetic screens: the +// evening outside (warm all over), a room (warm, black along the bottom), +// a fade (black all over), and warm with a thin dark edge (a shadow). +struct IndoorsCase{ + std::string name; + uint32_t fill; + double dark_bottom; // how much of the screen's height, from the bottom, is black + bool indoors; +}; + +class Test_IndoorsAnyLight : public UnitTest{ +public: + Test_IndoorsAnyLight() + : UnitTest("PokemonBDSP::AutoStory - indoors() under the evening tint") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "evening outside, orange all over", .fill = 0xffe0a040, .dark_bottom = 0, .indoors = false}, + {.name = "a room: orange, black below its floor", .fill = 0xffe0a040, .dark_bottom = 0.10, .indoors = true}, + {.name = "a fade: black all over", .fill = 0xff000000, .dark_bottom = 0, .indoors = false}, + {.name = "orange with a thin shadow at the bottom", .fill = 0xffe0a040, .dark_bottom = 0.01, .indoors = false}, + {.name = "daytime grass", .fill = 0xff60b040, .dark_bottom = 0.10, .indoors = false}, + }; + for (const IndoorsCase& item : cases){ + ImageRGB32 screen(1920, 1080); + const size_t dark_from = (size_t)(1080 * (1 - item.dark_bottom)); + for (size_t y = 0; y < 1080; y++){ + for (size_t x = 0; x < 1920; x++){ + screen.pixel(x, y) = y >= dark_from ? 0xff000000 : item.fill; + } + } + if (indoors(screen) != item.indoors){ + return item.name + (item.indoors ? ": read as outside." : ": read as inside."); + } + } + return true; + } +}; + +// door_fade_look(): out of a door is a dark look, then a bright one that is +// not a room. r259 turned round in Sandgem's lit Center, read "not a room" +// once at full brightness, and walked east inside it as if outside. +struct DoorLook{ + double brightness; + bool room; +}; +struct DoorCase{ + std::string name; + std::vector looks; + // The look (1-based) that reads out, or 0 for none. + size_t out_at; +}; + +class Test_DoorFade : public UnitTest{ +public: + Test_DoorFade() + : UnitTest("PokemonBDSP::AutoStory - out of a door needs its fade") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "r259: a bright look in the Center that misses the room", .looks = {{458, true}, {440, false}, {457, true}}, .out_at = 0}, + {.name = "the fade, then the town", .looks = {{458, true}, {300, true}, {60, false}, {310, false}}, .out_at = 4}, + {.name = "the fade, then the room again", .looks = {{458, true}, {60, false}, {420, true}}, .out_at = 0}, + {.name = "the fade, still dim", .looks = {{60, false}, {150, false}, {320, false}}, .out_at = 3}, + }; + for (const DoorCase& item : cases){ + DoorFadeWatch watch; + size_t out_at = 0; + for (size_t i = 0; i < item.looks.size() && out_at == 0; i++){ + if (door_fade_look(watch, item.looks[i].brightness, item.looks[i].room)){ + out_at = i + 1; + } + } + if (out_at != item.out_at){ + return item.name + ": out at look " + std::to_string(out_at) + ", expected " + std::to_string(item.out_at) + "."; + } + } + return true; + } +}; + + +class Test_LocationBanner : public UnitTest{ +public: + Test_LocationBanner() + : UnitTest("PokemonBDSP::AutoStory - location banner match") + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + struct Case{ + const char* read; + const char* expected; + bool match; + }; + const Case cases[] = { + {"sandgemtown", "Sandgem Town", true}, + {"andgemltown", "Sandgem Town", true}, // r109's OCR + {"Route 202", "Route 202", true}, + {"route2o2", "Route 202", false}, // a digit read as a letter is not trusted + {"route201", "Route 202", false}, + {"jubilifecity", "Sandgem Town", false}, + {"twinleaftown", "Sandgem Town", false}, + {"", "Sandgem Town", false}, + }; + for (const Case& c : cases){ + if (location_banner_matches(c.read, c.expected) != c.match){ + return std::string("Banner \"") + c.read + "\" for " + c.expected + + (c.match ? " should match." : " should not match."); + } + } + return true; + } +}; + + +class Test_Indoors : public UnitTest{ +public: + Test_Indoors() + : UnitTest("PokemonBDSP::AutoStory - indoors") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + struct Case{ const char* file; bool inside; }; + const Case cases[] = { + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c4.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterInsideUpper-20261030-r151a.png", true}, + {"PokemonBDSP/AutoStory/SandgemCenterInside-20261030-053555.png", true}, + {"PokemonBDSP/AutoStory/JubilifeSchoolInside-20261030.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", false}, + {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep-20261030.png", false}, + {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep2-20261030.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterFrontDoor-20261030-q2.png", false}, + {"PokemonBDSP/AutoStory/SandgemCenterBelowSign-20261030-053527.png", false}, + {"PokemonBDSP/AutoStory/SandgemMartDoorUpRight-20261030-023443.png", false}, + }; + for (const Case& c : cases){ + const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; + if (!Filesystem::is_regular_file(path)){ + return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); + } + const bool inside = indoors(ImageRGB32(path)); + logger.log(std::string(c.file) + ": " + (inside ? "indoors" : "outside")); + if (inside != c.inside){ + return std::string(c.file) + ": expected " + (c.inside ? "indoors" : "outside") + "."; + } + } + return true; + } +}; + + +class Test_LocationBannerShowing : public UnitTest{ +public: + Test_LocationBannerShowing() + : UnitTest("PokemonBDSP::AutoStory - location banner showing") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + struct Case{ const char* file; bool banner; }; + const Case cases[] = { + {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", true}, + {"PokemonBDSP/AutoStory/JubilifeSchoolDoorstep-20261030.png", true}, + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c4.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterInsideUpper-20261030-r151a.png", false}, + {"PokemonBDSP/AutoStory/JubilifeCenterFrontDoor-20261030-q2.png", false}, + }; + for (const Case& c : cases){ + const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; + if (!Filesystem::is_regular_file(path)){ + return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); + } + const bool banner = location_banner_showing(ImageRGB32(path)); + logger.log(std::string(c.file) + ": banner " + (banner ? "shows" : "none")); + if (banner != c.banner){ + return std::string(c.file) + ": expected " + (c.banner ? "a banner" : "no banner") + "."; + } + } + return true; + } +}; + + +} + + +void add_tests_AutoStory_Walk(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); + database.add(); + database.add(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h index ac120c6244..266dfa1c0d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h @@ -1,27 +1,27 @@ -/* BDSP AutoStory Walk Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Walk_Tests_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Walk_Tests_H - -#include "Common/Cpp/TestRunners/UnitTest.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -// The walker's screen reads: indoors() on synthetic screens and -// screenshots, the door's fade, and the location banner. -void add_tests_AutoStory_Walk(UnitTestDatabase& database); - - - -} -} -} -#endif +/* BDSP AutoStory Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Walk_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Walk_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The walker's screen reads: indoors() on synthetic screens and +// screenshots, the door's fade, and the location banner. +void add_tests_AutoStory_Walk(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp index 12baf6710f..c7e7a3458c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp @@ -1,68 +1,68 @@ -/* BDSP AutoStory - Indoors - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "PokemonBDSP_AutoStory_Indoors.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -// Near-black pixels in one edge strip of the screen, out of all its pixels. -struct EdgeDark{ - size_t dark = 0; - size_t count = 0; -}; -void add_pixel(EdgeDark& edge, bool dark){ - edge.dark += dark; - edge.count++; -} -bool mostly_dark(const EdgeDark& edge){ - return edge.count > 0 && edge.dark * 100 >= edge.count * 15; -} - -} - -bool indoors(const ImageViewRGB32& screen){ - const size_t width = screen.width(), height = screen.height(); - const size_t strip_h = height * 12 / 100, strip_w = width * 12 / 100; - size_t warm = 0; - size_t count = 0; - EdgeDark top, bottom, left, right; - for (size_t y = 0; y < height; y += 8){ - for (size_t x = 0; x < width; x += 8){ - const Color pixel(screen.pixel(x, y)); - count++; - warm += pixel.red() > 150 && pixel.red() > pixel.blue() + 70 && pixel.green() > pixel.blue() + 20; - const bool dark = pixel.red() + pixel.green() + pixel.blue() < 60; - if (y < strip_h){ - add_pixel(top, dark); - } - if (y >= height - strip_h){ - add_pixel(bottom, dark); - } - if (x < strip_w){ - add_pixel(left, dark); - } - if (x >= width - strip_w){ - add_pixel(right, dark); - } - } - } - if (count == 0 || warm * 4 <= count){ - return false; - } - return mostly_dark(top) || mostly_dark(bottom) || mostly_dark(left) || mostly_dark(right); -} - - - -} -} -} +/* BDSP AutoStory - Indoors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "PokemonBDSP_AutoStory_Indoors.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// Near-black pixels in one edge strip of the screen, out of all its pixels. +struct EdgeDark{ + size_t dark = 0; + size_t count = 0; +}; +void add_pixel(EdgeDark& edge, bool dark){ + edge.dark += dark; + edge.count++; +} +bool mostly_dark(const EdgeDark& edge){ + return edge.count > 0 && edge.dark * 100 >= edge.count * 15; +} + +} + +bool indoors(const ImageViewRGB32& screen){ + const size_t width = screen.width(), height = screen.height(); + const size_t strip_h = height * 12 / 100, strip_w = width * 12 / 100; + size_t warm = 0; + size_t count = 0; + EdgeDark top, bottom, left, right; + for (size_t y = 0; y < height; y += 8){ + for (size_t x = 0; x < width; x += 8){ + const Color pixel(screen.pixel(x, y)); + count++; + warm += pixel.red() > 150 && pixel.red() > pixel.blue() + 70 && pixel.green() > pixel.blue() + 20; + const bool dark = pixel.red() + pixel.green() + pixel.blue() < 60; + if (y < strip_h){ + add_pixel(top, dark); + } + if (y >= height - strip_h){ + add_pixel(bottom, dark); + } + if (x < strip_w){ + add_pixel(left, dark); + } + if (x >= width - strip_w){ + add_pixel(right, dark); + } + } + } + if (count == 0 || warm * 4 <= count){ + return false; + } + return mostly_dark(top) || mostly_dark(bottom) || mostly_dark(left) || mostly_dark(right); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h index 0d469836d0..9de7ba3159 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h @@ -1,33 +1,33 @@ -/* BDSP AutoStory - Indoors - * - * From: https://github.com/PokemonAutomation/ - * - * Whether the screen shows a room: the walker leaves a building by it. - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Indoors_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Indoors_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Whether the screen shows a building's inside: its warm walls and floor -// fill much of the view (Pokemon Centers, the Trainers' School: 42..65% of -// the screen), and the room floats in black, which shows along at least one -// edge (15% or more of a strip 12% deep). Warmth alone is not enough: the -// evening tint makes outside 50..72% warm (r256, r257, Sandgem), and -// Oreburgh's ground 58..69% by day. Of 1412 lab screenshots, the rule calls -// every outside one outside, at all hours, and the rooms rooms. A fade is -// dark everywhere but not warm, so it is not inside. -bool indoors(const ImageViewRGB32& screen); - - -} -} -} -#endif +/* BDSP AutoStory - Indoors + * + * From: https://github.com/PokemonAutomation/ + * + * Whether the screen shows a room: the walker leaves a building by it. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Indoors_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Indoors_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Whether the screen shows a building's inside: its warm walls and floor +// fill much of the view (Pokemon Centers, the Trainers' School: 42..65% of +// the screen), and the room floats in black, which shows along at least one +// edge (15% or more of a strip 12% deep). Warmth alone is not enough: the +// evening tint makes outside 50..72% warm (r256, r257, Sandgem), and +// Oreburgh's ground 58..69% by day. Of 1412 lab screenshots, the rule calls +// every outside one outside, at all hours, and the rooms rooms. A fade is +// dark everywhere but not warm, so it is not inside. +bool indoors(const ImageViewRGB32& screen); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp index 6b63b5cf71..f79677bbe1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -1,148 +1,148 @@ -/* BDSP AutoStory - Location - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Language.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_RawTesseractOCR.h" -#include "PokemonBDSP_AutoStory_Location.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -// The location banner: a white box at the top left that names a map for a -// few seconds after the player enters it. Left of the centred name it is plain -// white (251 on console B, against 27-75 for the trees there otherwise). -const ImageFloatBox LOCATION_BANNER_WHITE{0.035, 0.035, 0.085, 0.050}; -const ImageFloatBox LOCATION_BANNER_TEXT{0.100, 0.025, 0.300, 0.080}; - -// The save card's header: the map's name in salmon (255, 152, 140) on near -// white (245), top left, right of the card's red border. Too faint for OCR -// as it is: the reddish pixels are made black on white first. -const ImageFloatBox SAVE_SCREEN_LOCATION{0.036, 0.045, 0.274, 0.070}; -const uint32_t SAVE_SCREEN_TEXT_MIN = 0xff960000; -const uint32_t SAVE_SCREEN_TEXT_MAX = 0xffffa9a9; - -std::string digits_of(const std::string& text){ - std::string out; - for (char ch : text){ - if (std::isdigit((unsigned char)ch)){ - out.push_back(ch); - } - } - return out; -} - -} - - -std::string normalize_location_name(const std::string& text){ - std::string out; - for (unsigned char ch : text){ - if (std::isalnum(ch)){ - out.push_back((char)std::tolower(ch)); - } - } - return out; -} - -namespace{ -Language& story_language_setting(){ - static Language language = Language::English; - return language; -} -} - -Language story_language(){ - return story_language_setting(); -} - -void set_story_language(Language language){ - story_language_setting() = language; -} - -bool story_reads_text(){ - return story_reads_text(story_language()); -} - -bool story_reads_text(Language language){ - return language == Language::English; -} - -bool location_banner_showing(const ImageViewRGB32& screen){ - const ImageStats white = image_stats(extract_box_reference(screen, LOCATION_BANNER_WHITE)); - return white.average.sum() >= 690 && white.stddev.sum() <= 30; -} - -std::string location_banner_stats(const ImageViewRGB32& screen){ - const ImageStats white = image_stats(extract_box_reference(screen, LOCATION_BANNER_WHITE)); - return "mean " + std::to_string((int)white.average.sum()) + ", spread " + std::to_string((int)white.stddev.sum()); -} - -std::string read_location_banner(const ImageViewRGB32& screen){ - if (!location_banner_showing(screen)){ - return ""; - } - if (!story_reads_text()){ - return UNREAD_LOCATION; - } - return normalize_location_name(OCR::tesseract_ocr_read(Language::English, - extract_box_reference(screen, LOCATION_BANNER_TEXT))); -} - -std::string read_save_screen_location(const ImageViewRGB32& screen){ - if (!story_reads_text()){ - return UNREAD_LOCATION; - } - const ImageRGB32 text = to_blackwhite_rgb32_range( - extract_box_reference(screen, SAVE_SCREEN_LOCATION), true, SAVE_SCREEN_TEXT_MIN, SAVE_SCREEN_TEXT_MAX); - return normalize_location_name(OCR::tesseract_ocr_read(Language::English, text)); -} - -bool location_banner_matches(const std::string& read, const std::string& expected){ - // No reader for the game's language: a banner (or the save card) that - // showed is all there is; where we stand is the walk's to say. - if (read == UNREAD_LOCATION){ - return true; - } - const std::string a = normalize_location_name(read); - const std::string b = normalize_location_name(expected); - if (a.empty() || b.empty()){ - return false; - } - if (digits_of(a) != digits_of(b)){ - return false; - } - // Levenshtein distance. - std::vector row(b.size() + 1); - for (size_t j = 0; j <= b.size(); j++){ - row[j] = j; - } - for (size_t i = 1; i <= a.size(); i++){ - size_t diagonal = row[0]; - row[0] = i; - for (size_t j = 1; j <= b.size(); j++){ - const size_t above = row[j]; - row[j] = std::min({row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)}); - diagonal = above; - } - } - return row[b.size()] <= std::max(1, b.size() / 4); -} - - -} -} -} +/* BDSP AutoStory - Location + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Language.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_RawTesseractOCR.h" +#include "PokemonBDSP_AutoStory_Location.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// The location banner: a white box at the top left that names a map for a +// few seconds after the player enters it. Left of the centred name it is plain +// white (251 on console B, against 27-75 for the trees there otherwise). +const ImageFloatBox LOCATION_BANNER_WHITE{0.035, 0.035, 0.085, 0.050}; +const ImageFloatBox LOCATION_BANNER_TEXT{0.100, 0.025, 0.300, 0.080}; + +// The save card's header: the map's name in salmon (255, 152, 140) on near +// white (245), top left, right of the card's red border. Too faint for OCR +// as it is: the reddish pixels are made black on white first. +const ImageFloatBox SAVE_SCREEN_LOCATION{0.036, 0.045, 0.274, 0.070}; +const uint32_t SAVE_SCREEN_TEXT_MIN = 0xff960000; +const uint32_t SAVE_SCREEN_TEXT_MAX = 0xffffa9a9; + +std::string digits_of(const std::string& text){ + std::string out; + for (char ch : text){ + if (std::isdigit((unsigned char)ch)){ + out.push_back(ch); + } + } + return out; +} + +} + + +std::string normalize_location_name(const std::string& text){ + std::string out; + for (unsigned char ch : text){ + if (std::isalnum(ch)){ + out.push_back((char)std::tolower(ch)); + } + } + return out; +} + +namespace{ +Language& story_language_setting(){ + static Language language = Language::English; + return language; +} +} + +Language story_language(){ + return story_language_setting(); +} + +void set_story_language(Language language){ + story_language_setting() = language; +} + +bool story_reads_text(){ + return story_reads_text(story_language()); +} + +bool story_reads_text(Language language){ + return language == Language::English; +} + +bool location_banner_showing(const ImageViewRGB32& screen){ + const ImageStats white = image_stats(extract_box_reference(screen, LOCATION_BANNER_WHITE)); + return white.average.sum() >= 690 && white.stddev.sum() <= 30; +} + +std::string location_banner_stats(const ImageViewRGB32& screen){ + const ImageStats white = image_stats(extract_box_reference(screen, LOCATION_BANNER_WHITE)); + return "mean " + std::to_string((int)white.average.sum()) + ", spread " + std::to_string((int)white.stddev.sum()); +} + +std::string read_location_banner(const ImageViewRGB32& screen){ + if (!location_banner_showing(screen)){ + return ""; + } + if (!story_reads_text()){ + return UNREAD_LOCATION; + } + return normalize_location_name(OCR::tesseract_ocr_read(Language::English, + extract_box_reference(screen, LOCATION_BANNER_TEXT))); +} + +std::string read_save_screen_location(const ImageViewRGB32& screen){ + if (!story_reads_text()){ + return UNREAD_LOCATION; + } + const ImageRGB32 text = to_blackwhite_rgb32_range( + extract_box_reference(screen, SAVE_SCREEN_LOCATION), true, SAVE_SCREEN_TEXT_MIN, SAVE_SCREEN_TEXT_MAX); + return normalize_location_name(OCR::tesseract_ocr_read(Language::English, text)); +} + +bool location_banner_matches(const std::string& read, const std::string& expected){ + // No reader for the game's language: a banner (or the save card) that + // showed is all there is; where we stand is the walk's to say. + if (read == UNREAD_LOCATION){ + return true; + } + const std::string a = normalize_location_name(read); + const std::string b = normalize_location_name(expected); + if (a.empty() || b.empty()){ + return false; + } + if (digits_of(a) != digits_of(b)){ + return false; + } + // Levenshtein distance. + std::vector row(b.size() + 1); + for (size_t j = 0; j <= b.size(); j++){ + row[j] = j; + } + for (size_t i = 1; i <= a.size(); i++){ + size_t diagonal = row[0]; + row[0] = i; + for (size_t j = 1; j <= b.size(); j++){ + const size_t above = row[j]; + row[j] = std::min({row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)}); + diagonal = above; + } + } + return row[b.size()] <= std::max(1, b.size() / 4); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h index 24bdc2ecc0..683874d64c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h @@ -1,67 +1,67 @@ -/* BDSP AutoStory - Location - * - * From: https://github.com/PokemonAutomation/ - * - * Where the game says the player is: the location banner shown on entering - * a map, and the map named on the save screen's card. - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Location_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Location_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Lower-case letters and digits only: "Route 202" and "ROUTE 2O2 " compare -// by "route202". -std::string normalize_location_name(const std::string& text); - -// The game's language, for the reads that still use text (item names, the -// location banner, a sign's or talk's first box), set once from the -// program's options (StoryRunOptions) before the story runs; English until -// then. story_reads_text() says whether those reads have a model and -// dictionary for it (English only, so far); when not, callers use -// language-free checks: the banner's box showing, a sign's box opening, the -// first row of a Bag pocket. -Language story_language(); -void set_story_language(Language language); -bool story_reads_text(); -bool story_reads_text(Language language); - -// What the reads below return for a banner or save card that showed, when -// there is no text reader for the game's language (story_reads_text()): -// location_banner_matches() takes it as a match. -inline const std::string UNREAD_LOCATION = "(unread)"; - -// The location banner (the white box at the top left that names a map for a -// few seconds after the player enters it), read by OCR and normalized; -// empty when no banner shows. -std::string read_location_banner(const ImageViewRGB32& screen); -// Whether the location banner's white box shows, without reading it. -bool location_banner_showing(const ImageViewRGB32& screen); -// The banner box's mean and spread, for the log. -std::string location_banner_stats(const ImageViewRGB32& screen); - -// The map named at the top left of the save screen's card ("Sandgem Town", -// "Route 202"), read by OCR and normalized; empty if nothing reads. -std::string read_save_screen_location(const ImageViewRGB32& screen); - -// Whether the location banner's OCR `read` names the map `expected`. Both -// are compared as lower-case letters and digits. OCR drops or swaps letters -// ("andgemltown" for Sandgem Town on r109), so up to a quarter of the name's -// letters may differ; the digits must match exactly, so Route 201 is never -// read as Route 202. -bool location_banner_matches(const std::string& read, const std::string& expected); - - -} -} -} -#endif +/* BDSP AutoStory - Location + * + * From: https://github.com/PokemonAutomation/ + * + * Where the game says the player is: the location banner shown on entering + * a map, and the map named on the save screen's card. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Location_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Location_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Lower-case letters and digits only: "Route 202" and "ROUTE 2O2 " compare +// by "route202". +std::string normalize_location_name(const std::string& text); + +// The game's language, for the reads that still use text (item names, the +// location banner, a sign's or talk's first box), set once from the +// program's options (StoryRunOptions) before the story runs; English until +// then. story_reads_text() says whether those reads have a model and +// dictionary for it (English only, so far); when not, callers use +// language-free checks: the banner's box showing, a sign's box opening, the +// first row of a Bag pocket. +Language story_language(); +void set_story_language(Language language); +bool story_reads_text(); +bool story_reads_text(Language language); + +// What the reads below return for a banner or save card that showed, when +// there is no text reader for the game's language (story_reads_text()): +// location_banner_matches() takes it as a match. +inline const std::string UNREAD_LOCATION = "(unread)"; + +// The location banner (the white box at the top left that names a map for a +// few seconds after the player enters it), read by OCR and normalized; +// empty when no banner shows. +std::string read_location_banner(const ImageViewRGB32& screen); +// Whether the location banner's white box shows, without reading it. +bool location_banner_showing(const ImageViewRGB32& screen); +// The banner box's mean and spread, for the log. +std::string location_banner_stats(const ImageViewRGB32& screen); + +// The map named at the top left of the save screen's card ("Sandgem Town", +// "Route 202"), read by OCR and normalized; empty if nothing reads. +std::string read_save_screen_location(const ImageViewRGB32& screen); + +// Whether the location banner's OCR `read` names the map `expected`. Both +// are compared as lower-case letters and digits. OCR drops or swaps letters +// ("andgemltown" for Sandgem Town on r109), so up to a quarter of the name's +// letters may differ; the digits must match exactly, so Route 201 is never +// read as Route 202. +bool location_banner_matches(const std::string& read, const std::string& expected); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp index 7ac01390db..eab60111f3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp @@ -1,42 +1,42 @@ -/* BDSP AutoStory - Overlay Log - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_AutoStory_OverlayLog.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color){ - // The log box is 35% of the video wide at a font 4% of its height: about - // 34 characters. - constexpr size_t WIDTH = 34; - std::string line; - size_t start = 0; - while (start < text.size()){ - size_t end = text.find(' ', start); - if (end == std::string::npos){ - end = text.size(); - } - const std::string word = text.substr(start, end - start); - if (!line.empty() && line.size() + 1 + word.size() > WIDTH){ - overlay.add_log(line, color); - line = " "; - } - line += (line.empty() || line == " " ? "" : " ") + word; - start = end + 1; - } - if (!line.empty()){ - overlay.add_log(line, color); - } -} - - - -} -} -} +/* BDSP AutoStory - Overlay Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_OverlayLog.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color){ + // The log box is 35% of the video wide at a font 4% of its height: about + // 34 characters. + constexpr size_t WIDTH = 34; + std::string line; + size_t start = 0; + while (start < text.size()){ + size_t end = text.find(' ', start); + if (end == std::string::npos){ + end = text.size(); + } + const std::string word = text.substr(start, end - start); + if (!line.empty() && line.size() + 1 + word.size() > WIDTH){ + overlay.add_log(line, color); + line = " "; + } + line += (line.empty() || line == " " ? "" : " ") + word; + start = end + 1; + } + if (!line.empty()){ + overlay.add_log(line, color); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h index f030b54f1c..803b9bc4aa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h @@ -1,27 +1,27 @@ -/* BDSP AutoStory - Overlay Log - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OverlayLog_H -#define PokemonAutomation_PokemonBDSP_AutoStory_OverlayLog_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Adds `text` to the video overlay's log, split at spaces into lines short -// enough for the log box, which draws each line on one row and cuts it off. -void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color); - - -} -} -} -#endif +/* BDSP AutoStory - Overlay Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OverlayLog_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OverlayLog_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Adds `text` to the video overlay's log, split at spaces into lines short +// enough for the log box, which draws each line on one row and cuts it off. +void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index f4ed4a1bb1..da8af82032 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -1,799 +1,799 @@ -/* BDSP AutoStory - Planned Route - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Filesystem/Filesystem.h" -#include "CommonFramework/GlobalAutoPaths.h" -#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Navigation/Pokemon_RouteLog.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP_AutoStory_Location.h" -#include "PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_PlannedRoute.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace std::chrono_literals; -using namespace Pokemon; - - -namespace{ - -// World tiles as tiles of the named maps, for the shared route log -// (Pokemon_RouteLog.h); a tile no map holds is a "world" tile. -std::vector route_tiles(const StoryWorld& maps, const std::vector& tiles){ - std::vector out; - for (const TilePos& pos : tiles){ - const std::optional local = maps.to_local(pos); - out.push_back(local ? RouteTile{local->map, local->pos} : RouteTile{"world", pos}); - } - return out; -} - -std::string describe(const StoryWorld& maps, const std::vector& tiles){ - return Pokemon::describe(route_tiles(maps, tiles)); -} - -RouteLogLeg route_log_leg(const TileLeg& leg){ - return {.action = RouteLegAction::WALK, .direction = leg.direction, .tiles = leg.tiles, - .end = leg.ends_at_wall ? RouteLegEnd::WALL : RouteLegEnd::OPEN}; -} - -PlannedRouteLeg planned_route_leg(const StoryWorld& maps, const PlannedLeg& leg){ - return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; -} - -void log_plan(VideoStream& stream, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ - std::vector logged; - for (const PlannedLeg& leg : legs){ - logged.push_back(planned_route_leg(maps, leg)); - } - stream.log(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged)); -} - -// Logs a leg that ended on its planned tiles, and how that is known: an -// open leg counts its taps through a wild battle, so its end is assumed; a -// leg to a wall is walked again to its wall. -void log_leg_done(VideoStream& stream, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ - const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; - stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), - assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); -} - -// The tiles the player passes when walking `tiles` tiles from `from`, the -// first one after `from` first. Stops early where the player is stopped. -std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ - std::vector path; - size_t travelled = 0; - while (travelled < tiles){ - const std::optional next = step(grid, from, direction); - if (!next){ - break; - } - travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); - from = *next; - path.push_back(from); - } - return path; -} - -// Holding toward a wall with people or Pokemon moving beside us never reads -// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking -// scrolls the view far more (35 to 90). True if holding toward (x, y) for -// 1.6 s changes the screen less than walking would: we stand at a wall. -bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ - constexpr double WALKING_CHANGE = 25.0; - context.wait_for_all_requests(); - VideoSnapshot before = stream.video().snapshot(); - double most = 0; - for (size_t chunk = 0; chunk < 4 && before; chunk++){ - pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); - context.wait_for_all_requests(); - VideoSnapshot after = stream.video().snapshot(); - if (!after){ - return false; - } - most = std::max(most, walk_screen_change(*before.frame, *after.frame)); - before = std::move(after); - } - stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + - (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); - return before && most < WALKING_CHANGE; -} - -// The map all of `tiles` are on, or empty if they are on several or none. -std::string map_of(const StoryWorld& maps, const std::vector& tiles){ - std::string name; - for (const TilePos& pos : tiles){ - const std::optional tile = maps.to_local(pos); - if (!tile || (!name.empty() && tile->map != name)){ - return ""; - } - name = tile->map; - } - return name; -} - -} - - -namespace{ - -// Sorted by row, then column, without repeats. -std::vector sorted_unique(std::vector tiles){ - std::sort(tiles.begin(), tiles.end(), [](const TilePos& a, const TilePos& b){ - return a.y != b.y ? a.y < b.y : a.x < b.x; - }); - tiles.erase(std::unique(tiles.begin(), tiles.end()), tiles.end()); - return tiles; -} - -std::string quoted_list(const std::vector& reads){ - std::string text; - for (const std::string& read : reads){ - text += (text.empty() ? "\"" : ", \"") + read + "\""; - } - return text; -} - -// Long enough to reach the wall from the farthest tile, with room for a -// slow start; past the wall the player stands still. -Milliseconds wall_limit(const TileLeg& leg){ - const Milliseconds per_tile = route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; - return ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; -} - -// Tiles a walk to the wall moved, from the time it walked. -size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ - const Milliseconds moving = walk.walked - ROUTE_START_DELAY - - (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); - return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); -} - -// Whether a leg's walk goes on to the next leg or the route plans again. -enum class LegNext{ - NEXT_LEG, - REPLAN, -}; - -// One planned leg as it is walked: where it goes, and the location -// banners read on the way. -struct LegWalk{ - const PlannedLeg& planned; - std::string label; - JoystickPosition stick; - std::string map_before; - std::string map_after; - std::vector banners = {}; - WalkResult result{WalkStop::LIMIT, 0ms, 0}; - // Tiles the first tap of an open leg moved (see open_leg()). - size_t turn_moved = 0; -}; - -bool banner_ok(const LegWalk& walk){ - return std::any_of(walk.banners.begin(), walk.banners.end(), [&](const std::string& read){ - return location_banner_matches(read, walk.map_after); - }); -} - -// Notes the location banners the walk passes, to check map changes. A wild -// battle or a second walk to the wall may follow the banner: any banner -// seen during the leg counts. -bool watch_banner(LegWalk& walk, const ImageViewRGB32& screen){ - if (walk.banners.empty() || (!walk.map_after.empty() && !banner_ok(walk) && walk.banners.size() < 8)){ - const std::string read = read_location_banner(screen); - if (!read.empty() && (walk.banners.empty() || walk.banners.back() != read)){ - walk.banners.push_back(read); - } - } - return false; -} - -// Running on the D-pad, reading the banners on the way. -DpadWalkOptions run_watching(LegWalk& walk){ - return {.arrived = [&walk](const ImageViewRGB32& screen){ return watch_banner(walk, screen); }, .pace = DpadPace::RUN}; -} - -// walk_route(): plans, walks each leg, and plans again from where the walk -// turned out to be when something stopped it. -class RouteWalker{ -public: - RouteWalker( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, RouteTrainers& trainers, const RouteWalkPlan& plan - ) - : m_stream(stream) - , m_context(context) - , m_escape(escape) - , m_maps(maps) - , m_grid(maps) - , m_trainers(trainers) - , m_plan(plan) - {} - - std::vector run(std::vector from); - -private: - std::vector plan_legs() const; - LegNext walk_leg(const PlannedLeg& planned, size_t number, size_t count); - std::vector arrive() const; - - // Legs to a wall. - LegNext wall_leg(LegWalk& walk); - size_t unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest); - LegNext stopped_short_of_wall(LegWalk& walk, size_t walked_tiles); - void check_at_wall(LegWalk& walk); - void on_to_wall(LegWalk& walk); - - // Open legs, tapped. - LegNext open_leg(LegWalk& walk); - void turn_tap(LegWalk& walk); - LegNext blocked_open_leg(LegWalk& walk, size_t moved); - - // After each leg. - void check_banners(LegWalk& walk); - LegNext after_leg(LegWalk& walk); - std::vector watching_trainers(const std::vector>& paths) const; - LegNext unknown_trainer(LegWalk& walk, const std::vector>& paths); - LegNext known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching); - - void talk_to_blocker(const std::string& leg_label); - LegNext replan_from(const LegWalk& walk, std::vector stopped, const std::string& why); - void mark_blocker(const LegWalk& walk, const std::vector& stopped); - - VideoStream& m_stream; - ProControllerContext& m_context; - const WildBattleEscape& m_escape; - const StoryWorld& m_maps; - // Our own copy, so things found in the way can be added to it. - StoryWorld m_grid; - RouteTrainers& m_trainers; - const RouteWalkPlan& m_plan; - std::vector m_from; - // Which way the player faces, once a leg has set it. - std::optional m_facing; - // Every banner read on the way, to check the map we arrive on against. - std::vector m_all_banners; - std::string m_map_start; -}; - -std::vector RouteWalker::run(std::vector from){ - // Tiles to avoid are ground the game lets us walk on (a trainer's line - // of sight), so they are off the map, not walls: a leg must not end - // "at" one, or the walk would run on through it. - for (const TilePos& pos : m_plan.avoid){ - if (std::find(from.begin(), from.end(), pos) == from.end()){ - m_grid.uncover(pos); - } - } - m_from = std::move(from); - m_map_start = map_of(m_maps, m_from); - for (size_t plans = 0; plans < 8; plans++){ - const std::vector legs = plan_legs(); - route_status(m_stream, m_plan.label + ": " + std::to_string(legs.size()) + " legs planned"); - log_plan(m_stream, m_maps, m_plan.label, m_from, legs); - bool replanned = false; - for (size_t number = 1; number <= legs.size() && !replanned; number++){ - replanned = walk_leg(legs[number - 1], number, legs.size()) == LegNext::REPLAN; - } - if (!replanned){ - return arrive(); - } - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - m_plan.label + ": too many plans.", m_stream); -} - -std::vector RouteWalker::plan_legs() const{ - std::optional> legs = plan_robust_route(m_grid, m_from, m_plan.goal, m_plan.costs); - if (!legs){ - // From a few possible tiles the exact-open-leg costs found no - // plan where the default ones did (r240a, three tiles on Route - // 204's row 27); the default plan is longer but sound. - m_stream.log("[Route] " + m_plan.label + ": no plan with the route costs from " + describe(m_maps, m_from) + - "; trying the default costs.", COLOR_ORANGE); - legs = plan_robust_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); - } - if (!legs){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - m_plan.label + ": no plan from " + describe(m_maps, m_from) + ".", m_stream); - } - return std::move(*legs); -} - -LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t count){ - route_status(m_stream, route_leg_line(number, count, planned_route_leg(m_maps, planned))); - LegWalk walk{ - .planned = planned, - .label = m_plan.label + ": " + to_string(planned.leg), - .stick = route_stick(planned.leg.direction), - .map_before = map_of(m_maps, m_from), - .map_after = map_of(m_maps, planned.after), - }; - const LegNext next = planned.leg.ends_at_wall ? wall_leg(walk) : open_leg(walk); - if (next == LegNext::REPLAN){ - return next; - } - m_facing = planned.leg.direction; - check_banners(walk); - if (walk.result.stop == WalkStop::TRANSITION){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": unexpected transition.", m_stream); - } - return after_leg(walk); -} - -// Legs whose ends span two maps skip the per-leg check; the walk as a -// whole must still have seen the banner of the map it ends on. -std::vector RouteWalker::arrive() const{ - const std::string map_end = map_of(m_maps, m_from); - const bool changed_map = !m_map_start.empty() && !map_end.empty() && map_end != m_map_start; - const bool seen = std::any_of(m_all_banners.begin(), m_all_banners.end(), [&](const std::string& read){ - return location_banner_matches(read, map_end); - }); - if (changed_map && !seen){ - const std::string reads = quoted_list(m_all_banners); - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - m_plan.label + ": arrived at " + describe(m_maps, m_from) + " on the map, but " + map_end + - "'s location banner never showed (read " + (reads.empty() ? "nothing" : reads) + ").", m_stream); - } - m_stream.log(ROUTE_LOG_TAG + route_arrived_line(m_plan.label, route_tiles(m_maps, m_from))); - return m_from; -} - - -// Run (B held) on the D-pad: a leg to a wall ends at the wall however fast -// we get there, and the D-pad keeps to the row. -LegNext RouteWalker::wall_leg(LegWalk& walk){ - const TileLeg& leg = walk.planned.leg; - const Milliseconds limit = wall_limit(leg); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); - // A wild battle may end the walk early. Walking to a wall again ends in - // the same place, so finish the leg. - const bool interrupted = walk.result.wild_battles > 0; - for (size_t again = 0; again < 3 && walk.result.wild_battles > 0 && - (walk.result.stop == WalkStop::LIMIT || walk.result.stop == WalkStop::BLOCKED); again++ - ){ - m_stream.log("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again."); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); - } - if (interrupted){ - return LegNext::NEXT_LEG; - } - // A wall well before the nearest one the map has: something the map - // does not know is in the way. Work out where we stopped from the time - // walked, put it on our map and plan again from there. - size_t nearest = SIZE_MAX; - for (const TilePos& pos : m_from){ - nearest = std::min(nearest, slide_to_wall(m_grid, pos, leg.direction).tiles); - } - size_t walked_tiles = tiles_moved(walk.result, route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP); - walked_tiles = unstick_wall_leg(walk, walked_tiles, nearest); - // Any stop short of the wall's distance: someone who stays put is - // talked to, and the leg is planned again from where we are. Within the - // time count's slack this may be the wall itself, where A does nothing - // and the new plan walks no further (r239a: a wanderer 3 tiles short - // passed as "about 8 of 10", and every later leg was off by those tiles). - if (walk.result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ - return stopped_short_of_wall(walk, walked_tiles); - } - // A leg to the wall that ran out of time is not at its wall: the open - // leg before it stopped short, and it ran along another row (r127a went - // west along Sandgem's row 13 for row 14, and the next leg north walked - // into the lab). Out of tall grass a stop reads, so walk on: a player - // still moving is not where the plan has him. - if (walk.result.stop == WalkStop::LIMIT && route_wall_readable(m_grid, walk.planned.after)){ - check_at_wall(walk); - } - return LegNext::NEXT_LEG; -} - -// A walk to the wall that stopped well short of it: tap through a corner, -// then wait for someone in the way. Returns the tiles walked by then. -size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest){ - const Milliseconds per_tile = route_ms_per_tile(walk.planned.leg.direction) / ROUTE_RUN_SPEEDUP; - const Milliseconds limit = wall_limit(walk.planned.leg); - // A stick walk can catch a corner when we stand part of a tile off - // centre, where a D-pad tap, which moves whole tiles, gets through: on - // Route 203's stairs the walk west stopped nine times in a row and two - // taps crossed (r225a, 2026-10-31). Tap twice, then walk on to the wall. - if (walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ - const Direction direction = walk.planned.leg.direction; - const DpadPosition dpad = - direction == Direction::NORTH ? DPAD_UP : - direction == Direction::SOUTH ? DPAD_DOWN : - direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; - m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); - for (size_t tap = 0; tap < 2; tap++){ - pbf_press_dpad(m_context, dpad, 160ms, 640ms); - } - m_context.wait_for_all_requests(); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); - walked_tiles += tiles_moved(walk.result, per_tile); - } - // Someone walking about may stand in the way for a moment: wait and - // walk to the wall again before calling it an obstacle. - for (size_t again = 0; again < 2 && walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++){ - m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(m_context, 2500ms); - m_context.wait_for_all_requests(); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); - walked_tiles += tiles_moved(walk.result, per_tile); - } - return walked_tiles; -} - -LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ - // Someone who stays put: talk to them. A trainer we walked up to from - // the side starts the battle this way. - talk_to_blocker(walk.label); - std::vector stopped; - for (const TilePos& pos : m_from){ - const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, SIZE_MAX); - for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ - stopped.push_back(k == 0 ? pos : path[k - 1]); - } - } - stopped = sorted_unique(std::move(stopped)); - if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": stopped early, and no tile fits.", m_stream); - } - mark_blocker(walk, stopped); - return replan_from(walk, std::move(stopped), "stopped early after about " + std::to_string(walked_tiles) + " tiles"); -} - -void RouteWalker::check_at_wall(LegWalk& walk){ - const WalkResult check = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, 2000ms, - walk.label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); - if (check.stop == WalkStop::DIALOG){ - // A trainer who saw us froze the walk (the "!") until its time ran - // out, then walked over (r241a: Aroma Lady Taylor's line crosses - // Route 204's corridor). Battle, then walk on to the wall: where - // they saw us from is not reliable (BDSP's trainers stand a few - // tiles from Platinum's, r242a), and a leg to a wall ends at its - // wall however far it got. - route_status(m_stream, walk.label + ": a trainer stopped us on the way; battling."); - m_trainers.fight("a trainer on the way"); - m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), - walk.label + ": on to the wall", run_watching(walk)); - } - if (check.stop != WalkStop::BLOCKED && - !(check.stop == WalkStop::LIMIT && holding_against_wall(m_stream, m_context, walk.stick.x, walk.stick.y, walk.label + ": at the wall?")) - ){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": ran out of time short of the wall, and walking on gets " + - walk_stop_name(check.stop) + ": not where the plan has us.", m_stream); - } -} - -// After a battle on a leg to a wall: a leg to a wall ends at its wall -// however far it got, so walk on to it and carry on. -void RouteWalker::on_to_wall(LegWalk& walk){ - m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), - walk.label + ": on to the wall", run_watching(walk)); - m_from = walk.planned.after; - log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, 0); -} - - -// Whole tiles on the D-pad, a tap each: a tap moves exactly one tile, while -// a stick hold timed for three moved one in the Ravaged Path (r235b) and the -// belief drifted four rows. -LegNext RouteWalker::open_leg(LegWalk& walk){ - const TileLeg& leg = walk.planned.leg; - if (m_facing != leg.direction){ - turn_tap(walk); - } - if (leg.tiles > walk.turn_moved){ - walk.result = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - walk.turn_moved, walk.label); - } - // A wild battle starts once the step onto the grass is done, so the - // taps still count; the walk went on after it. - if (walk.result.wild_battles > 0){ - m_stream.log("[Route] " + walk.label + ": " + std::to_string(walk.result.wild_battles) + - " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); - } - // Taps that moved nothing: someone stands in the way (the Youngster - // below the Ravaged Path wanders across the row under the cliff, r239a, - // r240a). Two still taps end the walk, so the tiles moved are the taps - // less those two. Wait once for them to move on and tap the rest (r246a - // lost 20 s per block on three waits); someone who stays is talked to, - // put on the map, and the leg planned again from the tile we stand on, - // which the taps give exactly. - size_t moved = std::min(leg.tiles, walk.result.moved_chunks + walk.turn_moved); - if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ - m_stream.log("[Route] " + walk.label + ": blocked after " + std::to_string(moved) + " of " + - std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(m_context, 2500ms); - m_context.wait_for_all_requests(); - const WalkResult rest = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - moved, walk.label + ": the rest"); - moved = std::min(leg.tiles, moved + rest.moved_chunks); - walk.result.stop = rest.stop; - walk.result.walked += rest.walked; - walk.result.wild_battles += rest.wild_battles; - } - if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ - return blocked_open_leg(walk, moved); - } - return LegNext::NEXT_LEG; -} - -// The first tap of a leg was meant to turn, but a 160 ms D-pad tap turns -// and steps whichever way the player faced (r248a: all seven did; r246a: -// "south 1" out of the cave went two tiles, onto the Youngster's row), so -// the tap is measured like any other and a step counts for the leg. -void RouteWalker::turn_tap(LegWalk& walk){ - const DpadPosition dpad = walk.stick.x < 0 ? DPAD_LEFT : walk.stick.x > 0 ? DPAD_RIGHT : walk.stick.y > 0 ? DPAD_UP : DPAD_DOWN; - m_context.wait_for_all_requests(); - VideoSnapshot before = m_stream.video().snapshot(); - pbf_press_dpad(m_context, dpad, 160ms, 700ms); - m_context.wait_for_all_requests(); - VideoSnapshot after = m_stream.video().snapshot(); - if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ - walk.turn_moved = 1; - m_stream.log("[Route] " + walk.label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); - } -} - -LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ - talk_to_blocker(walk.label); - std::vector stopped; - for (const TilePos& pos : m_from){ - const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, moved); - stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); - } - stopped = sorted_unique(std::move(stopped)); - mark_blocker(walk, stopped); - return replan_from(walk, std::move(stopped), - "blocked after " + std::to_string(moved) + " of " + std::to_string(walk.planned.leg.tiles) + " tiles"); -} - - -// Entering another map shows its name; a missing or wrong name means the -// walk did not end where the plan says. From tiles on several maps (a leg -// not confirmed) the banner may already have shown. -void RouteWalker::check_banners(LegWalk& walk){ - m_context.wait_for_all_requests(); - if (VideoSnapshot screen = m_stream.video().snapshot()){ - watch_banner(walk, *screen.frame); - } - const std::string banner_text = quoted_list(walk.banners); - m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); - if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + - (banner_text.empty() ? "nothing" : banner_text) + ".", m_stream); - } - if (!banner_text.empty()){ - m_stream.log("[Route] " + walk.label + ": location banner " + banner_text + "."); - } - // Where each leg ended, to compare with the plan after a run. - if (VideoSnapshot screen = m_stream.video().snapshot()){ - const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; - Filesystem::create_directories(Filesystem::Path(folder)); - screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(walk.label) + ".png"); - } -} - -// A trainer who sees us freezes the player and walks over; the dialogue -// may open after the walk has ended. -LegNext RouteWalker::after_leg(LegWalk& walk){ - const TileLeg& leg = walk.planned.leg; - std::vector> paths; - for (const TilePos& pos : m_from){ - paths.push_back(leg_path(m_grid, pos, leg.direction, leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); - } - const std::vector watching = watching_trainers(paths); - bool talking = walk.result.stop == WalkStop::DIALOG; - if (!talking){ - ShortDialogWatcher dialog(COLOR_YELLOW); - const Milliseconds wait = watching.empty() ? 500ms : 4000ms; - talking = wait_until(m_stream, m_context, wait, {{dialog}}) == 0; - } - if (!talking){ - m_from = walk.planned.after; - log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); - return LegNext::NEXT_LEG; - } - if (watching.empty()){ - return unknown_trainer(walk, paths); - } - return known_trainer(walk, paths, watching); -} - -// The trainers whose sight one of the leg's possible paths enters. -std::vector RouteWalker::watching_trainers(const std::vector>& paths) const{ - std::vector watching; - for (size_t t = 0; t < m_trainers.sights.size(); t++){ - const std::vector sight = sight_tiles(m_grid, m_trainers.sights[t]); - const bool seen = std::any_of(paths.begin(), paths.end(), [&](const std::vector& path){ - return std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ - return std::find(sight.begin(), sight.end(), pos) != sight.end(); - }); - }); - if (seen){ - watching.push_back(t); - } - } - return watching; -} - -// A trainer the map does not have. Fight, then plan again from anywhere -// the leg could have stopped. -LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ - std::vector anywhere = m_from; - for (const std::vector& path : paths){ - anywhere.insert(anywhere.end(), path.begin(), path.end()); - } - anywhere = sorted_unique(std::move(anywhere)); - route_status(m_stream, m_plan.label + ": a trainer the map lacks stopped us; fighting."); - m_trainers.fight("unknown trainer"); - if (walk.planned.leg.ends_at_wall){ - on_to_wall(walk); - return LegNext::NEXT_LEG; - } - m_from = std::move(anywhere); - return LegNext::REPLAN; -} - -LegNext RouteWalker::known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching){ - // Each possible start tile was stopped on the first tile of its path - // inside a watching trainer's sight. - const TrainerSight trainer = m_trainers.sights[watching[0]]; - std::vector stopped; - for (const std::vector& path : paths){ - const auto first_seen = std::find_if(path.begin(), path.end(), [&](const TilePos& pos){ - return std::any_of(watching.begin(), watching.end(), [&](size_t t){ - const std::vector sight = sight_tiles(m_grid, m_trainers.sights[t]); - return std::find(sight.begin(), sight.end(), pos) != sight.end(); - }); - }); - if (first_seen != path.end()){ - stopped.push_back(*first_seen); - } - } - if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": " + trainer.name + " talked, but no path enters their sight.", m_stream); - } - m_stream.log(ROUTE_LOG_TAG + route_trainer_line(m_plan.label, trainer.name, route_tiles(m_maps, stopped))); - route_status(m_stream, "Fighting " + trainer.name + "."); - m_trainers.fight(trainer.name); - m_trainers.sights.erase(m_trainers.sights.begin() + watching[0]); - // Their sight line only says roughly where: BDSP's trainers stand a few - // tiles from Platinum's (r242a). A leg to a wall walks on to its wall. - if (walk.planned.leg.ends_at_wall){ - on_to_wall(walk); - return LegNext::NEXT_LEG; - } - // An open leg counts only the taps that moved: the trainer freezes the - // player on the tile they saw, and the taps pressed while they walk - // over move nobody (r248a: "4 taps" were 2 steps; the belief of two - // tiles then cost a 12-tile run to a wall and 5 back). - const size_t taps = std::min(walk.planned.leg.tiles, walk.result.moved_chunks + walk.turn_moved); - std::vector by_taps; - for (const TilePos& pos : m_from){ - const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, walk.planned.leg.tiles); - const size_t k = std::min(taps, path.size()); - by_taps.push_back(k == 0 ? pos : path[k - 1]); - } - return replan_from(walk, sorted_unique(std::move(by_taps)), std::to_string(taps) + " taps before the battle"); -} - - -// Presses A at whoever stopped the walk; a trainer we walked up to from -// the side starts the battle this way. -void RouteWalker::talk_to_blocker(const std::string& leg_label){ - pbf_press_button(m_context, BUTTON_A, 80ms, 200ms); - ShortDialogWatcher dialog(COLOR_YELLOW); - if (wait_until(m_stream, m_context, 2000ms, {{dialog}}) == 0){ - route_status(m_stream, leg_label + ": someone is in the way; talking to them."); - m_trainers.fight("someone in the way"); - } -} - -// One tile we may stand on: what stopped us is on the next tile, and goes -// on our map. -void RouteWalker::mark_blocker(const LegWalk& walk, const std::vector& stopped){ - if (stopped.size() != 1){ - return; - } - const TilePos blocker = stopped[0].next(walk.planned.leg.direction); - m_grid.block(blocker); - m_stream.log("[Route] " + walk.label + ": something the map lacks is at " + - describe(m_maps, blocker) + "; marked it.", COLOR_ORANGE); -} - -LegNext RouteWalker::replan_from(const LegWalk& walk, std::vector stopped, const std::string& why){ - m_stream.log(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.planned.leg), why, route_tiles(m_maps, stopped)), COLOR_ORANGE); - m_facing = walk.planned.leg.direction; - m_from = std::move(stopped); - return LegNext::REPLAN; -} - -} - - -std::vector walk_route( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector from, - RouteTrainers& trainers, const RouteWalkPlan& plan -){ - return RouteWalker(stream, context, escape, maps, trainers, plan).run(std::move(from)); -} - -std::vector walk_waypoints( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector from, - RouteTrainers& trainers, const WaypointWalkPlan& plan -){ - for (size_t i = 0; i < plan.waypoints.size(); i++){ - const TilePos goal = plan.waypoints[i]; - from = walk_route(stream, context, escape, maps, from, trainers, { - .goal = [goal](const TilePos& pos){ return pos == goal; }, - .label = plan.label + " (" + std::to_string(i + 1) + "/" + std::to_string(plan.waypoints.size()) + - ", to " + describe(maps, goal) + ")", - .avoid = {}, - .costs = plan.costs, - }); - } - return from; -} - -void talk_to_npc( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector& at, - RouteTrainers& trainers, const NpcTalk& talk -){ - for (Direction side : talk.sides){ - const TilePos stand = talk.npc.next(side); - if (!standable(maps, stand)){ - continue; - } - at = walk_route(stream, context, escape, maps, at, trainers, { - .goal = [stand](const TilePos& pos){ return pos == stand; }, - .label = talk.label, - .avoid = {}, - .costs = route_plan_costs(), - }); - // Face the NPC: the opposite of the side we stand on. - const Direction face = - side == Direction::NORTH ? Direction::SOUTH : - side == Direction::SOUTH ? Direction::NORTH : - side == Direction::EAST ? Direction::WEST : Direction::EAST; - route_turn(stream, context, face); - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - context.wait_for_all_requests(); - ShortDialogWatcher dialog(COLOR_CYAN); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, talk.label + ": talking from " + describe(maps, stand) + "."); - return; - } - route_status(stream, talk.label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - talk.label + ": no side of " + describe(maps, talk.npc) + " started a dialogue.", stream); -} - - - -} -} -} +/* BDSP AutoStory - Planned Route + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_PlannedRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using namespace Pokemon; + + +namespace{ + +// World tiles as tiles of the named maps, for the shared route log +// (Pokemon_RouteLog.h); a tile no map holds is a "world" tile. +std::vector route_tiles(const StoryWorld& maps, const std::vector& tiles){ + std::vector out; + for (const TilePos& pos : tiles){ + const std::optional local = maps.to_local(pos); + out.push_back(local ? RouteTile{local->map, local->pos} : RouteTile{"world", pos}); + } + return out; +} + +std::string describe(const StoryWorld& maps, const std::vector& tiles){ + return Pokemon::describe(route_tiles(maps, tiles)); +} + +RouteLogLeg route_log_leg(const TileLeg& leg){ + return {.action = RouteLegAction::WALK, .direction = leg.direction, .tiles = leg.tiles, + .end = leg.ends_at_wall ? RouteLegEnd::WALL : RouteLegEnd::OPEN}; +} + +PlannedRouteLeg planned_route_leg(const StoryWorld& maps, const PlannedLeg& leg){ + return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; +} + +void log_plan(VideoStream& stream, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ + std::vector logged; + for (const PlannedLeg& leg : legs){ + logged.push_back(planned_route_leg(maps, leg)); + } + stream.log(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged)); +} + +// Logs a leg that ended on its planned tiles, and how that is known: an +// open leg counts its taps through a wild battle, so its end is assumed; a +// leg to a wall is walked again to its wall. +void log_leg_done(VideoStream& stream, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ + const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; + stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), + assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); +} + +// The tiles the player passes when walking `tiles` tiles from `from`, the +// first one after `from` first. Stops early where the player is stopped. +std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ + std::vector path; + size_t travelled = 0; + while (travelled < tiles){ + const std::optional next = step(grid, from, direction); + if (!next){ + break; + } + travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); + from = *next; + path.push_back(from); + } + return path; +} + +// Holding toward a wall with people or Pokemon moving beside us never reads +// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking +// scrolls the view far more (35 to 90). True if holding toward (x, y) for +// 1.6 s changes the screen less than walking would: we stand at a wall. +bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ + constexpr double WALKING_CHANGE = 25.0; + context.wait_for_all_requests(); + VideoSnapshot before = stream.video().snapshot(); + double most = 0; + for (size_t chunk = 0; chunk < 4 && before; chunk++){ + pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); + context.wait_for_all_requests(); + VideoSnapshot after = stream.video().snapshot(); + if (!after){ + return false; + } + most = std::max(most, walk_screen_change(*before.frame, *after.frame)); + before = std::move(after); + } + stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + + (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); + return before && most < WALKING_CHANGE; +} + +// The map all of `tiles` are on, or empty if they are on several or none. +std::string map_of(const StoryWorld& maps, const std::vector& tiles){ + std::string name; + for (const TilePos& pos : tiles){ + const std::optional tile = maps.to_local(pos); + if (!tile || (!name.empty() && tile->map != name)){ + return ""; + } + name = tile->map; + } + return name; +} + +} + + +namespace{ + +// Sorted by row, then column, without repeats. +std::vector sorted_unique(std::vector tiles){ + std::sort(tiles.begin(), tiles.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + tiles.erase(std::unique(tiles.begin(), tiles.end()), tiles.end()); + return tiles; +} + +std::string quoted_list(const std::vector& reads){ + std::string text; + for (const std::string& read : reads){ + text += (text.empty() ? "\"" : ", \"") + read + "\""; + } + return text; +} + +// Long enough to reach the wall from the farthest tile, with room for a +// slow start; past the wall the player stands still. +Milliseconds wall_limit(const TileLeg& leg){ + const Milliseconds per_tile = route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; + return ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; +} + +// Tiles a walk to the wall moved, from the time it walked. +size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ + const Milliseconds moving = walk.walked - ROUTE_START_DELAY - + (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); + return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); +} + +// Whether a leg's walk goes on to the next leg or the route plans again. +enum class LegNext{ + NEXT_LEG, + REPLAN, +}; + +// One planned leg as it is walked: where it goes, and the location +// banners read on the way. +struct LegWalk{ + const PlannedLeg& planned; + std::string label; + JoystickPosition stick; + std::string map_before; + std::string map_after; + std::vector banners = {}; + WalkResult result{WalkStop::LIMIT, 0ms, 0}; + // Tiles the first tap of an open leg moved (see open_leg()). + size_t turn_moved = 0; +}; + +bool banner_ok(const LegWalk& walk){ + return std::any_of(walk.banners.begin(), walk.banners.end(), [&](const std::string& read){ + return location_banner_matches(read, walk.map_after); + }); +} + +// Notes the location banners the walk passes, to check map changes. A wild +// battle or a second walk to the wall may follow the banner: any banner +// seen during the leg counts. +bool watch_banner(LegWalk& walk, const ImageViewRGB32& screen){ + if (walk.banners.empty() || (!walk.map_after.empty() && !banner_ok(walk) && walk.banners.size() < 8)){ + const std::string read = read_location_banner(screen); + if (!read.empty() && (walk.banners.empty() || walk.banners.back() != read)){ + walk.banners.push_back(read); + } + } + return false; +} + +// Running on the D-pad, reading the banners on the way. +DpadWalkOptions run_watching(LegWalk& walk){ + return {.arrived = [&walk](const ImageViewRGB32& screen){ return watch_banner(walk, screen); }, .pace = DpadPace::RUN}; +} + +// walk_route(): plans, walks each leg, and plans again from where the walk +// turned out to be when something stopped it. +class RouteWalker{ +public: + RouteWalker( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, RouteTrainers& trainers, const RouteWalkPlan& plan + ) + : m_stream(stream) + , m_context(context) + , m_escape(escape) + , m_maps(maps) + , m_grid(maps) + , m_trainers(trainers) + , m_plan(plan) + {} + + std::vector run(std::vector from); + +private: + std::vector plan_legs() const; + LegNext walk_leg(const PlannedLeg& planned, size_t number, size_t count); + std::vector arrive() const; + + // Legs to a wall. + LegNext wall_leg(LegWalk& walk); + size_t unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest); + LegNext stopped_short_of_wall(LegWalk& walk, size_t walked_tiles); + void check_at_wall(LegWalk& walk); + void on_to_wall(LegWalk& walk); + + // Open legs, tapped. + LegNext open_leg(LegWalk& walk); + void turn_tap(LegWalk& walk); + LegNext blocked_open_leg(LegWalk& walk, size_t moved); + + // After each leg. + void check_banners(LegWalk& walk); + LegNext after_leg(LegWalk& walk); + std::vector watching_trainers(const std::vector>& paths) const; + LegNext unknown_trainer(LegWalk& walk, const std::vector>& paths); + LegNext known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching); + + void talk_to_blocker(const std::string& leg_label); + LegNext replan_from(const LegWalk& walk, std::vector stopped, const std::string& why); + void mark_blocker(const LegWalk& walk, const std::vector& stopped); + + VideoStream& m_stream; + ProControllerContext& m_context; + const WildBattleEscape& m_escape; + const StoryWorld& m_maps; + // Our own copy, so things found in the way can be added to it. + StoryWorld m_grid; + RouteTrainers& m_trainers; + const RouteWalkPlan& m_plan; + std::vector m_from; + // Which way the player faces, once a leg has set it. + std::optional m_facing; + // Every banner read on the way, to check the map we arrive on against. + std::vector m_all_banners; + std::string m_map_start; +}; + +std::vector RouteWalker::run(std::vector from){ + // Tiles to avoid are ground the game lets us walk on (a trainer's line + // of sight), so they are off the map, not walls: a leg must not end + // "at" one, or the walk would run on through it. + for (const TilePos& pos : m_plan.avoid){ + if (std::find(from.begin(), from.end(), pos) == from.end()){ + m_grid.uncover(pos); + } + } + m_from = std::move(from); + m_map_start = map_of(m_maps, m_from); + for (size_t plans = 0; plans < 8; plans++){ + const std::vector legs = plan_legs(); + route_status(m_stream, m_plan.label + ": " + std::to_string(legs.size()) + " legs planned"); + log_plan(m_stream, m_maps, m_plan.label, m_from, legs); + bool replanned = false; + for (size_t number = 1; number <= legs.size() && !replanned; number++){ + replanned = walk_leg(legs[number - 1], number, legs.size()) == LegNext::REPLAN; + } + if (!replanned){ + return arrive(); + } + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + m_plan.label + ": too many plans.", m_stream); +} + +std::vector RouteWalker::plan_legs() const{ + std::optional> legs = plan_robust_route(m_grid, m_from, m_plan.goal, m_plan.costs); + if (!legs){ + // From a few possible tiles the exact-open-leg costs found no + // plan where the default ones did (r240a, three tiles on Route + // 204's row 27); the default plan is longer but sound. + m_stream.log("[Route] " + m_plan.label + ": no plan with the route costs from " + describe(m_maps, m_from) + + "; trying the default costs.", COLOR_ORANGE); + legs = plan_robust_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); + } + if (!legs){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + m_plan.label + ": no plan from " + describe(m_maps, m_from) + ".", m_stream); + } + return std::move(*legs); +} + +LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t count){ + route_status(m_stream, route_leg_line(number, count, planned_route_leg(m_maps, planned))); + LegWalk walk{ + .planned = planned, + .label = m_plan.label + ": " + to_string(planned.leg), + .stick = route_stick(planned.leg.direction), + .map_before = map_of(m_maps, m_from), + .map_after = map_of(m_maps, planned.after), + }; + const LegNext next = planned.leg.ends_at_wall ? wall_leg(walk) : open_leg(walk); + if (next == LegNext::REPLAN){ + return next; + } + m_facing = planned.leg.direction; + check_banners(walk); + if (walk.result.stop == WalkStop::TRANSITION){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": unexpected transition.", m_stream); + } + return after_leg(walk); +} + +// Legs whose ends span two maps skip the per-leg check; the walk as a +// whole must still have seen the banner of the map it ends on. +std::vector RouteWalker::arrive() const{ + const std::string map_end = map_of(m_maps, m_from); + const bool changed_map = !m_map_start.empty() && !map_end.empty() && map_end != m_map_start; + const bool seen = std::any_of(m_all_banners.begin(), m_all_banners.end(), [&](const std::string& read){ + return location_banner_matches(read, map_end); + }); + if (changed_map && !seen){ + const std::string reads = quoted_list(m_all_banners); + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + m_plan.label + ": arrived at " + describe(m_maps, m_from) + " on the map, but " + map_end + + "'s location banner never showed (read " + (reads.empty() ? "nothing" : reads) + ").", m_stream); + } + m_stream.log(ROUTE_LOG_TAG + route_arrived_line(m_plan.label, route_tiles(m_maps, m_from))); + return m_from; +} + + +// Run (B held) on the D-pad: a leg to a wall ends at the wall however fast +// we get there, and the D-pad keeps to the row. +LegNext RouteWalker::wall_leg(LegWalk& walk){ + const TileLeg& leg = walk.planned.leg; + const Milliseconds limit = wall_limit(leg); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + // A wild battle may end the walk early. Walking to a wall again ends in + // the same place, so finish the leg. + const bool interrupted = walk.result.wild_battles > 0; + for (size_t again = 0; again < 3 && walk.result.wild_battles > 0 && + (walk.result.stop == WalkStop::LIMIT || walk.result.stop == WalkStop::BLOCKED); again++ + ){ + m_stream.log("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again."); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + } + if (interrupted){ + return LegNext::NEXT_LEG; + } + // A wall well before the nearest one the map has: something the map + // does not know is in the way. Work out where we stopped from the time + // walked, put it on our map and plan again from there. + size_t nearest = SIZE_MAX; + for (const TilePos& pos : m_from){ + nearest = std::min(nearest, slide_to_wall(m_grid, pos, leg.direction).tiles); + } + size_t walked_tiles = tiles_moved(walk.result, route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP); + walked_tiles = unstick_wall_leg(walk, walked_tiles, nearest); + // Any stop short of the wall's distance: someone who stays put is + // talked to, and the leg is planned again from where we are. Within the + // time count's slack this may be the wall itself, where A does nothing + // and the new plan walks no further (r239a: a wanderer 3 tiles short + // passed as "about 8 of 10", and every later leg was off by those tiles). + if (walk.result.stop == WalkStop::BLOCKED && walked_tiles < nearest){ + return stopped_short_of_wall(walk, walked_tiles); + } + // A leg to the wall that ran out of time is not at its wall: the open + // leg before it stopped short, and it ran along another row (r127a went + // west along Sandgem's row 13 for row 14, and the next leg north walked + // into the lab). Out of tall grass a stop reads, so walk on: a player + // still moving is not where the plan has him. + if (walk.result.stop == WalkStop::LIMIT && route_wall_readable(m_grid, walk.planned.after)){ + check_at_wall(walk); + } + return LegNext::NEXT_LEG; +} + +// A walk to the wall that stopped well short of it: tap through a corner, +// then wait for someone in the way. Returns the tiles walked by then. +size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest){ + const Milliseconds per_tile = route_ms_per_tile(walk.planned.leg.direction) / ROUTE_RUN_SPEEDUP; + const Milliseconds limit = wall_limit(walk.planned.leg); + // A stick walk can catch a corner when we stand part of a tile off + // centre, where a D-pad tap, which moves whole tiles, gets through: on + // Route 203's stairs the walk west stopped nine times in a row and two + // taps crossed (r225a, 2026-10-31). Tap twice, then walk on to the wall. + if (walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ + const Direction direction = walk.planned.leg.direction; + const DpadPosition dpad = + direction == Direction::NORTH ? DPAD_UP : + direction == Direction::SOUTH ? DPAD_DOWN : + direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; + m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); + for (size_t tap = 0; tap < 2; tap++){ + pbf_press_dpad(m_context, dpad, 160ms, 640ms); + } + m_context.wait_for_all_requests(); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + walked_tiles += tiles_moved(walk.result, per_tile); + } + // Someone walking about may stand in the way for a moment: wait and + // walk to the wall again before calling it an obstacle. + for (size_t again = 0; again < 2 && walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++){ + m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(m_context, 2500ms); + m_context.wait_for_all_requests(); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + walked_tiles += tiles_moved(walk.result, per_tile); + } + return walked_tiles; +} + +LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ + // Someone who stays put: talk to them. A trainer we walked up to from + // the side starts the battle this way. + talk_to_blocker(walk.label); + std::vector stopped; + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, SIZE_MAX); + for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ + stopped.push_back(k == 0 ? pos : path[k - 1]); + } + } + stopped = sorted_unique(std::move(stopped)); + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": stopped early, and no tile fits.", m_stream); + } + mark_blocker(walk, stopped); + return replan_from(walk, std::move(stopped), "stopped early after about " + std::to_string(walked_tiles) + " tiles"); +} + +void RouteWalker::check_at_wall(LegWalk& walk){ + const WalkResult check = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, 2000ms, + walk.label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); + if (check.stop == WalkStop::DIALOG){ + // A trainer who saw us froze the walk (the "!") until its time ran + // out, then walked over (r241a: Aroma Lady Taylor's line crosses + // Route 204's corridor). Battle, then walk on to the wall: where + // they saw us from is not reliable (BDSP's trainers stand a few + // tiles from Platinum's, r242a), and a leg to a wall ends at its + // wall however far it got. + route_status(m_stream, walk.label + ": a trainer stopped us on the way; battling."); + m_trainers.fight("a trainer on the way"); + m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); + walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), + walk.label + ": on to the wall", run_watching(walk)); + } + if (check.stop != WalkStop::BLOCKED && + !(check.stop == WalkStop::LIMIT && holding_against_wall(m_stream, m_context, walk.stick.x, walk.stick.y, walk.label + ": at the wall?")) + ){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": ran out of time short of the wall, and walking on gets " + + walk_stop_name(check.stop) + ": not where the plan has us.", m_stream); + } +} + +// After a battle on a leg to a wall: a leg to a wall ends at its wall +// however far it got, so walk on to it and carry on. +void RouteWalker::on_to_wall(LegWalk& walk){ + m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); + walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), + walk.label + ": on to the wall", run_watching(walk)); + m_from = walk.planned.after; + log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, 0); +} + + +// Whole tiles on the D-pad, a tap each: a tap moves exactly one tile, while +// a stick hold timed for three moved one in the Ravaged Path (r235b) and the +// belief drifted four rows. +LegNext RouteWalker::open_leg(LegWalk& walk){ + const TileLeg& leg = walk.planned.leg; + if (m_facing != leg.direction){ + turn_tap(walk); + } + if (leg.tiles > walk.turn_moved){ + walk.result = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - walk.turn_moved, walk.label); + } + // A wild battle starts once the step onto the grass is done, so the + // taps still count; the walk went on after it. + if (walk.result.wild_battles > 0){ + m_stream.log("[Route] " + walk.label + ": " + std::to_string(walk.result.wild_battles) + + " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); + } + // Taps that moved nothing: someone stands in the way (the Youngster + // below the Ravaged Path wanders across the row under the cliff, r239a, + // r240a). Two still taps end the walk, so the tiles moved are the taps + // less those two. Wait once for them to move on and tap the rest (r246a + // lost 20 s per block on three waits); someone who stays is talked to, + // put on the map, and the leg planned again from the tile we stand on, + // which the taps give exactly. + size_t moved = std::min(leg.tiles, walk.result.moved_chunks + walk.turn_moved); + if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ + m_stream.log("[Route] " + walk.label + ": blocked after " + std::to_string(moved) + " of " + + std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); + pbf_wait(m_context, 2500ms); + m_context.wait_for_all_requests(); + const WalkResult rest = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - moved, walk.label + ": the rest"); + moved = std::min(leg.tiles, moved + rest.moved_chunks); + walk.result.stop = rest.stop; + walk.result.walked += rest.walked; + walk.result.wild_battles += rest.wild_battles; + } + if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ + return blocked_open_leg(walk, moved); + } + return LegNext::NEXT_LEG; +} + +// The first tap of a leg was meant to turn, but a 160 ms D-pad tap turns +// and steps whichever way the player faced (r248a: all seven did; r246a: +// "south 1" out of the cave went two tiles, onto the Youngster's row), so +// the tap is measured like any other and a step counts for the leg. +void RouteWalker::turn_tap(LegWalk& walk){ + const DpadPosition dpad = walk.stick.x < 0 ? DPAD_LEFT : walk.stick.x > 0 ? DPAD_RIGHT : walk.stick.y > 0 ? DPAD_UP : DPAD_DOWN; + m_context.wait_for_all_requests(); + VideoSnapshot before = m_stream.video().snapshot(); + pbf_press_dpad(m_context, dpad, 160ms, 700ms); + m_context.wait_for_all_requests(); + VideoSnapshot after = m_stream.video().snapshot(); + if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ + walk.turn_moved = 1; + m_stream.log("[Route] " + walk.label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); + } +} + +LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ + talk_to_blocker(walk.label); + std::vector stopped; + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, moved); + stopped.push_back(moved == 0 || path.empty() ? pos : path[std::min(moved, path.size()) - 1]); + } + stopped = sorted_unique(std::move(stopped)); + mark_blocker(walk, stopped); + return replan_from(walk, std::move(stopped), + "blocked after " + std::to_string(moved) + " of " + std::to_string(walk.planned.leg.tiles) + " tiles"); +} + + +// Entering another map shows its name; a missing or wrong name means the +// walk did not end where the plan says. From tiles on several maps (a leg +// not confirmed) the banner may already have shown. +void RouteWalker::check_banners(LegWalk& walk){ + m_context.wait_for_all_requests(); + if (VideoSnapshot screen = m_stream.video().snapshot()){ + watch_banner(walk, *screen.frame); + } + const std::string banner_text = quoted_list(walk.banners); + m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); + if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + + (banner_text.empty() ? "nothing" : banner_text) + ".", m_stream); + } + if (!banner_text.empty()){ + m_stream.log("[Route] " + walk.label + ": location banner " + banner_text + "."); + } + // Where each leg ended, to compare with the plan after a run. + if (VideoSnapshot screen = m_stream.video().snapshot()){ + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; + Filesystem::create_directories(Filesystem::Path(folder)); + screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(walk.label) + ".png"); + } +} + +// A trainer who sees us freezes the player and walks over; the dialogue +// may open after the walk has ended. +LegNext RouteWalker::after_leg(LegWalk& walk){ + const TileLeg& leg = walk.planned.leg; + std::vector> paths; + for (const TilePos& pos : m_from){ + paths.push_back(leg_path(m_grid, pos, leg.direction, leg.ends_at_wall ? SIZE_MAX : leg.tiles + 1)); + } + const std::vector watching = watching_trainers(paths); + bool talking = walk.result.stop == WalkStop::DIALOG; + if (!talking){ + ShortDialogWatcher dialog(COLOR_YELLOW); + const Milliseconds wait = watching.empty() ? 500ms : 4000ms; + talking = wait_until(m_stream, m_context, wait, {{dialog}}) == 0; + } + if (!talking){ + m_from = walk.planned.after; + log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); + return LegNext::NEXT_LEG; + } + if (watching.empty()){ + return unknown_trainer(walk, paths); + } + return known_trainer(walk, paths, watching); +} + +// The trainers whose sight one of the leg's possible paths enters. +std::vector RouteWalker::watching_trainers(const std::vector>& paths) const{ + std::vector watching; + for (size_t t = 0; t < m_trainers.sights.size(); t++){ + const std::vector sight = sight_tiles(m_grid, m_trainers.sights[t]); + const bool seen = std::any_of(paths.begin(), paths.end(), [&](const std::vector& path){ + return std::any_of(path.begin(), path.end(), [&](const TilePos& pos){ + return std::find(sight.begin(), sight.end(), pos) != sight.end(); + }); + }); + if (seen){ + watching.push_back(t); + } + } + return watching; +} + +// A trainer the map does not have. Fight, then plan again from anywhere +// the leg could have stopped. +LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ + std::vector anywhere = m_from; + for (const std::vector& path : paths){ + anywhere.insert(anywhere.end(), path.begin(), path.end()); + } + anywhere = sorted_unique(std::move(anywhere)); + route_status(m_stream, m_plan.label + ": a trainer the map lacks stopped us; fighting."); + m_trainers.fight("unknown trainer"); + if (walk.planned.leg.ends_at_wall){ + on_to_wall(walk); + return LegNext::NEXT_LEG; + } + m_from = std::move(anywhere); + return LegNext::REPLAN; +} + +LegNext RouteWalker::known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching){ + // Each possible start tile was stopped on the first tile of its path + // inside a watching trainer's sight. + const TrainerSight trainer = m_trainers.sights[watching[0]]; + std::vector stopped; + for (const std::vector& path : paths){ + const auto first_seen = std::find_if(path.begin(), path.end(), [&](const TilePos& pos){ + return std::any_of(watching.begin(), watching.end(), [&](size_t t){ + const std::vector sight = sight_tiles(m_grid, m_trainers.sights[t]); + return std::find(sight.begin(), sight.end(), pos) != sight.end(); + }); + }); + if (first_seen != path.end()){ + stopped.push_back(*first_seen); + } + } + if (stopped.empty()){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": " + trainer.name + " talked, but no path enters their sight.", m_stream); + } + m_stream.log(ROUTE_LOG_TAG + route_trainer_line(m_plan.label, trainer.name, route_tiles(m_maps, stopped))); + route_status(m_stream, "Fighting " + trainer.name + "."); + m_trainers.fight(trainer.name); + m_trainers.sights.erase(m_trainers.sights.begin() + watching[0]); + // Their sight line only says roughly where: BDSP's trainers stand a few + // tiles from Platinum's (r242a). A leg to a wall walks on to its wall. + if (walk.planned.leg.ends_at_wall){ + on_to_wall(walk); + return LegNext::NEXT_LEG; + } + // An open leg counts only the taps that moved: the trainer freezes the + // player on the tile they saw, and the taps pressed while they walk + // over move nobody (r248a: "4 taps" were 2 steps; the belief of two + // tiles then cost a 12-tile run to a wall and 5 back). + const size_t taps = std::min(walk.planned.leg.tiles, walk.result.moved_chunks + walk.turn_moved); + std::vector by_taps; + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, walk.planned.leg.tiles); + const size_t k = std::min(taps, path.size()); + by_taps.push_back(k == 0 ? pos : path[k - 1]); + } + return replan_from(walk, sorted_unique(std::move(by_taps)), std::to_string(taps) + " taps before the battle"); +} + + +// Presses A at whoever stopped the walk; a trainer we walked up to from +// the side starts the battle this way. +void RouteWalker::talk_to_blocker(const std::string& leg_label){ + pbf_press_button(m_context, BUTTON_A, 80ms, 200ms); + ShortDialogWatcher dialog(COLOR_YELLOW); + if (wait_until(m_stream, m_context, 2000ms, {{dialog}}) == 0){ + route_status(m_stream, leg_label + ": someone is in the way; talking to them."); + m_trainers.fight("someone in the way"); + } +} + +// One tile we may stand on: what stopped us is on the next tile, and goes +// on our map. +void RouteWalker::mark_blocker(const LegWalk& walk, const std::vector& stopped){ + if (stopped.size() != 1){ + return; + } + const TilePos blocker = stopped[0].next(walk.planned.leg.direction); + m_grid.block(blocker); + m_stream.log("[Route] " + walk.label + ": something the map lacks is at " + + describe(m_maps, blocker) + "; marked it.", COLOR_ORANGE); +} + +LegNext RouteWalker::replan_from(const LegWalk& walk, std::vector stopped, const std::string& why){ + m_stream.log(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.planned.leg), why, route_tiles(m_maps, stopped)), COLOR_ORANGE); + m_facing = walk.planned.leg.direction; + m_from = std::move(stopped); + return LegNext::REPLAN; +} + +} + + +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan +){ + return RouteWalker(stream, context, escape, maps, trainers, plan).run(std::move(from)); +} + +std::vector walk_waypoints( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const WaypointWalkPlan& plan +){ + for (size_t i = 0; i < plan.waypoints.size(); i++){ + const TilePos goal = plan.waypoints[i]; + from = walk_route(stream, context, escape, maps, from, trainers, { + .goal = [goal](const TilePos& pos){ return pos == goal; }, + .label = plan.label + " (" + std::to_string(i + 1) + "/" + std::to_string(plan.waypoints.size()) + + ", to " + describe(maps, goal) + ")", + .avoid = {}, + .costs = plan.costs, + }); + } + return from; +} + +void talk_to_npc( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector& at, + RouteTrainers& trainers, const NpcTalk& talk +){ + for (Direction side : talk.sides){ + const TilePos stand = talk.npc.next(side); + if (!standable(maps, stand)){ + continue; + } + at = walk_route(stream, context, escape, maps, at, trainers, { + .goal = [stand](const TilePos& pos){ return pos == stand; }, + .label = talk.label, + .avoid = {}, + .costs = route_plan_costs(), + }); + // Face the NPC: the opposite of the side we stand on. + const Direction face = + side == Direction::NORTH ? Direction::SOUTH : + side == Direction::SOUTH ? Direction::NORTH : + side == Direction::EAST ? Direction::WEST : Direction::EAST; + route_turn(stream, context, face); + pbf_press_button(context, BUTTON_A, 80ms, 200ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ + route_status(stream, talk.label + ": talking from " + describe(maps, stand) + "."); + return; + } + route_status(stream, talk.label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + talk.label + ": no side of " + describe(maps, talk.npc) + " started a dialogue.", stream); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index e6d38f1b5f..845b8977d7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -1,107 +1,107 @@ -/* BDSP AutoStory - Planned Route - * - * From: https://github.com/PokemonAutomation/ - * - * Walks a plan made on the story maps: legs to a wall are held until the - * player stops, open legs are tapped a tile at a time. Tracks every tile - * the player may be on, and plans again after something stops the walk. - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_H -#define PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_H - -#include -#include -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" -#include "PokemonBDSP_AutoStory_Walk.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Called when a trainer's dialogue has opened, or when someone standing in -// the way was talked to. Fights the battle if one starts, and returns to the -// overworld either way. -using RouteTrainerFight = std::function; - -// The trainers a route walk may meet, and how to fight them. A trainer who -// is fought is taken off `sights`. -struct RouteTrainers{ - std::vector sights; - RouteTrainerFight fight; -}; - -// Where walk_route() goes: until every tile the player may be on is -// `goal`. Tiles in `avoid` (where someone wanders, a trainer's sight) are -// planned as off the map. -struct RouteWalkPlan{ - std::function goal; - std::string label; - std::vector avoid = {}; - RobustPlanCosts costs = route_plan_costs(); -}; - -// Walks from any of the world tiles `from` of `maps` until every tile the -// player may be on is `plan.goal`, and returns those tiles. Trainers who -// see the player are fought and taken off `trainers`. Fails with a -// screenshot on a transition, a dialogue no trainer explains, or when no -// plan exists. A walk from one map to another must see the second map's -// location banner on the way: a walk whose legs all ended on walls can -// still end in the wrong place (r124a saved in Sandgem Town after -// "arriving" on Route 202). -std::vector walk_route( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector from, - RouteTrainers& trainers, const RouteWalkPlan& plan -); - -// The corners of a line a human walked, and the costs to plan each -// stretch with. -struct WaypointWalkPlan{ - std::vector waypoints; - std::string label; - RobustPlanCosts costs = waypoint_plan_costs(); -}; - -// Walks `from` to each of `plan.waypoints` in turn, with walk_route() for -// every stretch, and returns where the last one ended: the plan is the -// line, with the walker's handling of trainers and blocks on each stretch -// (Route 204 North, 2026-10-31). -std::vector walk_waypoints( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector from, - RouteTrainers& trainers, const WaypointWalkPlan& plan -); - -// Whom talk_to_npc() talks to: the NPC on world tile `npc`, from the sides -// in `sides` (the side of the NPC to stand on), in order. -struct NpcTalk{ - Pokemon::TilePos npc; - std::vector sides; - std::string label; -}; - -// Walks next to `talk.npc`, faces them and presses A, trying each side -// until a dialogue opens. `at` is where the player may be, and is updated. -// Fails with a screenshot if no side starts a dialogue. A press from a -// diagonal tile, or from a tile a row off, talks to nobody, so each side is -// tried in turn. -void talk_to_npc( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector& at, - RouteTrainers& trainers, const NpcTalk& talk -); - - - -} -} -} -#endif +/* BDSP AutoStory - Planned Route + * + * From: https://github.com/PokemonAutomation/ + * + * Walks a plan made on the story maps: legs to a wall are held until the + * player stops, open legs are tapped a tile at a time. Tracks every tile + * the player may be on, and plans again after something stops the walk. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_H +#define PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_H + +#include +#include +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Called when a trainer's dialogue has opened, or when someone standing in +// the way was talked to. Fights the battle if one starts, and returns to the +// overworld either way. +using RouteTrainerFight = std::function; + +// The trainers a route walk may meet, and how to fight them. A trainer who +// is fought is taken off `sights`. +struct RouteTrainers{ + std::vector sights; + RouteTrainerFight fight; +}; + +// Where walk_route() goes: until every tile the player may be on is +// `goal`. Tiles in `avoid` (where someone wanders, a trainer's sight) are +// planned as off the map. +struct RouteWalkPlan{ + std::function goal; + std::string label; + std::vector avoid = {}; + RobustPlanCosts costs = route_plan_costs(); +}; + +// Walks from any of the world tiles `from` of `maps` until every tile the +// player may be on is `plan.goal`, and returns those tiles. Trainers who +// see the player are fought and taken off `trainers`. Fails with a +// screenshot on a transition, a dialogue no trainer explains, or when no +// plan exists. A walk from one map to another must see the second map's +// location banner on the way: a walk whose legs all ended on walls can +// still end in the wrong place (r124a saved in Sandgem Town after +// "arriving" on Route 202). +std::vector walk_route( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan +); + +// The corners of a line a human walked, and the costs to plan each +// stretch with. +struct WaypointWalkPlan{ + std::vector waypoints; + std::string label; + RobustPlanCosts costs = waypoint_plan_costs(); +}; + +// Walks `from` to each of `plan.waypoints` in turn, with walk_route() for +// every stretch, and returns where the last one ended: the plan is the +// line, with the walker's handling of trainers and blocks on each stretch +// (Route 204 North, 2026-10-31). +std::vector walk_waypoints( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const WaypointWalkPlan& plan +); + +// Whom talk_to_npc() talks to: the NPC on world tile `npc`, from the sides +// in `sides` (the side of the NPC to stand on), in order. +struct NpcTalk{ + Pokemon::TilePos npc; + std::vector sides; + std::string label; +}; + +// Walks next to `talk.npc`, faces them and presses A, trying each side +// until a dialogue opens. `at` is where the player may be, and is updated. +// Fails with a screenshot if no side starts a dialogue. A press from a +// diagonal tile, or from a tile a row off, talks to nobody, so each side is +// tried in turn. +void talk_to_npc( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + const StoryWorld& maps, std::vector& at, + RouteTrainers& trainers, const NpcTalk& talk +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index d7d6367e9c..803019b456 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -1,294 +1,294 @@ -/* BDSP AutoStory - Route Walk - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Filesystem/Filesystem.h" -#include "CommonFramework/GlobalAutoPaths.h" -#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Navigation/Pokemon_RouteLog.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" -#include "PokemonBDSP_AutoStory_Location.h" -#include "PokemonBDSP_AutoStory_Walk.h" -#include "PokemonBDSP_AutoStory_Indoors.h" -#include "PokemonBDSP_AutoStory_OverlayLog.h" -#include "PokemonBDSP_AutoStory_RouteWalk.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace std::chrono_literals; -using namespace Pokemon; - - -namespace{ - -bool across(Direction direction){ - return direction == Direction::EAST || direction == Direction::WEST; -} - -} - -Milliseconds route_ms_per_tile(Direction direction){ - return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; -} - -JoystickPosition route_stick(Direction direction){ - switch (direction){ - case Direction::NORTH: - return {0, 1}; - case Direction::EAST: - return {1, 0}; - case Direction::SOUTH: - return {0, -1}; - case Direction::WEST: - return {-1, 0}; - } - return {0, 0}; -} - - -bool route_wall_readable(const StoryWorld& grid, const std::vector& after){ - return std::none_of(after.begin(), after.end(), [&](const TilePos& pos){ - return grid.tile(pos) == TileKind::TALL_GRASS; - }); -} - -void route_status(VideoStream& stream, const std::string& text){ - stream.log("[Route] " + text, COLOR_BLUE); - add_wrapped_log(stream.overlay(), text, COLOR_WHITE); -} - -Milliseconds route_open_hold(Direction direction, size_t tiles){ - const Milliseconds step = route_ms_per_tile(direction); - return step * tiles - step / 2; -} - -void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ - stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); - pbf_move_left_joystick(context, route_stick(direction), ROUTE_TURN_TAP, 300ms); - context.wait_for_all_requests(); -} - -std::optional talk_to_adjacent_npc( - VideoStream& stream, ProControllerContext& context, - const std::vector& directions, - const std::string& label, Milliseconds wait -){ - for (Direction direction : directions){ - route_turn(stream, context, direction); - pbf_press_button(context, BUTTON_A, 80ms, 0ms); - context.wait_for_all_requests(); - ShortDialogWatcher dialog(COLOR_CYAN); - if (wait_until(stream, context, wait, {{dialog}}) == 0){ - stream.log("[Route] " + label + ": answered from the " + direction_name(direction) + "."); - return direction; - } - } - stream.log("[Route] " + label + ": nobody answered next to us."); - return std::nullopt; -} - -bool talk_with_nudges( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - Direction facing, const std::string& label, Milliseconds wait, - const std::function& accept -){ - const bool vertical = facing == Direction::NORTH || facing == Direction::SOUTH; - const Direction minus = vertical ? Direction::WEST : Direction::NORTH; - const Direction plus = vertical ? Direction::EAST : Direction::SOUTH; - int at = 0; - for (int offset : {0, -1, 1, -2, 2}){ - const Direction side = offset < at ? minus : plus; - for (; at != offset; at += offset < at ? -1 : 1){ - pbf_move_left_joystick(context, route_stick(side), ROUTE_NUDGE_TAP, 300ms); - } - if (offset != 0){ - route_turn(stream, context, facing); - // A tap in a cave or in grass can start a wild battle, after - // which we are not where the nudges think: let the caller line up again. - if (run_from_late_encounter(stream, context, escape, label + ": nudge")){ - return false; - } - } - context.wait_for_all_requests(); - const VideoSnapshot before = stream.video().snapshot(); - pbf_press_button(context, BUTTON_A, 80ms, 0ms); - context.wait_for_all_requests(); - ShortDialogWatcher dialog(COLOR_CYAN); - if (wait_until(stream, context, wait, {{dialog}}) == 0){ - const VideoSnapshot after = stream.video().snapshot(); - if (!accept || (before && after && accept(*before.frame, *after.frame))){ - stream.log("[Route] " + label + ": answered " + std::to_string(offset) + " nudge(s) from where we stood."); - return true; - } - stream.log("[Route] " + label + ": something else answered " + std::to_string(offset) + " nudge(s) from where we stood; closing it."); - for (size_t press = 0; press < 3; press++){ - pbf_press_button(context, BUTTON_B, 80ms, 700ms); - } - context.wait_for_all_requests(); - } - } - stream.log("[Route] " + label + ": nobody answered within two nudges either side."); - return false; -} - - -void finish_dialogue( - VideoStream& stream, ProControllerContext& context, - Button button, const std::string& label, Milliseconds timeout -){ - // No line counts: talks differ in length (r115a: 8 A left the Poke Mart - // lady's Potions talk open). The box blinks off between lines and during - // "obtained" jingles, so only a stable absence ends the talk. - const WallClock none = WallClock::max(); - ShortDialogDetector dialog; - OverworldDetector overworld; - const WallClock deadline = current_time() + timeout; - WallClock quiet_since = none; - WallClock unknown_since = none; - while (current_time() < deadline){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - const WallClock now = current_time(); - const bool talking = frame && dialog.detect(frame); - if (frame && !talking && overworld.detect(frame)){ - unknown_since = none; - if (quiet_since == none){ - quiet_since = now; - }else if (now - quiet_since >= 1500ms){ - return; - } - context.wait_for(200ms); - continue; - } - quiet_since = none; - // Press only on a box (an A on the overworld talks again), or on a - // screen that is neither for 3 s. - if (talking || (unknown_since != none && now - unknown_since >= 3000ms)){ - unknown_since = none; - pbf_press_button(context, button, 80ms, 1200ms); - continue; - } - if (unknown_since == none){ - unknown_since = now; - } - context.wait_for(200ms); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": the dialogue did not end within " + - std::to_string(std::chrono::duration_cast(timeout).count()) + " s.", stream); -} - -void enter_door_north(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ - // Sideways steps to try after a blocked walk: east, then back west and - // one more. - const Direction steps[] = {Direction::EAST, Direction::WEST, Direction::WEST}; - for (size_t attempt = 0; attempt <= 3; attempt++){ - const WalkResult walk = walk_until(stream, context, escape, {0, 1}, 2500ms, label); - if (walk.stop == WalkStop::TRANSITION){ - context.wait_for(1500ms); - return; - } - if (attempt == 3){ - break; - } - route_status(stream, label + ": the door frame stopped us; one tile " + - (steps[attempt] == Direction::EAST ? "east." : "west.")); - route_turn(stream, context, steps[attempt]); - const double x = steps[attempt] == Direction::EAST ? 1 : -1; - pbf_move_left_joystick(context, {x, 0}, route_open_hold(steps[attempt], 1), 200ms); - context.wait_for_all_requests(); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": could not go through the door.", stream); -} - -bool door_fade_look(DoorFadeWatch& watch, double brightness, bool room){ - if (brightness < DOOR_FADE_DARK){ - watch.saw_dark = true; - } - return watch.saw_dark && !room && brightness >= DOOR_OUTSIDE_BRIGHT; -} - -bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room){ - // Both are asked: the fade watch keeps what it has seen. - const bool faded = door_fade_look(watch, brightness, room); - return faded || !room; -} - -namespace{ - -// Three looks half a second apart, none a room: outside, whatever the fade -// did. A look of a lit Center can miss its black edge (r259 at 800 ms), -// three in a row standing still do not. -bool outside_for_three_looks(VideoStream& stream, ProControllerContext& context, const std::string& label){ - for (size_t look = 0; look < 3; look++){ - context.wait_for_all_requests(); - VideoSnapshot now = stream.video().snapshot(); - const bool room = !now || indoors(*now.frame); - stream.log("[Route] " + label + ": standing look " + std::to_string(look + 1) + ": " + (room ? "a room" : "not a room") + "."); - if (room){ - return false; - } - pbf_wait(context, 500ms); - } - return true; -} - -} - -void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ - // A last line of talk may still be up, and it would stop the walk. - pbf_mash_button(context, BUTTON_B, 2000ms); - context.wait_for_all_requests(); - // Stop the walk at the fade or at the first look that is not a room: a - // stick held on walks on outside (r124a ten rows south of the Mart's - // door, r257 into a house, r261 three rows). Standing looks then confirm. - DoorFadeWatch watch; - auto out_of_door = [&](const ImageViewRGB32& screen){ - const double brightness = image_stats(screen).average.sum(); - const bool room = indoors(screen); - const bool out = door_walk_stops(watch, brightness, room); - stream.log(std::format("[Route] {}: look: brightness {:.0f}, {}, fade {}.", label, brightness, - room ? "a room" : "not a room", watch.saw_dark ? "seen" : "not seen")); - return out; - }; - bool out = false; - for (size_t tries = 0; tries < 5 && !out; tries++){ - const WalkResult walk = walk_until(stream, context, escape, {0, -1}, 6000ms, label, out_of_door); - if (walk.stop == WalkStop::DIALOG){ - pbf_mash_button(context, BUTTON_B, 2000ms); - } - // Let the fade-in finish, then look again standing still. - pbf_wait(context, 1500ms); - out = walk.stop == WalkStop::TRANSITION || outside_for_three_looks(stream, context, label); - if (!out){ - stream.log("[Route] " + label + ": still indoors; walking on."); - } - } - if (!out){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": did not get back out.", stream); - } - // Let the fade-in finish. - pbf_wait(context, 1500ms); -} - - - -} -} -} +/* BDSP AutoStory - Route Walk + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" +#include "PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_Walk.h" +#include "PokemonBDSP_AutoStory_Indoors.h" +#include "PokemonBDSP_AutoStory_OverlayLog.h" +#include "PokemonBDSP_AutoStory_RouteWalk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using namespace Pokemon; + + +namespace{ + +bool across(Direction direction){ + return direction == Direction::EAST || direction == Direction::WEST; +} + +} + +Milliseconds route_ms_per_tile(Direction direction){ + return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; +} + +JoystickPosition route_stick(Direction direction){ + switch (direction){ + case Direction::NORTH: + return {0, 1}; + case Direction::EAST: + return {1, 0}; + case Direction::SOUTH: + return {0, -1}; + case Direction::WEST: + return {-1, 0}; + } + return {0, 0}; +} + + +bool route_wall_readable(const StoryWorld& grid, const std::vector& after){ + return std::none_of(after.begin(), after.end(), [&](const TilePos& pos){ + return grid.tile(pos) == TileKind::TALL_GRASS; + }); +} + +void route_status(VideoStream& stream, const std::string& text){ + stream.log("[Route] " + text, COLOR_BLUE); + add_wrapped_log(stream.overlay(), text, COLOR_WHITE); +} + +Milliseconds route_open_hold(Direction direction, size_t tiles){ + const Milliseconds step = route_ms_per_tile(direction); + return step * tiles - step / 2; +} + +void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ + stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); + pbf_move_left_joystick(context, route_stick(direction), ROUTE_TURN_TAP, 300ms); + context.wait_for_all_requests(); +} + +std::optional talk_to_adjacent_npc( + VideoStream& stream, ProControllerContext& context, + const std::vector& directions, + const std::string& label, Milliseconds wait +){ + for (Direction direction : directions){ + route_turn(stream, context, direction); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, wait, {{dialog}}) == 0){ + stream.log("[Route] " + label + ": answered from the " + direction_name(direction) + "."); + return direction; + } + } + stream.log("[Route] " + label + ": nobody answered next to us."); + return std::nullopt; +} + +bool talk_with_nudges( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + Direction facing, const std::string& label, Milliseconds wait, + const std::function& accept +){ + const bool vertical = facing == Direction::NORTH || facing == Direction::SOUTH; + const Direction minus = vertical ? Direction::WEST : Direction::NORTH; + const Direction plus = vertical ? Direction::EAST : Direction::SOUTH; + int at = 0; + for (int offset : {0, -1, 1, -2, 2}){ + const Direction side = offset < at ? minus : plus; + for (; at != offset; at += offset < at ? -1 : 1){ + pbf_move_left_joystick(context, route_stick(side), ROUTE_NUDGE_TAP, 300ms); + } + if (offset != 0){ + route_turn(stream, context, facing); + // A tap in a cave or in grass can start a wild battle, after + // which we are not where the nudges think: let the caller line up again. + if (run_from_late_encounter(stream, context, escape, label + ": nudge")){ + return false; + } + } + context.wait_for_all_requests(); + const VideoSnapshot before = stream.video().snapshot(); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + context.wait_for_all_requests(); + ShortDialogWatcher dialog(COLOR_CYAN); + if (wait_until(stream, context, wait, {{dialog}}) == 0){ + const VideoSnapshot after = stream.video().snapshot(); + if (!accept || (before && after && accept(*before.frame, *after.frame))){ + stream.log("[Route] " + label + ": answered " + std::to_string(offset) + " nudge(s) from where we stood."); + return true; + } + stream.log("[Route] " + label + ": something else answered " + std::to_string(offset) + " nudge(s) from where we stood; closing it."); + for (size_t press = 0; press < 3; press++){ + pbf_press_button(context, BUTTON_B, 80ms, 700ms); + } + context.wait_for_all_requests(); + } + } + stream.log("[Route] " + label + ": nobody answered within two nudges either side."); + return false; +} + + +void finish_dialogue( + VideoStream& stream, ProControllerContext& context, + Button button, const std::string& label, Milliseconds timeout +){ + // No line counts: talks differ in length (r115a: 8 A left the Poke Mart + // lady's Potions talk open). The box blinks off between lines and during + // "obtained" jingles, so only a stable absence ends the talk. + const WallClock none = WallClock::max(); + ShortDialogDetector dialog; + OverworldDetector overworld; + const WallClock deadline = current_time() + timeout; + WallClock quiet_since = none; + WallClock unknown_since = none; + while (current_time() < deadline){ + context.wait_for_all_requests(); + const auto frame = stream.video().snapshot(); + const WallClock now = current_time(); + const bool talking = frame && dialog.detect(frame); + if (frame && !talking && overworld.detect(frame)){ + unknown_since = none; + if (quiet_since == none){ + quiet_since = now; + }else if (now - quiet_since >= 1500ms){ + return; + } + context.wait_for(200ms); + continue; + } + quiet_since = none; + // Press only on a box (an A on the overworld talks again), or on a + // screen that is neither for 3 s. + if (talking || (unknown_since != none && now - unknown_since >= 3000ms)){ + unknown_since = none; + pbf_press_button(context, button, 80ms, 1200ms); + continue; + } + if (unknown_since == none){ + unknown_since = now; + } + context.wait_for(200ms); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": the dialogue did not end within " + + std::to_string(std::chrono::duration_cast(timeout).count()) + " s.", stream); +} + +void enter_door_north(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ + // Sideways steps to try after a blocked walk: east, then back west and + // one more. + const Direction steps[] = {Direction::EAST, Direction::WEST, Direction::WEST}; + for (size_t attempt = 0; attempt <= 3; attempt++){ + const WalkResult walk = walk_until(stream, context, escape, {0, 1}, 2500ms, label); + if (walk.stop == WalkStop::TRANSITION){ + context.wait_for(1500ms); + return; + } + if (attempt == 3){ + break; + } + route_status(stream, label + ": the door frame stopped us; one tile " + + (steps[attempt] == Direction::EAST ? "east." : "west.")); + route_turn(stream, context, steps[attempt]); + const double x = steps[attempt] == Direction::EAST ? 1 : -1; + pbf_move_left_joystick(context, {x, 0}, route_open_hold(steps[attempt], 1), 200ms); + context.wait_for_all_requests(); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": could not go through the door.", stream); +} + +bool door_fade_look(DoorFadeWatch& watch, double brightness, bool room){ + if (brightness < DOOR_FADE_DARK){ + watch.saw_dark = true; + } + return watch.saw_dark && !room && brightness >= DOOR_OUTSIDE_BRIGHT; +} + +bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room){ + // Both are asked: the fade watch keeps what it has seen. + const bool faded = door_fade_look(watch, brightness, room); + return faded || !room; +} + +namespace{ + +// Three looks half a second apart, none a room: outside, whatever the fade +// did. A look of a lit Center can miss its black edge (r259 at 800 ms), +// three in a row standing still do not. +bool outside_for_three_looks(VideoStream& stream, ProControllerContext& context, const std::string& label){ + for (size_t look = 0; look < 3; look++){ + context.wait_for_all_requests(); + VideoSnapshot now = stream.video().snapshot(); + const bool room = !now || indoors(*now.frame); + stream.log("[Route] " + label + ": standing look " + std::to_string(look + 1) + ": " + (room ? "a room" : "not a room") + "."); + if (room){ + return false; + } + pbf_wait(context, 500ms); + } + return true; +} + +} + +void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ + // A last line of talk may still be up, and it would stop the walk. + pbf_mash_button(context, BUTTON_B, 2000ms); + context.wait_for_all_requests(); + // Stop the walk at the fade or at the first look that is not a room: a + // stick held on walks on outside (r124a ten rows south of the Mart's + // door, r257 into a house, r261 three rows). Standing looks then confirm. + DoorFadeWatch watch; + auto out_of_door = [&](const ImageViewRGB32& screen){ + const double brightness = image_stats(screen).average.sum(); + const bool room = indoors(screen); + const bool out = door_walk_stops(watch, brightness, room); + stream.log(std::format("[Route] {}: look: brightness {:.0f}, {}, fade {}.", label, brightness, + room ? "a room" : "not a room", watch.saw_dark ? "seen" : "not seen")); + return out; + }; + bool out = false; + for (size_t tries = 0; tries < 5 && !out; tries++){ + const WalkResult walk = walk_until(stream, context, escape, {0, -1}, 6000ms, label, out_of_door); + if (walk.stop == WalkStop::DIALOG){ + pbf_mash_button(context, BUTTON_B, 2000ms); + } + // Let the fade-in finish, then look again standing still. + pbf_wait(context, 1500ms); + out = walk.stop == WalkStop::TRANSITION || outside_for_three_looks(stream, context, label); + if (!out){ + stream.log("[Route] " + label + ": still indoors; walking on."); + } + } + if (!out){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": did not get back out.", stream); + } + // Let the fade-in finish. + pbf_wait(context, 1500ms); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index 6654a93379..97bda06d6e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -1,150 +1,150 @@ -/* BDSP AutoStory - Route Walk - * - * From: https://github.com/PokemonAutomation/ - * - * What walking on the story maps is made of: walking times per tile, the - * stick for a direction, turning, talking to someone next to us, finishing - * a dialogue, and going through doors. PlannedRoute walks whole plans. - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteWalk_H -#define PokemonAutomation_PokemonBDSP_AutoStory_RouteWalk_H - -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" -#include "PokemonBDSP_AutoStory_Walk.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Walking time per tile, measured on the console from the post-catch save: -// a row is deeper than a column is wide under the tilted camera. -constexpr Milliseconds ROUTE_MS_PER_TILE_ACROSS = Milliseconds(160); // east or west -constexpr Milliseconds ROUTE_MS_PER_TILE_UP_DOWN = Milliseconds(240); // north or south -// From pressing the stick to the first step, when standing still. -constexpr Milliseconds ROUTE_START_DELAY = Milliseconds(250); -// Running (B held) covers a tile in this fraction of the walking time. B -// held with the D-pad did not run: r238a walked the Ravaged Path's corridor -// at 160 ms a tile, and a limit set for twice that speed cut a wall leg -// short by two tiles. 1 until running is measured to work. -constexpr int ROUTE_RUN_SPEEDUP = 1; - -// Walking time per tile in `direction`. -Milliseconds route_ms_per_tile(Pokemon::Direction direction); -// The left stick for a direction. Row 0 is the top of a map, and the -// stick's y is positive upward. -JoystickPosition route_stick(Pokemon::Direction direction); - -// How long to hold the stick for an open leg of `tiles` tiles, for a player -// already facing that way: a step once started is always finished, so stop -// half a tile early. On the console a 1290ms hold west went 9 tiles and an -// 800ms hold south 4: the player starts at once and finishes the step. -Milliseconds route_open_hold(Pokemon::Direction direction, size_t tiles); - -// A tap this short turns a player who faces another way, without a step: on -// the console a 150ms tap south after walking north only turned the player. -constexpr Milliseconds ROUTE_TURN_TAP = Milliseconds(100); - -// Turns the player to face `direction` without moving. Only for a player who -// faces another way: one already facing it may take a step. -void route_turn(VideoStream& stream, ProControllerContext& context, Pokemon::Direction direction); - -// Talks to someone on a tile next to ours, without trusting the tile we -// counted ourselves onto: for each of `directions` in order, turns that way, -// presses A and waits up to `wait` for a dialogue. Returns the direction that -// answered, its dialogue open, or none if nobody did. Turns are taps (see -// route_turn()), so do not list the way the player already faces first. -std::optional talk_to_adjacent_npc( - VideoStream& stream, ProControllerContext& context, - const std::vector& directions, - const std::string& label, Milliseconds wait = Milliseconds(1500) -); - -// Talks to someone straight ahead in `facing`, where we may stand a little -// off their tile: BDSP moves by any distance, and a sideways tap moves about -// a third of a tile (a 50ms tap 0.2 to 0.45 tiles, a 100ms turn tap 0.4, on -// the console 2026-10-31). Presses A, and while nobody answers shifts by one -// such tap at a time to -1, +1, -2, +2 taps from the start and tries again. -// Never turns away and back between tries: each turn is a tap that moves us -// (s03e2 drifted east of Roark a third of a tile per try). Returns whether a -// dialogue opened, left open; false also after a wild battle on a nudge, -// which leaves us off the place we were. -// `accept`, if given, looks at the screen before A and once the dialogue -// is open, and says whether it is the one wanted: a rock or a sign next to -// someone answers A too (r187a read "It's a rugged rock" beside Roark). A -// dialogue it turns down is closed with B and the nudges go on. -bool talk_with_nudges( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - Pokemon::Direction facing, const std::string& label, - Milliseconds wait = Milliseconds(3000), - const std::function& accept = nullptr -); -constexpr Milliseconds ROUTE_NUDGE_TAP = Milliseconds(50); - -// Whether a walk to the wall that ends on any of `after` can tell it has -// stopped: not in tall grass, whose sway keeps the screen changing at a -// wall. Elsewhere, a walk to the wall that stops confirms where it ended. -bool route_wall_readable(const StoryWorld& grid, const std::vector& after); - -// Shows what the route walk is doing in the log and the video overlay. -void route_status(VideoStream& stream, const std::string& text); - -// Finishes a dialogue that has opened, however many lines it has: presses -// `button` while a dialogue box shows, and returns once the overworld has -// shown with no box for 1.5 s (the box blinks off between lines and during -// "obtained" jingles). Use A where the talk asks Yes/No or gives an item (A -// answers Yes and closes "obtained" lines; B would answer No), B elsewhere -// (B never starts a new talk). Fails with a screenshot after `timeout`. -void finish_dialogue( - VideoStream& stream, ProControllerContext& context, - Button button, const std::string& label, - Milliseconds timeout = std::chrono::seconds(40) -); - -// For a player on the tile below a door: walks north through it. If a wall -// stops the walk (the door frame, a tile off the opening), steps a tile east, -// then west, and tries again. Fails with a screenshot if no step goes in. -void enter_door_north(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); - -// For a player inside a building whose door is straight south: closes any -// talk still up and walks south out of it, stopping at the door's fade or -// the first look that is not a room, so it ends a tile or so outside. Out is -// then three standing looks in a row that are not a room: one look of a lit -// Center can miss its black edge (r259). Fails with a screenshot if five -// walks south get nowhere. -void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); - -// Brightness (mean r + g + b) below which a look is the door's fade, and -// above which a look that is not a room is outside. -inline constexpr double DOOR_FADE_DARK = 120.0; -inline constexpr double DOOR_OUTSIDE_BRIGHT = 200.0; - -// What leave_door_south() has seen of the door's fade so far. -struct DoorFadeWatch{ - bool saw_dark = false; -}; -// Takes one look (its brightness, and whether indoors() read a room) and -// returns whether we are out: a dark look seen, and now a bright one that -// is not a room. -bool door_fade_look(DoorFadeWatch& watch, double brightness, bool room); -// Whether leave_door_south()'s walk stops at this look: at the door's fade -// out (door_fade_look()), or at the first look that is not a room, so a -// held stick does not walk on outside (r261 three rows). -bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room); - - - -} -} -} -#endif +/* BDSP AutoStory - Route Walk + * + * From: https://github.com/PokemonAutomation/ + * + * What walking on the story maps is made of: walking times per tile, the + * stick for a direction, turning, talking to someone next to us, finishing + * a dialogue, and going through doors. PlannedRoute walks whole plans. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteWalk_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteWalk_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Walking time per tile, measured on the console from the post-catch save: +// a row is deeper than a column is wide under the tilted camera. +constexpr Milliseconds ROUTE_MS_PER_TILE_ACROSS = Milliseconds(160); // east or west +constexpr Milliseconds ROUTE_MS_PER_TILE_UP_DOWN = Milliseconds(240); // north or south +// From pressing the stick to the first step, when standing still. +constexpr Milliseconds ROUTE_START_DELAY = Milliseconds(250); +// Running (B held) covers a tile in this fraction of the walking time. B +// held with the D-pad did not run: r238a walked the Ravaged Path's corridor +// at 160 ms a tile, and a limit set for twice that speed cut a wall leg +// short by two tiles. 1 until running is measured to work. +constexpr int ROUTE_RUN_SPEEDUP = 1; + +// Walking time per tile in `direction`. +Milliseconds route_ms_per_tile(Pokemon::Direction direction); +// The left stick for a direction. Row 0 is the top of a map, and the +// stick's y is positive upward. +JoystickPosition route_stick(Pokemon::Direction direction); + +// How long to hold the stick for an open leg of `tiles` tiles, for a player +// already facing that way: a step once started is always finished, so stop +// half a tile early. On the console a 1290ms hold west went 9 tiles and an +// 800ms hold south 4: the player starts at once and finishes the step. +Milliseconds route_open_hold(Pokemon::Direction direction, size_t tiles); + +// A tap this short turns a player who faces another way, without a step: on +// the console a 150ms tap south after walking north only turned the player. +constexpr Milliseconds ROUTE_TURN_TAP = Milliseconds(100); + +// Turns the player to face `direction` without moving. Only for a player who +// faces another way: one already facing it may take a step. +void route_turn(VideoStream& stream, ProControllerContext& context, Pokemon::Direction direction); + +// Talks to someone on a tile next to ours, without trusting the tile we +// counted ourselves onto: for each of `directions` in order, turns that way, +// presses A and waits up to `wait` for a dialogue. Returns the direction that +// answered, its dialogue open, or none if nobody did. Turns are taps (see +// route_turn()), so do not list the way the player already faces first. +std::optional talk_to_adjacent_npc( + VideoStream& stream, ProControllerContext& context, + const std::vector& directions, + const std::string& label, Milliseconds wait = Milliseconds(1500) +); + +// Talks to someone straight ahead in `facing`, where we may stand a little +// off their tile: BDSP moves by any distance, and a sideways tap moves about +// a third of a tile (a 50ms tap 0.2 to 0.45 tiles, a 100ms turn tap 0.4, on +// the console 2026-10-31). Presses A, and while nobody answers shifts by one +// such tap at a time to -1, +1, -2, +2 taps from the start and tries again. +// Never turns away and back between tries: each turn is a tap that moves us +// (s03e2 drifted east of Roark a third of a tile per try). Returns whether a +// dialogue opened, left open; false also after a wild battle on a nudge, +// which leaves us off the place we were. +// `accept`, if given, looks at the screen before A and once the dialogue +// is open, and says whether it is the one wanted: a rock or a sign next to +// someone answers A too (r187a read "It's a rugged rock" beside Roark). A +// dialogue it turns down is closed with B and the nudges go on. +bool talk_with_nudges( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + Pokemon::Direction facing, const std::string& label, + Milliseconds wait = Milliseconds(3000), + const std::function& accept = nullptr +); +constexpr Milliseconds ROUTE_NUDGE_TAP = Milliseconds(50); + +// Whether a walk to the wall that ends on any of `after` can tell it has +// stopped: not in tall grass, whose sway keeps the screen changing at a +// wall. Elsewhere, a walk to the wall that stops confirms where it ended. +bool route_wall_readable(const StoryWorld& grid, const std::vector& after); + +// Shows what the route walk is doing in the log and the video overlay. +void route_status(VideoStream& stream, const std::string& text); + +// Finishes a dialogue that has opened, however many lines it has: presses +// `button` while a dialogue box shows, and returns once the overworld has +// shown with no box for 1.5 s (the box blinks off between lines and during +// "obtained" jingles). Use A where the talk asks Yes/No or gives an item (A +// answers Yes and closes "obtained" lines; B would answer No), B elsewhere +// (B never starts a new talk). Fails with a screenshot after `timeout`. +void finish_dialogue( + VideoStream& stream, ProControllerContext& context, + Button button, const std::string& label, + Milliseconds timeout = std::chrono::seconds(40) +); + +// For a player on the tile below a door: walks north through it. If a wall +// stops the walk (the door frame, a tile off the opening), steps a tile east, +// then west, and tries again. Fails with a screenshot if no step goes in. +void enter_door_north(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); + +// For a player inside a building whose door is straight south: closes any +// talk still up and walks south out of it, stopping at the door's fade or +// the first look that is not a room, so it ends a tile or so outside. Out is +// then three standing looks in a row that are not a room: one look of a lit +// Center can miss its black edge (r259). Fails with a screenshot if five +// walks south get nowhere. +void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); + +// Brightness (mean r + g + b) below which a look is the door's fade, and +// above which a look that is not a room is outside. +inline constexpr double DOOR_FADE_DARK = 120.0; +inline constexpr double DOOR_OUTSIDE_BRIGHT = 200.0; + +// What leave_door_south() has seen of the door's fade so far. +struct DoorFadeWatch{ + bool saw_dark = false; +}; +// Takes one look (its brightness, and whether indoors() read a room) and +// returns whether we are out: a dark look seen, and now a bright one that +// is not a room. +bool door_fade_look(DoorFadeWatch& watch, double brightness, bool room); +// Whether leave_door_south()'s walk stops at this look: at the door's fade +// out (door_fade_look()), or at the first look that is not a room, so a +// held stick does not walk on outside (r261 three rows). +bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index 0f5d15fc9f..e0e3104d80 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -1,561 +1,561 @@ -/* BDSP AutoStory - Walk - * - * From: https://github.com/PokemonAutomation/ - * - * BattleDialogWatcher adapted from PokemonAutomation/Arduino-Source#1717 by - * Developer-Butters. - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP_AutoStory_Walk.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace std::chrono_literals; - - -const char* walk_stop_name(WalkStop stop){ - switch (stop){ - case WalkStop::ARRIVED: return "arrived"; - case WalkStop::DIALOG: return "dialog"; - case WalkStop::TRANSITION: return "transition"; - case WalkStop::BLOCKED: return "blocked"; - case WalkStop::LIMIT: return "limit"; - } - return "?"; -} - -double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after){ - // Small copies: only the whole-view scroll matters, not detail. - return ImageMatch::pixel_RMSD(before.scale_to(192, 108), after.scale_to(192, 108)); -} - - -namespace{ - -// The battle's text box, held for 250ms. -class BattleDialogWatcher : public DetectorToFinder{ -public: - explicit BattleDialogWatcher(Color color) - : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) - {} -}; - -VideoSnapshot snapshot_or_fail(VideoStream& stream, const std::string& label){ - VideoSnapshot frame = stream.video().snapshot(); - if (!frame){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": No video frame.", stream); - } - return frame; -} - -// After a black screen: a wild battle if a battle screen shows up, else a transition. -bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context){ - BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); - BattleDialogWatcher battle_dialog(COLOR_YELLOW); - BlackScreenWatcher gone(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 100, 10, - BlackScreenWatcher::FinderType::GONE, 500ms); - const int ret = wait_until(stream, context, 10s, {{battle_menu}, {battle_dialog}, {gone}}); - if (ret == 2){ - // The battle intro also starts from black; give its first screen a moment. - BattleMenuWatcher late_menu(BattleType::STANDARD, COLOR_YELLOW); - BattleDialogWatcher late_dialog(COLOR_YELLOW); - return wait_until(stream, context, 2s, {{late_menu}, {late_dialog}}) >= 0; - } - return ret >= 0; -} - -// A grass encounter opens with a leaf animation, neither white nor black, and -// shows the battle's text box a few seconds later. After a change of the -// whole screen that walking cannot make, wait for the battle to show. -bool battle_follows(VideoStream& stream, ProControllerContext& context){ - BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); - BattleDialogWatcher battle_dialog(COLOR_YELLOW); - return wait_until(stream, context, 5s, {{battle_menu}, {battle_dialog}}) >= 0; -} - -} - -// A step in tall grass that was started before the stick was released still -// finishes, and its encounter starts after the walk has ended. Watch a little -// longer, and run from it. Returns whether there was one. -bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ - VideoSnapshot before = stream.video().snapshot(); - WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); - BlackScreenWatcher black(COLOR_RED); - BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); - BattleDialogWatcher battle_dialog(COLOR_YELLOW); - const int ret = wait_until(stream, context, 1200ms, {{encounter_flash}, {black}, {battle_menu}, {battle_dialog}}); - bool battle = ret == 0 || ret == 2 || ret == 3 || (ret == 1 && black_screen_was_battle(stream, context)); - if (ret < 0){ - VideoSnapshot after = stream.video().snapshot(); - battle = before && after && walk_screen_change(*before.frame, *after.frame) > WALK_SCENE_CHANGE && - battle_follows(stream, context); - } - if (!battle){ - return false; - } - stream.log("[Walk] " + label + ": wild battle after the walk; running."); - escape(stream, context); - context.wait_for_all_requests(); - return true; -} -namespace{ - -// Samples the screen every 100ms for probe_walk() and stops it once the view -// has been still for 800ms. -class WalkProbeSampler : public VisualInferenceCallback{ -public: - WalkProbeSampler(WalkProbe& result, double moving_change, WallClock start) - : VisualInferenceCallback("WalkProbeSampler") - , m_result(result) - , m_moving_change(moving_change) - , m_start(start) - {} - virtual void make_overlays(VideoOverlaySet&) const override{} - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - if (m_has_last && timestamp - m_last_time < 100ms){ - return false; - } - const Milliseconds at = std::chrono::duration_cast(timestamp - m_start); - ImageRGB32 small = frame.scale_to(192, 108); - if (m_has_last){ - const double change = ImageMatch::pixel_RMSD(m_last, small); - m_result.samples.push_back({at, change}); - if (change >= m_moving_change){ - if (m_result.first_move < 0ms){ - m_result.first_move = at; - } - m_result.last_move = at; - } - } - m_last = std::move(small); - m_last_time = timestamp; - m_has_last = true; - const Milliseconds still_since = m_result.last_move < 0ms ? 0ms : m_result.last_move; - return at - still_since >= 800ms; - } - -private: - WalkProbe& m_result; - double m_moving_change; - WallClock m_start; - ImageRGB32 m_last; - WallClock m_last_time; - bool m_has_last = false; -}; - -} - - -namespace{ - -// What a walk presses. -enum class WalkInput{ - STICK, - DPAD, - DPAD_RUN, // the D-pad with B held - TAPS, // a D-pad tap a tile, 800 ms each -}; -// What a battle that starts on the way is. -enum class WildPolicy{ - RUN_FROM, // a wild battle: run, and walk on - STOP_AT, // no wild Pokemon here: a trainer's, so the walk stops with DIALOG -}; - -struct WalkSpec{ - JoystickPosition stick; - Milliseconds limit = 0ms; - std::string label; - WalkArrived arrived = nullptr; - WalkInput input = WalkInput::STICK; - WildPolicy wild = WildPolicy::RUN_FROM; -}; - -// What a chunk of the walk decided: stop with `stop`, walk the next chunk, -// or (after the watchers) look at how the screen changed. -enum class ChunkNext{ - STOP, - NEXT_CHUNK, - LOOK, -}; -struct ChunkVerdict{ - ChunkNext next = ChunkNext::LOOK; - WalkStop stop = WalkStop::LIMIT; -}; - -// walk_until() and its variants: holds the input a chunk at a time, and -// after each chunk reads the watchers, then the screen. -class WalkUntil{ -public: - WalkUntil(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const WalkSpec& spec) - : m_stream(stream) - , m_context(context) - , m_escape(escape) - , m_spec(spec) - , m_dpad(spec.stick.x < 0 ? DPAD_LEFT : spec.stick.x > 0 ? DPAD_RIGHT : spec.stick.y > 0 ? DPAD_UP : DPAD_DOWN) - {} - - WalkResult run(){ - // A tile a tap: 160 ms held, the rest released, so each chunk is one tile. - const Milliseconds CHUNK = m_spec.input == WalkInput::TAPS ? 800ms : 400ms; - m_context.wait_for_all_requests(); - m_before = snapshot_or_fail(m_stream, m_spec.label); - while (true){ - if (m_spec.arrived && m_spec.arrived(*m_before.frame)){ - return finish(WalkStop::ARRIVED); - } - if (m_result.walked >= m_spec.limit){ - return finish(WalkStop::LIMIT); - } - const Milliseconds chunk = std::min(CHUNK, m_spec.limit - m_result.walked); - const int ret = hold(chunk); - m_result.walked += chunk; - ChunkVerdict verdict = after_watchers(ret); - if (verdict.next == ChunkNext::LOOK){ - verdict = look(); - } - if (verdict.next == ChunkNext::STOP){ - return finish(verdict.stop); - } - } - } - -private: - int hold(Milliseconds chunk){ - WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); - BlackScreenWatcher black(COLOR_RED); - BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); - ShortDialogWatcher dialog(COLOR_YELLOW); - BattleDialogWatcher battle_dialog(COLOR_YELLOW); - return run_until( - m_stream, m_context, - [&](ProControllerContext& context){ - press(context, chunk); - }, - {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} - ); - } - - void press(ProControllerContext& context, Milliseconds chunk) const{ - switch (m_spec.input){ - case WalkInput::TAPS: - pbf_press_dpad(context, m_dpad, 160ms, chunk - 160ms); - return; - case WalkInput::DPAD_RUN: - ssf_press_button(context, BUTTON_B, 0ms, chunk, 0ms); - ssf_press_dpad(context, m_dpad, chunk, chunk, 0ms); - return; - case WalkInput::DPAD: - pbf_press_dpad(context, m_dpad, chunk, 0ms); - return; - case WalkInput::STICK: - pbf_move_left_joystick(context, m_spec.stick, chunk, 0ms); - return; - } - } - - // The watchers: 0 the encounter flash, 1 black, 2 the battle menu, 3 a - // dialogue, 4 the battle's text box. - ChunkVerdict after_watchers(int ret){ - bool battle = ret == 0 || ret == 2 || ret == 4; - if (ret == 1){ - battle = black_screen_was_battle(m_stream, m_context); - if (!battle){ - return {ChunkNext::STOP, WalkStop::TRANSITION}; - } - } - if (battle && m_spec.wild == WildPolicy::STOP_AT){ - m_stream.log("[Walk] " + m_spec.label + ": a battle started; a trainer's here."); - return {ChunkNext::STOP, WalkStop::DIALOG}; - } - if (battle){ - escape_battle("wild battle; running."); - return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; - } - if (ret == 3){ - return {ChunkNext::STOP, WalkStop::DIALOG}; - } - return {ChunkNext::LOOK, WalkStop::LIMIT}; - } - - ChunkVerdict look(){ - m_context.wait_for_all_requests(); - VideoSnapshot after = snapshot_or_fail(m_stream, m_spec.label); - const double change = walk_screen_change(*m_before.frame, *after.frame); - m_stream.log("[Walk] " + m_spec.label + ": " + std::to_string(m_result.walked.count()) + - "ms, screen change " + std::to_string(change) + "."); - if (change > WALK_SCENE_CHANGE && m_spec.wild == WildPolicy::STOP_AT && battle_follows(m_stream, m_context)){ - m_stream.log("[Walk] " + m_spec.label + ": a battle started; a trainer's here."); - return {ChunkNext::STOP, WalkStop::DIALOG}; - } - if (change > WALK_SCENE_CHANGE && battle_follows(m_stream, m_context)){ - escape_battle("wild battle (leaf opening); running."); - return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; - } - // Two still chunks in a row, so one dropped frame does not stop us. A - // frame exactly the same is a stalled video or a game hitch, not a wall: - // standing at a wall still animates. - if (change == 0){ - m_before = std::move(after); - return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; - } - const bool still = still_chunk(change); - if (!still){ - m_result.moved_chunks++; - } - m_unchanged = still ? m_unchanged + 1 : 0; - if (m_unchanged >= 2){ - return {ChunkNext::STOP, WalkStop::BLOCKED}; - } - m_before = std::move(after); - return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; - } - - // The largest change a chunk of this walk made is a step. A bump into an - // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old - // woman), over the fixed line of 16, so for taps "still" is also - // anything under 40% of the walk's own steps. - bool still_chunk(double change){ - m_largest = std::max(m_largest, change); - const double line = m_spec.input == WalkInput::TAPS - ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * m_largest) - : WALK_BLOCKED_CHANGE; - return change < line; - } - - void escape_battle(const std::string& what){ - m_result.wild_battles++; - m_stream.log("[Walk] " + m_spec.label + ": " + what); - m_escape(m_stream, m_context); - m_context.wait_for_all_requests(); - m_before = snapshot_or_fail(m_stream, m_spec.label); - m_unchanged = 0; - } - - WalkResult finish(WalkStop stop){ - m_result.stop = stop; - if (m_spec.wild == WildPolicy::RUN_FROM && (stop == WalkStop::LIMIT || stop == WalkStop::BLOCKED) && - run_from_late_encounter(m_stream, m_context, m_escape, m_spec.label) - ){ - m_result.wild_battles++; - } - m_stream.log("[Walk] " + m_spec.label + ": " + walk_stop_name(stop) + " after " + - std::to_string(m_result.walked.count()) + "ms, " + - std::to_string(m_result.wild_battles) + " wild battle(s)."); - return m_result; - } - - VideoStream& m_stream; - ProControllerContext& m_context; - const WildBattleEscape& m_escape; - const WalkSpec& m_spec; - const DpadPosition m_dpad; - WalkResult m_result{WalkStop::LIMIT, 0ms, 0}; - VideoSnapshot m_before; - size_t m_unchanged = 0; - double m_largest = 0; -}; - -WalkResult walk_until_spec( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const WalkSpec& spec -){ - return WalkUntil(stream, context, escape, spec).run(); -} - -} - -WalkResult walk_until( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label, - const WalkArrived& arrived -){ - return walk_until_spec(stream, context, escape, { - .stick = stick, .limit = limit, .label = label, .arrived = arrived, - .input = WalkInput::STICK, .wild = WildPolicy::RUN_FROM, - }); -} - -WalkResult walk_until_dpad( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label, - const DpadWalkOptions& options -){ - return walk_until_spec(stream, context, escape, { - .stick = stick, .limit = limit, .label = label, .arrived = options.arrived, - .input = options.pace == DpadPace::RUN ? WalkInput::DPAD_RUN : WalkInput::DPAD, - .wild = WildPolicy::RUN_FROM, - }); -} - -WalkResult walk_tiles_dpad( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, size_t tiles, const std::string& label -){ - return walk_until_spec(stream, context, escape, { - .stick = stick, .limit = 800ms * tiles, .label = label, .arrived = nullptr, - .input = WalkInput::TAPS, .wild = WildPolicy::RUN_FROM, - }); -} - -WalkResult walk_until_no_wild( - VideoStream& stream, ProControllerContext& context, - JoystickPosition stick, Milliseconds limit, const std::string& label -){ - // With no wild Pokemon any battle is a trainer's, and the walk stops at - // it (DIALOG) without running. - const WildBattleEscape no_wild = [](VideoStream& stream, ProControllerContext&){ - throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "walk_until_no_wild() ran from a battle."); - }; - return walk_until_spec(stream, context, no_wild, { - .stick = stick, .limit = limit, .label = label, .arrived = nullptr, - .input = WalkInput::STICK, .wild = WildPolicy::STOP_AT, - }); -} - -WalkResult walk_for( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds duration, const std::string& label -){ - WalkResult result{WalkStop::LIMIT, duration, 0}; - context.wait_for_all_requests(); - WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); - BlackScreenWatcher black(COLOR_RED); - BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); - ShortDialogWatcher dialog(COLOR_YELLOW); - BattleDialogWatcher battle_dialog(COLOR_YELLOW); - const int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_move_left_joystick(context, stick, duration, 0ms); - }, - {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} - ); - bool battle = ret == 0 || ret == 2 || ret == 4; - if (ret == 1){ - battle = black_screen_was_battle(stream, context); - if (!battle){ - result.stop = WalkStop::TRANSITION; - } - } - if (battle){ - result.wild_battles = 1; - stream.log("[Walk] " + label + ": wild battle; running."); - escape(stream, context); - context.wait_for_all_requests(); - } - if (ret == 3){ - result.stop = WalkStop::DIALOG; - } - // An encounter after the hold leaves us where the walk ended, so it does - // not count as cutting the walk short. - if (ret < 0){ - run_from_late_encounter(stream, context, escape, label); - } - stream.log("[Walk] " + label + ": " + walk_stop_name(result.stop) + " after a " + - std::to_string(duration.count()) + "ms hold, " + std::to_string(result.wild_battles) + " wild battle(s)."); - return result; -} - -WalkResult walk_to_talk( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label -){ - WalkResult total{WalkStop::LIMIT, 0ms, 0}; - while (total.walked < limit){ - const WalkResult step = walk_until(stream, context, escape, stick, - std::min(400ms, limit - total.walked), label); - total.walked += step.walked; - total.wild_battles += step.wild_battles; - if (step.stop == WalkStop::DIALOG || step.stop == WalkStop::TRANSITION){ - total.stop = step.stop; - return total; - } - ShortDialogWatcher dialog(COLOR_YELLOW); - const int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 80ms, 720ms); - }, - {{dialog}} - ); - if (ret == 0){ - total.stop = WalkStop::DIALOG; - stream.log("[Walk] " + label + ": talking after " + std::to_string(total.walked.count()) + "ms."); - return total; - } - } - stream.log("[Walk] " + label + ": nobody to talk to within " + std::to_string(limit.count()) + "ms."); - return total; -} - -WalkProbe probe_walk( - VideoStream& stream, ProControllerContext& context, - JoystickPosition stick, Milliseconds limit, - double moving_change, const std::string& label -){ - WalkProbe result; - context.wait_for_all_requests(); - WalkProbeSampler sampler(result, moving_change, current_time()); - run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_move_left_joystick(context, stick, limit, 0ms); - }, - {{sampler}} - ); - context.wait_for_all_requests(); - stream.log("[Walk] " + label + ": probe moved from " + std::to_string(result.first_move.count()) + - "ms to " + std::to_string(result.last_move.count()) + "ms."); - return result; -} - -WalkResult walk_to_wall( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label -){ - const WalkResult result = walk_until(stream, context, escape, stick, limit, label); - if (result.stop == WalkStop::DIALOG || result.stop == WalkStop::TRANSITION){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": " + walk_stop_name(result.stop) + " instead of a wall.", stream); - } - if (result.stop == WalkStop::LIMIT){ - stream.log("[Walk] " + label + ": held for the whole limit without seeing the stop; taking the wall as reached."); - } - return result; -} - -WalkResult walk_expecting( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label, - const WalkExpectation& expected -){ - const WalkResult result = walk_until(stream, context, escape, stick, limit, label, expected.arrived); - if (result.stop != expected.stop){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": expected " + walk_stop_name(expected.stop) + ", got " + - walk_stop_name(result.stop) + ".", stream); - } - return result; -} - - -} -} -} +/* BDSP AutoStory - Walk + * + * From: https://github.com/PokemonAutomation/ + * + * BattleDialogWatcher adapted from PokemonAutomation/Arduino-Source#1717 by + * Developer-Butters. + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; + + +const char* walk_stop_name(WalkStop stop){ + switch (stop){ + case WalkStop::ARRIVED: return "arrived"; + case WalkStop::DIALOG: return "dialog"; + case WalkStop::TRANSITION: return "transition"; + case WalkStop::BLOCKED: return "blocked"; + case WalkStop::LIMIT: return "limit"; + } + return "?"; +} + +double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after){ + // Small copies: only the whole-view scroll matters, not detail. + return ImageMatch::pixel_RMSD(before.scale_to(192, 108), after.scale_to(192, 108)); +} + + +namespace{ + +// The battle's text box, held for 250ms. +class BattleDialogWatcher : public DetectorToFinder{ +public: + explicit BattleDialogWatcher(Color color) + : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) + {} +}; + +VideoSnapshot snapshot_or_fail(VideoStream& stream, const std::string& label){ + VideoSnapshot frame = stream.video().snapshot(); + if (!frame){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": No video frame.", stream); + } + return frame; +} + +// After a black screen: a wild battle if a battle screen shows up, else a transition. +bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context){ + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + BlackScreenWatcher gone(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 100, 10, + BlackScreenWatcher::FinderType::GONE, 500ms); + const int ret = wait_until(stream, context, 10s, {{battle_menu}, {battle_dialog}, {gone}}); + if (ret == 2){ + // The battle intro also starts from black; give its first screen a moment. + BattleMenuWatcher late_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher late_dialog(COLOR_YELLOW); + return wait_until(stream, context, 2s, {{late_menu}, {late_dialog}}) >= 0; + } + return ret >= 0; +} + +// A grass encounter opens with a leaf animation, neither white nor black, and +// shows the battle's text box a few seconds later. After a change of the +// whole screen that walking cannot make, wait for the battle to show. +bool battle_follows(VideoStream& stream, ProControllerContext& context){ + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + return wait_until(stream, context, 5s, {{battle_menu}, {battle_dialog}}) >= 0; +} + +} + +// A step in tall grass that was started before the stick was released still +// finishes, and its encounter starts after the walk has ended. Watch a little +// longer, and run from it. Returns whether there was one. +bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ + VideoSnapshot before = stream.video().snapshot(); + WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); + BlackScreenWatcher black(COLOR_RED); + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + const int ret = wait_until(stream, context, 1200ms, {{encounter_flash}, {black}, {battle_menu}, {battle_dialog}}); + bool battle = ret == 0 || ret == 2 || ret == 3 || (ret == 1 && black_screen_was_battle(stream, context)); + if (ret < 0){ + VideoSnapshot after = stream.video().snapshot(); + battle = before && after && walk_screen_change(*before.frame, *after.frame) > WALK_SCENE_CHANGE && + battle_follows(stream, context); + } + if (!battle){ + return false; + } + stream.log("[Walk] " + label + ": wild battle after the walk; running."); + escape(stream, context); + context.wait_for_all_requests(); + return true; +} +namespace{ + +// Samples the screen every 100ms for probe_walk() and stops it once the view +// has been still for 800ms. +class WalkProbeSampler : public VisualInferenceCallback{ +public: + WalkProbeSampler(WalkProbe& result, double moving_change, WallClock start) + : VisualInferenceCallback("WalkProbeSampler") + , m_result(result) + , m_moving_change(moving_change) + , m_start(start) + {} + virtual void make_overlays(VideoOverlaySet&) const override{} + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + if (m_has_last && timestamp - m_last_time < 100ms){ + return false; + } + const Milliseconds at = std::chrono::duration_cast(timestamp - m_start); + ImageRGB32 small = frame.scale_to(192, 108); + if (m_has_last){ + const double change = ImageMatch::pixel_RMSD(m_last, small); + m_result.samples.push_back({at, change}); + if (change >= m_moving_change){ + if (m_result.first_move < 0ms){ + m_result.first_move = at; + } + m_result.last_move = at; + } + } + m_last = std::move(small); + m_last_time = timestamp; + m_has_last = true; + const Milliseconds still_since = m_result.last_move < 0ms ? 0ms : m_result.last_move; + return at - still_since >= 800ms; + } + +private: + WalkProbe& m_result; + double m_moving_change; + WallClock m_start; + ImageRGB32 m_last; + WallClock m_last_time; + bool m_has_last = false; +}; + +} + + +namespace{ + +// What a walk presses. +enum class WalkInput{ + STICK, + DPAD, + DPAD_RUN, // the D-pad with B held + TAPS, // a D-pad tap a tile, 800 ms each +}; +// What a battle that starts on the way is. +enum class WildPolicy{ + RUN_FROM, // a wild battle: run, and walk on + STOP_AT, // no wild Pokemon here: a trainer's, so the walk stops with DIALOG +}; + +struct WalkSpec{ + JoystickPosition stick; + Milliseconds limit = 0ms; + std::string label; + WalkArrived arrived = nullptr; + WalkInput input = WalkInput::STICK; + WildPolicy wild = WildPolicy::RUN_FROM; +}; + +// What a chunk of the walk decided: stop with `stop`, walk the next chunk, +// or (after the watchers) look at how the screen changed. +enum class ChunkNext{ + STOP, + NEXT_CHUNK, + LOOK, +}; +struct ChunkVerdict{ + ChunkNext next = ChunkNext::LOOK; + WalkStop stop = WalkStop::LIMIT; +}; + +// walk_until() and its variants: holds the input a chunk at a time, and +// after each chunk reads the watchers, then the screen. +class WalkUntil{ +public: + WalkUntil(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const WalkSpec& spec) + : m_stream(stream) + , m_context(context) + , m_escape(escape) + , m_spec(spec) + , m_dpad(spec.stick.x < 0 ? DPAD_LEFT : spec.stick.x > 0 ? DPAD_RIGHT : spec.stick.y > 0 ? DPAD_UP : DPAD_DOWN) + {} + + WalkResult run(){ + // A tile a tap: 160 ms held, the rest released, so each chunk is one tile. + const Milliseconds CHUNK = m_spec.input == WalkInput::TAPS ? 800ms : 400ms; + m_context.wait_for_all_requests(); + m_before = snapshot_or_fail(m_stream, m_spec.label); + while (true){ + if (m_spec.arrived && m_spec.arrived(*m_before.frame)){ + return finish(WalkStop::ARRIVED); + } + if (m_result.walked >= m_spec.limit){ + return finish(WalkStop::LIMIT); + } + const Milliseconds chunk = std::min(CHUNK, m_spec.limit - m_result.walked); + const int ret = hold(chunk); + m_result.walked += chunk; + ChunkVerdict verdict = after_watchers(ret); + if (verdict.next == ChunkNext::LOOK){ + verdict = look(); + } + if (verdict.next == ChunkNext::STOP){ + return finish(verdict.stop); + } + } + } + +private: + int hold(Milliseconds chunk){ + WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); + BlackScreenWatcher black(COLOR_RED); + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + ShortDialogWatcher dialog(COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + return run_until( + m_stream, m_context, + [&](ProControllerContext& context){ + press(context, chunk); + }, + {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} + ); + } + + void press(ProControllerContext& context, Milliseconds chunk) const{ + switch (m_spec.input){ + case WalkInput::TAPS: + pbf_press_dpad(context, m_dpad, 160ms, chunk - 160ms); + return; + case WalkInput::DPAD_RUN: + ssf_press_button(context, BUTTON_B, 0ms, chunk, 0ms); + ssf_press_dpad(context, m_dpad, chunk, chunk, 0ms); + return; + case WalkInput::DPAD: + pbf_press_dpad(context, m_dpad, chunk, 0ms); + return; + case WalkInput::STICK: + pbf_move_left_joystick(context, m_spec.stick, chunk, 0ms); + return; + } + } + + // The watchers: 0 the encounter flash, 1 black, 2 the battle menu, 3 a + // dialogue, 4 the battle's text box. + ChunkVerdict after_watchers(int ret){ + bool battle = ret == 0 || ret == 2 || ret == 4; + if (ret == 1){ + battle = black_screen_was_battle(m_stream, m_context); + if (!battle){ + return {ChunkNext::STOP, WalkStop::TRANSITION}; + } + } + if (battle && m_spec.wild == WildPolicy::STOP_AT){ + m_stream.log("[Walk] " + m_spec.label + ": a battle started; a trainer's here."); + return {ChunkNext::STOP, WalkStop::DIALOG}; + } + if (battle){ + escape_battle("wild battle; running."); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; + } + if (ret == 3){ + return {ChunkNext::STOP, WalkStop::DIALOG}; + } + return {ChunkNext::LOOK, WalkStop::LIMIT}; + } + + ChunkVerdict look(){ + m_context.wait_for_all_requests(); + VideoSnapshot after = snapshot_or_fail(m_stream, m_spec.label); + const double change = walk_screen_change(*m_before.frame, *after.frame); + m_stream.log("[Walk] " + m_spec.label + ": " + std::to_string(m_result.walked.count()) + + "ms, screen change " + std::to_string(change) + "."); + if (change > WALK_SCENE_CHANGE && m_spec.wild == WildPolicy::STOP_AT && battle_follows(m_stream, m_context)){ + m_stream.log("[Walk] " + m_spec.label + ": a battle started; a trainer's here."); + return {ChunkNext::STOP, WalkStop::DIALOG}; + } + if (change > WALK_SCENE_CHANGE && battle_follows(m_stream, m_context)){ + escape_battle("wild battle (leaf opening); running."); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; + } + // Two still chunks in a row, so one dropped frame does not stop us. A + // frame exactly the same is a stalled video or a game hitch, not a wall: + // standing at a wall still animates. + if (change == 0){ + m_before = std::move(after); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; + } + const bool still = still_chunk(change); + if (!still){ + m_result.moved_chunks++; + } + m_unchanged = still ? m_unchanged + 1 : 0; + if (m_unchanged >= 2){ + return {ChunkNext::STOP, WalkStop::BLOCKED}; + } + m_before = std::move(after); + return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; + } + + // The largest change a chunk of this walk made is a step. A bump into an + // NPC measured 17.2 after steps of 63 to 65 (r250a, Floaroma's old + // woman), over the fixed line of 16, so for taps "still" is also + // anything under 40% of the walk's own steps. + bool still_chunk(double change){ + m_largest = std::max(m_largest, change); + const double line = m_spec.input == WalkInput::TAPS + ? std::max(WALK_TAP_BLOCKED_CHANGE, 0.4 * m_largest) + : WALK_BLOCKED_CHANGE; + return change < line; + } + + void escape_battle(const std::string& what){ + m_result.wild_battles++; + m_stream.log("[Walk] " + m_spec.label + ": " + what); + m_escape(m_stream, m_context); + m_context.wait_for_all_requests(); + m_before = snapshot_or_fail(m_stream, m_spec.label); + m_unchanged = 0; + } + + WalkResult finish(WalkStop stop){ + m_result.stop = stop; + if (m_spec.wild == WildPolicy::RUN_FROM && (stop == WalkStop::LIMIT || stop == WalkStop::BLOCKED) && + run_from_late_encounter(m_stream, m_context, m_escape, m_spec.label) + ){ + m_result.wild_battles++; + } + m_stream.log("[Walk] " + m_spec.label + ": " + walk_stop_name(stop) + " after " + + std::to_string(m_result.walked.count()) + "ms, " + + std::to_string(m_result.wild_battles) + " wild battle(s)."); + return m_result; + } + + VideoStream& m_stream; + ProControllerContext& m_context; + const WildBattleEscape& m_escape; + const WalkSpec& m_spec; + const DpadPosition m_dpad; + WalkResult m_result{WalkStop::LIMIT, 0ms, 0}; + VideoSnapshot m_before; + size_t m_unchanged = 0; + double m_largest = 0; +}; + +WalkResult walk_until_spec( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const WalkSpec& spec +){ + return WalkUntil(stream, context, escape, spec).run(); +} + +} + +WalkResult walk_until( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkArrived& arrived +){ + return walk_until_spec(stream, context, escape, { + .stick = stick, .limit = limit, .label = label, .arrived = arrived, + .input = WalkInput::STICK, .wild = WildPolicy::RUN_FROM, + }); +} + +WalkResult walk_until_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const DpadWalkOptions& options +){ + return walk_until_spec(stream, context, escape, { + .stick = stick, .limit = limit, .label = label, .arrived = options.arrived, + .input = options.pace == DpadPace::RUN ? WalkInput::DPAD_RUN : WalkInput::DPAD, + .wild = WildPolicy::RUN_FROM, + }); +} + +WalkResult walk_tiles_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, size_t tiles, const std::string& label +){ + return walk_until_spec(stream, context, escape, { + .stick = stick, .limit = 800ms * tiles, .label = label, .arrived = nullptr, + .input = WalkInput::TAPS, .wild = WildPolicy::RUN_FROM, + }); +} + +WalkResult walk_until_no_wild( + VideoStream& stream, ProControllerContext& context, + JoystickPosition stick, Milliseconds limit, const std::string& label +){ + // With no wild Pokemon any battle is a trainer's, and the walk stops at + // it (DIALOG) without running. + const WildBattleEscape no_wild = [](VideoStream& stream, ProControllerContext&){ + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "walk_until_no_wild() ran from a battle."); + }; + return walk_until_spec(stream, context, no_wild, { + .stick = stick, .limit = limit, .label = label, .arrived = nullptr, + .input = WalkInput::STICK, .wild = WildPolicy::STOP_AT, + }); +} + +WalkResult walk_for( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds duration, const std::string& label +){ + WalkResult result{WalkStop::LIMIT, duration, 0}; + context.wait_for_all_requests(); + WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); + BlackScreenWatcher black(COLOR_RED); + BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); + ShortDialogWatcher dialog(COLOR_YELLOW); + BattleDialogWatcher battle_dialog(COLOR_YELLOW); + const int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_move_left_joystick(context, stick, duration, 0ms); + }, + {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} + ); + bool battle = ret == 0 || ret == 2 || ret == 4; + if (ret == 1){ + battle = black_screen_was_battle(stream, context); + if (!battle){ + result.stop = WalkStop::TRANSITION; + } + } + if (battle){ + result.wild_battles = 1; + stream.log("[Walk] " + label + ": wild battle; running."); + escape(stream, context); + context.wait_for_all_requests(); + } + if (ret == 3){ + result.stop = WalkStop::DIALOG; + } + // An encounter after the hold leaves us where the walk ended, so it does + // not count as cutting the walk short. + if (ret < 0){ + run_from_late_encounter(stream, context, escape, label); + } + stream.log("[Walk] " + label + ": " + walk_stop_name(result.stop) + " after a " + + std::to_string(duration.count()) + "ms hold, " + std::to_string(result.wild_battles) + " wild battle(s)."); + return result; +} + +WalkResult walk_to_talk( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label +){ + WalkResult total{WalkStop::LIMIT, 0ms, 0}; + while (total.walked < limit){ + const WalkResult step = walk_until(stream, context, escape, stick, + std::min(400ms, limit - total.walked), label); + total.walked += step.walked; + total.wild_battles += step.wild_battles; + if (step.stop == WalkStop::DIALOG || step.stop == WalkStop::TRANSITION){ + total.stop = step.stop; + return total; + } + ShortDialogWatcher dialog(COLOR_YELLOW); + const int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 80ms, 720ms); + }, + {{dialog}} + ); + if (ret == 0){ + total.stop = WalkStop::DIALOG; + stream.log("[Walk] " + label + ": talking after " + std::to_string(total.walked.count()) + "ms."); + return total; + } + } + stream.log("[Walk] " + label + ": nobody to talk to within " + std::to_string(limit.count()) + "ms."); + return total; +} + +WalkProbe probe_walk( + VideoStream& stream, ProControllerContext& context, + JoystickPosition stick, Milliseconds limit, + double moving_change, const std::string& label +){ + WalkProbe result; + context.wait_for_all_requests(); + WalkProbeSampler sampler(result, moving_change, current_time()); + run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_move_left_joystick(context, stick, limit, 0ms); + }, + {{sampler}} + ); + context.wait_for_all_requests(); + stream.log("[Walk] " + label + ": probe moved from " + std::to_string(result.first_move.count()) + + "ms to " + std::to_string(result.last_move.count()) + "ms."); + return result; +} + +WalkResult walk_to_wall( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label +){ + const WalkResult result = walk_until(stream, context, escape, stick, limit, label); + if (result.stop == WalkStop::DIALOG || result.stop == WalkStop::TRANSITION){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": " + walk_stop_name(result.stop) + " instead of a wall.", stream); + } + if (result.stop == WalkStop::LIMIT){ + stream.log("[Walk] " + label + ": held for the whole limit without seeing the stop; taking the wall as reached."); + } + return result; +} + +WalkResult walk_expecting( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkExpectation& expected +){ + const WalkResult result = walk_until(stream, context, escape, stick, limit, label, expected.arrived); + if (result.stop != expected.stop){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + label + ": expected " + walk_stop_name(expected.stop) + ", got " + + walk_stop_name(result.stop) + ".", stream); + } + return result; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index 9beb976f6e..504edccfe8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -1,189 +1,189 @@ -/* BDSP AutoStory - Walk - * - * From: https://github.com/PokemonAutomation/ - * - * Walking that reads the screen instead of trusting a duration: hold a - * direction and stop on whatever the screen says happened. - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Walk_H -#define PokemonAutomation_PokemonBDSP_AutoStory_Walk_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "Controllers/Joystick.h" -#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Runs from a wild battle that has interrupted a walk, and returns once the -// player stands on the overworld again. The walker only sees that a battle -// started; how to leave it is the program's battle code, passed in. -using WildBattleEscape = std::function; - -enum class WalkStop{ - ARRIVED, // `arrived` matched. - DIALOG, // A dialogue box opened: an NPC or a trainer stopped us. - TRANSITION, // The screen went black and came back without a battle: a door or a new area. - BLOCKED, // The screen stopped changing: we are walking into a wall. - LIMIT, // Walked `limit` without any of the above. -}; -const char* walk_stop_name(WalkStop stop); - -// Whether the walk has arrived, from the screen after each chunk. -using WalkArrived = std::function; - -struct WalkResult{ - WalkStop stop; - Milliseconds walked; - size_t wild_battles; - // Chunks whose screen change passed the blocked threshold: on a tap - // walk, the taps that moved a tile. A trainer's freeze and a bump do - // not count (r248a: "4 taps before the battle" were 2 steps and 2 - // taps into Taylor's freeze). - size_t moved_chunks = 0; -}; - -// Holds the left stick at `stick` until one of the WalkStop events. Wild battles on -// the way are run from, and walking resumes. Does not throw for any WalkStop; the -// caller decides which ones are expected. -WalkResult walk_until( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label, - const WalkArrived& arrived = nullptr -); - -// How walk_until_dpad() presses: RUN holds B too, twice as fast and as -// tile-true. -enum class DpadPace{ - WALK, - RUN, -}; -struct DpadWalkOptions{ - WalkArrived arrived = nullptr; - DpadPace pace = DpadPace::WALK; -}; - -// walk_until() on the D-pad, for a straight walk along a row or a column -// (`stick` is one of the four directions). The D-pad moves whole tiles and -// keeps to the row: the stick drifts off it, catches tree corners and slides -// a row on stairs (Route 203, r226a and r227b; by hand the D-pad went -// through the same places). -WalkResult walk_until_dpad( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label, - const DpadWalkOptions& options = {} -); - -// A set number of whole tiles on the D-pad, a tap a tile (a tap moves -// exactly one tile; a stick hold timed for n tiles is a tile or two off), -// with the same watch for wild battles and dialogue as walk_until(). Ends -// LIMIT after `tiles` taps, or BLOCKED when two taps in a row move nothing. -WalkResult walk_tiles_dpad( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, size_t tiles, const std::string& label -); - -// walk_until() where there are no wild Pokemon (a gym, a building): any -// battle that starts is a trainer's, so the walk stops with DIALOG, left in -// the battle for the caller to fight, instead of trying to run from it -// (r206d tried to run from the second Oreburgh Gym trainer). -WalkResult walk_until_no_wild( - VideoStream& stream, ProControllerContext& context, - JoystickPosition stick, Milliseconds limit, const std::string& label -); - -// Holds the left stick at `stick` for `duration` in one go, for a walk of a -// set length: walk_until() checks the screen between short holds, and each -// break can cost a step. Stops early for a dialog or a transition. A wild -// battle is run from and ends the walk with `wild_battles` 1, at a place the -// caller cannot know. -WalkResult walk_for( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds duration, const std::string& label -); - -// The stop walk_expecting() requires, and what counts as arrived. -struct WalkExpectation{ - WalkStop stop = WalkStop::ARRIVED; - WalkArrived arrived = nullptr; -}; -// walk_until() that requires `expected.stop`. Fails with the screenshot otherwise. -WalkResult walk_expecting( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label, - const WalkExpectation& expected -); - -// After a move that may have walked onto an encounter tile (a tap in a cave -// or in tall grass): waits briefly for a wild battle and runs from it. -// Returns whether there was one; we may then be off the place we expected. -bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); - -// walk_until() toward a wall the route was measured to end at. Seeing the -// stop only ends the hold early: holding on for the whole `limit` also -// counts as there, as people or animations nearby can keep the screen -// changing at a wall (s03a1: a hiker and a child by the Mart fence; s03c1: -// Roark's pickaxe; r162a: Jubilife's TV). A wrong place is caught by the -// next gate. Fails on a dialog or a transition: we are not where we think. -WalkResult walk_to_wall( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label -); - -// Walks toward someone to talk to: after each short stretch, presses A and stops -// once a dialogue opens. Use it where walking into the person does not read as -// BLOCKED, e.g. in tall grass, whose sway keeps the screen changing. -WalkResult walk_to_talk( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - JoystickPosition stick, Milliseconds limit, const std::string& label -); - -// How much the screen changed between two frames, 0 for identical. Walking scrolls -// the whole view: 16 to 85 per 400ms on Route 202, against about 6 for running in -// place against trees. -double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after); -constexpr double WALK_BLOCKED_CHANGE = 10.0; -// For whole-tile D-pad taps: a tap that moves changes the screen by 21 to 50 -// (r244a: 40 per tap along Route 204's row 27); a tap into a wall or an NPC -// bumps for 10 to 13.4, and an NPC walking past does the same, so 10 counted -// bumps as steps (r244a, 2026-10-31). -constexpr double WALK_TAP_BLOCKED_CHANGE = 16.0; -// More than walking changes in 400ms: a new scene, such as a battle opening. -constexpr double WALK_SCENE_CHANGE = 120.0; - - -// One straight walk timed finely, to check a map against the game: holds the -// stick at `stick` and samples the screen every 100ms until the view has been -// still for 800ms or `limit` runs out. Times count from the start of the hold. -// A sample moved if it changed by at least `moving_change`: still is 4 to 7, -// walking 16 to 85. Handles no battles or dialogs: use it on open ground, -// away from tall grass. -struct WalkProbe{ - Milliseconds first_move{-1}; // the first sample that moved; -1 if none did - Milliseconds last_move{-1}; // the last sample that moved; -1 if none did - struct Sample{ - Milliseconds at; - double change; // walk_screen_change() since the previous sample - }; - std::vector samples; -}; -WalkProbe probe_walk( - VideoStream& stream, ProControllerContext& context, - JoystickPosition stick, Milliseconds limit, - double moving_change, const std::string& label -); - - -} -} -} -#endif +/* BDSP AutoStory - Walk + * + * From: https://github.com/PokemonAutomation/ + * + * Walking that reads the screen instead of trusting a duration: hold a + * direction and stop on whatever the screen says happened. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Walk_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Walk_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Controllers/Joystick.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Runs from a wild battle that has interrupted a walk, and returns once the +// player stands on the overworld again. The walker only sees that a battle +// started; how to leave it is the program's battle code, passed in. +using WildBattleEscape = std::function; + +enum class WalkStop{ + ARRIVED, // `arrived` matched. + DIALOG, // A dialogue box opened: an NPC or a trainer stopped us. + TRANSITION, // The screen went black and came back without a battle: a door or a new area. + BLOCKED, // The screen stopped changing: we are walking into a wall. + LIMIT, // Walked `limit` without any of the above. +}; +const char* walk_stop_name(WalkStop stop); + +// Whether the walk has arrived, from the screen after each chunk. +using WalkArrived = std::function; + +struct WalkResult{ + WalkStop stop; + Milliseconds walked; + size_t wild_battles; + // Chunks whose screen change passed the blocked threshold: on a tap + // walk, the taps that moved a tile. A trainer's freeze and a bump do + // not count (r248a: "4 taps before the battle" were 2 steps and 2 + // taps into Taylor's freeze). + size_t moved_chunks = 0; +}; + +// Holds the left stick at `stick` until one of the WalkStop events. Wild battles on +// the way are run from, and walking resumes. Does not throw for any WalkStop; the +// caller decides which ones are expected. +WalkResult walk_until( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkArrived& arrived = nullptr +); + +// How walk_until_dpad() presses: RUN holds B too, twice as fast and as +// tile-true. +enum class DpadPace{ + WALK, + RUN, +}; +struct DpadWalkOptions{ + WalkArrived arrived = nullptr; + DpadPace pace = DpadPace::WALK; +}; + +// walk_until() on the D-pad, for a straight walk along a row or a column +// (`stick` is one of the four directions). The D-pad moves whole tiles and +// keeps to the row: the stick drifts off it, catches tree corners and slides +// a row on stairs (Route 203, r226a and r227b; by hand the D-pad went +// through the same places). +WalkResult walk_until_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const DpadWalkOptions& options = {} +); + +// A set number of whole tiles on the D-pad, a tap a tile (a tap moves +// exactly one tile; a stick hold timed for n tiles is a tile or two off), +// with the same watch for wild battles and dialogue as walk_until(). Ends +// LIMIT after `tiles` taps, or BLOCKED when two taps in a row move nothing. +WalkResult walk_tiles_dpad( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, size_t tiles, const std::string& label +); + +// walk_until() where there are no wild Pokemon (a gym, a building): any +// battle that starts is a trainer's, so the walk stops with DIALOG, left in +// the battle for the caller to fight, instead of trying to run from it +// (r206d tried to run from the second Oreburgh Gym trainer). +WalkResult walk_until_no_wild( + VideoStream& stream, ProControllerContext& context, + JoystickPosition stick, Milliseconds limit, const std::string& label +); + +// Holds the left stick at `stick` for `duration` in one go, for a walk of a +// set length: walk_until() checks the screen between short holds, and each +// break can cost a step. Stops early for a dialog or a transition. A wild +// battle is run from and ends the walk with `wild_battles` 1, at a place the +// caller cannot know. +WalkResult walk_for( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds duration, const std::string& label +); + +// The stop walk_expecting() requires, and what counts as arrived. +struct WalkExpectation{ + WalkStop stop = WalkStop::ARRIVED; + WalkArrived arrived = nullptr; +}; +// walk_until() that requires `expected.stop`. Fails with the screenshot otherwise. +WalkResult walk_expecting( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label, + const WalkExpectation& expected +); + +// After a move that may have walked onto an encounter tile (a tap in a cave +// or in tall grass): waits briefly for a wild battle and runs from it. +// Returns whether there was one; we may then be off the place we expected. +bool run_from_late_encounter(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label); + +// walk_until() toward a wall the route was measured to end at. Seeing the +// stop only ends the hold early: holding on for the whole `limit` also +// counts as there, as people or animations nearby can keep the screen +// changing at a wall (s03a1: a hiker and a child by the Mart fence; s03c1: +// Roark's pickaxe; r162a: Jubilife's TV). A wrong place is caught by the +// next gate. Fails on a dialog or a transition: we are not where we think. +WalkResult walk_to_wall( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label +); + +// Walks toward someone to talk to: after each short stretch, presses A and stops +// once a dialogue opens. Use it where walking into the person does not read as +// BLOCKED, e.g. in tall grass, whose sway keeps the screen changing. +WalkResult walk_to_talk( + VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, + JoystickPosition stick, Milliseconds limit, const std::string& label +); + +// How much the screen changed between two frames, 0 for identical. Walking scrolls +// the whole view: 16 to 85 per 400ms on Route 202, against about 6 for running in +// place against trees. +double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after); +constexpr double WALK_BLOCKED_CHANGE = 10.0; +// For whole-tile D-pad taps: a tap that moves changes the screen by 21 to 50 +// (r244a: 40 per tap along Route 204's row 27); a tap into a wall or an NPC +// bumps for 10 to 13.4, and an NPC walking past does the same, so 10 counted +// bumps as steps (r244a, 2026-10-31). +constexpr double WALK_TAP_BLOCKED_CHANGE = 16.0; +// More than walking changes in 400ms: a new scene, such as a battle opening. +constexpr double WALK_SCENE_CHANGE = 120.0; + + +// One straight walk timed finely, to check a map against the game: holds the +// stick at `stick` and samples the screen every 100ms until the view has been +// still for 800ms or `limit` runs out. Times count from the start of the hold. +// A sample moved if it changed by at least `moving_change`: still is 4 to 7, +// walking 16 to 85. Handles no battles or dialogs: use it on open ground, +// away from tall grass. +struct WalkProbe{ + Milliseconds first_move{-1}; // the first sample that moved; -1 if none did + Milliseconds last_move{-1}; // the last sample that moved; -1 if none did + struct Sample{ + Milliseconds at; + double change; // walk_screen_change() since the previous sample + }; + std::vector samples; +}; +WalkProbe probe_walk( + VideoStream& stream, ProControllerContext& context, + JoystickPosition stick, Milliseconds limit, + double moving_change, const std::string& label +); + + +} +} +} +#endif From 4cec241a2c602976122f205fe9e1a2732fa97825 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 17:20:57 -0800 Subject: [PATCH 28/74] BDSP walker: give up after the third dialogue the map does not explain r14 walked into Barry's Route 201 warning, which no map records, took it for an unknown trainer, replanned into it again and looped for minutes. A route now fails on the third such stop instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index da8af82032..e7bccff334 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -267,6 +267,8 @@ class RouteWalker{ // Every banner read on the way, to check the map we arrive on against. std::vector m_all_banners; std::string m_map_start; + // Dialogue the map does not explain, so far on this route. + size_t m_unexplained_talks = 0; }; std::vector RouteWalker::run(std::vector from){ @@ -643,6 +645,12 @@ LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector 2){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + walk.label + ": dialogue the map does not explain stopped us 3 times.", m_stream); + } route_status(m_stream, m_plan.label + ": a trainer the map lacks stopped us; fighting."); m_trainers.fight("unknown trainer"); if (walk.planned.leg.ends_at_wall){ From 33761c21c627bc5804d2a9fb88d8bb9c0947a950 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 18:18:41 -0800 Subject: [PATCH 29/74] BDSP walker: a scene at a map's edge stands in for the missing banner Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index e7bccff334..8db5d2c782 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -579,6 +579,14 @@ void RouteWalker::check_banners(LegWalk& walk){ const std::string banner_text = quoted_list(walk.banners); m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ + // A scene that starts as we cross the edge covers the banner (r19: Rowan + // and Dawn on Route 201's edge). With no banner read and a dialogue up, + // let the next step, the scene, decide where we are. + VideoSnapshot now = m_stream.video().snapshot(); + if (banner_text.empty() && now && ShortDialogDetector().detect(*now.frame)){ + m_stream.log("[Route] " + walk.label + ": no banner, but a scene started; going on.", COLOR_ORANGE); + return; + } OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + (banner_text.empty() ? "nothing" : banner_text) + ".", m_stream); From b95836c411458c4bb039ea3d6fe2414955a4f7d9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 18:22:46 -0800 Subject: [PATCH 30/74] BDSP walker: wait for the scene's first line before failing on a missing banner Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 8db5d2c782..44f5629512 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -581,9 +581,10 @@ void RouteWalker::check_banners(LegWalk& walk){ if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ // A scene that starts as we cross the edge covers the banner (r19: Rowan // and Dawn on Route 201's edge). With no banner read and a dialogue up, - // let the next step, the scene, decide where we are. - VideoSnapshot now = m_stream.video().snapshot(); - if (banner_text.empty() && now && ShortDialogDetector().detect(*now.frame)){ + // let the next step, the scene, decide where we are. The scene may still + // be walking its people in (r20), so give its first line a few seconds. + ShortDialogWatcher scene_line(COLOR_YELLOW); + if (banner_text.empty() && wait_until(m_stream, m_context, 6000ms, {{scene_line}}) == 0){ m_stream.log("[Route] " + walk.label + ": no banner, but a scene started; going on.", COLOR_ORANGE); return; } From 608a99c78b9afe0e24307dfb67a807f02bcff961 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 18:26:53 -0800 Subject: [PATCH 31/74] BDSP walker: no banner read is a warning; only a wrong banner fails Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 44f5629512..fdc58baed1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -579,13 +579,12 @@ void RouteWalker::check_banners(LegWalk& walk){ const std::string banner_text = quoted_list(walk.banners); m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ - // A scene that starts as we cross the edge covers the banner (r19: Rowan - // and Dawn on Route 201's edge). With no banner read and a dialogue up, - // let the next step, the scene, decide where we are. The scene may still - // be walking its people in (r20), so give its first line a few seconds. - ShortDialogWatcher scene_line(COLOR_YELLOW); - if (banner_text.empty() && wait_until(m_stream, m_context, 6000ms, {{scene_line}}) == 0){ - m_stream.log("[Route] " + walk.label + ": no banner, but a scene started; going on.", COLOR_ORANGE); + // No banner read at all is weak evidence: a scene can cover it (r19), and + // the Lakefront-to-Route 201 crossing showed none we could read (r20, r21). + // Go on and let the next step check where we are; a banner for another + // map still fails. + if (banner_text.empty()){ + m_stream.log("[Route] " + walk.label + ": no banner read for " + walk.map_after + "; going on.", COLOR_ORANGE); return; } OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, From 31816e59e910c297e5032ffac1006e54c001f4f8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 18:30:37 -0800 Subject: [PATCH 32/74] BDSP walker: arriving with no banner read at all is a warning too Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index fdc58baed1..001f1455d4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -345,7 +345,11 @@ std::vector RouteWalker::arrive() const{ const bool seen = std::any_of(m_all_banners.begin(), m_all_banners.end(), [&](const std::string& read){ return location_banner_matches(read, map_end); }); - if (changed_map && !seen){ + // No banner read at all is only a warning (r20-r22: none we could read on + // the Lakefront-to-Route 201 crossing); the next step checks where we are. + if (changed_map && m_all_banners.empty()){ + m_stream.log("[Route] " + m_plan.label + ": no banner read for " + map_end + "; going on.", COLOR_ORANGE); + }else if (changed_map && !seen){ const std::string reads = quoted_list(m_all_banners); OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, m_plan.label + ": arrived at " + describe(m_maps, m_from) + " on the map, but " + map_end + From d839fb9475cd3dec8f10dc94cb98a71588f0d48d Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 19:39:25 -0800 Subject: [PATCH 33/74] BDSP walker: time wall legs at the plan's pace, walk or run B held with the D-pad runs once the player has the Running Shoes: r27 ran 35 tiles north in about 5.75 s, and the walking count put the stop 11 tiles short of the wall. Legs that reach their wall log the pace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 14 +++++++--- .../PokemonBDSP_AutoStory_PlannedRoute.h | 3 +++ .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 5 +++- .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 26 +++++++++++++------ 4 files changed, 36 insertions(+), 12 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 001f1455d4..3ce37c13c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -150,8 +150,10 @@ std::string quoted_list(const std::vector& reads){ // Long enough to reach the wall from the farthest tile, with room for a // slow start; past the wall the player stands still. +// At a run the limit is still timed at a walk: a pace measured too fast +// must not cut a long leg short. Milliseconds wall_limit(const TileLeg& leg){ - const Milliseconds per_tile = route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP; + const Milliseconds per_tile = route_ms_per_tile(leg.direction, MoveSpeed::WALK); return ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; } @@ -385,7 +387,13 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ for (const TilePos& pos : m_from){ nearest = std::min(nearest, slide_to_wall(m_grid, pos, leg.direction).tiles); } - size_t walked_tiles = tiles_moved(walk.result, route_ms_per_tile(leg.direction) / ROUTE_RUN_SPEEDUP); + size_t walked_tiles = tiles_moved(walk.result, route_ms_per_tile(leg.direction, m_plan.speed)); + // Every leg that reaches its wall measures the pace: the tiles are known. + if (walk.result.stop == WalkStop::BLOCKED && nearest != SIZE_MAX && walked_tiles >= nearest){ + m_stream.log("[Speed] " + std::string(m_plan.speed == MoveSpeed::RUN ? "run" : "walk") + " " + + direction_name(leg.direction) + ": " + std::to_string(nearest) + " tiles in " + + std::to_string(walk.result.walked.count()) + " ms to the wall."); + } walked_tiles = unstick_wall_leg(walk, walked_tiles, nearest); // Any stop short of the wall's distance: someone who stays put is // talked to, and the leg is planned again from where we are. Within the @@ -409,7 +417,7 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ // A walk to the wall that stopped well short of it: tap through a corner, // then wait for someone in the way. Returns the tiles walked by then. size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest){ - const Milliseconds per_tile = route_ms_per_tile(walk.planned.leg.direction) / ROUTE_RUN_SPEEDUP; + const Milliseconds per_tile = route_ms_per_tile(walk.planned.leg.direction, m_plan.speed); const Milliseconds limit = wall_limit(walk.planned.leg); // A stick walk can catch a corner when we stand part of a tile off // centre, where a D-pad tap, which moves whole tiles, gets through: on diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 845b8977d7..8577d82743 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -19,6 +19,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_Walk.h" namespace PokemonAutomation{ @@ -46,6 +47,8 @@ struct RouteWalkPlan{ std::string label; std::vector avoid = {}; RobustPlanCosts costs = route_plan_costs(); + // The pace of legs to a wall, which their tile counts are timed by. + MoveSpeed speed = MoveSpeed::WALK; }; // Walks from any of the world tiles `from` of `maps` until every tile the diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index 803019b456..6af44d9591 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -41,7 +41,10 @@ bool across(Direction direction){ } -Milliseconds route_ms_per_tile(Direction direction){ +Milliseconds route_ms_per_tile(Direction direction, MoveSpeed speed){ + if (speed == MoveSpeed::RUN){ + return across(direction) ? ROUTE_RUN_MS_PER_TILE_ACROSS : ROUTE_RUN_MS_PER_TILE_UP_DOWN; + } return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index 97bda06d6e..b686d72e77 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -33,14 +33,24 @@ constexpr Milliseconds ROUTE_MS_PER_TILE_ACROSS = Milliseconds(160); // east constexpr Milliseconds ROUTE_MS_PER_TILE_UP_DOWN = Milliseconds(240); // north or south // From pressing the stick to the first step, when standing still. constexpr Milliseconds ROUTE_START_DELAY = Milliseconds(250); -// Running (B held) covers a tile in this fraction of the walking time. B -// held with the D-pad did not run: r238a walked the Ravaged Path's corridor -// at 160 ms a tile, and a limit set for twice that speed cut a wall leg -// short by two tiles. 1 until running is measured to work. -constexpr int ROUTE_RUN_SPEEDUP = 1; - -// Walking time per tile in `direction`. -Milliseconds route_ms_per_tile(Pokemon::Direction direction); +// How fast the player moves on a leg to a wall (B held with the D-pad). +// B only runs once Mom has given the Running Shoes (00.03); before that +// it walks. The bike comes later, with its own measured times. +enum class MoveSpeed{ + WALK, + RUN, +}; + +// Running time per tile, measured on the console: r27 ran Twinleaf's +// column 17 north onto Route 201, 35 tiles in about 5.75 s (164 ms a +// tile) where walking took 240. Across is scaled the same until measured. +// Rounded down: a count from too fast a pace runs over, which a wall leg +// forgives, where one from too slow a pace stops short of the wall. +constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_ACROSS = Milliseconds(100); +constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_UP_DOWN = Milliseconds(150); + +// Time per tile in `direction` at `speed`. +Milliseconds route_ms_per_tile(Pokemon::Direction direction, MoveSpeed speed = MoveSpeed::WALK); // The left stick for a direction. Row 0 is the top of a map, and the // stick's y is positive upward. JoystickPosition route_stick(Pokemon::Direction direction); From 2daaa60dd271dce793ac3d49aa252478bd64ade6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 19:58:44 -0800 Subject: [PATCH 34/74] BDSP navigation: people on the maps are no wall to stop against A leg to a wall that ends against someone standing still stops there, but they may turn and talk or walk off: r29 ran east into Mom, who talked. Tiles blocked on the console stay walls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 16 +++++++++++++--- .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 3 +++ .../PokemonBDSP_AutoStory_StoryWorld_Tests.cpp | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index 656c684217..fade601390 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -127,11 +127,13 @@ void StoryWorld::rebuild(){ void StoryWorld::paint(const Placed& placed, const TilePos& corner){ for (int y = 0; y < placed.tiles.height; y++){ for (int x = 0; x < placed.tiles.width; x++){ - Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, placed.tiles.at({x, y}), false}; + Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, placed.tiles.at({x, y}), false, false}; } } for (const TilePos& pos : placed.occupied){ - Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}).occupied = true; + Cell& standing = Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}); + standing.occupied = true; + standing.person = true; } } @@ -162,6 +164,11 @@ bool StoryWorld::occupied(const TilePos& pos) const{ return found != nullptr && found->occupied; } +bool StoryWorld::person(const TilePos& pos) const{ + const Cell* found = cell(pos); + return found != nullptr && found->person; +} + void StoryWorld::block(const TilePos& pos){ if (Cell* found = cell(pos)){ found->occupied = true; @@ -223,9 +230,12 @@ std::optional step(const StoryWorld& world, const TilePos& from, Direct return std::nullopt; } +// Someone standing in the way stops us too, but is no wall to stop against: +// they may turn and talk, or walk off (r29 ran east into Mom, who talked). bool at_wall(const StoryWorld& world, const TilePos& pos, Direction direction){ const std::optional next = world.tile(pos.next(direction)); - return next && *next != TileKind::DOOR && !step(world, pos, direction).has_value(); + return next && *next != TileKind::DOOR && !world.person(pos.next(direction)) && + !step(world, pos, direction).has_value(); } std::string describe(const StoryWorld& world, const TilePos& pos){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index 1953009657..3e660cfcfb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -49,6 +49,8 @@ class StoryWorld{ // Whether someone or something stands still on this tile, or it was // blocked with block(). bool occupied(const Pokemon::TilePos& pos) const; + // Whether one of the maps' people stands on this tile (not a block()). + bool person(const Pokemon::TilePos& pos) const; // Blocks a tile found in the way on the console. Tiles off the maps // are left alone. @@ -73,6 +75,7 @@ class StoryWorld{ bool covered = false; Pokemon::TileKind tile = Pokemon::TileKind::WALL; bool occupied = false; + bool person = false; }; void check_overlap(const Placed& map) const; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp index 3fd80e93b8..3531d72fd9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -96,7 +96,7 @@ class Test_StoryWorldSteps : public UnitTest{ {.name = "a west ledge hops west", .rows = {".<."}, .from = {2, 0}, .direction = Direction::WEST, .lands = TilePos{0, 0}}, {.name = "a west ledge stops east", .rows = {".<."}, .direction = Direction::EAST, .at_wall = true}, {.name = "a ledge onto a wall stops", .rows = {".", "v", "#"}, .direction = Direction::SOUTH, .at_wall = true}, - {.name = "a person standing still", .rows = {".", "."}, .standing = {{0, 0}}, .from = {0, 1}, .at_wall = true}, + {.name = "a person standing still", .rows = {".", "."}, .standing = {{0, 0}}, .from = {0, 1}, .at_wall = false}, {.name = "a wanderer does not block", .rows = {".", "."}, .wandering = {{0, 0}}, .from = {0, 1}, .lands = TilePos{0, 0}}, }; for (const StepCase& item : cases){ From aade8837765d14625e9c6ddc7899e8fad260ec26 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 20:00:12 -0800 Subject: [PATCH 35/74] BDSP navigation: occupied() tells people from blocked tiles, in StoryWorld's seven methods Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 21 +++++++------------ .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 16 +++++++------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index fade601390..df99467c0f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -114,7 +114,7 @@ void StoryWorld::rebuild(){ } for (const TilePos& pos : m_blocked){ if (Cell* blocked = cell(pos)){ - blocked->occupied = true; + blocked->occupant = BLOCKED; } } for (const TilePos& pos : m_uncovered){ @@ -127,13 +127,11 @@ void StoryWorld::rebuild(){ void StoryWorld::paint(const Placed& placed, const TilePos& corner){ for (int y = 0; y < placed.tiles.height; y++){ for (int x = 0; x < placed.tiles.width; x++){ - Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, placed.tiles.at({x, y}), false, false}; + Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}) = Cell{true, placed.tiles.at({x, y}), NOBODY}; } } for (const TilePos& pos : placed.occupied){ - Cell& standing = Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}); - standing.occupied = true; - standing.person = true; + Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}).occupant = PERSON; } } @@ -159,19 +157,14 @@ std::optional StoryWorld::tile(const TilePos& pos) const{ return found->tile; } -bool StoryWorld::occupied(const TilePos& pos) const{ +StoryWorld::Occupant StoryWorld::occupied(const TilePos& pos) const{ const Cell* found = cell(pos); - return found != nullptr && found->occupied; -} - -bool StoryWorld::person(const TilePos& pos) const{ - const Cell* found = cell(pos); - return found != nullptr && found->person; + return found == nullptr ? NOBODY : found->occupant; } void StoryWorld::block(const TilePos& pos){ if (Cell* found = cell(pos)){ - found->occupied = true; + found->occupant = BLOCKED; m_blocked.push_back(pos); } } @@ -234,7 +227,7 @@ std::optional step(const StoryWorld& world, const TilePos& from, Direct // they may turn and talk, or walk off (r29 ran east into Mom, who talked). bool at_wall(const StoryWorld& world, const TilePos& pos, Direction direction){ const std::optional next = world.tile(pos.next(direction)); - return next && *next != TileKind::DOOR && !world.person(pos.next(direction)) && + return next && *next != TileKind::DOOR && world.occupied(pos.next(direction)) != StoryWorld::PERSON && !step(world, pos, direction).has_value(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index 3e660cfcfb..e78a7ee5ee 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -46,11 +46,14 @@ class StoryWorld{ // The tile, or nothing off the maps. std::optional tile(const Pokemon::TilePos& pos) const; - // Whether someone or something stands still on this tile, or it was - // blocked with block(). - bool occupied(const Pokemon::TilePos& pos) const; - // Whether one of the maps' people stands on this tile (not a block()). - bool person(const Pokemon::TilePos& pos) const; + // Who or what stands still on a tile: one of the maps' people, or a + // tile blocked with block(). NOBODY is false, the others true. + enum Occupant{ + NOBODY = 0, + PERSON, + BLOCKED, + }; + Occupant occupied(const Pokemon::TilePos& pos) const; // Blocks a tile found in the way on the console. Tiles off the maps // are left alone. @@ -74,8 +77,7 @@ class StoryWorld{ struct Cell{ bool covered = false; Pokemon::TileKind tile = Pokemon::TileKind::WALL; - bool occupied = false; - bool person = false; + Occupant occupant = NOBODY; }; void check_overlap(const Placed& map) const; From 1c0ffea21cb2eaceed65a6f096154ea152cbf6ad Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 20:18:29 -0800 Subject: [PATCH 36/74] BDSP maps: the house's 1F row 8 is open at x 4 (console) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json index 7929140ede..2a7a89546d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json @@ -1,6 +1,6 @@ { "name": "PlayerHouse1F", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp, but (4, 8) is open on the console: west along row 8 stops at x 4 (r32, 2026-11-01)", "revision": "c6689696d5fb", "date": "2026-11-01"}, "tiles": [ "#############", "#############", @@ -10,7 +10,7 @@ "#SSS..SS....#", "#...........#", "#...........#", - "#..##.......#", + "#..#........#", "##.##......##", "##....D....##", "#############" From 1ce3bb14117dbf49610f774b87070893baea10c1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 20:40:51 -0800 Subject: [PATCH 37/74] BDSP walker: watch for the new map's banner a while after the last leg Sandgem's banner showed about a second after the walk ended (r35). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 3ce37c13c3..f21131a8d9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -344,12 +344,23 @@ LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t c std::vector RouteWalker::arrive() const{ const std::string map_end = map_of(m_maps, m_from); const bool changed_map = !m_map_start.empty() && !map_end.empty() && map_end != m_map_start; - const bool seen = std::any_of(m_all_banners.begin(), m_all_banners.end(), [&](const std::string& read){ + bool seen = std::any_of(m_all_banners.begin(), m_all_banners.end(), [&](const std::string& read){ return location_banner_matches(read, map_end); }); + // The banner can come up after the last leg ends: Sandgem's showed about + // a second later (r35). Watch for it a while before judging. + for (const WallClock end = current_time() + 3000ms; changed_map && !seen && current_time() < end;){ + m_context.wait_for_all_requests(); + if (const VideoSnapshot screen = m_stream.video().snapshot()){ + seen = location_banner_matches(read_location_banner(*screen.frame), map_end); + } + if (!seen){ + m_context.wait_for(250ms); + } + } // No banner read at all is only a warning (r20-r22: none we could read on // the Lakefront-to-Route 201 crossing); the next step checks where we are. - if (changed_map && m_all_banners.empty()){ + if (changed_map && !seen && m_all_banners.empty()){ m_stream.log("[Route] " + m_plan.label + ": no banner read for " + map_end + "; going on.", COLOR_ORANGE); }else if (changed_map && !seen){ const std::string reads = quoted_list(m_all_banners); From 058c104c0943715108f47290a536ea3d44538e96 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 21:29:34 -0800 Subject: [PATCH 38/74] BDSP maps: the lab's door mat in Sandgem, a row below its door A run west along row 11 went into the lab at (8, 11) (r41, r42). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json index 4f7a4e61b4..61111248ec 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -1,6 +1,6 @@ { "name": "SandgemTown", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", "revision": "default branch", "date": "2026-10-31"}, + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396; console: the lab's door mat (8, 11) takes us in from the side (r41, r42)", "revision": "default branch", "date": "2026-10-31"}, "tiles": [ "########################......####", "########################......####", @@ -13,7 +13,7 @@ "####################......########", "####################......########", "########D##....##D##S....S#D######", - ".....S........................####", + ".....S..D.....................####", "..............................####", "..............................####", "..............................####", From 2a21276ea4eea857b9b17c3c77bea8016db25a55 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 21:29:34 -0800 Subject: [PATCH 39/74] Revert "BDSP maps: the lab's door mat in Sandgem, a row below its door" v3's Mart lady walk went west along that row past the mat on console; r42's entry is likely a story trigger or the run, not the map. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json index 4f7a4e61b4..61111248ec 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -1,6 +1,6 @@ { "name": "SandgemTown", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", "revision": "default branch", "date": "2026-10-31"}, + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396; console: the lab's door mat (8, 11) takes us in from the side (r41, r42)", "revision": "default branch", "date": "2026-10-31"}, "tiles": [ "########################......####", "########################......####", @@ -13,7 +13,7 @@ "####################......########", "####################......########", "########D##....##D##S....S#D######", - ".....S........................####", + ".....S..D.....................####", "..............................####", "..............................####", "..............................####", From ed3b0b00639593c40571f042253f903aaf8b73f2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 21:31:38 -0800 Subject: [PATCH 40/74] BDSP maps: Sandgem's row 11 has no door at the lab's mat after all The commit before this one, misnamed "Revert ...", put a door at (8, 11); v3's Mart lady walk went west past that mat on console, so it goes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json index 61111248ec..4f7a4e61b4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -1,6 +1,6 @@ { "name": "SandgemTown", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396; console: the lab's door mat (8, 11) takes us in from the side (r41, r42)", "revision": "default branch", "date": "2026-10-31"}, + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", "revision": "default branch", "date": "2026-10-31"}, "tiles": [ "########################......####", "########################......####", @@ -13,7 +13,7 @@ "####################......########", "####################......########", "########D##....##D##S....S#D######", - ".....S..D.....................####", + ".....S........................####", "..............................####", "..............................####", "..............................####", From ec50ad2ebbf5a028195c6b2fcf651ab0638383ee Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 22:47:29 -0800 Subject: [PATCH 41/74] BDSP AutoStory walk: turn with a 50 ms D-pad tap A 100 ms stick tap stepped about 0.6 tile off the grid (r49: a tile west of Sandgem's Center door). 40 to 80 ms D-pad taps only turned, on the console. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 6 +++++- .../AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h | 9 ++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index 6af44d9591..bfc9160262 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -81,7 +81,11 @@ Milliseconds route_open_hold(Direction direction, size_t tiles){ void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); - pbf_move_left_joystick(context, route_stick(direction), ROUTE_TURN_TAP, 300ms); + const DpadPosition dpad = + direction == Direction::NORTH ? DPAD_UP : + direction == Direction::SOUTH ? DPAD_DOWN : + direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; + pbf_press_dpad(context, dpad, ROUTE_TURN_TAP, 300ms); context.wait_for_all_requests(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index b686d72e77..1568e5ae26 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -61,9 +61,12 @@ JoystickPosition route_stick(Pokemon::Direction direction); // 800ms hold south 4: the player starts at once and finishes the step. Milliseconds route_open_hold(Pokemon::Direction direction, size_t tiles); -// A tap this short turns a player who faces another way, without a step: on -// the console a 150ms tap south after walking north only turned the player. -constexpr Milliseconds ROUTE_TURN_TAP = Milliseconds(100); +// A D-pad tap this short only turns, whichever way the player faced: on the +// console 40, 50, 60 and 80 ms taps each turned without a step. A 100 ms +// stick tap stepped about 0.6 tile, off the tile grid, and a 160 ms D-pad +// tap steps a whole tile (r49: a stick "turn" put us a tile west of +// Sandgem's Center door; r248a). +constexpr Milliseconds ROUTE_TURN_TAP = Milliseconds(50); // Turns the player to face `direction` without moving. Only for a player who // faces another way: one already facing it may take a step. From ac97a4d0822210334deb1f1a83a06cf71bdcba53 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 23:17:02 -0800 Subject: [PATCH 42/74] BDSP AutoStory walk: after a trainer on a wall leg, judge the walk on Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index f21131a8d9..4e4b303185 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -483,7 +483,7 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ } void RouteWalker::check_at_wall(LegWalk& walk){ - const WalkResult check = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, 2000ms, + WalkResult check = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, 2000ms, walk.label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); if (check.stop == WalkStop::DIALOG){ // A trainer who saw us froze the walk (the "!") until its time ran @@ -497,6 +497,10 @@ void RouteWalker::check_at_wall(LegWalk& walk){ m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), walk.label + ": on to the wall", run_watching(walk)); + // Where the walk on stopped is what counts now, not the line that + // stopped the check (r54: at the wall after Route 202's second + // trainer, and failed on the "dialog"). + check = walk.result; } if (check.stop != WalkStop::BLOCKED && !(check.stop == WalkStop::LIMIT && holding_against_wall(m_stream, m_context, walk.stick.x, walk.stick.y, walk.label + ": at the wall?")) From b6990c88bdfd9725e8f46ab6bee06bb0fc3cb42c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 1 Nov 2026 23:35:05 -0800 Subject: [PATCH 43/74] BDSP AutoStory walk: after a trainer on an open leg, plan from the taps and the sight line Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 4e4b303185..a7a8a9f711 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -737,7 +737,12 @@ LegNext RouteWalker::known_trainer(LegWalk& walk, const std::vector Date: Mon, 2 Nov 2026 00:02:49 -0800 Subject: [PATCH 44/74] BDSP AutoStory walk: turn an open leg with a tap too short to step The 160 ms turn tap's step was guessed from the screen and counted a tile it had not walked (r60: a column off below Jubilife's Center). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index a7a8a9f711..0a061b3184 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -564,21 +564,15 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ return LegNext::NEXT_LEG; } -// The first tap of a leg was meant to turn, but a 160 ms D-pad tap turns -// and steps whichever way the player faced (r248a: all seven did; r246a: -// "south 1" out of the cave went two tiles, onto the Youngster's row), so -// the tap is measured like any other and a step counts for the leg. +// Turns to the leg's way with a tap too short to step (50 ms: on the +// console 40 to 80 ms taps only turned). The leg's taps then each move a +// tile. The old 160 ms "turn" tap stepped whichever way we faced, and +// guessing from the screen whether it had was wrong both ways (r248a +// stepped; r60 only turned but counted a tile, a column off below +// Jubilife's Center). void RouteWalker::turn_tap(LegWalk& walk){ - const DpadPosition dpad = walk.stick.x < 0 ? DPAD_LEFT : walk.stick.x > 0 ? DPAD_RIGHT : walk.stick.y > 0 ? DPAD_UP : DPAD_DOWN; - m_context.wait_for_all_requests(); - VideoSnapshot before = m_stream.video().snapshot(); - pbf_press_dpad(m_context, dpad, 160ms, 700ms); - m_context.wait_for_all_requests(); - VideoSnapshot after = m_stream.video().snapshot(); - if (before && after && walk_screen_change(*before.frame, *after.frame) > WALK_TAP_BLOCKED_CHANGE){ - walk.turn_moved = 1; - m_stream.log("[Route] " + walk.label + ": the turn tap moved a tile (already facing that way); it counts.", COLOR_ORANGE); - } + route_turn(m_stream, m_context, walk.planned.leg.direction); + walk.turn_moved = 0; } LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ From 433501b6e3f7fd3ccfb4c6ce3bc01018099f6a7f Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 00:10:48 -0800 Subject: [PATCH 45/74] BDSP AutoStory walk: a straight stick walk goes on the D-pad The stick stops between tiles (a 100 ms tap moved ~0.6 tile), and walks after stick holds ran a column off (r57 to r61). Diagonals stay on the stick. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index e0e3104d80..f4066a9ed7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -65,6 +65,17 @@ VideoSnapshot snapshot_or_fail(VideoStream& stream, const std::string& label){ return frame; } +// A stick straight north, south, east or west goes on the D-pad: the D-pad +// moves whole tiles, the stick stops between them (on the console a 100 ms +// stick tap moved ~0.6 tile; r57 to r61 walked a column off after stick +// holds). Diagonals stay on the stick. +bool straight(JoystickPosition stick){ + return (stick.x == 0) != (stick.y == 0); +} +DpadPosition dpad_toward(JoystickPosition stick){ + return stick.x < 0 ? DPAD_LEFT : stick.x > 0 ? DPAD_RIGHT : stick.y > 0 ? DPAD_UP : DPAD_DOWN; +} + // After a black screen: a wild battle if a battle screen shows up, else a transition. bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context){ BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); @@ -388,7 +399,7 @@ WalkResult walk_until( ){ return walk_until_spec(stream, context, escape, { .stick = stick, .limit = limit, .label = label, .arrived = arrived, - .input = WalkInput::STICK, .wild = WildPolicy::RUN_FROM, + .input = straight(stick) ? WalkInput::DPAD : WalkInput::STICK, .wild = WildPolicy::RUN_FROM, }); } @@ -443,7 +454,11 @@ WalkResult walk_for( const int ret = run_until( stream, context, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, stick, duration, 0ms); + if (straight(stick)){ + pbf_press_dpad(context, dpad_toward(stick), duration, 0ms); + }else{ + pbf_move_left_joystick(context, stick, duration, 0ms); + } }, {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} ); From ac5f55d63546708fe382688275fb71899b89d51e Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 00:24:57 -0800 Subject: [PATCH 46/74] BDSP AutoStory walk: put the route walker's console steps behind RouteIO No behaviour change. RouteWalker (walk_route(), talk_to_npc()) now does everything on the console through a RouteIO: walks to a wall, D-pad tap walks, presses and waits, the dialogue watch, the at-the-wall holding check, screen looks and its log and failures. ConsoleRouteIO is today's code: holding_against_wall() moved unchanged into RouteIO.cpp, and each call site makes the same controller commands, waits and reads as before. walk_route() and talk_to_npc() keep their signatures and build a ConsoleRouteIO; overloads take a RouteIO so tests can script the console. route_turn() and the walker's taps, A presses and waits are now a RouteInput (kind, direction, hold, release, count, whether to wait for them), pressed by press_route_input(); route_turn_tap() is the D-pad tap route_turn() turns with. Review with: git diff --color-moved=dimmed-zebra --color-moved-ws=allow-indentation-change HEAD~1 HEAD Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 287 ++++++++---------- .../PokemonBDSP_AutoStory_PlannedRoute.h | 11 + .../Utils/PokemonBDSP_AutoStory_RouteIO.cpp | 101 ++++++ .../Utils/PokemonBDSP_AutoStory_RouteIO.h | 103 +++++++ .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 38 ++- .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 28 ++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 7 files changed, 411 insertions(+), 159 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 0a061b3184..bbeafd4c0e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -7,17 +7,13 @@ #include #include #include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/PrettyPrint.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/GlobalAutoPaths.h" -#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "Pokemon/Navigation/Pokemon_RouteLog.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_RouteIO.h" #include "PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_PlannedRoute.h" @@ -55,21 +51,21 @@ PlannedRouteLeg planned_route_leg(const StoryWorld& maps, const PlannedLeg& leg) return {.leg = route_log_leg(leg.leg), .after = route_tiles(maps, leg.after)}; } -void log_plan(VideoStream& stream, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ +void log_plan(RouteIO& io, const StoryWorld& maps, const std::string& label, const std::vector& from, const std::vector& legs){ std::vector logged; for (const PlannedLeg& leg : legs){ logged.push_back(planned_route_leg(maps, leg)); } - stream.log(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged)); + io.note(ROUTE_LOG_TAG + route_plan_line(label, route_tiles(maps, from), logged), RouteNote::LOG); } // Logs a leg that ended on its planned tiles, and how that is known: an // open leg counts its taps through a wild battle, so its end is assumed; a // leg to a wall is walked again to its wall. -void log_leg_done(VideoStream& stream, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ +void log_leg_done(RouteIO& io, const StoryWorld& maps, const std::string& label, const PlannedLeg& planned, size_t wild_battles){ const bool assumed = !planned.leg.ends_at_wall && wild_battles > 0; - stream.log(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), - assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : "")); + io.note(ROUTE_LOG_TAG + route_leg_end_line(label, route_log_leg(planned.leg), route_tiles(maps, planned.after), + assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : ""), RouteNote::LOG); } // The tiles the player passes when walking `tiles` tiles from `from`, the @@ -89,30 +85,6 @@ std::vector leg_path(const StoryWorld& grid, TilePos from, Direction di return path; } -// Holding toward a wall with people or Pokemon moving beside us never reads -// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking -// scrolls the view far more (35 to 90). True if holding toward (x, y) for -// 1.6 s changes the screen less than walking would: we stand at a wall. -bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ - constexpr double WALKING_CHANGE = 25.0; - context.wait_for_all_requests(); - VideoSnapshot before = stream.video().snapshot(); - double most = 0; - for (size_t chunk = 0; chunk < 4 && before; chunk++){ - pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); - context.wait_for_all_requests(); - VideoSnapshot after = stream.video().snapshot(); - if (!after){ - return false; - } - most = std::max(most, walk_screen_change(*before.frame, *after.frame)); - before = std::move(after); - } - stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + - (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); - return before && most < WALKING_CHANGE; -} - // The map all of `tiles` are on, or empty if they are on several or none. std::string map_of(const StoryWorld& maps, const std::vector& tiles){ std::string name; @@ -157,6 +129,28 @@ Milliseconds wall_limit(const TileLeg& leg){ return ROUTE_START_DELAY + per_tile * leg.tiles * 5 / 4 + 1000ms; } +// Fails the program with `message` (RouteNote::FAILURE). +[[noreturn]] void fail(RouteIO& io, const std::string& message){ + io.note(message, RouteNote::FAILURE); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); +} + +// route_turn() through `io`. +void turn(RouteIO& io, Direction direction){ + io.note(std::string("[Route] Turning ") + direction_name(direction) + ".", RouteNote::LOG); + io.press(route_turn_tap(direction)); +} + +// A press of A, to talk to someone in front of us. +RouteInput press_a(RouteInputEnd end){ + return {.kind = RouteInputKind::BUTTON_A, .direction = Direction::NORTH, .hold = 80ms, .release = 200ms, + .count = 1, .end = end}; +} + +// A wait for someone walking about to get out of the way. +constexpr RouteInput WAIT_FOR_THE_WAY{.kind = RouteInputKind::WAIT, .direction = Direction::NORTH, .hold = 2500ms, + .release = 0ms, .count = 1, .end = RouteInputEnd::DONE}; + // Tiles a walk to the wall moved, from the time it walked. size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ const Milliseconds moving = walk.walked - ROUTE_START_DELAY - @@ -175,7 +169,6 @@ enum class LegNext{ struct LegWalk{ const PlannedLeg& planned; std::string label; - JoystickPosition stick; std::string map_before; std::string map_after; std::vector banners = {}; @@ -212,13 +205,8 @@ DpadWalkOptions run_watching(LegWalk& walk){ // turned out to be when something stopped it. class RouteWalker{ public: - RouteWalker( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, RouteTrainers& trainers, const RouteWalkPlan& plan - ) - : m_stream(stream) - , m_context(context) - , m_escape(escape) + RouteWalker(RouteIO& io, const StoryWorld& maps, RouteTrainers& trainers, const RouteWalkPlan& plan) + : m_io(io) , m_maps(maps) , m_grid(maps) , m_trainers(trainers) @@ -255,9 +243,7 @@ class RouteWalker{ LegNext replan_from(const LegWalk& walk, std::vector stopped, const std::string& why); void mark_blocker(const LegWalk& walk, const std::vector& stopped); - VideoStream& m_stream; - ProControllerContext& m_context; - const WildBattleEscape& m_escape; + RouteIO& m_io; const StoryWorld& m_maps; // Our own copy, so things found in the way can be added to it. StoryWorld m_grid; @@ -286,8 +272,8 @@ std::vector RouteWalker::run(std::vector from){ m_map_start = map_of(m_maps, m_from); for (size_t plans = 0; plans < 8; plans++){ const std::vector legs = plan_legs(); - route_status(m_stream, m_plan.label + ": " + std::to_string(legs.size()) + " legs planned"); - log_plan(m_stream, m_maps, m_plan.label, m_from, legs); + m_io.note(m_plan.label + ": " + std::to_string(legs.size()) + " legs planned", RouteNote::STATUS); + log_plan(m_io, m_maps, m_plan.label, m_from, legs); bool replanned = false; for (size_t number = 1; number <= legs.size() && !replanned; number++){ replanned = walk_leg(legs[number - 1], number, legs.size()) == LegNext::REPLAN; @@ -296,8 +282,7 @@ std::vector RouteWalker::run(std::vector from){ return arrive(); } } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - m_plan.label + ": too many plans.", m_stream); + fail(m_io, m_plan.label + ": too many plans."); } std::vector RouteWalker::plan_legs() const{ @@ -306,23 +291,21 @@ std::vector RouteWalker::plan_legs() const{ // From a few possible tiles the exact-open-leg costs found no // plan where the default ones did (r240a, three tiles on Route // 204's row 27); the default plan is longer but sound. - m_stream.log("[Route] " + m_plan.label + ": no plan with the route costs from " + describe(m_maps, m_from) + - "; trying the default costs.", COLOR_ORANGE); + m_io.note("[Route] " + m_plan.label + ": no plan with the route costs from " + describe(m_maps, m_from) + + "; trying the default costs.", RouteNote::WARNING); legs = plan_robust_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); } if (!legs){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - m_plan.label + ": no plan from " + describe(m_maps, m_from) + ".", m_stream); + fail(m_io, m_plan.label + ": no plan from " + describe(m_maps, m_from) + "."); } return std::move(*legs); } LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t count){ - route_status(m_stream, route_leg_line(number, count, planned_route_leg(m_maps, planned))); + m_io.note(route_leg_line(number, count, planned_route_leg(m_maps, planned)), RouteNote::STATUS); LegWalk walk{ .planned = planned, .label = m_plan.label + ": " + to_string(planned.leg), - .stick = route_stick(planned.leg.direction), .map_before = map_of(m_maps, m_from), .map_after = map_of(m_maps, planned.after), }; @@ -333,8 +316,7 @@ LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t c m_facing = planned.leg.direction; check_banners(walk); if (walk.result.stop == WalkStop::TRANSITION){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": unexpected transition.", m_stream); + fail(m_io, walk.label + ": unexpected transition."); } return after_leg(walk); } @@ -350,25 +332,24 @@ std::vector RouteWalker::arrive() const{ // The banner can come up after the last leg ends: Sandgem's showed about // a second later (r35). Watch for it a while before judging. for (const WallClock end = current_time() + 3000ms; changed_map && !seen && current_time() < end;){ - m_context.wait_for_all_requests(); - if (const VideoSnapshot screen = m_stream.video().snapshot()){ - seen = location_banner_matches(read_location_banner(*screen.frame), map_end); - } + m_io.look([&](const ImageViewRGB32& screen){ + seen = location_banner_matches(read_location_banner(screen), map_end); + }); if (!seen){ - m_context.wait_for(250ms); + m_io.press({.kind = RouteInputKind::PAUSE, .direction = Direction::NORTH, .hold = 250ms, .release = 0ms, + .count = 1, .end = RouteInputEnd::QUEUED}); } } // No banner read at all is only a warning (r20-r22: none we could read on // the Lakefront-to-Route 201 crossing); the next step checks where we are. if (changed_map && !seen && m_all_banners.empty()){ - m_stream.log("[Route] " + m_plan.label + ": no banner read for " + map_end + "; going on.", COLOR_ORANGE); + m_io.note("[Route] " + m_plan.label + ": no banner read for " + map_end + "; going on.", RouteNote::WARNING); }else if (changed_map && !seen){ const std::string reads = quoted_list(m_all_banners); - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - m_plan.label + ": arrived at " + describe(m_maps, m_from) + " on the map, but " + map_end + - "'s location banner never showed (read " + (reads.empty() ? "nothing" : reads) + ").", m_stream); + fail(m_io, m_plan.label + ": arrived at " + describe(m_maps, m_from) + " on the map, but " + map_end + + "'s location banner never showed (read " + (reads.empty() ? "nothing" : reads) + ")."); } - m_stream.log(ROUTE_LOG_TAG + route_arrived_line(m_plan.label, route_tiles(m_maps, m_from))); + m_io.note(ROUTE_LOG_TAG + route_arrived_line(m_plan.label, route_tiles(m_maps, m_from)), RouteNote::LOG); return m_from; } @@ -378,15 +359,15 @@ std::vector RouteWalker::arrive() const{ LegNext RouteWalker::wall_leg(LegWalk& walk){ const TileLeg& leg = walk.planned.leg; const Milliseconds limit = wall_limit(leg); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label, .options = run_watching(walk)}); // A wild battle may end the walk early. Walking to a wall again ends in // the same place, so finish the leg. const bool interrupted = walk.result.wild_battles > 0; for (size_t again = 0; again < 3 && walk.result.wild_battles > 0 && (walk.result.stop == WalkStop::LIMIT || walk.result.stop == WalkStop::BLOCKED); again++ ){ - m_stream.log("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again."); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + m_io.note("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again.", RouteNote::LOG); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label, .options = run_watching(walk)}); } if (interrupted){ return LegNext::NEXT_LEG; @@ -401,9 +382,9 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ size_t walked_tiles = tiles_moved(walk.result, route_ms_per_tile(leg.direction, m_plan.speed)); // Every leg that reaches its wall measures the pace: the tiles are known. if (walk.result.stop == WalkStop::BLOCKED && nearest != SIZE_MAX && walked_tiles >= nearest){ - m_stream.log("[Speed] " + std::string(m_plan.speed == MoveSpeed::RUN ? "run" : "walk") + " " + + m_io.note("[Speed] " + std::string(m_plan.speed == MoveSpeed::RUN ? "run" : "walk") + " " + direction_name(leg.direction) + ": " + std::to_string(nearest) + " tiles in " + - std::to_string(walk.result.walked.count()) + " ms to the wall."); + std::to_string(walk.result.walked.count()) + " ms to the wall.", RouteNote::LOG); } walked_tiles = unstick_wall_leg(walk, walked_tiles, nearest); // Any stop short of the wall's distance: someone who stays put is @@ -435,28 +416,20 @@ size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t // Route 203's stairs the walk west stopped nine times in a row and two // taps crossed (r225a, 2026-10-31). Tap twice, then walk on to the wall. if (walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest){ - const Direction direction = walk.planned.leg.direction; - const DpadPosition dpad = - direction == Direction::NORTH ? DPAD_UP : - direction == Direction::SOUTH ? DPAD_DOWN : - direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; - m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; two D-pad taps, then on to the wall.", COLOR_ORANGE); - for (size_t tap = 0; tap < 2; tap++){ - pbf_press_dpad(m_context, dpad, 160ms, 640ms); - } - m_context.wait_for_all_requests(); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + m_io.note("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; two D-pad taps, then on to the wall.", RouteNote::WARNING); + m_io.press({.kind = RouteInputKind::DPAD, .direction = walk.planned.leg.direction, .hold = 160ms, .release = 640ms, + .count = 2, .end = RouteInputEnd::DONE}); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label, .options = run_watching(walk)}); walked_tiles += tiles_moved(walk.result, per_tile); } // Someone walking about may stand in the way for a moment: wait and // walk to the wall again before calling it an obstacle. for (size_t again = 0; again < 2 && walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++){ - m_stream.log("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + - " tiles, short of the wall; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(m_context, 2500ms); - m_context.wait_for_all_requests(); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, limit, walk.label, run_watching(walk)); + m_io.note("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + + " tiles, short of the wall; waiting for the way to clear.", RouteNote::WARNING); + m_io.press(WAIT_FOR_THE_WAY); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label, .options = run_watching(walk)}); walked_tiles += tiles_moved(walk.result, per_tile); } return walked_tiles; @@ -475,16 +448,15 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ } stopped = sorted_unique(std::move(stopped)); if (stopped.empty()){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": stopped early, and no tile fits.", m_stream); + fail(m_io, walk.label + ": stopped early, and no tile fits."); } mark_blocker(walk, stopped); return replan_from(walk, std::move(stopped), "stopped early after about " + std::to_string(walked_tiles) + " tiles"); } void RouteWalker::check_at_wall(LegWalk& walk){ - WalkResult check = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, 2000ms, - walk.label + ": at the wall?", {.arrived = nullptr, .pace = DpadPace::RUN}); + WalkResult check = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = 2000ms, + .label = walk.label + ": at the wall?", .options = {.arrived = nullptr, .pace = DpadPace::RUN}}); if (check.stop == WalkStop::DIALOG){ // A trainer who saw us froze the walk (the "!") until its time ran // out, then walked over (r241a: Aroma Lady Taylor's line crosses @@ -492,33 +464,32 @@ void RouteWalker::check_at_wall(LegWalk& walk){ // they saw us from is not reliable (BDSP's trainers stand a few // tiles from Platinum's, r242a), and a leg to a wall ends at its // wall however far it got. - route_status(m_stream, walk.label + ": a trainer stopped us on the way; battling."); + m_io.note(walk.label + ": a trainer stopped us on the way; battling.", RouteNote::STATUS); m_trainers.fight("a trainer on the way"); - m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); - walk.result = walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), - walk.label + ": on to the wall", run_watching(walk)); + m_io.note("[Route] " + walk.label + ": on to the wall after the battle.", RouteNote::WARNING); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = wall_limit(walk.planned.leg), + .label = walk.label + ": on to the wall", .options = run_watching(walk)}); // Where the walk on stopped is what counts now, not the line that // stopped the check (r54: at the wall after Route 202's second // trainer, and failed on the "dialog"). check = walk.result; } if (check.stop != WalkStop::BLOCKED && - !(check.stop == WalkStop::LIMIT && holding_against_wall(m_stream, m_context, walk.stick.x, walk.stick.y, walk.label + ": at the wall?")) + !(check.stop == WalkStop::LIMIT && m_io.holding_against_wall(walk.planned.leg.direction, walk.label + ": at the wall?")) ){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": ran out of time short of the wall, and walking on gets " + - walk_stop_name(check.stop) + ": not where the plan has us.", m_stream); + fail(m_io, walk.label + ": ran out of time short of the wall, and walking on gets " + + walk_stop_name(check.stop) + ": not where the plan has us."); } } // After a battle on a leg to a wall: a leg to a wall ends at its wall // however far it got, so walk on to it and carry on. void RouteWalker::on_to_wall(LegWalk& walk){ - m_stream.log("[Route] " + walk.label + ": on to the wall after the battle.", COLOR_ORANGE); - walk_until_dpad(m_stream, m_context, m_escape, walk.stick, wall_limit(walk.planned.leg), - walk.label + ": on to the wall", run_watching(walk)); + m_io.note("[Route] " + walk.label + ": on to the wall after the battle.", RouteNote::WARNING); + m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = wall_limit(walk.planned.leg), + .label = walk.label + ": on to the wall", .options = run_watching(walk)}); m_from = walk.planned.after; - log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, 0); + log_leg_done(m_io, m_maps, m_plan.label, walk.planned, 0); } @@ -531,13 +502,13 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ turn_tap(walk); } if (leg.tiles > walk.turn_moved){ - walk.result = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - walk.turn_moved, walk.label); + walk.result = m_io.walk_taps(leg.direction, leg.tiles - walk.turn_moved, walk.label); } // A wild battle starts once the step onto the grass is done, so the // taps still count; the walk went on after it. if (walk.result.wild_battles > 0){ - m_stream.log("[Route] " + walk.label + ": " + std::to_string(walk.result.wild_battles) + - " wild battle(s) on the way; the tap count holds.", COLOR_ORANGE); + m_io.note("[Route] " + walk.label + ": " + std::to_string(walk.result.wild_battles) + + " wild battle(s) on the way; the tap count holds.", RouteNote::WARNING); } // Taps that moved nothing: someone stands in the way (the Youngster // below the Ravaged Path wanders across the row under the cliff, r239a, @@ -548,11 +519,10 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ // which the taps give exactly. size_t moved = std::min(leg.tiles, walk.result.moved_chunks + walk.turn_moved); if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ - m_stream.log("[Route] " + walk.label + ": blocked after " + std::to_string(moved) + " of " + - std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", COLOR_ORANGE); - pbf_wait(m_context, 2500ms); - m_context.wait_for_all_requests(); - const WalkResult rest = walk_tiles_dpad(m_stream, m_context, m_escape, walk.stick, leg.tiles - moved, walk.label + ": the rest"); + m_io.note("[Route] " + walk.label + ": blocked after " + std::to_string(moved) + " of " + + std::to_string(leg.tiles) + " tiles; waiting for the way to clear.", RouteNote::WARNING); + m_io.press(WAIT_FOR_THE_WAY); + const WalkResult rest = m_io.walk_taps(leg.direction, leg.tiles - moved, walk.label + ": the rest"); moved = std::min(leg.tiles, moved + rest.moved_chunks); walk.result.stop = rest.stop; walk.result.walked += rest.walked; @@ -571,7 +541,7 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ // stepped; r60 only turned but counted a tile, a column off below // Jubilife's Center). void RouteWalker::turn_tap(LegWalk& walk){ - route_turn(m_stream, m_context, walk.planned.leg.direction); + turn(m_io, walk.planned.leg.direction); walk.turn_moved = 0; } @@ -593,10 +563,9 @@ LegNext RouteWalker::blocked_open_leg(LegWalk& walk, size_t moved){ // walk did not end where the plan says. From tiles on several maps (a leg // not confirmed) the banner may already have shown. void RouteWalker::check_banners(LegWalk& walk){ - m_context.wait_for_all_requests(); - if (VideoSnapshot screen = m_stream.video().snapshot()){ - watch_banner(walk, *screen.frame); - } + m_io.look([&walk](const ImageViewRGB32& screen){ + watch_banner(walk, screen); + }); const std::string banner_text = quoted_list(walk.banners); m_all_banners.insert(m_all_banners.end(), walk.banners.begin(), walk.banners.end()); if (!walk.map_before.empty() && !walk.map_after.empty() && walk.map_after != walk.map_before && !banner_ok(walk)){ @@ -605,22 +574,21 @@ void RouteWalker::check_banners(LegWalk& walk){ // Go on and let the next step check where we are; a banner for another // map still fails. if (banner_text.empty()){ - m_stream.log("[Route] " + walk.label + ": no banner read for " + walk.map_after + "; going on.", COLOR_ORANGE); + m_io.note("[Route] " + walk.label + ": no banner read for " + walk.map_after + "; going on.", RouteNote::WARNING); return; } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + - (banner_text.empty() ? "nothing" : banner_text) + ".", m_stream); + fail(m_io, walk.label + ": expected to enter " + walk.map_after + ", but the location banner read " + + (banner_text.empty() ? "nothing" : banner_text) + "."); } if (!banner_text.empty()){ - m_stream.log("[Route] " + walk.label + ": location banner " + banner_text + "."); + m_io.note("[Route] " + walk.label + ": location banner " + banner_text + ".", RouteNote::LOG); } // Where each leg ended, to compare with the plan after a run. - if (VideoSnapshot screen = m_stream.video().snapshot()){ + m_io.look([&walk](const ImageViewRGB32& screen){ const std::string folder = SCREENSHOTS_PATH() + "AutoStory/route/"; Filesystem::create_directories(Filesystem::Path(folder)); - screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(walk.label) + ".png"); - } + screen.save(folder + now_to_filestring() + "-" + normalize_location_name(walk.label) + ".png"); + }); } // A trainer who sees us freezes the player and walks over; the dialogue @@ -634,13 +602,12 @@ LegNext RouteWalker::after_leg(LegWalk& walk){ const std::vector watching = watching_trainers(paths); bool talking = walk.result.stop == WalkStop::DIALOG; if (!talking){ - ShortDialogWatcher dialog(COLOR_YELLOW); const Milliseconds wait = watching.empty() ? 500ms : 4000ms; - talking = wait_until(m_stream, m_context, wait, {{dialog}}) == 0; + talking = m_io.dialog_within(wait, COLOR_YELLOW); } if (!talking){ m_from = walk.planned.after; - log_leg_done(m_stream, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); + log_leg_done(m_io, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); return LegNext::NEXT_LEG; } if (watching.empty()){ @@ -677,10 +644,9 @@ LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector 2){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - walk.label + ": dialogue the map does not explain stopped us 3 times.", m_stream); + fail(m_io, walk.label + ": dialogue the map does not explain stopped us 3 times."); } - route_status(m_stream, m_plan.label + ": a trainer the map lacks stopped us; fighting."); + m_io.note(m_plan.label + ": a trainer the map lacks stopped us; fighting.", RouteNote::STATUS); m_trainers.fight("unknown trainer"); if (walk.planned.leg.ends_at_wall){ on_to_wall(walk); @@ -707,11 +673,10 @@ LegNext RouteWalker::known_trainer(LegWalk& walk, const std::vector& } const TilePos blocker = stopped[0].next(walk.planned.leg.direction); m_grid.block(blocker); - m_stream.log("[Route] " + walk.label + ": something the map lacks is at " + - describe(m_maps, blocker) + "; marked it.", COLOR_ORANGE); + m_io.note("[Route] " + walk.label + ": something the map lacks is at " + + describe(m_maps, blocker) + "; marked it.", RouteNote::WARNING); } LegNext RouteWalker::replan_from(const LegWalk& walk, std::vector stopped, const std::string& why){ - m_stream.log(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.planned.leg), why, route_tiles(m_maps, stopped)), COLOR_ORANGE); + m_io.note(ROUTE_LOG_TAG + route_replan_line(m_plan.label, route_log_leg(walk.planned.leg), why, route_tiles(m_maps, stopped)), RouteNote::WARNING); m_facing = walk.planned.leg.direction; m_from = std::move(stopped); return LegNext::REPLAN; @@ -778,7 +742,15 @@ std::vector walk_route( const StoryWorld& maps, std::vector from, RouteTrainers& trainers, const RouteWalkPlan& plan ){ - return RouteWalker(stream, context, escape, maps, trainers, plan).run(std::move(from)); + ConsoleRouteIO io(stream, context, escape); + return walk_route(io, maps, std::move(from), trainers, plan); +} + +std::vector walk_route( + RouteIO& io, const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan +){ + return RouteWalker(io, maps, trainers, plan).run(std::move(from)); } std::vector walk_waypoints( @@ -803,13 +775,21 @@ void talk_to_npc( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const StoryWorld& maps, std::vector& at, RouteTrainers& trainers, const NpcTalk& talk +){ + ConsoleRouteIO io(stream, context, escape); + talk_to_npc(io, maps, at, trainers, talk); +} + +void talk_to_npc( + RouteIO& io, const StoryWorld& maps, std::vector& at, + RouteTrainers& trainers, const NpcTalk& talk ){ for (Direction side : talk.sides){ const TilePos stand = talk.npc.next(side); if (!standable(maps, stand)){ continue; } - at = walk_route(stream, context, escape, maps, at, trainers, { + at = walk_route(io, maps, at, trainers, { .goal = [stand](const TilePos& pos){ return pos == stand; }, .label = talk.label, .avoid = {}, @@ -820,18 +800,15 @@ void talk_to_npc( side == Direction::NORTH ? Direction::SOUTH : side == Direction::SOUTH ? Direction::NORTH : side == Direction::EAST ? Direction::WEST : Direction::EAST; - route_turn(stream, context, face); - pbf_press_button(context, BUTTON_A, 80ms, 200ms); - context.wait_for_all_requests(); - ShortDialogWatcher dialog(COLOR_CYAN); - if (wait_until(stream, context, 2000ms, {{dialog}}) == 0){ - route_status(stream, talk.label + ": talking from " + describe(maps, stand) + "."); + turn(io, face); + io.press(press_a(RouteInputEnd::DONE)); + if (io.dialog_within(2000ms, COLOR_CYAN)){ + io.note(talk.label + ": talking from " + describe(maps, stand) + ".", RouteNote::STATUS); return; } - route_status(stream, talk.label + ": nobody answered from " + describe(maps, stand) + "; trying another side."); + io.note(talk.label + ": nobody answered from " + describe(maps, stand) + "; trying another side.", RouteNote::STATUS); } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - talk.label + ": no side of " + describe(maps, talk.npc) + " started a dialogue.", stream); + fail(io, talk.label + ": no side of " + describe(maps, talk.npc) + " started a dialogue."); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 8577d82743..e422d6891c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -19,6 +19,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_RouteIO.h" #include "PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_Walk.h" @@ -64,6 +65,11 @@ std::vector walk_route( const StoryWorld& maps, std::vector from, RouteTrainers& trainers, const RouteWalkPlan& plan ); +// walk_route() through `io`. +std::vector walk_route( + RouteIO& io, const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan +); // The corners of a line a human walked, and the costs to plan each // stretch with. @@ -101,6 +107,11 @@ void talk_to_npc( const StoryWorld& maps, std::vector& at, RouteTrainers& trainers, const NpcTalk& talk ); +// talk_to_npc() through `io`. +void talk_to_npc( + RouteIO& io, const StoryWorld& maps, std::vector& at, + RouteTrainers& trainers, const NpcTalk& talk +); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp new file mode 100644 index 0000000000..37e6e3b06a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp @@ -0,0 +1,101 @@ +/* BDSP AutoStory - Route IO + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP_AutoStory_RouteIO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using namespace Pokemon; + + +namespace{ + +// Holding toward a wall with people or Pokemon moving beside us never reads +// as blocked (8 to 16 per 400 ms in the Oreburgh Mine, s03d1), but walking +// scrolls the view far more (35 to 90). True if holding toward (x, y) for +// 1.6 s changes the screen less than walking would: we stand at a wall. +bool holding_against_wall(VideoStream& stream, ProControllerContext& context, double x, double y, const std::string& label){ + constexpr double WALKING_CHANGE = 25.0; + context.wait_for_all_requests(); + VideoSnapshot before = stream.video().snapshot(); + double most = 0; + for (size_t chunk = 0; chunk < 4 && before; chunk++){ + pbf_move_left_joystick(context, {x, y}, 400ms, 0ms); + context.wait_for_all_requests(); + VideoSnapshot after = stream.video().snapshot(); + if (!after){ + return false; + } + most = std::max(most, walk_screen_change(*before.frame, *after.frame)); + before = std::move(after); + } + stream.log("[Walk] " + label + ": most screen change holding on " + std::to_string(most) + + (most < WALKING_CHANGE ? ", less than walking: at the wall." : ", as much as walking: still moving.")); + return before && most < WALKING_CHANGE; +} + +} + + +WalkResult ConsoleRouteIO::walk_to_wall(const RouteWallWalk& walk){ + return walk_until_dpad(m_stream, m_context, m_escape, route_stick(walk.direction), walk.limit, walk.label, walk.options); +} + +WalkResult ConsoleRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + return walk_tiles_dpad(m_stream, m_context, m_escape, route_stick(direction), tiles, label); +} + +void ConsoleRouteIO::press(const RouteInput& input){ + press_route_input(m_context, input); +} + +bool ConsoleRouteIO::dialog_within(Milliseconds wait, Color color){ + ShortDialogWatcher dialog(color); + return wait_until(m_stream, m_context, wait, {{dialog}}) == 0; +} + +bool ConsoleRouteIO::holding_against_wall(Direction direction, const std::string& label){ + const JoystickPosition stick = route_stick(direction); + return PokemonBDSP::holding_against_wall(m_stream, m_context, stick.x, stick.y, label); +} + +void ConsoleRouteIO::look(const std::function& at){ + m_context.wait_for_all_requests(); + if (VideoSnapshot screen = m_stream.video().snapshot()){ + at(*screen.frame); + } +} + +void ConsoleRouteIO::note(const std::string& text, RouteNote kind){ + switch (kind){ + case RouteNote::LOG: + m_stream.log(text); + return; + case RouteNote::WARNING: + m_stream.log(text, COLOR_ORANGE); + return; + case RouteNote::STATUS: + route_status(m_stream, text); + return; + case RouteNote::FAILURE: + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, text, m_stream); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h new file mode 100644 index 0000000000..1db4631068 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h @@ -0,0 +1,103 @@ +/* BDSP AutoStory - Route IO + * + * From: https://github.com/PokemonAutomation/ + * + * What the planned route walker (PlannedRoute) does on the console: walks, + * presses, screen reads and its log. The walker's decisions take a RouteIO, + * so tests can run them on a script of console outcomes; ConsoleRouteIO is + * the console. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteIO_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteIO_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A walk on the D-pad toward a wall: walk_until_dpad() toward `direction`. +struct RouteWallWalk{ + Pokemon::Direction direction; + Milliseconds limit; + std::string label; + DpadWalkOptions options; +}; + +// How a line goes to the log. +enum class RouteNote{ + LOG, + WARNING, // in orange + STATUS, // route_status(): also on the video overlay + FAILURE, // fails the program with a screenshot; does not return +}; + +class RouteIO{ +public: + virtual ~RouteIO() = default; + + // Holds the D-pad toward a wall (walk_until_dpad()). + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) = 0; + + // Taps `tiles` whole tiles toward `direction` (walk_tiles_dpad()). + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) = 0; + + // Presses or waits (press_route_input()). + virtual void press(const RouteInput& input) = 0; + + // Whether a dialogue box shows within `wait`. + virtual bool dialog_within(Milliseconds wait, Color color) = 0; + + // Holds the stick toward `direction` for 1.6 s, and returns whether the + // screen changed less than walking would: we stand at a wall. + virtual bool holding_against_wall(Pokemon::Direction direction, const std::string& label) = 0; + + // Once the presses so far are done, shows `at` the screen, if there is one. + virtual void look(const std::function& at) = 0; + + // Writes `text` to the log; a FAILURE fails the program. + virtual void note(const std::string& text, RouteNote kind) = 0; +}; + + +// The console: today's walker steps, unchanged. +class ConsoleRouteIO : public RouteIO{ +public: + ConsoleRouteIO(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape) + : m_stream(stream) + , m_context(context) + , m_escape(escape) + {} + + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual void press(const RouteInput& input) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + virtual bool holding_against_wall(Pokemon::Direction direction, const std::string& label) override; + virtual void look(const std::function& at) override; + virtual void note(const std::string& text, RouteNote kind) override; + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + const WildBattleEscape& m_escape; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index bfc9160262..cbd3f3c2d4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -79,14 +79,44 @@ Milliseconds route_open_hold(Direction direction, size_t tiles){ return step * tiles - step / 2; } -void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ - stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); +void press_route_input(ProControllerContext& context, const RouteInput& input){ + const Direction direction = input.direction; const DpadPosition dpad = direction == Direction::NORTH ? DPAD_UP : direction == Direction::SOUTH ? DPAD_DOWN : direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; - pbf_press_dpad(context, dpad, ROUTE_TURN_TAP, 300ms); - context.wait_for_all_requests(); + for (size_t press = 0; press < input.count; press++){ + switch (input.kind){ + case RouteInputKind::DPAD: + pbf_press_dpad(context, dpad, input.hold, input.release); + break; + case RouteInputKind::STICK: + pbf_move_left_joystick(context, route_stick(direction), input.hold, input.release); + break; + case RouteInputKind::BUTTON_A: + pbf_press_button(context, BUTTON_A, input.hold, input.release); + break; + case RouteInputKind::WAIT: + pbf_wait(context, input.hold); + break; + case RouteInputKind::PAUSE: + context.wait_for(input.hold); + break; + } + } + if (input.end == RouteInputEnd::DONE){ + context.wait_for_all_requests(); + } +} + +RouteInput route_turn_tap(Direction direction){ + return {.kind = RouteInputKind::DPAD, .direction = direction, .hold = ROUTE_TURN_TAP, .release = 300ms, + .count = 1, .end = RouteInputEnd::DONE}; +} + +void route_turn(VideoStream& stream, ProControllerContext& context, Direction direction){ + stream.log(std::string("[Route] Turning ") + direction_name(direction) + "."); + press_route_input(context, route_turn_tap(direction)); } std::optional talk_to_adjacent_npc( diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index 1568e5ae26..ea46031644 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -68,6 +68,34 @@ Milliseconds route_open_hold(Pokemon::Direction direction, size_t tiles); // Sandgem's Center door; r248a). constexpr Milliseconds ROUTE_TURN_TAP = Milliseconds(50); +// What a RouteInput presses. +enum class RouteInputKind{ + DPAD, // the D-pad toward `direction`: whole tiles + STICK, // the left stick toward `direction`: any distance + BUTTON_A, + WAIT, // nothing, for `hold`, after what is already queued + PAUSE, // nothing, for `hold` from now (ControllerContext::wait_for()) +}; +// Whether press_route_input() returns once the presses are done, or at once. +enum class RouteInputEnd{ + DONE, + QUEUED, +}; +// A short press, `count` times: held for `hold`, then let go for `release`. +// `direction` is for DPAD and STICK only. +struct RouteInput{ + RouteInputKind kind; + Pokemon::Direction direction; + Milliseconds hold; + Milliseconds release; + size_t count; + RouteInputEnd end; +}; +void press_route_input(ProControllerContext& context, const RouteInput& input); + +// The tap route_turn() turns with: on the D-pad, ROUTE_TURN_TAP long. +RouteInput route_turn_tap(Pokemon::Direction direction); + // Turns the player to face `direction` without moving. Only for a player who // faces another way: one already facing it may take a step. void route_turn(VideoStream& stream, ProControllerContext& context, Pokemon::Direction direction); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 4c4e69c4f8..801fa55772 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1659,6 +1659,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp From e8a5efc8b32e6ccc49c628700d7b68d8b229f03b Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 00:25:04 -0800 Subject: [PATCH 47/74] BDSP AutoStory walk: test the route walker on scripted console outcomes ScriptedRouteIO plays a strict script of console calls and outcomes; a call the script does not expect fails the test. New tests: - A trainer's line freezes the at-the-wall check (DIALOG), the battle runs, and the walk on reaches the wall (BLOCKED): the walker goes on (r54: it judged the stale DIALOG and failed). - Logan (Route 202, (26, 4), looking south) stops an open leg west along row 5 after 3 taps: the replan starts from (27, 5) and (26, 5), and its legs never walk into him from either (r55). - A wall leg out of time whose check also runs out of time counts as at the wall only when the holding check says so. - route_turn() turns with one D-pad tap of at most 80 ms (40 to 80 ms only turned on the console; a 100 ms stick tap stepped 0.6 tile). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 385 ++++++++++++++++++ ...PokemonBDSP_AutoStory_PlannedRoute_Tests.h | 28 ++ .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 32 ++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 5 files changed, 449 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 60409b4a26..145096b969 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -6,6 +6,7 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" @@ -26,6 +27,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_StoryMaps(database); add_tests_AutoStory_Segment00(database); add_tests_AutoStory_Walk(database); + add_tests_AutoStory_PlannedRoute(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp new file mode 100644 index 0000000000..ac87afdcc7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -0,0 +1,385 @@ +/* BDSP AutoStory Planned Route Tests + * + * From: https://github.com/PokemonAutomation/ + * + * walk_route() (Utils/PokemonBDSP_AutoStory_PlannedRoute.h) on a script + * of console outcomes: each case lists the walks, presses and screen reads + * the walker must make, in order, and what the console answers. A call the + * script does not expect fails the case. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "Utils/PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP_AutoStory_PlannedRoute_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TilePos; + + +// One call the walker is expected to make, and what the console answers: +// `walk` for a walk, `answer` for a dialogue watch or the holding check. +struct ScriptStep{ + std::string call; + WalkResult walk; + bool answer; +}; + +ScriptStep walk_step(std::string call, WalkStop stop, Milliseconds walked, size_t moved){ + return {.call = std::move(call), .walk = {.stop = stop, .walked = walked, .wild_battles = 0, .moved_chunks = moved}, .answer = false}; +} +ScriptStep answer_step(std::string call, bool answer){ + return {.call = std::move(call), .walk = {.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}, .answer = answer}; +} +ScriptStep press_step(std::string call){ + return answer_step(std::move(call), false); +} + +// What the console did on a scripted walk: the steps called so far, every +// line logged, and the legs walked (to a wall, or a number of taps). +struct Script{ + std::vector steps; + size_t next = 0; + std::vector notes = {}; + std::vector legs = {}; +}; + +// Thrown by ScriptedRouteIO: a call the script did not expect, or the +// walker failing the program. +struct ScriptMismatch{ + std::string message; +}; +struct RouteFailed{ + std::string message; +}; + +std::string describe(const RouteInput& input){ + const char* kind = + input.kind == RouteInputKind::DPAD ? "D-pad" : + input.kind == RouteInputKind::STICK ? "stick" : + input.kind == RouteInputKind::BUTTON_A ? "A" : + input.kind == RouteInputKind::WAIT ? "wait" : "pause"; + const bool directed = input.kind == RouteInputKind::DPAD || input.kind == RouteInputKind::STICK; + return std::format("{}{}{} {} ms x{}", kind, directed ? " " : "", directed ? Pokemon::direction_name(input.direction) : "", + input.hold.count(), input.count); +} + +// The console as a script: each call must be the script's next step. +// look() sees no screen. +class ScriptedRouteIO : public RouteIO{ +public: + explicit ScriptedRouteIO(Script& script) + : m_script(script) + {} + + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + m_script.legs.push_back({.direction = walk.direction, .tiles = 0, .ends_at_wall = true}); + return expect("wall: " + walk.label).walk; + } + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + m_script.legs.push_back({.direction = direction, .tiles = tiles, .ends_at_wall = false}); + return expect(std::format("{} taps: {}", tiles, label)).walk; + } + virtual void press(const RouteInput& input) override{ + expect(describe(input)); + } + virtual bool dialog_within(Milliseconds wait, Color) override{ + return expect(std::format("dialog within {} ms", wait.count())).answer; + } + virtual bool holding_against_wall(Direction direction, const std::string&) override{ + return expect(std::string("holding ") + Pokemon::direction_name(direction)).answer; + } + virtual void look(const std::function&) override{} + virtual void note(const std::string& text, RouteNote kind) override{ + m_script.notes.push_back(text); + if (kind == RouteNote::FAILURE){ + throw RouteFailed{text}; + } + } + +private: + const ScriptStep& expect(const std::string& call){ + if (m_script.next >= m_script.steps.size()){ + throw ScriptMismatch{"a call after the script's end: \"" + call + "\""}; + } + const ScriptStep& step = m_script.steps[m_script.next++]; + if (step.call != call){ + throw ScriptMismatch{std::format("step {}: expected \"{}\", got \"{}\"", m_script.next, step.call, call)}; + } + return step; + } + + Script& m_script; +}; + + +// How a scripted walk ended: where it arrived, or why it failed. +struct ScriptedWalk{ + std::vector at; + std::string failure; + std::vector fights; +}; + +ScriptedWalk walk_script(const StoryWorld& maps, const TilePos& from, const TilePos& goal, std::vector sights, Script& script){ + ScriptedWalk out; + RouteTrainers trainers{ + .sights = std::move(sights), + .fight = [&out](const std::string& trainer){ out.fights.push_back(trainer); }, + }; + ScriptedRouteIO io(script); + try{ + out.at = walk_route(io, maps, {from}, trainers, { + .goal = [goal](const TilePos& pos){ return pos == goal; }, + .label = "T", + .avoid = {}, + .costs = route_plan_costs(), + .speed = MoveSpeed::WALK, + }); + }catch (const RouteFailed& e){ + out.failure = e.message; + } + return out; +} + +// The script's calls all made, or which are left. +std::string script_left(const Script& script){ + if (script.next == script.steps.size()){ + return ""; + } + return std::format("{} of {} steps called; next \"{}\".", script.next, script.steps.size(), script.steps[script.next].call); +} + +StoryWorld make_world(const std::vector& rows){ + Pokemon::MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + + +// r54: a trainer's line froze the check walk at a leg's wall; after the +// battle the walk on reached the wall, but the check still judged the +// frozen walk's DIALOG and failed. The walk on is what counts. +class Test_WallLegTrainerOnTheWay : public UnitTest{ +public: + Test_WallLegTrainerOnTheWay() + : UnitTest("PokemonBDSP::AutoStory - Planned route: a trainer on a wall leg, then on to the wall") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + Script script{.steps = { + walk_step("wall: T: east 4 (to wall)", WalkStop::LIMIT, 2050ms, 0), + walk_step("wall: T: east 4 (to wall): at the wall?", WalkStop::DIALOG, 400ms, 0), + walk_step("wall: T: east 4 (to wall): on to the wall", WalkStop::BLOCKED, 1200ms, 0), + answer_step("dialog within 500 ms", false), + }}; + try{ + const ScriptedWalk walk = walk_script(make_world({"#.....#"}), {1, 0}, {5, 0}, {}, script); + if (!walk.failure.empty()){ + return "failed after the walk on reached the wall: " + walk.failure; + } + if (walk.fights != std::vector{"a trainer on the way"}){ + return std::format("fought {} times, expected once.", walk.fights.size()); + } + if (walk.at != std::vector{{5, 0}}){ + return "did not arrive at (5, 0)."; + } + }catch (const ScriptMismatch& e){ + return e.message; + } + const std::string left = script_left(script); + return left.empty() ? UnitTestResult(true) : UnitTestResult(left); + } +}; + + +// A leg to a wall that ran out of time: a check walk that also runs out +// of time counts as at the wall only if holding on there changes the +// screen less than walking (r127a ran along the wrong row). +struct WallCheckCase{ + std::string name; + std::vector check; + bool fails; +}; + +class Test_WallLegLimit : public UnitTest{ +public: + Test_WallLegLimit() + : UnitTest("PokemonBDSP::AutoStory - Planned route: a wall leg out of time needs the holding check") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::vector cases{ + {.name = "the check stops at the wall", .check = { + walk_step("wall: T: east 4 (to wall): at the wall?", WalkStop::BLOCKED, 1050ms, 0), + answer_step("dialog within 500 ms", false), + }, .fails = false}, + {.name = "the check runs out of time, holding on reads a wall", .check = { + walk_step("wall: T: east 4 (to wall): at the wall?", WalkStop::LIMIT, 2000ms, 0), + answer_step("holding east", true), + answer_step("dialog within 500 ms", false), + }, .fails = false}, + {.name = "the check runs out of time, holding on still moves", .check = { + walk_step("wall: T: east 4 (to wall): at the wall?", WalkStop::LIMIT, 2000ms, 0), + answer_step("holding east", false), + }, .fails = true}, + }; + for (const WallCheckCase& item : cases){ + Script script{.steps = {walk_step("wall: T: east 4 (to wall)", WalkStop::LIMIT, 2050ms, 0)}}; + script.steps.insert(script.steps.end(), item.check.begin(), item.check.end()); + try{ + const ScriptedWalk walk = walk_script(make_world({"#.....#"}), {1, 0}, {5, 0}, {}, script); + if (walk.failure.empty() == item.fails){ + return item.name + (item.fails ? ": went on as at the wall." : ": failed: " + walk.failure); + } + }catch (const ScriptMismatch& e){ + return item.name + ": " + e.message; + } + const std::string left = script_left(script); + if (!left.empty()){ + return item.name + ": " + left; + } + } + return true; + } +}; + + +// Whether walking `legs` from `from` ever steps into `person`'s tile: a +// leg to a wall that stops against them, or a tap toward them. +bool walks_into(const StoryWorld& world, TilePos from, const std::vector& legs, const TilePos& person){ + for (const TileLeg& leg : legs){ + for (size_t tap = 0; leg.ends_at_wall || tap < leg.tiles; tap++){ + if (from.next(leg.direction) == person){ + return true; + } + const std::optional next = step(world, from, leg.direction); + if (!next){ + break; + } + from = *next; + } + } + return false; +} + +// Route 202 alone, at its own tiles, and Logan's sight: he stands at +// (26, 4) and looks south. +StoryWorld route202_world(){ + StoryWorld world; + world.add("Route 202", story_map("Route202"), {0, 0}); + return world; +} +std::vector logan_sight(){ + std::vector sights; + for (const TrainerSight& sight : route202_trainer_sights()){ + if (sight.name == "logan"){ + sights.push_back(sight); + } + } + return sights; +} + +// Whether the replan after the battle starts from each of `tiles`. +std::string check_replan_from(const Script& script, const std::vector& tiles){ + const auto replan = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("planning again") != std::string::npos; + }); + if (replan == script.notes.end()){ + return "never planned again after the battle."; + } + for (const std::string& tile : tiles){ + if (replan->find(tile) == std::string::npos){ + return "the replan does not start from " + tile + ": " + *replan; + } + } + return ""; +} + +// r55: Logan (Route 202, (26, 4), looking south) stopped an open leg west +// along row 5. "5 taps" were 4, under his nose at (26, 5); the replan from +// the tap count alone walked into him. The replan must start from both the +// tile the taps give and the tile where the leg enters his sight, and walk +// on from either without bumping into him. +class Test_OpenLegKnownTrainer : public UnitTest{ +public: + Test_OpenLegKnownTrainer() + : UnitTest("PokemonBDSP::AutoStory - Planned route: a known trainer stops an open leg") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StoryWorld world = route202_world(); + // West along row 5 from (30, 5) to (24, 5): his line is the 4th tap, + // and his dialogue comes after 3 taps that moved. + Script script{.steps = { + press_step("D-pad west 50 ms x1"), + walk_step("6 taps: T: west 6 (open)", WalkStop::DIALOG, 1500ms, 3), + walk_step("wall: T: east 4 (to wall)", WalkStop::BLOCKED, 2000ms, 0), + answer_step("dialog within 500 ms", false), + press_step("D-pad west 50 ms x1"), + walk_step("6 taps: T: west 6 (open)", WalkStop::LIMIT, 1500ms, 6), + answer_step("dialog within 500 ms", false), + }}; + ScriptedWalk walk; + try{ + walk = walk_script(world, {30, 5}, {24, 5}, logan_sight(), script); + }catch (const ScriptMismatch& e){ + return e.message; + } + if (!walk.failure.empty() || walk.fights != std::vector{"logan"}){ + return std::format("expected to fight Logan once and go on; fought {}, failure \"{}\".", walk.fights.size(), walk.failure); + } + // The taps say (27, 5); his sight line crosses the row at (26, 5). + const std::string replan = check_replan_from(script, {"Route 202 (27, 5)", "Route 202 (26, 5)"}); + if (!replan.empty()){ + return replan; + } + const std::vector after_battle(script.legs.begin() + 1, script.legs.end()); + const TilePos logan = map_point("Route202", "trainer_logan"); + for (const TilePos& from : {TilePos{27, 5}, TilePos{26, 5}}){ + if (walks_into(world, from, after_battle, logan)){ + return "the replan walks into Logan from " + Pokemon::to_string(from) + "."; + } + } + if (walk.at != std::vector{{24, 5}}){ + return "did not arrive at (24, 5)."; + } + const std::string left = script_left(script); + return left.empty() ? UnitTestResult(true) : UnitTestResult(left); + } +}; + +} + + +void add_tests_AutoStory_PlannedRoute(UnitTestDatabase& database){ + database.add(); + database.add(); + database.add(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h new file mode 100644 index 0000000000..13331b8db4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory Planned Route Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_PlannedRoute_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// walk_route() on a script of console outcomes (a ScriptedRouteIO): what +// the walker does after a trainer stops a leg, and when a leg to a wall +// counts as at its wall. +void add_tests_AutoStory_PlannedRoute(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index 9357b6cee2..c38ff46daf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -23,6 +23,37 @@ namespace PokemonBDSP{ namespace{ +// A turn must not step: on the console D-pad taps of 40 to 80 ms only +// turned, a 160 ms D-pad tap stepped a whole tile, and a 100 ms stick tap +// stepped about 0.6 tile, off the tile grid (r49, r248a). So route_turn() +// taps the D-pad, once, for at most 80 ms. +class Test_RouteTurnTap : public UnitTest{ +public: + Test_RouteTurnTap() + : UnitTest("PokemonBDSP::AutoStory - a turn is a D-pad tap too short to step") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + constexpr Milliseconds LONGEST_TURN(80); + for (Pokemon::Direction direction : {Pokemon::Direction::NORTH, Pokemon::Direction::SOUTH, Pokemon::Direction::EAST, Pokemon::Direction::WEST}){ + const RouteInput tap = route_turn_tap(direction); + const std::string name = std::string("turning ") + Pokemon::direction_name(direction); + if (tap.kind != RouteInputKind::DPAD){ + return name + ": not a D-pad tap; a stick tap moves part of a tile."; + } + if (tap.direction != direction || tap.count != 1){ + return name + ": expected one tap that way."; + } + if (tap.hold > LONGEST_TURN){ + return name + ": a " + std::to_string(tap.hold.count()) + " ms tap; over 80 ms may step."; + } + } + if (ROUTE_TURN_TAP > LONGEST_TURN){ + return "ROUTE_TURN_TAP is " + std::to_string(ROUTE_TURN_TAP.count()) + " ms; over 80 ms may step."; + } + return true; + } +}; + // indoors() decides when leave_door_south() is out: r257 walked on south // past Sandgem's road into a house after leaving the Center, because the // evening tint made the outside as warm as a room. Synthetic screens: the @@ -211,6 +242,7 @@ class Test_LocationBannerShowing : public UnitTest{ void add_tests_AutoStory_Walk(UnitTestDatabase& database){ + database.add(); database.add(); database.add(); database.add(); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 801fa55772..4ff2eeeaf0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1641,6 +1641,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp From 8a4342ff0ac23bda3b86a721751f46e974f03812 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 01:57:46 -0800 Subject: [PATCH 48/74] BDSP AutoStory walk: a quiet tap followed by a moving one counted as a step A tap whose view barely changed (the president walking off as we turned) was counted as not moving, so "east 2" read "moved 1" while the console showed both tiles walked (r67). What blocks one tap still blocks the next, so a quiet tap that a moving tap follows moved too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index f4066a9ed7..53d7a461e0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -329,7 +329,11 @@ class WalkUntil{ } const bool still = still_chunk(change); if (!still){ - m_result.moved_chunks++; + // A quiet tap and then a moving one: the first moved too. What + // blocks a tap still blocks the next; the view barely changed + // while the president walked off (r67: "east 2 moved 1", and + // the console showed both tiles walked). + m_result.moved_chunks += 1 + (m_spec.input == WalkInput::TAPS ? m_unchanged : 0); } m_unchanged = still ? m_unchanged + 1 : 0; if (m_unchanged >= 2){ From cc0bd03f76c7f45abd95c496706c65dfa15c917c Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 07:16:21 -0800 Subject: [PATCH 49/74] BDSP maps: read a warp's destination from MapData's optional `to` nav/shared made a warp's destination optional (left out for a map not loaded). Every BDSP warp still has to lead to a point that exists. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp index b242068168..df0a559e8e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp @@ -202,8 +202,11 @@ class Test_StoryMapPoints : public UnitTest{ checked++; } for (const Pokemon::MapWarp& warp : map.warps){ + if (!warp.to){ + return std::format("{}: the warp at {} leads nowhere.", name, Pokemon::to_string(TilePos{warp.x, warp.y})); + } try{ - map_point(warp.to_map, warp.to_point); + map_point(warp.to->map, warp.to->point); }catch (InternalProgramError& e){ return std::format("{}: the warp at {}: {}", name, Pokemon::to_string(TilePos{warp.x, warp.y}), e.message()); } From d5c17a055158b4991fec5effb1a4b5962900248d Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 07:17:20 -0800 Subject: [PATCH 50/74] BDSP navigation: build against the new MapData tile kinds and fields nav/shared added the tile kinds OUTSIDE and CLOSED_*, renamed WanderBox to TileBox and gave MapObject trainer and hide_flag. None of the new kinds is a ledge; BDSP maps don't use their glyphs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 5 +++++ .../AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index df99467c0f..9ae90edb75 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -37,6 +37,11 @@ std::optional ledge_direction(TileKind tile){ case TileKind::WATER: case TileKind::DOOR: case TileKind::SIGN: + case TileKind::OUTSIDE: + case TileKind::CLOSED_NORTH: + case TileKind::CLOSED_SOUTH: + case TileKind::CLOSED_WEST: + case TileKind::CLOSED_EAST: return std::nullopt; } throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown TileKind."); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp index 3531d72fd9..d297d2be99 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -46,12 +46,14 @@ MapData make_map( map.objects.push_back({ .name = "standing", .kind = Pokemon::ObjectKind::NPC, .x = pos.x, .y = pos.y, .facing = std::nullopt, .wander = std::nullopt, + .trainer = std::nullopt, .hide_flag = std::nullopt, }); } for (const TilePos& pos : wandering){ map.objects.push_back({ .name = "wandering", .kind = Pokemon::ObjectKind::NPC, .x = pos.x, .y = pos.y, - .facing = std::nullopt, .wander = Pokemon::WanderBox{pos.x, pos.y, pos.x, pos.y}, + .facing = std::nullopt, .wander = Pokemon::TileBox{pos.x, pos.y, pos.x, pos.y}, + .trainer = std::nullopt, .hide_flag = std::nullopt, }); } return map; From cc669ea7077ccfe12df1eae805d54be8d20fc250 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 06:46:29 -0800 Subject: [PATCH 51/74] BDSP maps: list every cell a map's rectangle touches in its source The cell list stepped 32 tiles from the rectangle's corner, so a rectangle not starting on a cell edge missed its last cell: Route203.json named narc_0016 and narc_0019 but not narc_0020. Its tiles are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E (cherry picked from commit 6517171a9d87b0d6db1d2436932cc73e364c81b2) --- .../PokemonBDSP/Programs/AutoStory/Maps/Route203.json | 2 +- devtools/maps/bdsp_maps.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json index 88f443c610..2e3c409907 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json @@ -1,6 +1,6 @@ { "name": "Route203", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0019.bin; zone_event narc_0329", "revision": "default branch", "date": "2026-10-31"}, + "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0019.bin, files/fielddata/land_data/land_data_release/narc_0020.bin; zone_event narc_0329", "revision": "default branch", "date": "2026-10-31"}, "tiles": [ "#############################################################", "#############################################################", diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py index 01e01b1ebc..4e027f0a28 100644 --- a/devtools/maps/bdsp_maps.py +++ b/devtools/maps/bdsp_maps.py @@ -517,8 +517,10 @@ def decode_map(name): for x, tile in enumerate(row): if tile == 'W': row[x] = 'D' if (x, y) in doors else '.' - lands = sorted({world.land_id(x, z) for z in range(z0, z0 + height, decomp.CELL) - for x in range(x0, x0 + width, decomp.CELL)} - {None}) + # Every cell the rectangle touches, also when it does not start on a cell's edge. + C = decomp.CELL + lands = sorted({world.land_id(C * col, C * row) for row in range(z0 // C, (z0 + height - 1) // C + 1) + for col in range(x0 // C, (x0 + width - 1) // C + 1)} - {None}) unverified = '; decomp only, not checked on the console' if spec.get('unverified') else '' source = { 'decomp_file': f'{repo}: ' + ', '.join(game.land_path(land) for land in lands) From 5d6015237f53a195311d18f1c8a8f1c536a416d4 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 07:11:13 -0800 Subject: [PATCH 52/74] BDSP maps: PlayerHouse1F and Route201's console fixes as generator patches Both files had their console measurements (r32's open tile in the house, r16's trees and sign on Route 201) edited into the tiles by hand, so bdsp_maps.py --check failed for them. The generator's PATCHES table now holds them; the tiles go back to the decomp's and the loader applies the patches, so the walked grid is unchanged. --check passes for all 21 maps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E (cherry picked from commit 1f14bca446c165429b75a809098c0a5fefc81589) --- .../Programs/AutoStory/Maps/PlayerHouse1F.json | 7 +++++-- .../Programs/AutoStory/Maps/Route201.json | 9 +++++++++ devtools/maps/bdsp_maps.py | 12 ++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json index 2a7a89546d..a97ce8bbc3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json @@ -1,6 +1,6 @@ { "name": "PlayerHouse1F", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp, but (4, 8) is open on the console: west along row 8 stops at x 4 (r32, 2026-11-01)", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, "tiles": [ "#############", "#############", @@ -10,7 +10,7 @@ "#SSS..SS....#", "#...........#", "#...........#", - "#..#........#", + "#..##.......#", "##.##......##", "##....D....##", "#############" @@ -25,5 +25,8 @@ ], "objects": [ {"name": "mom_0", "kind": "npc", "x": 7, "y": 8, "facing": "north"} + ], + "patches": [ + {"x": 4, "y": 8, "glyph": ".", "measured_by": "r32, 2026-11-01"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json index 88f0b99f7e..91ba7195f7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json @@ -42,5 +42,14 @@ {"name": "pokemon_breeder_m_0", "kind": "npc", "x": 27, "y": 15, "wander": {"x0": 26, "y0": 14, "x1": 28, "y1": 16}}, {"name": "school_kid_m_9", "kind": "npc", "x": 57, "y": 8, "facing": "west"}, {"name": "lass_11", "kind": "npc", "x": 46, "y": 16, "wander": {"x0": 44, "y0": 16, "x1": 48, "y1": 16}} + ], + "patches": [ + {"x": 8, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"x": 9, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"x": 10, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"x": 11, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"x": 12, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"x": 13, "y": 18, "glyph": "S", "measured_by": "r16, 2026-10-31"}, + {"x": 13, "y": 17, "glyph": ".", "measured_by": "r16, 2026-10-31"} ] } diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py index 4e027f0a28..4a12ed05b0 100644 --- a/devtools/maps/bdsp_maps.py +++ b/devtools/maps/bdsp_maps.py @@ -421,6 +421,18 @@ def box(x0, y0, x1, y1): # was blocked at once. + [(21, 30, '#', 'r254, 2026-11-01')] ), + 'PlayerHouse1F': [ + # Open on the console, a wall in the data: west along row 8 stops + # at x 4 (r32). + (4, 8, '.', 'r32, 2026-11-01'), + ], + 'Route201': ( + # Row 18 west of the exit path is trees on the console, open in the + # decomp, and the 201 sign stands at (13, 18), not (13, 17) (r16, + # walked by hand). + [(x, 18, '#', 'r16, 2026-10-31') for x in range(8, 13)] + + [(13, 18, 'S', 'r16, 2026-10-31'), (13, 17, '.', 'r16, 2026-10-31')] + ), 'Route204North': [ # Grass in the data, blocked on the console twice. (12, 6, '#', 'r248a, 2026-10-31'), From 45144bf3521542b6cefef93c14769feee336e7ae Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 10:19:36 -0800 Subject: [PATCH 53/74] BDSP maps: write each map's coord events from the decomp Each map JSON now lists its events file's coord events (the scene triggers) under "coord_events": local box, story variable and value, and a source naming the file, index, world tile and script. Diamond's events files carry them after the warps; their variable numbers are named from pokeplatinum's generated/vars_flags.txt, which agrees with Platinum's own events on every trigger both games have. The five interiors read pokeplatinum's JSON. COORD_EVENTS names the triggers the story uses and adds Mom's call (6, 9) in the player's house, found on the console (r45, r46), so hand-measured triggers survive regeneration. The shared map loader ignores the key. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Programs/AutoStory/Maps/FloaromaTown.json | 3 + .../Programs/AutoStory/Maps/JubilifeCity.json | 7 ++ .../Programs/AutoStory/Maps/OreburghCity.json | 4 ++ .../Programs/AutoStory/Maps/OreburghGate.json | 3 + .../AutoStory/Maps/PlayerHouse1F.json | 4 ++ .../AutoStory/Maps/PlayerHouse2F.json | 8 ++- .../Programs/AutoStory/Maps/Route201.json | 5 ++ .../Programs/AutoStory/Maps/Route202.json | 3 + .../Programs/AutoStory/Maps/Route203.json | 3 + .../Programs/AutoStory/Maps/SandgemTown.json | 3 + .../Programs/AutoStory/Maps/TwinleafTown.json | 4 ++ .../AutoStory/Maps/VerityLakefront.json | 6 +- devtools/maps/bdsp_maps.py | 66 +++++++++++++++-- devtools/maps/decomp.py | 71 +++++++++++++++++-- devtools/maps/tests/test_decomp.py | 58 ++++++++++++++- 15 files changed, 235 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json index db9cf8a5df..f6f6bfd349 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json @@ -52,5 +52,8 @@ {"name": "camper_12", "kind": "npc", "x": 6, "y": 10}, {"name": "old_woman", "kind": "npc", "x": 3, "y": 25}, {"name": "old_man", "kind": "npc", "x": 2, "y": 25} + ], + "coord_events": [ + {"name": "coord_event_0", "x": 10, "y": 29, "width": 3, "length": 1, "var": "VAR_UNK_0x4072", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0404.bin coord_events[0] (170, 669), script 2"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json index 71aed1d875..4f28c563a9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json @@ -135,5 +135,12 @@ {"name": "clown_tv_station", "kind": "npc", "x": 36, "y": 16}, {"name": "kid_with_nds_29", "kind": "npc", "x": 52, "y": 46}, {"name": "kid_with_nds_30", "kind": "npc", "x": 54, "y": 46} + ], + "coord_events": [ + {"name": "dawn_at_the_steps", "x": 45, "y": 60, "width": 4, "length": 1, "var": "VAR_JUBILIFE_CITY_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[0] (173, 796), script 2"}, + {"name": "coord_event_1", "x": 45, "y": 7, "width": 3, "length": 1, "var": "VAR_JUBILIFE_CITY_STATE", "value": 3, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[1] (173, 743), script 4"}, + {"name": "coord_event_2", "x": 60, "y": 21, "width": 1, "length": 4, "var": "VAR_JUBILIFE_CITY_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[2] (188, 757), script 3"}, + {"name": "coord_event_3", "x": 27, "y": 43, "width": 1, "length": 3, "var": "VAR_GTS_ACCESS_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[3] (155, 779), script 19"}, + {"name": "poketch_president", "x": 44, "y": 40, "width": 5, "length": 1, "var": "VAR_POKETCH_CAMPAIGN_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[4] (172, 776), script 17"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json index 4cdef2c0b0..0043b0bea2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json @@ -87,5 +87,9 @@ {"name": "guitarist_20", "kind": "npc", "x": 23, "y": 13, "wander": {"x0": 22, "y0": 10, "x1": 24, "y1": 16}}, {"name": "battle_girl_21", "kind": "npc", "x": 36, "y": 23, "wander": {"x0": 36, "y0": 21, "x1": 36, "y1": 25}}, {"name": "machop_22", "kind": "npc", "x": 55, "y": 56, "wander": {"x0": 53, "y0": 54, "x1": 57, "y1": 58}} + ], + "coord_events": [ + {"name": "coord_event_0", "x": 10, "y": 12, "width": 1, "length": 4, "var": "VAR_OREBURGH_CITY_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[0] (266, 748), script 3"}, + {"name": "coord_event_1", "x": 6, "y": 12, "width": 1, "length": 4, "var": "VAR_OREBURGH_CITY_STATE", "value": 2, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[1] (262, 748), script 4"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json index 14c30e35f5..f3f6b5a73b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json @@ -39,5 +39,8 @@ {"name": "picnicker_0", "kind": "npc", "x": 24, "y": 21, "facing": "south"}, {"name": "camper_1", "kind": "npc", "x": 17, "y": 25, "facing": "north"}, {"name": "hiker_10", "kind": "npc", "x": 7, "y": 20, "facing": "south"} + ], + "coord_events": [ + {"name": "coord_event_0", "x": 7, "y": 22, "width": 1, "length": 1, "var": "VAR_OREBURGH_GATE_1F_HIKER_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0250.bin coord_events[0] (7, 22), script 3"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json index a97ce8bbc3..c959a1a426 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json @@ -26,6 +26,10 @@ "objects": [ {"name": "mom_0", "kind": "npc", "x": 7, "y": 8, "facing": "north"} ], + "coord_events": [ + {"name": "moms_warning", "x": 6, "y": 10, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_STATE", "value": 1, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_1f.json coord_events[0] (6, 10), script 5"}, + {"name": "moms_call", "x": 6, "y": 9, "width": 1, "length": 1, "var": "CONSOLE_MOMS_CALL", "value": 0, "source": "console r45, r46 (2026-11-01): after her heal Mom calls us back as we step above the door; no coord event in the decomp"} + ], "patches": [ {"x": 4, "y": 8, "glyph": ".", "measured_by": "r32, 2026-11-01"} ] diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json index a33faa27b9..c78c817c70 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json @@ -18,5 +18,11 @@ "points": { "stairs": [8, 4], "start": [4, 6] - } + }, + "coord_events": [ + {"name": "coord_event_0", "x": 4, "y": 5, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[0] (4, 5), script 7"}, + {"name": "coord_event_1", "x": 3, "y": 6, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[1] (3, 6), script 8"}, + {"name": "coord_event_2", "x": 5, "y": 6, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[2] (5, 6), script 9"}, + {"name": "coord_event_3", "x": 4, "y": 7, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[3] (4, 7), script 10"} + ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json index 91ba7195f7..fe88167472 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json @@ -43,6 +43,11 @@ {"name": "school_kid_m_9", "kind": "npc", "x": 57, "y": 8, "facing": "west"}, {"name": "lass_11", "kind": "npc", "x": 46, "y": 16, "wander": {"x0": 44, "y0": 16, "x1": 48, "y1": 16}} ], + "coord_events": [ + {"name": "barry_warning", "x": 14, "y": 18, "width": 6, "length": 1, "var": "VAR_FOLLOWER_RIVAL_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[0] (110, 857), script 2"}, + {"name": "rowan_stop", "x": 5, "y": 14, "width": 1, "length": 3, "var": "VAR_FOLLOWER_RIVAL_STATE", "value": 2, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[1] (101, 853), script 5"}, + {"name": "coord_event_2", "x": 14, "y": 19, "width": 6, "length": 1, "var": "VAR_FOLLOWER_RIVAL_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[2] (110, 858), script 3"} + ], "patches": [ {"x": 8, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, {"x": 9, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json index e52d694739..50486733f1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json @@ -123,6 +123,9 @@ {"name": "youngster_7", "kind": "npc", "x": 10, "y": 8, "wander": {"x0": 9, "y0": 8, "x1": 11, "y1": 8}}, {"name": "item_8", "kind": "item", "x": 3, "y": 6} ], + "coord_events": [ + {"name": "catch_tutorial", "x": 21, "y": 25, "width": 1, "length": 5, "var": "VAR_ROUTE_202_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0328.bin coord_events[0] (180, 825), script 6"} + ], "patches": [ {"x": 15, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, {"x": 16, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json index 2e3c409907..faccffbe74 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json @@ -60,5 +60,8 @@ {"name": "item_10", "kind": "item", "x": 31, "y": 5}, {"name": "item_11", "kind": "item", "x": 20, "y": 10}, {"name": "lass_12", "kind": "npc", "x": 15, "y": 17, "wander": {"x0": 14, "y0": 17, "x1": 16, "y1": 17}} + ], + "coord_events": [ + {"name": "coord_event_0", "x": 5, "y": 17, "width": 1, "length": 4, "var": "VAR_ROUTE_203_RIVAL_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0329.bin coord_events[0] (196, 757), script 6"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json index 4f7a4e61b4..3691f9266e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -51,5 +51,8 @@ }, "objects": [ {"name": "youngster_0", "kind": "npc", "x": 27, "y": 23, "wander": {"x0": 26, "y0": 22, "x1": 28, "y1": 24}} + ], + "coord_events": [ + {"name": "dawn_walks_us_to_the_lab", "x": 4, "y": 10, "width": 1, "length": 6, "var": "VAR_SANDGEM_TOWN_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0396.bin coord_events[0] (164, 842), script 2"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json index ff22e6feba..9441a324e5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json @@ -46,5 +46,9 @@ {"name": "pokemon_breeder_f_0", "kind": "npc", "x": 23, "y": 14, "wander": {"x0": 22, "y0": 14, "x1": 24, "y1": 14}}, {"name": "collector_1", "kind": "npc", "x": 12, "y": 25}, {"name": "guitarist_3", "kind": "npc", "x": 12, "y": 5} + ], + "coord_events": [ + {"name": "coord_event_0", "x": 12, "y": 3, "width": 8, "length": 1, "var": "VAR_TWINLEAF_TOWN_GUITARIST_TRIGGER_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[0] (108, 867), script 4"}, + {"name": "barry_doorstep", "x": 9, "y": 12, "width": 1, "length": 1, "var": "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[1] (105, 876), script 2"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json index ec50cf46e9..f7e12b3b98 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json @@ -39,5 +39,9 @@ "lakefront_arrival": [31, 23], "below_lake_entrance": [17, 14], "lake_entrance": [17, 12] - } + }, + "coord_events": [ + {"name": "lake_entrance", "x": 16, "y": 12, "width": 2, "length": 1, "var": "VAR_VERITY_LAKEFRONT_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[0] (80, 844), script 3"}, + {"name": "coord_event_1", "x": 16, "y": 12, "width": 2, "length": 1, "var": "VAR_VERITY_LAKEFRONT_STATE", "value": 3, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[1] (80, 844), script 4"} + ] } diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py index 4a12ed05b0..6454bb3b47 100644 --- a/devtools/maps/bdsp_maps.py +++ b/devtools/maps/bdsp_maps.py @@ -28,6 +28,9 @@ - PATCHES: tiles measured on the console that differ from Diamond's, with the run that measured them. The map's tiles stay the decompilation's; the loader applies the patches. +- COORD_EVENTS: names for the events file's coord events (the scene + triggers), and triggers found on the console that the decompilation + doesn't have, with the run that found them. The legend is the schema's: '#' wall, '.' open, '~' tall grass, 'w' water, '^' 'v' '<' '>' ledges hopped the arrow's way, 'D' a door or cave mouth @@ -39,7 +42,14 @@ a route is coded only over tiles a human or a probe has walked; a map change re-runs every checkpoint that walks it. Bulbapedia's DP images (12 px rows for 16 px columns, cliffs painted tall) are for drawing routes over, not for -terrain. Scenes' coord events have no place in the schema (Segment00Lines). +terrain. + +Each map lists its events file's coord events under "coord_events" (the +shared schema, Pokemon_MapData.h, leaves the key to the game; BDSP AutoStory's +Data/PokemonBDSP_AutoStory_CoordEvents.h reads it): `width` columns and +`length` rows from local (x, y), armed while the story variable `var` holds +`value`, and a `source` that names the file, the event's index, its world +tile and its script. Boxes are clipped to the map's rectangle. """ import argparse import json @@ -138,7 +148,7 @@ # 00.01 to 00.03's interiors, from pokeplatinum (c6689696d5fb), each # the only cell of its own matrix: decomp only, not yet checked on the # console. Mom's warning on the way out is a coord event on the - # player's door tile (6, 10), which the schema has no place for. + # player's door tile (6, 10). 'PlayerHouse1F': {'header': 'TWINLEAF_TOWN_PLAYER_HOUSE_1F', 'rect': (0, 0, 13, 12), **INTERIOR}, 'PlayerHouse2F': {'header': 'TWINLEAF_TOWN_PLAYER_HOUSE_2F', 'rect': (0, 0, 12, 12), **INTERIOR}, 'RivalHouse1F': {'header': 'TWINLEAF_TOWN_RIVAL_HOUSE_1F', 'rect': (0, 0, 13, 12), **INTERIOR}, @@ -440,6 +450,29 @@ def box(x0, y0, x1, y1): } +# Coord events by events-file index: their names (the default is +# coord_event_), and under 'add' the triggers the console found that +# the decompilation doesn't have. +COORD_EVENTS = { + # Barry stops us on row 18 (POINTS barry_warning); Rowan on column 5 + # (POINTS rowan_stop). + 'Route201': {0: 'barry_warning', 1: 'rowan_stop'}, + 'Route202': {0: 'catch_tutorial'}, + 'SandgemTown': {0: 'dawn_walks_us_to_the_lab'}, + 'JubilifeCity': {0: 'dawn_at_the_steps', 4: 'poketch_president'}, + 'TwinleafTown': {1: 'barry_doorstep'}, + 'VerityLakefront': {0: 'lake_entrance'}, + 'PlayerHouse1F': { + 0: 'moms_warning', + 'add': [ + {'name': 'moms_call', 'x': 6, 'y': 9, 'width': 1, 'length': 1, 'var': 'CONSOLE_MOMS_CALL', 'value': 0, + 'measured_by': 'console r45, r46 (2026-11-01): after her heal Mom calls us back as we step above' + ' the door; no coord event in the decomp'}, + ], + }, +} + + def no_fetch(repo, path): raise SystemExit(f'{repo}/{path} is not in {CACHE}. Fetch it with `python3 -m devtools.maps decomp ...` first.') @@ -501,6 +534,29 @@ def place_objects(name, events, rect, rows): return objects +def coord_events(name, repo, game, events_id, rect): + """The map's coord events: the events file's, clipped to `rect`, then COORD_EVENTS' additions.""" + x0, z0, width, height = rect + names = COORD_EVENTS.get(name, {}) + out = [] + for index, event in enumerate(game.events(events_id).coord_events): + left, top = max(event.x, x0), max(event.z, z0) + right, bottom = min(event.x + event.width, x0 + width), min(event.z + event.length, z0 + height) + if left >= right or top >= bottom: + continue + out.append({ + 'name': names.get(index, f'coord_event_{index}'), + 'x': left - x0, 'y': top - z0, 'width': right - left, 'length': bottom - top, + 'var': event.var, 'value': event.value, + 'source': f'{repo} {game.events_path(events_id)} coord_events[{index}] ({event.x}, {event.z}),' + f' script {event.script}', + }) + for added in names.get('add', []): + fields = {k: v for k, v in added.items() if k != 'measured_by'} + out.append({**fields, 'source': added['measured_by']}) + return out + + def decode_map(name): spec = MAPS[name] repo = spec.get('repo', decomp.Diamond.REPO) @@ -540,7 +596,8 @@ def decode_map(name): 'revision': spec.get('revision', 'default branch'), 'date': spec.get('read', READ), } - return [''.join(row) for row in rows], objects, source + triggers = coord_events(name, repo, game, header.events_id, spec['rect']) + return [''.join(row) for row in rows], objects, source, triggers def points_of(name): @@ -556,7 +613,7 @@ def points_of(name): def map_text(name): """The map's JSON: one line per row, point, object and patch.""" - tiles, objects, source = decode_map(name) + tiles, objects, source, triggers = decode_map(name) lines = ['{', f' "name": {json.dumps(name)},', f' "source": {json.dumps(source)},', ' "tiles": ['] lines += [f' {json.dumps(row)},' for row in tiles] lines[-1] = lines[-1].rstrip(',') @@ -574,6 +631,7 @@ def section(key, items): section('points', [f'{json.dumps(p)}: [{x}, {y}]' for p, (x, y) in points_of(name).items()]) section('warps', [json.dumps({'x': x, 'y': y, 'to_map': m, 'to_point': p}) for x, y, m, p in WARPS.get(name, [])]) section('objects', [json.dumps(o) for o in objects]) + section('coord_events', [json.dumps(e) for e in triggers]) section('patches', [json.dumps({'x': x, 'y': y, 'glyph': g, 'measured_by': m}) for x, y, g, m in PATCHES.get(name, [])]) lines.append('}') diff --git a/devtools/maps/decomp.py b/devtools/maps/decomp.py index f5e85b6c55..881fa19347 100644 --- a/devtools/maps/decomp.py +++ b/devtools/maps/decomp.py @@ -12,8 +12,11 @@ pokeplatinum keeps matrices and events as JSON and its map headers in include/data/map_headers.h. pokediamond keeps them as binary NARC entries (the layout pokeplatinum's tools/jsoncnv packs) with the header table in -arm9/src/map_header.c, and gives sprites, movement types and trainer types -by number; pokeplatinum's generated/*.txt tables name them. BDSP keeps +arm9/src/map_header.c, and gives sprites, movement types, trainer types and +story variables by number; pokeplatinum's generated/*.txt tables name them. +An events file lists bg events, object events, warps and coord events (the +scene triggers: stepping onto one of a box of tiles while a story variable +holds a value starts a script), in that order. BDSP keeps Diamond/Pearl's layout; Platinum's few changes show up on the console. """ import datetime @@ -153,11 +156,24 @@ class Sign: z: int +@dataclass +class CoordEvent: + """A scene trigger: `width` x `length` tiles from (x, z), armed while `var` holds `value`.""" + script: int + x: int + z: int + width: int + length: int + var: str + value: int + + @dataclass class Events: objects: list = field(default_factory=list) warps: list = field(default_factory=list) signs: list = field(default_factory=list) + coord_events: list = field(default_factory=list) def strip_prefix(name, prefix): @@ -203,8 +219,11 @@ def land_data(self, land_id): def events_name(self, events_id): return f'{events_id}.json' + def events_path(self, events_id): + return f'res/field/events/{events_id}.json' + def events(self, events_id): - data = json.loads(self.source.text(f'res/field/events/{events_id}.json')) + data = json.loads(self.source.text(self.events_path(events_id))) events = Events() for o in data.get('object_events', []): trainer = o['trainer_type'] != 'TRAINER_TYPE_NONE' @@ -222,6 +241,9 @@ def events(self, events_id): for b in data.get('bg_events', []): if b['type'] in BG_SIGNS: events.signs.append(Sign(b['x'], b['z'])) + for c in data.get('coord_events', []): + events.coord_events.append(CoordEvent( + c['script'], c['x'], c['z'], c['width'], c['length'], c['var'], c['value'])) return events @@ -231,6 +253,11 @@ class Diamond: Sprites, movement types and trainer types are numbers there; `names` is a Source for pret/pokeplatinum, whose generated/*.txt tables list them in order (checked on Route 204 North: the same twelve objects come out). + Story variables are numbered from 0x4000 in both games; Platinum's + generated/vars_flags.txt (a C enum) names them (checked: the coord events + that pokeplatinum also has on Route 202, Sandgem, Jubilife and the + player's house come out with Platinum's variable names). A number that + table does not name stays a number. """ REPO = 'pret/pokediamond' GAME = 'Pokemon Diamond' @@ -271,6 +298,16 @@ def named(self, table, prefix, value): entries = self.table(table) return strip_prefix(entries[value], prefix) if value < len(entries) else str(value) + def var_name(self, number): + if 'vars' not in self._tables: + values = enum_values(self.names.text('generated/vars_flags.txt').splitlines()) + names = {} + for name, value in values.items(): + if name.startswith('VAR_'): + names.setdefault(value, name) + self._tables['vars'] = names + return self._tables['vars'].get(number, str(number)) + def matrix(self, matrix_id): data = self.source.read(f'files/fielddata/mapmatrix/map_matrix/narc_{matrix_id:04d}.bin') width, height, has_headers, has_altitudes, name_len = struct.unpack_from('<5B', data, 0) @@ -297,8 +334,11 @@ def land_data(self, land_id): def events_name(self, events_id): return f'zone_event narc_{events_id:04d}' + def events_path(self, events_id): + return f'files/fielddata/eventdata/zone_event_release/narc_{events_id:04d}.bin' + def events(self, events_id): - data = self.source.read(f'files/fielddata/eventdata/zone_event_release/narc_{events_id:04d}.bin') + data = self.source.read(self.events_path(events_id)) events = Events() offset = 0 (count,) = struct.unpack_from(' value of a C enum's lines: `NAME` (the previous value + 1) or `NAME = number or NAME`.""" + values = {} + following = 0 + for line in lines: + name, _, value = (part.strip() for part in line.partition('=')) + if not name: + continue + if value: + following = int(value, 0) if value[0].isdigit() else values[value] + values[name] = following + following += 1 + return values + + def title(constant): """AROMA_LADY_TAYLOR -> Aroma Lady Taylor.""" return ' '.join(w.capitalize() for w in constant.split('_')) diff --git a/devtools/maps/tests/test_decomp.py b/devtools/maps/tests/test_decomp.py index daf514c156..57f25908a5 100644 --- a/devtools/maps/tests/test_decomp.py +++ b/devtools/maps/tests/test_decomp.py @@ -4,7 +4,9 @@ import unittest from pathlib import Path -from devtools.maps import decomp +from unittest import mock + +from devtools.maps import bdsp_maps, decomp # One synthetic 32 x 32 cell, open ground but for the first row: # wall, tall grass, ledge south, ledge east, door, warp tile, water, cave wall, cave floor. @@ -67,7 +69,9 @@ def platinum_tree(root): ], 'warp_events': [{'x': 5, 'z': 0, 'dest_header_id': 'MAP_HEADER_OTHER', 'dest_warp_id': 0}, {'x': 4, 'z': 1, 'dest_header_id': 'MAP_HEADER_OTHER', 'dest_warp_id': 1}], - 'coord_events': []})) + 'coord_events': [ + {'script': 6, 'x': 2, 'z': 3, 'y': 0, 'width': 1, 'length': 5, 'var': 'VAR_TEST_STATE', 'value': 0}, + {'script': 7, 'x': 30, 'z': 0, 'y': 0, 'width': 4, 'length': 1, 'var': '16390', 'value': 2}]})) def diamond_tree(root): @@ -88,6 +92,7 @@ def diamond_tree(root): gfx[4], gfx[20], gfx[87], gfx[94] = 'OBJ_EVENT_GFX_YOUNGSTER', 'OBJ_EVENT_GFX_LASS', 'OBJ_EVENT_GFX_POKEBALL', 'OBJ_EVENT_GFX_ARROW_SIGNPOST' write(root, 'generated/movement_types.txt', '\n'.join(movement)) write(root, 'generated/object_events_gfx.txt', '\n'.join(gfx)) + write(root, 'generated/vars_flags.txt', 'FLAG_UNUSED\nVARS_START = 16384\nVAR_UNUSED_0x4000 = VARS_START\nVAR_TEST_STATE\n') def obj(gfx_id, movement_id, trainer, flag, data0, range_x, x, z): return struct.pack('<14HI', 0, gfx_id, movement_id, trainer, flag, 1, 0, data0, 0, 0, range_x, 0, x, z, 0) @@ -97,7 +102,8 @@ def obj(gfx_id, movement_id, trainer, flag, data0, range_x, x, z): events += obj(87, 0, 0, 1000, 0, 0, 9, 0) + obj(94, 0, 0, 0, 13, 0, 10, 0) + obj(20, 15, 1, 0, 4, 0, 11, 0) events += obj(4, 5, 0, 0, 0, 2, 12, 0) + obj(20, 0, 0, 0, 0, 0, 40, 0) events += struct.pack(' Date: Thu, 5 Nov 2026 19:44:41 -0800 Subject: [PATCH 54/74] BDSP AutoStory maps: align with PR #231 lint conventions --- .../Data/PokemonBDSP_AutoStory_Maps.cpp | 8 +- .../Data/PokemonBDSP_AutoStory_Maps.h | 6 +- .../PokemonBDSP_AutoStory_Maps_Tests.cpp | 150 ++++++++++-------- .../PokemonBDSP_AutoStory_Maps_Tests.h | 7 +- 4 files changed, 98 insertions(+), 73 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp index 065b53300a..1992a6cb4d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp @@ -35,7 +35,7 @@ const std::map>& story_maps_by_name(){ return maps; } -} +} // namespace const MapData& story_map(std::string_view name){ @@ -72,6 +72,6 @@ std::vector map_region(std::string_view map, std::string_view region){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h index e6e3a96bef..988fb7b52f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h @@ -51,7 +51,7 @@ std::vector map_region(std::string_view map, std::string_view -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp index df0a559e8e..01174e5b99 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp @@ -56,32 +56,26 @@ std::string region_of(const std::string& point){ // Every built-in map parses through the shared loader, named as its file. -class Test_StoryMapsLoad : public UnitTest{ -public: - Test_StoryMapsLoad() - : UnitTest("PokemonBDSP::AutoStory - Maps: the built-in JSON maps load") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - if (bdsp_map_json().empty()){ - return std::string("No built-in maps."); - } - for (const auto& [name, json] : bdsp_map_json()){ - try{ - const MapData& map = story_map(name); - if (map.name != name){ - return std::format("{}.json: story_map() returned \"{}\".", name, map.name); - } - logger.log(std::format( - "{}: {} x {}, {} points, {} objects, {} patches", - name, map.tiles.width, map.tiles.height, map.points.size(), map.objects.size(), map.patches.size() - )); - }catch (Exception& e){ - return std::format("{}: {}: {}", name, e.name(), e.message()); +UnitTestResult test_story_maps_load(Logger& logger){ + if (bdsp_map_json().empty()){ + return std::string("No built-in maps."); + } + for (const auto& [name, json] : bdsp_map_json()){ + try{ + const MapData& map = story_map(name); + if (map.name != name){ + return std::format("{}.json: story_map() returned \"{}\".", name, map.name); } + logger.log(std::format( + "{}: {} x {}, {} points, {} objects, {} patches", + name, map.tiles.width, map.tiles.height, map.points.size(), map.objects.size(), map.patches.size() + )); + }catch (Exception& e){ + return std::format("{}: {}: {}", name, e.name(), e.message()); } - return true; } -}; + return true; +} // What a named point must be on. Points not listed are ground the player @@ -171,12 +165,7 @@ std::string check_ground(const MapData& map, const TilePos& pos){ // Every point is ground with nobody on it, unless point_cases() says // otherwise; every numbered region runs from 1 with no gap; every case // names a point the map has; every warp leads to a point that exists. -class Test_StoryMapPoints : public UnitTest{ -public: - Test_StoryMapPoints() - : UnitTest("PokemonBDSP::AutoStory - Maps: points stand where they can") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_story_map_points(Logger& logger){ for (const PointCase& item : point_cases()){ const MapData& map = story_map(item.map); if (!map.points.contains(item.point) && !map.points.contains(item.point + ".1")){ @@ -214,17 +203,11 @@ class Test_StoryMapPoints : public UnitTest{ } logger.log(std::format("{} points checked.", checked)); return true; - } -}; +} // Everyone stands on ground, and a wanderer's box holds their tile. -class Test_StoryMapObjects : public UnitTest{ -public: - Test_StoryMapObjects() - : UnitTest("PokemonBDSP::AutoStory - Maps: objects stand on open ground") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_story_map_objects(Logger& logger){ size_t checked = 0; for (const auto& [name, json] : bdsp_map_json()){ const MapData& map = story_map(name); @@ -242,8 +225,7 @@ class Test_StoryMapObjects : public UnitTest{ } logger.log(std::format("{} objects checked.", checked)); return true; - } -}; +} // Route 202's regions are the tiles the story code computed before they @@ -272,12 +254,7 @@ std::vector after_training_area(const MapData& map){ return standable_in_box(map, {catch_spot.x - 1, catch_spot.y - 2}, {catch_spot.x + 1, catch_spot.y + 2}); } -class Test_Route202Regions : public UnitTest{ -public: - Test_Route202Regions() - : UnitTest("PokemonBDSP::AutoStory - Maps: Route 202's regions are what the story computed") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_route202_regions(Logger& logger){ const std::vector cases{ { .region = "catch_save_area", // story_catch_save_area() @@ -310,8 +287,7 @@ class Test_Route202Regions : public UnitTest{ logger.log(std::format("Route202 {}: {} tiles.", item.region, region.size())); } return true; - } -}; +} // map_point() and map_region() find what the story asks for, regions in @@ -323,12 +299,7 @@ struct LookupCase{ std::vector expected; }; -class Test_StoryMapLookups : public UnitTest{ -public: - Test_StoryMapLookups() - : UnitTest("PokemonBDSP::AutoStory - Maps: map_point() and map_region()") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_story_map_lookups(Logger&){ const std::vector cases{ { .name = "a point", @@ -376,21 +347,74 @@ class Test_StoryMapLookups : public UnitTest{ } } return true; - } +} + + +struct StoryMapsInput{ + std::string name; + std::function body; }; -} +struct StoryMapsExpectation{ +}; +struct StoryMapsCase{ + StoryMapsInput input; + StoryMapsExpectation expectation; +}; + +class Test_StoryMaps : public UnitTest{ +public: + explicit Test_StoryMaps(StoryMapsCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Maps: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StoryMapsCase m_case; +}; + +} // namespace + + +const StoryMapsCase STORY_MAPS_CASES[] = { + { + .input = {"the built-in JSON maps load", test_story_maps_load}, + .expectation = {}, + }, + { + .input = {"points stand where they can", test_story_map_points}, + .expectation = {}, + }, + { + .input = {"objects stand on open ground", test_story_map_objects}, + .expectation = {}, + }, + { + .input = {"map_point() and map_region()", test_story_map_lookups}, + .expectation = {}, + }, + { + .input = {"Route 202's regions are what the story computed", test_route202_regions}, + .expectation = {}, + }, +}; void add_tests_AutoStory_Maps(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); - database.add(); + for (const auto& item : STORY_MAPS_CASES){ + database.add(item); + } } -} -} -} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h index 59905aa331..dc3d4cc52e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h @@ -14,10 +14,11 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// Registers AutoStory map unit tests with the database. void add_tests_AutoStory_Maps(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif From 990a0e021715df4a257b6175230fbd7d714c8fd0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 5 Nov 2026 22:10:48 -0800 Subject: [PATCH 55/74] BDSP AutoStory nav: align with PR #231 lint conventions --- .../Data/PokemonBDSP_AutoStory_PlanCosts.cpp | 6 +- .../Data/PokemonBDSP_AutoStory_PlanCosts.h | 6 +- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 12 +- .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 12 +- .../PokemonBDSP_AutoStory_RouteRecords.cpp | 10 +- .../Data/PokemonBDSP_AutoStory_RouteRecords.h | 11 +- .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 11 +- .../PokemonBDSP_AutoStory_Segment00Lines.h | 12 +- .../Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 12 +- .../Data/PokemonBDSP_AutoStory_StoryMaps.h | 24 +++- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 8 +- .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 8 +- ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 105 ++++++++++------ ...PokemonBDSP_AutoStory_RoutePlanner_Tests.h | 6 +- .../PokemonBDSP_AutoStory_Segment00_Tests.cpp | 59 +++++++-- .../PokemonBDSP_AutoStory_Segment00_Tests.h | 6 +- .../PokemonBDSP_AutoStory_StoryMaps_Tests.cpp | 118 +++++++++++------- .../PokemonBDSP_AutoStory_StoryMaps_Tests.h | 6 +- ...PokemonBDSP_AutoStory_StoryWorld_Tests.cpp | 90 ++++++++----- .../PokemonBDSP_AutoStory_StoryWorld_Tests.h | 6 +- 20 files changed, 339 insertions(+), 189 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp index ce7b7bc124..c59cfc09a3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp @@ -41,6 +41,6 @@ RobustPlanCosts town_plan_costs(){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h index 7608e59c9e..62a7167cab 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h @@ -40,7 +40,7 @@ RobustPlanCosts town_plan_costs(); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index d836670c06..f867e407bc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -32,7 +32,7 @@ bool tall_grass(const StoryWorld& world, const TilePos& pos){ return world.tile(pos) == TileKind::TALL_GRASS; } -} +} // namespace WallHit slide_to_wall(const StoryWorld& world, const TilePos& from, Direction direction){ @@ -102,7 +102,7 @@ void check_standable(const StoryWorld& world, const TilePos& from, const TilePos } } -} +} // namespace std::optional> plan_tile_route( const StoryWorld& world, @@ -403,7 +403,7 @@ class RobustSearch{ std::priority_queue, EntryGreater> m_queue; }; -} +} // namespace std::optional> plan_robust_route( const StoryWorld& world, @@ -429,6 +429,6 @@ std::optional> plan_robust_route( -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index 9b96713184..a8660a078f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -32,6 +32,7 @@ struct WallHit{ Pokemon::TilePos wall; // the first tile the player could not enter bool anchored = false; // the player is held at `stop` (see StoryWorld::at_wall()) }; +// Computes straight-line sliding movement from tile position until hitting a wall. WallHit slide_to_wall(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); @@ -41,8 +42,10 @@ struct TileLeg{ size_t tiles = 0; // tiles travelled; a ledge hop counts 2 bool ends_at_wall = false; // the next tile in `direction` stops the player }; +// Formats tile movement leg into human-readable string representation. std::string to_string(const TileLeg& leg); +// Cost configuration parameters for tile route planning. struct TilePlanCosts{ int per_tile = 1; int per_grass_tile = 4; // extra for each tall-grass tile entered @@ -67,6 +70,7 @@ struct TrainerSight{ Pokemon::Direction facing = Pokemon::Direction::NORTH; int range = 4; }; +// Computes straight line-of-sight tiles for a trainer. std::vector sight_tiles(const StoryWorld& world, const TrainerSight& trainer); // For each leg, the trainers whose sight line it enters. @@ -94,8 +98,10 @@ struct PlannedLeg{ TileLeg leg; std::vector after; }; +// Formats planned route leg with uncertainties into human-readable representation. std::string to_string(const PlannedLeg& leg); +// Cost configuration parameters accounting for movement execution tolerances. struct RobustPlanCosts : TilePlanCosts{ // An open leg of n tiles may end open_error + n / open_error_per tiles // short or long: on the console 7 tiles went 9. @@ -138,7 +144,7 @@ std::optional> plan_robust_route( -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp index 9736436658..2522d854c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -141,7 +141,7 @@ std::vector segment01_records_from_jubilife(){ }; } -} +} // namespace // The walks planned on a grid (00.04 and 00.05's walk_route goals, 01.03's // Mine legs, 01.06's Route 203 and Jubilife legs, 01.08's Route 204 South, @@ -171,7 +171,7 @@ const std::vector& all(){ } -} -} -} -} +} // namespace RouteRecords +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h index 3097c7b65b..37105c81d8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h @@ -35,6 +35,7 @@ enum class LegEnd{ SCENE, // walks until a cutscene takes over }; +// Single directional leg within a recorded route with its ending condition. struct RouteLeg{ Pokemon::Direction direction; size_t tiles; @@ -46,6 +47,7 @@ struct RouteLeg{ bool exact = true; }; +// Recorded sequence of route legs associated with a story checkpoint. struct RouteRecord{ std::string checkpoint; // "01.05" std::string title; @@ -57,11 +59,12 @@ struct RouteRecord{ std::string source; // the code and the console runs behind it }; +// Returns all defined story route records across checkpoints. const std::vector& all(); -} -} -} -} +} // namespace RouteRecords +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp index 70b9d9bac1..9d7d7311ce 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -113,7 +113,8 @@ WalkedLine walked( ){ return {std::move(checkpoint), std::move(name), std::move(corners), std::move(ends_in), std::move(live_triggers)}; } -} + +} // namespace const std::vector& lines(){ static const std::vector lines{ @@ -139,7 +140,7 @@ const std::vector& lines(){ return lines; } -} -} -} -} +} // namespace Segment00Lines +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h index 940ec31426..8d794257d3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h @@ -30,6 +30,7 @@ namespace Segment00Lines{ // Map names in segment00_maps(); Route 201 and Sandgem Town go by // StoryMaps' MAP_ROUTE_201 and MAP_SANDGEM_TOWN. extern const char* const MAP_TWINLEAF_TOWN; +// Verity Lakefront overworld map name. extern const char* const MAP_VERITY_LAKEFRONT; // Twinleaf Town, Route 201, the Verity Lakefront and Sandgem Town joined on @@ -48,7 +49,9 @@ struct SceneTrigger{ int height; std::string when; // the story state it fires in }; +// Returns all scene trigger zones for Segment 00. const std::vector& scene_triggers(); +// Returns whether given map tile falls within the scene trigger zone. bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile); // A line walked corner to corner: every stretch between two corners is one @@ -60,14 +63,15 @@ struct WalkedLine{ std::string ends_in; // the scene the last corner steps into, "" for none std::vector live_triggers; // the scenes armed while this line is walked }; +// Returns all pre-defined walked route lines for Segment 00. const std::vector& lines(); // The route records start and end on named points of the maps (Twinleaf // Town's house_doorstep, Route 201's barry_warning, ...), all on the lines. -} -} -} -} +} // namespace Segment00Lines +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp index 02ab715514..7934c88438 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -66,7 +66,7 @@ bool in_region(const std::string& map, const std::string& region, const TilePos& return std::find(tiles.begin(), tiles.end(), pos) != tiles.end(); } -} +} // namespace // Offsets are the maps' places in the game's world grid (the decomp's @@ -106,7 +106,7 @@ bool on_route203_west_line(const TilePos& pos){ namespace{ const TilePos JUBILIFE_EAST_CORNER{42, 12}; const int JUBILIFE_EAST_BOTTOM = 25; -} +} // namespace const StoryWorld& jubilife_east_maps(){ static const StoryWorld maps = []{ const MapData& city = story_map("JubilifeCity"); @@ -209,7 +209,7 @@ std::vector route202_region(const char* region){ } return tiles; } -} +} // namespace std::vector story_catch_save_area(){ return route202_region("catch_save_area"); @@ -294,6 +294,6 @@ std::vector route204_south_tiles_to_avoid(){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h index 4e355d9eff..13e7fec7fc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h @@ -27,15 +27,25 @@ namespace PokemonBDSP{ // JSON map named without spaces ("Route 201" from Route201.json), except // MAP_ROUTE_204, which is Route204North.json. extern const char* const MAP_ROUTE_201; +// Sandgem Town overworld map name. extern const char* const MAP_SANDGEM_TOWN; +// Route 202 overworld map name. extern const char* const MAP_ROUTE_202; +// Jubilife City overworld map name. extern const char* const MAP_JUBILIFE_CITY; +// Oreburgh Mine map name. extern const char* const MAP_OREBURGH_MINE; +// Ravaged Path map name. extern const char* const MAP_RAVAGED_PATH; +// Route 204 North map name. extern const char* const MAP_ROUTE_204; +// Route 204 South map name. extern const char* const MAP_ROUTE_204_SOUTH; +// Route 203 overworld map name. extern const char* const MAP_ROUTE_203; +// Oreburgh City overworld map name. extern const char* const MAP_OREBURGH_CITY; +// Floaroma Town overworld map name. extern const char* const MAP_FLOAROMA_TOWN; // Route 201, Sandgem Town and Route 202. @@ -49,6 +59,7 @@ const StoryWorld& jubilife_maps(); // into Jubilife, so the plan ends there (no leg may leave the map) and a // walk west until Jubilife's banner shows goes on from there. const StoryWorld& route203_maps(); +// Returns whether given tile lies on the west line towards Jubilife. bool on_route203_west_line(const Pokemon::TilePos& pos); // Jubilife City's north-east corner (01.06), at its own tile coordinates: // the rest of the city is walled off, so the plan searches only the part @@ -56,7 +67,9 @@ bool on_route203_west_line(const Pokemon::TilePos& pos); // on the north road below the plaza: walking north from there goes up the // road to Route 204 (and Rowan's scene). const StoryWorld& jubilife_east_maps(); +// Returns entrance coordinates for east entrance of Jubilife. const std::vector& jubilife_east_entrance(); +// Returns whether given tile lies on the north road towards Route 204. bool on_jubilife_north_road(const Pokemon::TilePos& pos); // The Oreburgh Mine's coal room on its own (01.03). const StoryWorld& oreburgh_mine_maps(); @@ -67,6 +80,7 @@ StoryWorld ravaged_path_maps(const std::vector& smashed = {}); // Route 204's north half on its own (01.05), and whether a tile is on the // path north into Floaroma. const StoryWorld& route204_north_maps(); +// Returns whether given tile lies within the Floaroma entrance path. bool in_floaroma_path(const Pokemon::TilePos& pos); // Route 204's south half on its own (01.08): it joins the north half only @@ -75,6 +89,7 @@ const StoryWorld& route204_south_maps(); // Oreburgh City alone (01.04, 01.05), and Floaroma Town alone (01.11). const StoryWorld& oreburgh_city_maps(); +// Returns StoryWorld instance containing Floaroma Town alone. const StoryWorld& floaroma_maps(); // Whether a plan may cross this map. Towns are crossed by screen-driven @@ -114,8 +129,11 @@ std::vector story_trainer_sights(); // The trainers of a map, in its own tiles, with the sight ranges that fit // the console. A trainer who looks two ways is listed once per way. std::vector route202_trainer_sights(); +// Returns trainer sights for Route 204 North. std::vector route204_north_trainer_sights(); +// Returns trainer sights for Route 204 South. std::vector route204_south_trainer_sights(); +// Returns trainer sights for Oreburgh Gym. std::vector oreburgh_gym_trainer_sights(); // Route 204 South's tiles in the trainers' sight that a walk can avoid: @@ -124,7 +142,7 @@ std::vector route204_south_tiles_to_avoid(); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index 9ae90edb75..c245bf283e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -47,7 +47,7 @@ std::optional ledge_direction(TileKind tile){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown TileKind."); } -} +} // namespace void StoryWorld::add(std::string name, const Pokemon::MapData& map, const TilePos& offset){ @@ -246,6 +246,6 @@ std::string describe(const StoryWorld& world, const TilePos& pos){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index e78a7ee5ee..dc5b76e3c5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -34,6 +34,8 @@ struct MapTile{ }; +// Composite coordinate space combining multiple contiguous maps into one +// traversable overworld representation. class StoryWorld{ public: // Places `map` under `name` with its tile (0,0) at `offset`. Offsets are @@ -115,7 +117,7 @@ std::string describe(const StoryWorld& world, const Pokemon::TilePos& pos); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index 15a8111056..11f82e3cbd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -60,12 +60,7 @@ struct WallCase{ bool anchored = false; }; -class Test_WalkToWall : public UnitTest{ -public: - Test_WalkToWall() - : UnitTest("PokemonBDSP::AutoStory - Route planner: walking until stopped") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_walk_to_wall(Logger&){ const std::vector cases{ {.name = "to a wall", .rows = {"....#"}, .stop = {3, 0}, .tiles = 3, .anchored = true}, {.name = "off the map", .rows = {"...."}, .stop = {3, 0}, .tiles = 3, .anchored = false}, @@ -81,18 +76,12 @@ class Test_WalkToWall : public UnitTest{ } } return true; - } -}; +} // plan_tile_route() around a pillar: two legs, both to a wall, that trace // to the goal. -class Test_PlanTileRoute : public UnitTest{ -public: - Test_PlanTileRoute() - : UnitTest("PokemonBDSP::AutoStory - Route planner: legs to walls around a pillar") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_plan_tile_route(Logger& logger){ const StoryWorld world = make_world({"#####", "#...#", "#.#.#", "#...#", "#####"}); const std::optional> legs = plan_tile_route(world, {1, 1}, {3, 3}); if (!legs || legs->size() != 2 || !(*legs)[0].ends_at_wall || !(*legs)[1].ends_at_wall){ @@ -107,8 +96,7 @@ class Test_PlanTileRoute : public UnitTest{ return std::string("A route to the start is not empty."); } return true; - } -}; +} // plan_robust_route() from one or several tiles to a goal, with the open @@ -122,12 +110,7 @@ struct RobustCase{ std::string legs; }; -class Test_PlanRobustRoute : public UnitTest{ -public: - Test_PlanRobustRoute() - : UnitTest("PokemonBDSP::AutoStory - Route planner: robust plans") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_plan_robust_route(Logger&){ const StoryWorld world = make_world({"######", "#....#", "######"}); RobustPlanCosts exact_step; exact_step.exact_open_tiles = 1; @@ -149,18 +132,12 @@ class Test_PlanRobustRoute : public UnitTest{ return std::string("A start on a wall did not throw."); }catch (InternalProgramError&){} return true; - } -}; +} // A trainer's sight stops at the first tile the player cannot stand on, // and a leg through it is reported; a leg that is stopped throws. -class Test_TrainerSight : public UnitTest{ -public: - Test_TrainerSight() - : UnitTest("PokemonBDSP::AutoStory - Route planner: trainers' sight lines") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_trainer_sight(Logger&){ const StoryWorld world = make_world({".....", ".....", "..#.."}); const TrainerSight trainer{.name = "lass", .pos = {2, 0}, .facing = Direction::SOUTH, .range = 4}; if (sight_tiles(world, trainer) != std::vector{{2, 1}}){ @@ -176,20 +153,70 @@ class Test_TrainerSight : public UnitTest{ return std::string("A leg off the map did not throw."); }catch (InternalProgramError&){} return true; - } +} + + +struct RoutePlannerInput{ + std::string name; + std::function body; }; -} +struct RoutePlannerExpectation{ +}; +struct RoutePlannerCase{ + RoutePlannerInput input; + RoutePlannerExpectation expectation; +}; + +class Test_RoutePlanner : public UnitTest{ +public: + explicit Test_RoutePlanner(RoutePlannerCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Route planner: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RoutePlannerCase m_case; +}; + +} // namespace + + +const RoutePlannerCase ROUTE_PLANNER_CASES[] = { + { + .input = {"walking until stopped", test_walk_to_wall}, + .expectation = {}, + }, + { + .input = {"legs to walls around a pillar", test_plan_tile_route}, + .expectation = {}, + }, + { + .input = {"robust plans", test_plan_robust_route}, + .expectation = {}, + }, + { + .input = {"trainers' sight lines", test_trainer_sight}, + .expectation = {}, + }, +}; void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); + for (const auto& item : ROUTE_PLANNER_CASES){ + database.add(item); + } } -} -} -} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h index 526d0fe601..1a75a9811f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h @@ -18,7 +18,7 @@ namespace PokemonBDSP{ void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp index 479c1240c2..6c5ed6fd46 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp @@ -159,13 +159,7 @@ std::vector named_tiles(){ // every stretch plans as one straight leg on the decomp maps, and each // line enters its scene's trigger rectangle on its last tile only. The // named tiles the route records start from all lie on the lines. -class Test_Segment00Lines : public UnitTest{ -public: - Test_Segment00Lines() - : UnitTest("PokemonBDSP::AutoStory - Segment 00: the lines into each scene") - {} - - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_segment00_lines(Logger& logger){ const StoryWorld& maps = Segment00Lines::segment00_maps(); for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ if (trigger.width <= 0 || trigger.height <= 0){ @@ -199,17 +193,58 @@ class Test_Segment00Lines : public UnitTest{ } } return true; +} + + +struct Segment00Input{ + std::string name; + std::function body; +}; + +struct Segment00Expectation{ +}; + +struct Segment00Case{ + Segment00Input input; + Segment00Expectation expectation; +}; + +class Test_Segment00 : public UnitTest{ +public: + explicit Test_Segment00(Segment00Case test_case) + : UnitTest("PokemonBDSP::AutoStory - Segment 00: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } } + +private: + Segment00Case m_case; }; -} +} // namespace +const Segment00Case SEGMENT00_CASES[] = { + { + .input = {"the lines into each scene", test_segment00_lines}, + .expectation = {}, + }, +}; + void add_tests_AutoStory_Segment00(UnitTestDatabase& database){ - database.add(); + for (const auto& item : SEGMENT00_CASES){ + database.add(item); + } } -} -} -} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h index 1471536bd4..dfd010c7f4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h @@ -21,7 +21,7 @@ void add_tests_AutoStory_Segment00(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp index 3c6d8487cb..62dec89465 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -44,12 +44,7 @@ StoryWorld alone(const std::string& json_map){ // and r254 loaded the catch's save in the pocket behind the trees at // (21, 29), planned from the catch spot instead, and walked up and down // the lawn east of the grass for three minutes without a battle. -class Test_Route202CatchGrass : public UnitTest{ -public: - Test_Route202CatchGrass() - : UnitTest("PokemonBDSP::AutoStory - Route 202: the catch patch and the walk to it") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_route202_catch_grass(Logger& logger){ const StoryWorld route = alone("Route202"); for (int x = 15; x <= 20; x++){ const WallHit up = slide_to_wall(route, {x, 27}, Direction::NORTH); @@ -87,19 +82,13 @@ class Test_Route202CatchGrass : public UnitTest{ logger.log(std::format("From {} to the catch grass: {} legs, ending in the grass.", name, legs->size())); } return true; - } -}; +} // 00.04's way to Sandgem's Pokemon Center ends below the Center's sign, // walking north into it, then taps west along the doors' row to below the // door: the row must be open there, the door straight north of where the // taps end, and nothing else (a sign, the Mart's door) on the way. -class Test_SandgemCenterApproach : public UnitTest{ -public: - Test_SandgemCenterApproach() - : UnitTest("PokemonBDSP::AutoStory - Sandgem Town: below the Center's sign to below its door") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_sandgem_center_approach(Logger& logger){ const StoryWorld town = alone("SandgemTown"); const TilePos sign = map_point("SandgemTown", "pokemon_center_sign"); const TilePos door = map_point("SandgemTown", "pokemon_center_door"); @@ -124,19 +113,13 @@ class Test_SandgemCenterApproach : public UnitTest{ logger.log(std::format("Sandgem: below the sign {}, {} taps west to below the door {}.", Pokemon::to_string(sign.next(Direction::SOUTH)), sign.x - door.x, Pokemon::to_string(door))); return true; - } -}; +} // After training, 00.04 walks from wherever the training left us into // Sandgem, to where the road stops above the Mart, with the default costs // (heal_at_sandgem_center()): from the whole area and from each of its // tiles alone, a plan must exist and end there. -class Test_TrainingToSandgem : public UnitTest{ -public: - Test_TrainingToSandgem() - : UnitTest("PokemonBDSP::AutoStory - Route 202: from every tile of the training area into Sandgem") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_training_to_sandgem(Logger& logger){ const StoryWorld& maps = story_maps(); const TilePos entry = maps.to_world(MAP_SANDGEM_TOWN, map_point("SandgemTown", "route_202_entry_stop")); const std::vector area = story_after_training_area(); @@ -156,18 +139,12 @@ class Test_TrainingToSandgem : public UnitTest{ logger.log(std::format("From {} into Sandgem: {} legs.", name, legs->size())); } return true; - } -}; +} // The Oreburgh Gym's inside: the column up from the entrance runs to Roark // with nothing in the way but the two Youngsters' sight lines, which is // what 01.04's "north until a trainer stops us" relies on. -class Test_OreburghGymColumn : public UnitTest{ -public: - Test_OreburghGymColumn() - : UnitTest("PokemonBDSP::AutoStory - Oreburgh Gym: the column up to Roark") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_oreburgh_gym_column(Logger& logger){ const StoryWorld gym = alone("OreburghGym"); const TilePos entrance = map_point("OreburghGym", "entrance"); const TilePos roark = map_point("OreburghGym", "roark"); @@ -195,18 +172,12 @@ class Test_OreburghGymColumn : public UnitTest{ } } return true; - } -}; +} // Each traceable record with a start tile starts on ground, and its legs // counted in whole tiles trace on its map up to the first leg that ends // some other way. -class Test_RouteRecords : public UnitTest{ -public: - Test_RouteRecords() - : UnitTest("PokemonBDSP::AutoStory - Route records: counted legs trace on their maps") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_route_records(Logger& logger){ for (const RouteRecords::RouteRecord& record : RouteRecords::all()){ const std::string name = record.checkpoint + " " + record.title; const StoryWorld world = alone(record.map_file); @@ -231,21 +202,74 @@ class Test_RouteRecords : public UnitTest{ } } return true; +} + + +struct StoryMapsInput{ + std::string name; + std::function body; +}; + +struct StoryMapsExpectation{ +}; + +struct StoryMapsCase{ + StoryMapsInput input; + StoryMapsExpectation expectation; +}; + +class Test_StoryMaps : public UnitTest{ +public: + explicit Test_StoryMaps(StoryMapsCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } } + +private: + StoryMapsCase m_case; }; -} +} // namespace + +const StoryMapsCase STORY_MAPS_CASES[] = { + { + .input = {"Route 202: the catch patch and the walk to it", test_route202_catch_grass}, + .expectation = {}, + }, + { + .input = {"Sandgem Town: below the Center's sign to below its door", test_sandgem_center_approach}, + .expectation = {}, + }, + { + .input = {"Route 202: from every tile of the training area into Sandgem", test_training_to_sandgem}, + .expectation = {}, + }, + { + .input = {"Oreburgh Gym: the column up to Roark", test_oreburgh_gym_column}, + .expectation = {}, + }, + { + .input = {"Route records: counted legs trace on their maps", test_route_records}, + .expectation = {}, + }, +}; void add_tests_AutoStory_StoryMaps(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); - database.add(); + for (const auto& item : STORY_MAPS_CASES){ + database.add(item); + } } -} -} -} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h index 68fb96f3f3..c0ed36bd5b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h @@ -18,7 +18,7 @@ namespace PokemonBDSP{ void add_tests_AutoStory_StoryMaps(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp index d297d2be99..e4cca12a13 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -79,12 +79,7 @@ struct StepCase{ bool at_wall = false; }; -class Test_StoryWorldSteps : public UnitTest{ -public: - Test_StoryWorldSteps() - : UnitTest("PokemonBDSP::AutoStory - Story world: what each tile does to a step") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_story_world_steps(Logger&){ const std::vector cases{ {.name = "open ground", .rows = {".", "."}, .from = {0, 1}, .lands = TilePos{0, 0}}, {.name = "tall grass", .rows = {"~", "."}, .from = {0, 1}, .lands = TilePos{0, 0}}, @@ -113,18 +108,12 @@ class Test_StoryWorldSteps : public UnitTest{ } } return true; - } -}; +} // Two maps joined: tiles of each at their offsets, the gap between them // off the maps, and a shared wall border allowed where nothing else is. -class Test_StoryWorldJoin : public UnitTest{ -public: - Test_StoryWorldJoin() - : UnitTest("PokemonBDSP::AutoStory - Story world: maps joined at offsets") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_story_world_join(Logger&){ StoryWorld world; world.add("West", make_map({"##", ".#"}), {0, 0}); world.add("East", make_map({"#.", "#~"}), {1, -1}); @@ -154,18 +143,12 @@ class Test_StoryWorldJoin : public UnitTest{ return std::string("to_world() of an unknown map did not throw."); }catch (InternalProgramError&){} return true; - } -}; +} // block() and uncover() change what a tile does, and survive a map added // later that moves the world's origin. -class Test_StoryWorldBlockUncover : public UnitTest{ -public: - Test_StoryWorldBlockUncover() - : UnitTest("PokemonBDSP::AutoStory - Story world: blocked and uncovered tiles") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_story_world_block_uncover(Logger&){ StoryWorld world; world.add("Road", make_map({"...."}), {0, 0}); world.block({1, 0}); @@ -183,19 +166,66 @@ class Test_StoryWorldBlockUncover : public UnitTest{ return std::string("Adding a map lost the blocked or uncovered tile."); } return true; - } +} + + +struct StoryWorldInput{ + std::string name; + std::function body; }; -} +struct StoryWorldExpectation{ +}; +struct StoryWorldCase{ + StoryWorldInput input; + StoryWorldExpectation expectation; +}; + +class Test_StoryWorld : public UnitTest{ +public: + explicit Test_StoryWorld(StoryWorldCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Story world: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StoryWorldCase m_case; +}; + +} // namespace + + +const StoryWorldCase STORY_WORLD_CASES[] = { + { + .input = {"what each tile does to a step", test_story_world_steps}, + .expectation = {}, + }, + { + .input = {"maps joined at offsets", test_story_world_join}, + .expectation = {}, + }, + { + .input = {"blocked and uncovered tiles", test_story_world_block_uncover}, + .expectation = {}, + }, +}; void add_tests_AutoStory_StoryWorld(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); + for (const auto& item : STORY_WORLD_CASES){ + database.add(item); + } } -} -} -} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h index 0fee678878..de4006d340 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h @@ -18,7 +18,7 @@ namespace PokemonBDSP{ void add_tests_AutoStory_StoryWorld(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif From 0d6adc701a8a0e9679ef5f97291e768bb9cc24ad Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 5 Nov 2026 22:17:38 -0800 Subject: [PATCH 56/74] BDSP AutoStory walk: align with PR #231 lint conventions --- .../PokemonBDSP_TransitionWatchers.cpp | 6 +- .../PokemonBDSP_TransitionWatchers.h | 6 +- ...okemonBDSP_AutoStory_OverworldDetector.cpp | 6 +- .../PokemonBDSP_AutoStory_OverworldDetector.h | 7 +- ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 89 ++++++++---- ...PokemonBDSP_AutoStory_PlannedRoute_Tests.h | 6 +- .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 132 ++++++++++-------- .../PokemonBDSP_AutoStory_Walk_Tests.h | 6 +- .../Utils/PokemonBDSP_AutoStory_Indoors.cpp | 8 +- .../Utils/PokemonBDSP_AutoStory_Indoors.h | 6 +- .../Utils/PokemonBDSP_AutoStory_Location.cpp | 10 +- .../Utils/PokemonBDSP_AutoStory_Location.h | 9 +- .../PokemonBDSP_AutoStory_OverlayLog.cpp | 6 +- .../Utils/PokemonBDSP_AutoStory_OverlayLog.h | 6 +- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 10 +- .../PokemonBDSP_AutoStory_PlannedRoute.h | 6 +- .../Utils/PokemonBDSP_AutoStory_RouteIO.cpp | 8 +- .../Utils/PokemonBDSP_AutoStory_RouteIO.h | 7 +- .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 10 +- .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 11 +- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 12 +- .../Utils/PokemonBDSP_AutoStory_Walk.h | 14 +- 22 files changed, 222 insertions(+), 159 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp index 3cf98c2e72..d5e37c567f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.cpp @@ -40,6 +40,6 @@ bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h index 9091f99fb0..2dd7e59d7c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h @@ -45,7 +45,7 @@ class WhiteScreenOverWatcher : public VisualInferenceCallback{ }; -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp index 6b250862fd..effcc50af0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp @@ -131,6 +131,6 @@ bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context){ } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h index ce36eb5f86..f2717765b6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h @@ -81,6 +81,7 @@ class PoketchButtonDetector : public StaticScreenDetector { ImageFloatBox m_button; }; +// Inference watcher tracking the visibility of the Poketch button on screen. class PoketchButtonWatcher : public PoketchButtonDetector, public VisualInferenceCallback { public: PoketchButtonWatcher(Color color = COLOR_RED); @@ -94,7 +95,7 @@ class PoketchButtonWatcher : public PoketchButtonDetector, public VisualInferenc bool ensure_poketch_visible(VideoStream& stream, ProControllerContext& context); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp index ac87afdcc7..ca7f599636 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -183,12 +183,7 @@ StoryWorld make_world(const std::vector& rows){ // r54: a trainer's line froze the check walk at a leg's wall; after the // battle the walk on reached the wall, but the check still judged the // frozen walk's DIALOG and failed. The walk on is what counts. -class Test_WallLegTrainerOnTheWay : public UnitTest{ -public: - Test_WallLegTrainerOnTheWay() - : UnitTest("PokemonBDSP::AutoStory - Planned route: a trainer on a wall leg, then on to the wall") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_wall_leg_trainer_on_the_way(Logger&){ Script script{.steps = { walk_step("wall: T: east 4 (to wall)", WalkStop::LIMIT, 2050ms, 0), walk_step("wall: T: east 4 (to wall): at the wall?", WalkStop::DIALOG, 400ms, 0), @@ -211,8 +206,7 @@ class Test_WallLegTrainerOnTheWay : public UnitTest{ } const std::string left = script_left(script); return left.empty() ? UnitTestResult(true) : UnitTestResult(left); - } -}; +} // A leg to a wall that ran out of time: a check walk that also runs out @@ -224,12 +218,7 @@ struct WallCheckCase{ bool fails; }; -class Test_WallLegLimit : public UnitTest{ -public: - Test_WallLegLimit() - : UnitTest("PokemonBDSP::AutoStory - Planned route: a wall leg out of time needs the holding check") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_wall_leg_limit(Logger&){ const std::vector cases{ {.name = "the check stops at the wall", .check = { walk_step("wall: T: east 4 (to wall): at the wall?", WalkStop::BLOCKED, 1050ms, 0), @@ -262,8 +251,7 @@ class Test_WallLegLimit : public UnitTest{ } } return true; - } -}; +} // Whether walking `legs` from `from` ever steps into `person`'s tile: a @@ -322,12 +310,7 @@ std::string check_replan_from(const Script& script, const std::vector body; }; -} +struct PlannedRouteExpectation{ +}; +struct PlannedRouteCase{ + PlannedRouteInput input; + PlannedRouteExpectation expectation; +}; + +class Test_PlannedRoute : public UnitTest{ +public: + explicit Test_PlannedRoute(PlannedRouteCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Planned route: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + PlannedRouteCase m_case; +}; + +} // namespace + + +const PlannedRouteCase PLANNED_ROUTE_CASES[] = { + { + .input = {"a trainer on a wall leg, then on to the wall", test_wall_leg_trainer_on_the_way}, + .expectation = {}, + }, + { + .input = {"a wall leg out of time needs the holding check", test_wall_leg_limit}, + .expectation = {}, + }, + { + .input = {"a known trainer stops an open leg", test_open_leg_known_trainer}, + .expectation = {}, + }, +}; void add_tests_AutoStory_PlannedRoute(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); + for (const auto& item : PLANNED_ROUTE_CASES){ + database.add(item); + } } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h index 13331b8db4..740e5c27e8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h @@ -22,7 +22,7 @@ void add_tests_AutoStory_PlannedRoute(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index c38ff46daf..e29b302195 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -27,12 +27,7 @@ namespace{ // turned, a 160 ms D-pad tap stepped a whole tile, and a 100 ms stick tap // stepped about 0.6 tile, off the tile grid (r49, r248a). So route_turn() // taps the D-pad, once, for at most 80 ms. -class Test_RouteTurnTap : public UnitTest{ -public: - Test_RouteTurnTap() - : UnitTest("PokemonBDSP::AutoStory - a turn is a D-pad tap too short to step") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_route_turn_tap(Logger&){ constexpr Milliseconds LONGEST_TURN(80); for (Pokemon::Direction direction : {Pokemon::Direction::NORTH, Pokemon::Direction::SOUTH, Pokemon::Direction::EAST, Pokemon::Direction::WEST}){ const RouteInput tap = route_turn_tap(direction); @@ -51,8 +46,7 @@ class Test_RouteTurnTap : public UnitTest{ return "ROUTE_TURN_TAP is " + std::to_string(ROUTE_TURN_TAP.count()) + " ms; over 80 ms may step."; } return true; - } -}; +} // indoors() decides when leave_door_south() is out: r257 walked on south // past Sandgem's road into a house after leaving the Center, because the @@ -66,12 +60,7 @@ struct IndoorsCase{ bool indoors; }; -class Test_IndoorsAnyLight : public UnitTest{ -public: - Test_IndoorsAnyLight() - : UnitTest("PokemonBDSP::AutoStory - indoors() under the evening tint") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_indoors_any_light(Logger&){ const std::vector cases{ {.name = "evening outside, orange all over", .fill = 0xffe0a040, .dark_bottom = 0, .indoors = false}, {.name = "a room: orange, black below its floor", .fill = 0xffe0a040, .dark_bottom = 0.10, .indoors = true}, @@ -92,8 +81,7 @@ class Test_IndoorsAnyLight : public UnitTest{ } } return true; - } -}; +} // door_fade_look(): out of a door is a dark look, then a bright one that is // not a room. r259 turned round in Sandgem's lit Center, read "not a room" @@ -109,12 +97,7 @@ struct DoorCase{ size_t out_at; }; -class Test_DoorFade : public UnitTest{ -public: - Test_DoorFade() - : UnitTest("PokemonBDSP::AutoStory - out of a door needs its fade") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_door_fade(Logger&){ const std::vector cases{ {.name = "r259: a bright look in the Center that misses the room", .looks = {{458, true}, {440, false}, {457, true}}, .out_at = 0}, {.name = "the fade, then the town", .looks = {{458, true}, {300, true}, {60, false}, {310, false}}, .out_at = 4}, @@ -134,17 +117,10 @@ class Test_DoorFade : public UnitTest{ } } return true; - } -}; +} -class Test_LocationBanner : public UnitTest{ -public: - Test_LocationBanner() - : UnitTest("PokemonBDSP::AutoStory - location banner match") - {} - - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ +UnitTestResult test_location_banner(Logger&){ struct Case{ const char* read; const char* expected; @@ -167,16 +143,10 @@ class Test_LocationBanner : public UnitTest{ } } return true; - } -}; +} -class Test_Indoors : public UnitTest{ -public: - Test_Indoors() - : UnitTest("PokemonBDSP::AutoStory - indoors") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_indoors(Logger& logger){ struct Case{ const char* file; bool inside; }; const Case cases[] = { {"PokemonBDSP/AutoStory/JubilifeCenterInside-20261030-c6.png", true}, @@ -203,16 +173,10 @@ class Test_Indoors : public UnitTest{ } } return true; - } -}; +} -class Test_LocationBannerShowing : public UnitTest{ -public: - Test_LocationBannerShowing() - : UnitTest("PokemonBDSP::AutoStory - location banner showing") - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ +UnitTestResult test_location_banner_showing(Logger& logger){ struct Case{ const char* file; bool banner; }; const Case cases[] = { {"PokemonBDSP/AutoStory/JubilifeCenterDoorstep-20261030-c5.png", true}, @@ -234,24 +198,78 @@ class Test_LocationBannerShowing : public UnitTest{ } } return true; +} + + +struct AutoStoryWalkInput{ + std::string name; + std::function body; +}; + +struct AutoStoryWalkExpectation{ +}; + +struct AutoStoryWalkCase{ + AutoStoryWalkInput input; + AutoStoryWalkExpectation expectation; +}; + +class Test_AutoStoryWalk : public UnitTest{ +public: + explicit Test_AutoStoryWalk(AutoStoryWalkCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } } + +private: + AutoStoryWalkCase m_case; }; +} // namespace -} +const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { + { + .input = {"a turn is a D-pad tap too short to step", test_route_turn_tap}, + .expectation = {}, + }, + { + .input = {"indoors() under the evening tint", test_indoors_any_light}, + .expectation = {}, + }, + { + .input = {"out of a door needs its fade", test_door_fade}, + .expectation = {}, + }, + { + .input = {"location banner match", test_location_banner}, + .expectation = {}, + }, + { + .input = {"indoors", test_indoors}, + .expectation = {}, + }, + { + .input = {"location banner showing", test_location_banner_showing}, + .expectation = {}, + }, +}; void add_tests_AutoStory_Walk(UnitTestDatabase& database){ - database.add(); - database.add(); - database.add(); - database.add(); - database.add(); - database.add(); + for (const auto& item : AUTO_STORY_WALK_CASES){ + database.add(item); + } } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h index 266dfa1c0d..6532456aa1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h @@ -21,7 +21,7 @@ void add_tests_AutoStory_Walk(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp index c7e7a3458c..2ae32da5c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp @@ -27,7 +27,7 @@ bool mostly_dark(const EdgeDark& edge){ return edge.count > 0 && edge.dark * 100 >= edge.count * 15; } -} +} // namespace bool indoors(const ImageViewRGB32& screen){ const size_t width = screen.width(), height = screen.height(); @@ -63,6 +63,6 @@ bool indoors(const ImageViewRGB32& screen){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h index 9de7ba3159..b86d80d934 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h @@ -27,7 +27,7 @@ namespace PokemonBDSP{ bool indoors(const ImageViewRGB32& screen); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp index f79677bbe1..df31791552 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -45,7 +45,7 @@ std::string digits_of(const std::string& text){ return out; } -} +} // namespace std::string normalize_location_name(const std::string& text){ @@ -63,7 +63,7 @@ Language& story_language_setting(){ static Language language = Language::English; return language; } -} +} // namespace Language story_language(){ return story_language_setting(); @@ -143,6 +143,6 @@ bool location_banner_matches(const std::string& read, const std::string& expecte } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h index 683874d64c..cb4e4c8626 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h @@ -31,8 +31,11 @@ std::string normalize_location_name(const std::string& text); // language-free checks: the banner's box showing, a sign's box opening, the // first row of a Bag pocket. Language story_language(); +// Sets the active story language. void set_story_language(Language language); +// Returns whether text recognition is supported for the current story language. bool story_reads_text(); +// Returns whether text recognition is supported for the specified language. bool story_reads_text(Language language); // What the reads below return for a banner or save card that showed, when @@ -61,7 +64,7 @@ std::string read_save_screen_location(const ImageViewRGB32& screen); bool location_banner_matches(const std::string& read, const std::string& expected); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp index eab60111f3..f4cc54ee6e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.cpp @@ -37,6 +37,6 @@ void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h index 803b9bc4aa..5e79b82227 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_OverlayLog.h @@ -21,7 +21,7 @@ namespace PokemonBDSP{ void add_wrapped_log(VideoOverlay& overlay, const std::string& text, Color color); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index bbeafd4c0e..3b3bdf4564 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -98,7 +98,7 @@ std::string map_of(const StoryWorld& maps, const std::vector& tiles){ return name; } -} +} // namespace namespace{ @@ -734,7 +734,7 @@ LegNext RouteWalker::replan_from(const LegWalk& walk, std::vector stopp return LegNext::REPLAN; } -} +} // namespace std::vector walk_route( @@ -813,6 +813,6 @@ void talk_to_npc( -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index e422d6891c..5995c93a17 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -115,7 +115,7 @@ void talk_to_npc( -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp index 37e6e3b06a..ef4f69d5f3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.cpp @@ -46,7 +46,7 @@ bool holding_against_wall(VideoStream& stream, ProControllerContext& context, do return before && most < WALKING_CHANGE; } -} +} // namespace WalkResult ConsoleRouteIO::walk_to_wall(const RouteWallWalk& walk){ @@ -96,6 +96,6 @@ void ConsoleRouteIO::note(const std::string& text, RouteNote kind){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h index 1db4631068..0968862a21 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h @@ -44,6 +44,7 @@ enum class RouteNote{ FAILURE, // fails the program with a screenshot; does not return }; +// Abstract I/O interface for route traversal, logging, and controller execution. class RouteIO{ public: virtual ~RouteIO() = default; @@ -97,7 +98,7 @@ class ConsoleRouteIO : public RouteIO{ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index cbd3f3c2d4..2ee8492217 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -39,7 +39,7 @@ bool across(Direction direction){ return direction == Direction::EAST || direction == Direction::WEST; } -} +} // namespace Milliseconds route_ms_per_tile(Direction direction, MoveSpeed speed){ if (speed == MoveSpeed::RUN){ @@ -285,7 +285,7 @@ bool outside_for_three_looks(VideoStream& stream, ProControllerContext& context, return true; } -} +} // namespace void leave_door_south(VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, const std::string& label){ // A last line of talk may still be up, and it would stop the walk. @@ -326,6 +326,6 @@ void leave_door_south(VideoStream& stream, ProControllerContext& context, const -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index ea46031644..2eed12b8e9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -30,6 +30,7 @@ namespace PokemonBDSP{ // Walking time per tile, measured on the console from the post-catch save: // a row is deeper than a column is wide under the tilted camera. constexpr Milliseconds ROUTE_MS_PER_TILE_ACROSS = Milliseconds(160); // east or west +// Walking time per vertical tile (north or south). constexpr Milliseconds ROUTE_MS_PER_TILE_UP_DOWN = Milliseconds(240); // north or south // From pressing the stick to the first step, when standing still. constexpr Milliseconds ROUTE_START_DELAY = Milliseconds(250); @@ -47,6 +48,7 @@ enum class MoveSpeed{ // Rounded down: a count from too fast a pace runs over, which a wall leg // forgives, where one from too slow a pace stops short of the wall. constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_ACROSS = Milliseconds(100); +// Running time per vertical tile (north or south). constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_UP_DOWN = Milliseconds(150); // Time per tile in `direction` at `speed`. @@ -91,6 +93,7 @@ struct RouteInput{ size_t count; RouteInputEnd end; }; +// Executes the specified route input sequence on the controller context. void press_route_input(ProControllerContext& context, const RouteInput& input); // The tap route_turn() turns with: on the D-pad, ROUTE_TURN_TAP long. @@ -130,6 +133,7 @@ bool talk_with_nudges( Milliseconds wait = Milliseconds(3000), const std::function& accept = nullptr ); +// D-pad nudge tap duration for micro-adjusting player position. constexpr Milliseconds ROUTE_NUDGE_TAP = Milliseconds(50); // Whether a walk to the wall that ends on any of `after` can tell it has @@ -168,6 +172,7 @@ void leave_door_south(VideoStream& stream, ProControllerContext& context, const // Brightness (mean r + g + b) below which a look is the door's fade, and // above which a look that is not a room is outside. inline constexpr double DOOR_FADE_DARK = 120.0; +// Brightness threshold above which non-room frame is classified as outside. inline constexpr double DOOR_OUTSIDE_BRIGHT = 200.0; // What leave_door_south() has seen of the door's fade so far. @@ -185,7 +190,7 @@ bool door_walk_stops(DoorFadeWatch& watch, double brightness, bool room); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index 53d7a461e0..a89cc82a6c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -101,7 +101,7 @@ bool battle_follows(VideoStream& stream, ProControllerContext& context){ return wait_until(stream, context, 5s, {{battle_menu}, {battle_dialog}}) >= 0; } -} +} // namespace // A step in tall grass that was started before the stick was released still // finishes, and its encounter starts after the walk has ended. Watch a little @@ -172,7 +172,7 @@ class WalkProbeSampler : public VisualInferenceCallback{ bool m_has_last = false; }; -} +} // namespace namespace{ @@ -394,7 +394,7 @@ WalkResult walk_until_spec( return WalkUntil(stream, context, escape, spec).run(); } -} +} // namespace WalkResult walk_until( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, @@ -575,6 +575,6 @@ WalkResult walk_expecting( } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index 504edccfe8..f46828599d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -29,6 +29,7 @@ namespace PokemonBDSP{ // started; how to leave it is the program's battle code, passed in. using WildBattleEscape = std::function; +// Possible termination conditions for an automated walking sequence. enum class WalkStop{ ARRIVED, // `arrived` matched. DIALOG, // A dialogue box opened: an NPC or a trainer stopped us. @@ -36,11 +37,13 @@ enum class WalkStop{ BLOCKED, // The screen stopped changing: we are walking into a wall. LIMIT, // Walked `limit` without any of the above. }; +// Returns display name string corresponding to given WalkStop condition. const char* walk_stop_name(WalkStop stop); // Whether the walk has arrived, from the screen after each chunk. using WalkArrived = std::function; +// Result metrics and terminal state returned by automated walking execution. struct WalkResult{ WalkStop stop; Milliseconds walked; @@ -67,6 +70,7 @@ enum class DpadPace{ WALK, RUN, }; +// Configuration options controlling D-pad based walking maneuvers. struct DpadWalkOptions{ WalkArrived arrived = nullptr; DpadPace pace = DpadPace::WALK; @@ -80,7 +84,7 @@ struct DpadWalkOptions{ WalkResult walk_until_dpad( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, JoystickPosition stick, Milliseconds limit, const std::string& label, - const DpadWalkOptions& options = {} + const DpadWalkOptions& options = DpadWalkOptions() ); // A set number of whole tiles on the D-pad, a tap a tile (a tap moves @@ -151,6 +155,7 @@ WalkResult walk_to_talk( // the whole view: 16 to 85 per 400ms on Route 202, against about 6 for running in // place against trees. double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after); +// Screen change metric threshold indicative of blocked movement against an obstacle. constexpr double WALK_BLOCKED_CHANGE = 10.0; // For whole-tile D-pad taps: a tap that moves changes the screen by 21 to 50 // (r244a: 40 per tap along Route 204's row 27); a tap into a wall or an NPC @@ -176,6 +181,7 @@ struct WalkProbe{ }; std::vector samples; }; +// Probes walking movement and records timestamped screen change samples. WalkProbe probe_walk( VideoStream& stream, ProControllerContext& context, JoystickPosition stick, Milliseconds limit, @@ -183,7 +189,7 @@ WalkProbe probe_walk( ); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif From f7cd7ccf09231002cd57c3a424838c7f9c0f6f58 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 14:02:18 -0800 Subject: [PATCH 57/74] BDSP AutoStory maps: sync runtime maps from dayfine/PokemonSimulation --- .../Programs/AutoStory/Maps/FloaromaTown.json | 41 ++++++--- .../Programs/AutoStory/Maps/JubilifeCity.json | 91 ++++++++++++++----- .../Programs/AutoStory/Maps/LakeVerity.json | 15 ++- .../Programs/AutoStory/Maps/OreburghCity.json | 57 ++++++++---- .../Programs/AutoStory/Maps/OreburghGate.json | 27 ++++-- .../Programs/AutoStory/Maps/OreburghGym.json | 17 ++-- .../Programs/AutoStory/Maps/OreburghMine.json | 29 +++--- .../AutoStory/Maps/OreburghMineB1F.json | 50 ++++++++++ .../AutoStory/Maps/PlayerHouse1F.json | 37 ++++++-- .../AutoStory/Maps/PlayerHouse2F.json | 47 +++++++++- .../Programs/AutoStory/Maps/RavagedPath.json | 17 ++-- .../Programs/AutoStory/Maps/RivalHouse1F.json | 13 ++- .../Programs/AutoStory/Maps/RivalHouse2F.json | 11 ++- .../Programs/AutoStory/Maps/Route201.json | 61 +++++++++---- .../Programs/AutoStory/Maps/Route202.json | 59 +++++++----- .../Programs/AutoStory/Maps/Route203.json | 37 +++++--- .../AutoStory/Maps/Route204North.json | 31 ++++--- .../AutoStory/Maps/Route204South.json | 25 +++-- .../Programs/AutoStory/Maps/RowansLab.json | 17 ++-- .../Programs/AutoStory/Maps/SandgemTown.json | 23 ++++- .../Programs/AutoStory/Maps/TwinleafTown.json | 37 ++++++-- .../AutoStory/Maps/VerityLakefront.json | 27 +++++- 22 files changed, 567 insertions(+), 202 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json index f6f6bfd349..5ec01e577b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "FloaromaTown", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0032.bin; zone_event narc_0404", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0032.bin; zone_event narc_0404", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "######........................##", "##..##........................##", @@ -41,19 +46,27 @@ "old_man": [2, 25], "pokemon_center_door": [16, 26] }, - "objects": [ - {"name": "pokemon_breeder_f_0", "kind": "npc", "x": 19, "y": 21}, - {"name": "lass_1", "kind": "npc", "x": 10, "y": 5, "wander": {"x0": 9, "y0": 5, "x1": 11, "y1": 5}}, - {"name": "school_kid_m_2", "kind": "npc", "x": 16, "y": 16, "wander": {"x0": 15, "y0": 15, "x1": 17, "y1": 17}}, - {"name": "cyrus_3", "kind": "npc", "x": 11, "y": 26}, - {"name": "lass_4", "kind": "npc", "x": 23, "y": 11, "facing": "west"}, - {"name": "grunt_m_7", "kind": "npc", "x": 2, "y": 1, "facing": "east"}, - {"name": "grunt_m_8", "kind": "npc", "x": 3, "y": 1, "facing": "west"}, - {"name": "camper_12", "kind": "npc", "x": 6, "y": 10}, - {"name": "old_woman", "kind": "npc", "x": 3, "y": 25}, - {"name": "old_man", "kind": "npc", "x": 2, "y": 25} - ], "coord_events": [ - {"name": "coord_event_0", "x": 10, "y": 29, "width": 3, "length": 1, "var": "VAR_UNK_0x4072", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0404.bin coord_events[0] (170, 669), script 2"} + { + "name": "coord_event_0", + "coord": [10, 29], + "width": 3, + "length": 1, + "var": "VAR_UNK_0x4072", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0404.bin coord_events[0] (170, 669), script 2" + } + ], + "npcs": [ + {"name": "pokemon_breeder_f_0", "coord": [19, 21]}, + {"name": "lass_1", "coord": [10, 5], "wander": {"min": [9, 5], "max": [11, 5]}}, + {"name": "school_kid_m_2", "coord": [16, 16], "wander": {"min": [15, 15], "max": [17, 17]}}, + {"name": "cyrus_3", "coord": [11, 26]}, + {"name": "lass_4", "coord": [23, 11], "facing": "west"}, + {"name": "grunt_m_7", "coord": [2, 1], "facing": "east"}, + {"name": "grunt_m_8", "coord": [3, 1], "facing": "west"}, + {"name": "camper_12", "coord": [6, 10]}, + {"name": "old_woman", "coord": [3, 25]}, + {"name": "old_man", "coord": [2, 25]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json index 4f28c563a9..3ba40ce415 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "JubilifeCity", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0015.bin, files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0017.bin, files/fielddata/land_data/land_data_release/narc_0018.bin; zone_event narc_0002", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0015.bin, files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0017.bin, files/fielddata/land_data/land_data_release/narc_0018.bin; zone_event narc_0002", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "##########################################..............########", "##########################################..............########", @@ -119,28 +124,68 @@ "north_road.24": [47, 20], "north_road.25": [48, 20] }, - "objects": [ - {"name": "ace_trainer_f_0", "kind": "npc", "x": 22, "y": 20, "wander": {"x0": 21, "y0": 20, "x1": 23, "y1": 20}}, - {"name": "ace_trainer_m_1", "kind": "npc", "x": 46, "y": 21, "wander": {"x0": 45, "y0": 21, "x1": 47, "y1": 21}}, - {"name": "school_kid_m_2", "kind": "npc", "x": 17, "y": 55}, - {"name": "twin_3", "kind": "npc", "x": 33, "y": 18, "wander": {"x0": 32, "y0": 17, "x1": 34, "y1": 19}}, - {"name": "expert_m_4", "kind": "npc", "x": 44, "y": 44}, - {"name": "school_kid_m_5", "kind": "npc", "x": 51, "y": 34, "wander": {"x0": 51, "y0": 33, "x1": 51, "y1": 35}}, - {"name": "pokefan_m_6", "kind": "npc", "x": 41, "y": 30, "wander": {"x0": 40, "y0": 29, "x1": 42, "y1": 31}}, - {"name": "ace_trainer_m_22", "kind": "npc", "x": 36, "y": 25}, - {"name": "poketch_president", "kind": "npc", "x": 46, "y": 35}, - {"name": "clown_mart", "kind": "npc", "x": 55, "y": 33}, - {"name": "clown_poketch_company", "kind": "npc", "x": 15, "y": 18}, - {"name": "cashier_m_27", "kind": "npc", "x": 26, "y": 42}, - {"name": "clown_tv_station", "kind": "npc", "x": 36, "y": 16}, - {"name": "kid_with_nds_29", "kind": "npc", "x": 52, "y": 46}, - {"name": "kid_with_nds_30", "kind": "npc", "x": 54, "y": 46} - ], "coord_events": [ - {"name": "dawn_at_the_steps", "x": 45, "y": 60, "width": 4, "length": 1, "var": "VAR_JUBILIFE_CITY_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[0] (173, 796), script 2"}, - {"name": "coord_event_1", "x": 45, "y": 7, "width": 3, "length": 1, "var": "VAR_JUBILIFE_CITY_STATE", "value": 3, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[1] (173, 743), script 4"}, - {"name": "coord_event_2", "x": 60, "y": 21, "width": 1, "length": 4, "var": "VAR_JUBILIFE_CITY_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[2] (188, 757), script 3"}, - {"name": "coord_event_3", "x": 27, "y": 43, "width": 1, "length": 3, "var": "VAR_GTS_ACCESS_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[3] (155, 779), script 19"}, - {"name": "poketch_president", "x": 44, "y": 40, "width": 5, "length": 1, "var": "VAR_POKETCH_CAMPAIGN_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[4] (172, 776), script 17"} + { + "name": "dawn_at_the_steps", + "coord": [45, 60], + "width": 4, + "length": 1, + "var": "VAR_JUBILIFE_CITY_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[0] (173, 796), script 2" + }, + { + "name": "coord_event_1", + "coord": [45, 7], + "width": 3, + "length": 1, + "var": "VAR_JUBILIFE_CITY_STATE", + "value": 3, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[1] (173, 743), script 4" + }, + { + "name": "coord_event_2", + "coord": [60, 21], + "width": 1, + "length": 4, + "var": "VAR_JUBILIFE_CITY_STATE", + "value": 1, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[2] (188, 757), script 3" + }, + { + "name": "coord_event_3", + "coord": [27, 43], + "width": 1, + "length": 3, + "var": "VAR_GTS_ACCESS_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[3] (155, 779), script 19" + }, + { + "name": "poketch_president", + "coord": [44, 40], + "width": 5, + "length": 1, + "var": "VAR_POKETCH_CAMPAIGN_STATE", + "value": 1, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[4] (172, 776), script 17" + } + ], + "npcs": [ + {"name": "ace_trainer_f_0", "coord": [22, 20], "wander": {"min": [21, 20], "max": [23, 20]}}, + {"name": "ace_trainer_m_1", "coord": [46, 21], "wander": {"min": [45, 21], "max": [47, 21]}}, + {"name": "school_kid_m_2", "coord": [17, 55]}, + {"name": "twin_3", "coord": [33, 18], "wander": {"min": [32, 17], "max": [34, 19]}}, + {"name": "expert_m_4", "coord": [44, 44]}, + {"name": "school_kid_m_5", "coord": [51, 34], "wander": {"min": [51, 33], "max": [51, 35]}}, + {"name": "pokefan_m_6", "coord": [41, 30], "wander": {"min": [40, 29], "max": [42, 31]}}, + {"name": "ace_trainer_m_22", "coord": [36, 25]}, + {"name": "poketch_president", "coord": [46, 35]}, + {"name": "clown_mart", "coord": [55, 33]}, + {"name": "clown_poketch_company", "coord": [15, 18]}, + {"name": "cashier_m_27", "coord": [26, 42]}, + {"name": "clown_tv_station", "coord": [36, 16]}, + {"name": "kid_with_nds_29", "coord": [52, 46]}, + {"name": "kid_with_nds_30", "coord": [54, 46]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json index f7b521b3cb..db9fba355e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "LakeVerity", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0512.bin; zone_event narc_0298", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0512.bin; zone_event narc_0298", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "wwwwwwwwwwwwwwww################", "wwwwwwwwwwwwwwww################", @@ -35,9 +40,9 @@ "################################", "################################" ], - "objects": [ - {"name": "rowan", "kind": "npc", "x": 16, "y": 11, "facing": "north"}, - {"name": "counterpart", "kind": "npc", "x": 17, "y": 11, "facing": "north"}, - {"name": "starly_3", "kind": "npc", "x": 16, "y": 19, "facing": "north"} + "npcs": [ + {"name": "rowan", "coord": [16, 11], "facing": "north"}, + {"name": "counterpart", "coord": [17, 11], "facing": "north"}, + {"name": "starly_3", "coord": [16, 19], "facing": "north"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json index 0043b0bea2..523e5ac370 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "OreburghCity", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0022.bin, files/fielddata/land_data/land_data_release/narc_0023.bin, files/fielddata/land_data/land_data_release/narc_0024.bin, files/fielddata/land_data/land_data_release/narc_0175.bin; zone_event narc_0044", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0022.bin, files/fielddata/land_data/land_data_release/narc_0023.bin, files/fielddata/land_data/land_data_release/narc_0024.bin, files/fielddata/land_data/land_data_release/narc_0175.bin; zone_event narc_0044", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "#########################################......#################", "#########################################...S..#################", @@ -61,7 +66,7 @@ "#####################################..####.#S....###.....######", "###########################################.......####.......###", "############################################.....#####.......###", - "############################################.....#####.....#####", + "############################################DDDDD#####.....#####", "######################################################..#..#####", "################################################################", "################################################################", @@ -74,22 +79,38 @@ "gym_doorstep": [26, 21], "gate_mouth": [1, 13] }, - "objects": [ - {"name": "hiker_0", "kind": "npc", "x": 47, "y": 26, "wander": {"x0": 46, "y0": 25, "x1": 48, "y1": 27}}, - {"name": "school_kid_f_1", "kind": "npc", "x": 32, "y": 18, "wander": {"x0": 32, "y0": 16, "x1": 32, "y1": 20}}, - {"name": "pokefan_f_2", "kind": "npc", "x": 45, "y": 38, "wander": {"x0": 45, "y0": 37, "x1": 45, "y1": 39}}, - {"name": "youngster_4", "kind": "npc", "x": 10, "y": 16, "facing": "north"}, - {"name": "worker_15", "kind": "npc", "x": 11, "y": 25}, - {"name": "worker_16", "kind": "npc", "x": 56, "y": 57, "wander": {"x0": 55, "y0": 54, "x1": 57, "y1": 60}}, - {"name": "camper_17", "kind": "npc", "x": 36, "y": 19, "wander": {"x0": 33, "y0": 19, "x1": 39, "y1": 19}}, - {"name": "worker_18", "kind": "npc", "x": 37, "y": 39, "wander": {"x0": 36, "y0": 38, "x1": 38, "y1": 40}}, - {"name": "worker_19", "kind": "npc", "x": 50, "y": 41, "wander": {"x0": 50, "y0": 38, "x1": 50, "y1": 44}}, - {"name": "guitarist_20", "kind": "npc", "x": 23, "y": 13, "wander": {"x0": 22, "y0": 10, "x1": 24, "y1": 16}}, - {"name": "battle_girl_21", "kind": "npc", "x": 36, "y": 23, "wander": {"x0": 36, "y0": 21, "x1": 36, "y1": 25}}, - {"name": "machop_22", "kind": "npc", "x": 55, "y": 56, "wander": {"x0": 53, "y0": 54, "x1": 57, "y1": 58}} - ], "coord_events": [ - {"name": "coord_event_0", "x": 10, "y": 12, "width": 1, "length": 4, "var": "VAR_OREBURGH_CITY_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[0] (266, 748), script 3"}, - {"name": "coord_event_1", "x": 6, "y": 12, "width": 1, "length": 4, "var": "VAR_OREBURGH_CITY_STATE", "value": 2, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[1] (262, 748), script 4"} + { + "name": "coord_event_0", + "coord": [10, 12], + "width": 1, + "length": 4, + "var": "VAR_OREBURGH_CITY_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[0] (266, 748), script 3" + }, + { + "name": "coord_event_1", + "coord": [6, 12], + "width": 1, + "length": 4, + "var": "VAR_OREBURGH_CITY_STATE", + "value": 2, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[1] (262, 748), script 4" + } + ], + "npcs": [ + {"name": "hiker_0", "coord": [47, 26], "wander": {"min": [46, 25], "max": [48, 27]}}, + {"name": "school_kid_f_1", "coord": [32, 18], "wander": {"min": [32, 16], "max": [32, 20]}}, + {"name": "pokefan_f_2", "coord": [45, 38], "wander": {"min": [45, 37], "max": [45, 39]}}, + {"name": "youngster_4", "coord": [10, 16], "facing": "north"}, + {"name": "worker_15", "coord": [11, 25]}, + {"name": "worker_16", "coord": [56, 57], "wander": {"min": [55, 54], "max": [57, 60]}}, + {"name": "camper_17", "coord": [36, 19], "wander": {"min": [33, 19], "max": [39, 19]}}, + {"name": "worker_18", "coord": [37, 39], "wander": {"min": [36, 38], "max": [38, 40]}}, + {"name": "worker_19", "coord": [50, 41], "wander": {"min": [50, 38], "max": [50, 44]}}, + {"name": "guitarist_20", "coord": [23, 13], "wander": {"min": [22, 10], "max": [24, 16]}}, + {"name": "battle_girl_21", "coord": [36, 23], "wander": {"min": [36, 21], "max": [36, 25]}}, + {"name": "machop_22", "coord": [55, 56], "wander": {"min": [53, 54], "max": [57, 58]}} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json index f3f6b5a73b..d0d6ba3ad5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "OreburghGate", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0418.bin; zone_event narc_0250", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0418.bin; zone_event narc_0250", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "################################", "################################", @@ -35,12 +40,20 @@ "################################", "################################" ], - "objects": [ - {"name": "picnicker_0", "kind": "npc", "x": 24, "y": 21, "facing": "south"}, - {"name": "camper_1", "kind": "npc", "x": 17, "y": 25, "facing": "north"}, - {"name": "hiker_10", "kind": "npc", "x": 7, "y": 20, "facing": "south"} - ], "coord_events": [ - {"name": "coord_event_0", "x": 7, "y": 22, "width": 1, "length": 1, "var": "VAR_OREBURGH_GATE_1F_HIKER_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0250.bin coord_events[0] (7, 22), script 3"} + { + "name": "coord_event_0", + "coord": [7, 22], + "width": 1, + "length": 1, + "var": "VAR_OREBURGH_GATE_1F_HIKER_STATE", + "value": 1, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0250.bin coord_events[0] (7, 22), script 3" + } + ], + "npcs": [ + {"name": "picnicker_0", "coord": [24, 21], "facing": "south"}, + {"name": "camper_1", "coord": [17, 25], "facing": "north"}, + {"name": "hiker_10", "coord": [7, 20], "facing": "south"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json index 89341d5b3a..f9298e4aca 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "OreburghGym", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0228.bin; zone_event narc_0046", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0228.bin; zone_event narc_0046", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "################################", "################################", @@ -41,10 +46,10 @@ "trainer_first_tier": [4, 18], "trainer_second_tier": [7, 11] }, - "objects": [ - {"name": "roark_0", "kind": "npc", "x": 5, "y": 3, "facing": "south"}, - {"name": "gym_guide_1", "kind": "npc", "x": 6, "y": 23, "facing": "south"}, - {"name": "youngster_2", "kind": "npc", "x": 4, "y": 18, "facing": "east"}, - {"name": "youngster_3", "kind": "npc", "x": 7, "y": 11, "facing": "west"} + "npcs": [ + {"name": "roark_0", "coord": [5, 3], "facing": "south"}, + {"name": "gym_guide_1", "coord": [6, 23], "facing": "south"}, + {"name": "youngster_2", "coord": [4, 18], "facing": "east"}, + {"name": "youngster_3", "coord": [7, 11], "facing": "west"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json index d8ea9a4ff6..362506d13c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "OreburghMine", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0314.bin; zone_event narc_0197", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0314.bin; zone_event narc_0197", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "################################", "###############D################", @@ -42,15 +47,17 @@ "corridor_top.2": [15, 2], "corridor_top.3": [16, 2] }, - "objects": [ - {"name": "roark", "kind": "npc", "x": 18, "y": 28, "facing": "east"}, - {"name": "item_3", "kind": "item", "x": 4, "y": 28}, - {"name": "item_4", "kind": "item", "x": 26, "y": 24}, - {"name": "worker_5", "kind": "npc", "x": 8, "y": 28, "facing": "north"}, - {"name": "worker_6", "kind": "npc", "x": 26, "y": 20, "facing": "west"}, - {"name": "worker_7", "kind": "npc", "x": 21, "y": 15, "facing": "north"}, - {"name": "machop_8", "kind": "npc", "x": 12, "y": 28, "wander": {"x0": 11, "y0": 28, "x1": 13, "y1": 28}}, - {"name": "machop_9", "kind": "npc", "x": 20, "y": 15}, - {"name": "machop_10", "kind": "npc", "x": 27, "y": 15, "facing": "north"} + "npcs": [ + {"name": "roark", "coord": [18, 28], "facing": "east"}, + {"name": "worker_5", "coord": [8, 28], "facing": "north"}, + {"name": "worker_6", "coord": [26, 20], "facing": "west"}, + {"name": "worker_7", "coord": [21, 15], "facing": "north"}, + {"name": "machop_8", "coord": [12, 28], "wander": {"min": [11, 28], "max": [13, 28]}}, + {"name": "machop_9", "coord": [20, 15]}, + {"name": "machop_10", "coord": [27, 15], "facing": "north"} + ], + "items": [ + {"name": "item_3", "coord": [4, 28]}, + {"name": "item_4", "coord": [26, 24]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json new file mode 100644 index 0000000000..8b3ed98419 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json @@ -0,0 +1,50 @@ +{ + "format": "pokesim-runtime-map/2", + "name": "OreburghMineB1F", + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0313.bin; zone_event narc_0196", + "revision": "default branch", + "date": "2026-10-31" + }, + "tiles": [ + "################################", + "###########DDD##################", + "######...##...##.###############", + "######...##...##.###############", + "####.................###########", + "####.................###########", + "####.................###########", + "####.................###########", + "####.................###########", + "####.................###########", + "######.............#############", + "######.............#############", + "######.............#############", + "######.............#############", + "########.........###############", + "########.........###############", + "########.........###############", + "########.........###############", + "##########.....#################", + "##########.....#################", + "##########.....#################", + "##########.DDD.#################", + "############D###################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################", + "################################" + ], + "npcs": [ + {"name": "worker_0", "coord": [7, 4]}, + {"name": "twin_2", "coord": [6, 3]} + ], + "items": [ + {"name": "item_1", "coord": [19, 4]} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json index c959a1a426..f50a0f7ecb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "PlayerHouse1F", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": { + "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp only, not checked on the console", + "revision": "c6689696d5fb", + "date": "2026-11-01" + }, "tiles": [ "#############", "#############", @@ -21,16 +26,32 @@ "door": [6, 10] }, "warps": [ - {"x": 6, "y": 10, "to_map": "TwinleafTown", "to_point": "player_house_door"} - ], - "objects": [ - {"name": "mom_0", "kind": "npc", "x": 7, "y": 8, "facing": "north"} + {"coord": [6, 10], "to_map": "TwinleafTown", "to_point": "player_house_door"} ], "coord_events": [ - {"name": "moms_warning", "x": 6, "y": 10, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_STATE", "value": 1, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_1f.json coord_events[0] (6, 10), script 5"}, - {"name": "moms_call", "x": 6, "y": 9, "width": 1, "length": 1, "var": "CONSOLE_MOMS_CALL", "value": 0, "source": "console r45, r46 (2026-11-01): after her heal Mom calls us back as we step above the door; no coord event in the decomp"} + { + "name": "moms_warning", + "coord": [6, 10], + "width": 1, + "length": 1, + "var": "VAR_PLAYER_HOUSE_STATE", + "value": 1, + "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_1f.json coord_events[0] (6, 10), script 5" + }, + { + "name": "moms_call", + "coord": [6, 10], + "width": 1, + "length": 1, + "var": "CONSOLE_MOMS_CALL", + "value": 0, + "source": "console r45, r46 (2026-11-01): after her heal Mom calls us back as we step onto the mat (6, 10); no coord event in the decomp" + } ], "patches": [ - {"x": 4, "y": 8, "glyph": ".", "measured_by": "r32, 2026-11-01"} + {"coord": [4, 8], "glyph": ".", "measured_by": "r32, 2026-11-01"} + ], + "npcs": [ + {"name": "mom_0", "coord": [7, 8], "facing": "north"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json index c78c817c70..366de55b12 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "PlayerHouse2F", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_187.bin; events_twinleaf_town_player_house_2f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": { + "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_187.bin; events_twinleaf_town_player_house_2f.json; decomp only, not checked on the console", + "revision": "c6689696d5fb", + "date": "2026-11-01" + }, "tiles": [ "############", "############", @@ -20,9 +25,41 @@ "start": [4, 6] }, "coord_events": [ - {"name": "coord_event_0", "x": 4, "y": 5, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[0] (4, 5), script 7"}, - {"name": "coord_event_1", "x": 3, "y": 6, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[1] (3, 6), script 8"}, - {"name": "coord_event_2", "x": 5, "y": 6, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[2] (5, 6), script 9"}, - {"name": "coord_event_3", "x": 4, "y": 7, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[3] (4, 7), script 10"} + { + "name": "coord_event_0", + "coord": [4, 5], + "width": 1, + "length": 1, + "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", + "value": 0, + "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[0] (4, 5), script 7" + }, + { + "name": "coord_event_1", + "coord": [3, 6], + "width": 1, + "length": 1, + "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", + "value": 0, + "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[1] (3, 6), script 8" + }, + { + "name": "coord_event_2", + "coord": [5, 6], + "width": 1, + "length": 1, + "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", + "value": 0, + "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[2] (5, 6), script 9" + }, + { + "name": "coord_event_3", + "coord": [4, 7], + "width": 1, + "length": 1, + "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", + "value": 0, + "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[3] (4, 7), script 10" + } ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json index 7c48de6775..5fbeb4969b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "RavagedPath", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_435.bin, res/field/maps/data/map_data_436.bin; events_ravaged_path.json", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_435.bin, res/field/maps/data/map_data_436.bin; events_ravaged_path.json", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "................................", "................................", @@ -78,10 +83,10 @@ "before_rocks.1": [21, 42], "before_rocks.2": [21, 43] }, - "objects": [ - {"name": "item_27", "kind": "item", "x": 7, "y": 38}, - {"name": "item_28", "kind": "item", "x": 17, "y": 11}, - {"name": "item_29", "kind": "item", "x": 28, "y": 5}, - {"name": "item_30", "kind": "item", "x": 22, "y": 44} + "items": [ + {"name": "item_27", "coord": [7, 38]}, + {"name": "item_28", "coord": [17, 11]}, + {"name": "item_29", "coord": [28, 5]}, + {"name": "item_30", "coord": [22, 44]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json index 7d1b616c29..82a2a042e4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "RivalHouse1F", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_184.bin; events_twinleaf_town_rival_house_1f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": { + "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_184.bin; events_twinleaf_town_rival_house_1f.json; decomp only, not checked on the console", + "revision": "c6689696d5fb", + "date": "2026-11-01" + }, "tiles": [ "#############", "#############", @@ -20,9 +25,9 @@ "stairs": [2, 3] }, "warps": [ - {"x": 6, "y": 10, "to_map": "TwinleafTown", "to_point": "rival_house_door"} + {"coord": [6, 10], "to_map": "TwinleafTown", "to_point": "rival_house_door"} ], - "objects": [ - {"name": "pokefan_f_0", "kind": "npc", "x": 4, "y": 6} + "npcs": [ + {"name": "pokefan_f_0", "coord": [4, 6]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json index d0b03b36e6..3da7eb8d6a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "RivalHouse2F", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_185.bin; events_twinleaf_town_rival_house_2f.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": { + "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_185.bin; events_twinleaf_town_rival_house_2f.json; decomp only, not checked on the console", + "revision": "c6689696d5fb", + "date": "2026-11-01" + }, "tiles": [ "############", "############", @@ -19,7 +24,7 @@ "stairs": [3, 4], "barry_talk": [8, 5] }, - "objects": [ - {"name": "barry", "kind": "npc", "x": 9, "y": 5, "facing": "north"} + "npcs": [ + {"name": "barry", "coord": [9, 5], "facing": "north"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json index fe88167472..5b190bc277 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "Route201", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0005.bin, files/fielddata/land_data/land_data_release/narc_0006.bin; zone_event narc_0327", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0005.bin, files/fielddata/land_data/land_data_release/narc_0006.bin; zone_event narc_0327", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "################################################################", "################################################################", @@ -38,23 +43,47 @@ "rowan_stop": [5, 14], "route_201_east_end": [63, 5] }, - "objects": [ - {"name": "pokemon_breeder_m_0", "kind": "npc", "x": 27, "y": 15, "wander": {"x0": 26, "y0": 14, "x1": 28, "y1": 16}}, - {"name": "school_kid_m_9", "kind": "npc", "x": 57, "y": 8, "facing": "west"}, - {"name": "lass_11", "kind": "npc", "x": 46, "y": 16, "wander": {"x0": 44, "y0": 16, "x1": 48, "y1": 16}} - ], "coord_events": [ - {"name": "barry_warning", "x": 14, "y": 18, "width": 6, "length": 1, "var": "VAR_FOLLOWER_RIVAL_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[0] (110, 857), script 2"}, - {"name": "rowan_stop", "x": 5, "y": 14, "width": 1, "length": 3, "var": "VAR_FOLLOWER_RIVAL_STATE", "value": 2, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[1] (101, 853), script 5"}, - {"name": "coord_event_2", "x": 14, "y": 19, "width": 6, "length": 1, "var": "VAR_FOLLOWER_RIVAL_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[2] (110, 858), script 3"} + { + "name": "barry_warning", + "coord": [14, 18], + "width": 6, + "length": 1, + "var": "VAR_FOLLOWER_RIVAL_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[0] (110, 857), script 2" + }, + { + "name": "rowan_stop", + "coord": [5, 14], + "width": 1, + "length": 3, + "var": "VAR_FOLLOWER_RIVAL_STATE", + "value": 2, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[1] (101, 853), script 5" + }, + { + "name": "coord_event_2", + "coord": [14, 19], + "width": 6, + "length": 1, + "var": "VAR_FOLLOWER_RIVAL_STATE", + "value": 1, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[2] (110, 858), script 3" + } ], "patches": [ - {"x": 8, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"x": 9, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"x": 10, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"x": 11, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"x": 12, "y": 18, "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"x": 13, "y": 18, "glyph": "S", "measured_by": "r16, 2026-10-31"}, - {"x": 13, "y": 17, "glyph": ".", "measured_by": "r16, 2026-10-31"} + {"coord": [8, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"coord": [9, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"coord": [10, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"coord": [11, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"coord": [12, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, + {"coord": [13, 18], "glyph": "S", "measured_by": "r16, 2026-10-31"}, + {"coord": [13, 17], "glyph": ".", "measured_by": "r16, 2026-10-31"} + ], + "npcs": [ + {"name": "pokemon_breeder_m_0", "coord": [27, 15], "wander": {"min": [26, 14], "max": [28, 16]}}, + {"name": "school_kid_m_9", "coord": [57, 8], "facing": "west"}, + {"name": "lass_11", "coord": [46, 16], "wander": {"min": [44, 16], "max": [48, 16]}} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json index 50486733f1..896620ce5c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "Route202", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0014.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0328", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0014.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0328", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "###########........#################", "###########........#################", @@ -116,29 +121,39 @@ "catch_grass.8": [19, 27], "catch_grass.9": [20, 27] }, - "objects": [ - {"name": "youngster_0", "kind": "npc", "x": 7, "y": 13, "facing": "south"}, - {"name": "lass_1", "kind": "npc", "x": 22, "y": 18, "facing": "south"}, - {"name": "youngster_2", "kind": "npc", "x": 26, "y": 4, "facing": "south"}, - {"name": "youngster_7", "kind": "npc", "x": 10, "y": 8, "wander": {"x0": 9, "y0": 8, "x1": 11, "y1": 8}}, - {"name": "item_8", "kind": "item", "x": 3, "y": 6} - ], "coord_events": [ - {"name": "catch_tutorial", "x": 21, "y": 25, "width": 1, "length": 5, "var": "VAR_ROUTE_202_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0328.bin coord_events[0] (180, 825), script 6"} + { + "name": "catch_tutorial", + "coord": [21, 25], + "width": 1, + "length": 5, + "var": "VAR_ROUTE_202_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0328.bin coord_events[0] (180, 825), script 6" + } ], "patches": [ - {"x": 15, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 16, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 17, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 18, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 19, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 20, "y": 28, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 15, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 16, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 17, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 18, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 19, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 20, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"x": 21, "y": 30, "glyph": "#", "measured_by": "r254, 2026-11-01"} + {"coord": [15, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [16, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [17, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [18, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [19, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [20, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [15, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [16, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [17, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [18, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [19, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [20, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, + {"coord": [21, 30], "glyph": "#", "measured_by": "r254, 2026-11-01"} + ], + "npcs": [ + {"name": "youngster_0", "coord": [7, 13], "facing": "south"}, + {"name": "lass_1", "coord": [22, 18], "facing": "south"}, + {"name": "youngster_2", "coord": [26, 4], "facing": "south"}, + {"name": "youngster_7", "coord": [10, 8], "wander": {"min": [9, 8], "max": [11, 8]}} + ], + "items": [ + {"name": "item_8", "coord": [3, 6]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json index faccffbe74..8a66bb297f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "Route203", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0019.bin, files/fielddata/land_data/land_data_release/narc_0020.bin; zone_event narc_0329", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0019.bin, files/fielddata/land_data/land_data_release/narc_0020.bin; zone_event narc_0329", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "#############################################################", "#############################################################", @@ -52,16 +57,26 @@ "west_line.18": [41, 18], "west_line.19": [42, 18] }, - "objects": [ - {"name": "youngster_1", "kind": "npc", "x": 13, "y": 10, "facing": "west"}, - {"name": "lass_2", "kind": "npc", "x": 43, "y": 17, "facing": "west"}, - {"name": "youngster_3", "kind": "npc", "x": 31, "y": 16, "facing": "south"}, - {"name": "lass_4", "kind": "npc", "x": 49, "y": 8, "facing": "south"}, - {"name": "item_10", "kind": "item", "x": 31, "y": 5}, - {"name": "item_11", "kind": "item", "x": 20, "y": 10}, - {"name": "lass_12", "kind": "npc", "x": 15, "y": 17, "wander": {"x0": 14, "y0": 17, "x1": 16, "y1": 17}} - ], "coord_events": [ - {"name": "coord_event_0", "x": 5, "y": 17, "width": 1, "length": 4, "var": "VAR_ROUTE_203_RIVAL_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0329.bin coord_events[0] (196, 757), script 6"} + { + "name": "coord_event_0", + "coord": [5, 17], + "width": 1, + "length": 4, + "var": "VAR_ROUTE_203_RIVAL_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0329.bin coord_events[0] (196, 757), script 6" + } + ], + "npcs": [ + {"name": "youngster_1", "coord": [13, 10], "facing": "west"}, + {"name": "lass_2", "coord": [43, 17], "facing": "west"}, + {"name": "youngster_3", "coord": [31, 16], "facing": "south"}, + {"name": "lass_4", "coord": [49, 8], "facing": "south"}, + {"name": "lass_12", "coord": [15, 17], "wander": {"min": [14, 17], "max": [16, 17]}} + ], + "items": [ + {"name": "item_10", "coord": [31, 5]}, + {"name": "item_11", "coord": [20, 10]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json index 65fe1fb8cf..e98b687858 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "Route204North", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0031.bin; zone_event narc_0331", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0031.bin; zone_event narc_0331", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "########.#...###################", "########.#...###################", @@ -67,17 +72,19 @@ "trainer_taylor": [17, 20], "trainer_brandon": [20, 12] }, - "objects": [ - {"name": "bug_catcher_brandon", "kind": "npc", "x": 20, "y": 12}, - {"name": "pokemon_breeder_f_1", "kind": "npc", "x": 17, "y": 20}, - {"name": "twin_2", "kind": "npc", "x": 15, "y": 7, "facing": "south"}, - {"name": "twin_3", "kind": "npc", "x": 16, "y": 7, "facing": "south"}, - {"name": "youngster_4", "kind": "npc", "x": 15, "y": 28, "wander": {"x0": 14, "y0": 28, "x1": 16, "y1": 28}}, - {"name": "item_9", "kind": "item", "x": 2, "y": 10}, - {"name": "ace_trainer_f_10", "kind": "npc", "x": 31, "y": 4, "facing": "west"}, - {"name": "item_11", "kind": "item", "x": 20, "y": 23} - ], "patches": [ - {"x": 12, "y": 6, "glyph": "#", "measured_by": "r248a, 2026-10-31"} + {"coord": [12, 6], "glyph": "#", "measured_by": "r248a, 2026-10-31"} + ], + "npcs": [ + {"name": "bug_catcher_brandon", "coord": [20, 12]}, + {"name": "pokemon_breeder_f_1", "coord": [17, 20]}, + {"name": "twin_2", "coord": [15, 7], "facing": "south"}, + {"name": "twin_3", "coord": [16, 7], "facing": "south"}, + {"name": "youngster_4", "coord": [15, 28], "wander": {"min": [14, 28], "max": [16, 28]}}, + {"name": "ace_trainer_f_10", "coord": [31, 4], "facing": "west"} + ], + "items": [ + {"name": "item_9", "coord": [2, 10]}, + {"name": "item_11", "coord": [20, 23]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json index d70775dce3..ed745aa65e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "Route204South", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0021.bin; zone_event narc_0330", "revision": "default branch", "date": "2026-11-01"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0021.bin; zone_event narc_0330", + "revision": "default branch", + "date": "2026-11-01" + }, "tiles": [ "################################", "###########D###.################", @@ -44,13 +49,15 @@ "trainer_sarah": [12, 21], "trainer_tyler": [7, 18] }, - "objects": [ - {"name": "lass_0", "kind": "npc", "x": 12, "y": 21}, - {"name": "lass_1", "kind": "npc", "x": 11, "y": 8, "facing": "south"}, - {"name": "youngster_2", "kind": "npc", "x": 7, "y": 18}, - {"name": "youngster_3", "kind": "npc", "x": 13, "y": 2, "wander": {"x0": 12, "y0": 2, "x1": 14, "y1": 2}}, - {"name": "item_7", "kind": "item", "x": 2, "y": 28}, - {"name": "item_8", "kind": "item", "x": 29, "y": 12}, - {"name": "item_9", "kind": "item", "x": 17, "y": 18} + "npcs": [ + {"name": "lass_0", "coord": [12, 21]}, + {"name": "lass_1", "coord": [11, 8], "facing": "south"}, + {"name": "youngster_2", "coord": [7, 18]}, + {"name": "youngster_3", "coord": [13, 2], "wander": {"min": [12, 2], "max": [14, 2]}} + ], + "items": [ + {"name": "item_7", "coord": [2, 28]}, + {"name": "item_8", "coord": [29, 12]}, + {"name": "item_9", "coord": [17, 18]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json index 8faef4e607..0ba5cde636 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "RowansLab", - "source": {"decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_222.bin; events_sandgem_town_pokemon_research_lab.json; decomp only, not checked on the console", "revision": "c6689696d5fb", "date": "2026-11-01"}, + "source": { + "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_222.bin; events_sandgem_town_pokemon_research_lab.json; decomp only, not checked on the console", + "revision": "c6689696d5fb", + "date": "2026-11-01" + }, "tiles": [ "######################", "######################", @@ -26,11 +31,11 @@ "rowan_talk": [7, 6] }, "warps": [ - {"x": 7, "y": 15, "to_map": "SandgemTown", "to_point": "lab_door"} + {"coord": [7, 15], "to_map": "SandgemTown", "to_point": "lab_door"} ], - "objects": [ - {"name": "rowan", "kind": "npc", "x": 7, "y": 5, "facing": "south"}, - {"name": "scientist_m_1", "kind": "npc", "x": 3, "y": 12, "wander": {"x0": 1, "y0": 12, "x1": 5, "y1": 12}}, - {"name": "scientist_f_2", "kind": "npc", "x": 10, "y": 12} + "npcs": [ + {"name": "rowan", "coord": [7, 5], "facing": "south"}, + {"name": "scientist_m_1", "coord": [3, 12], "wander": {"min": [1, 12], "max": [5, 12]}}, + {"name": "scientist_f_2", "coord": [10, 12]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json index 3691f9266e..9c3f88a9d9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "SandgemTown", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "########################......####", "########################......####", @@ -49,10 +54,18 @@ "sandgem_arrival": [0, 12], "dawn_stop": [4, 12] }, - "objects": [ - {"name": "youngster_0", "kind": "npc", "x": 27, "y": 23, "wander": {"x0": 26, "y0": 22, "x1": 28, "y1": 24}} - ], "coord_events": [ - {"name": "dawn_walks_us_to_the_lab", "x": 4, "y": 10, "width": 1, "length": 6, "var": "VAR_SANDGEM_TOWN_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0396.bin coord_events[0] (164, 842), script 2"} + { + "name": "dawn_walks_us_to_the_lab", + "coord": [4, 10], + "width": 1, + "length": 6, + "var": "VAR_SANDGEM_TOWN_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0396.bin coord_events[0] (164, 842), script 2" + } + ], + "npcs": [ + {"name": "youngster_0", "coord": [27, 23], "wander": {"min": [26, 22], "max": [28, 24]}} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json index 9441a324e5..d8fa00a75c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "TwinleafTown", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0000.bin; zone_event narc_0389", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0000.bin; zone_event narc_0389", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "############........############", "#######....#........#....#######", @@ -42,13 +47,29 @@ "player_house_door": [20, 21], "rival_house_door": [9, 11] }, - "objects": [ - {"name": "pokemon_breeder_f_0", "kind": "npc", "x": 23, "y": 14, "wander": {"x0": 22, "y0": 14, "x1": 24, "y1": 14}}, - {"name": "collector_1", "kind": "npc", "x": 12, "y": 25}, - {"name": "guitarist_3", "kind": "npc", "x": 12, "y": 5} - ], "coord_events": [ - {"name": "coord_event_0", "x": 12, "y": 3, "width": 8, "length": 1, "var": "VAR_TWINLEAF_TOWN_GUITARIST_TRIGGER_STATE", "value": 1, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[0] (108, 867), script 4"}, - {"name": "barry_doorstep", "x": 9, "y": 12, "width": 1, "length": 1, "var": "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[1] (105, 876), script 2"} + { + "name": "coord_event_0", + "coord": [12, 3], + "width": 8, + "length": 1, + "var": "VAR_TWINLEAF_TOWN_GUITARIST_TRIGGER_STATE", + "value": 1, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[0] (108, 867), script 4" + }, + { + "name": "barry_doorstep", + "coord": [9, 12], + "width": 1, + "length": 1, + "var": "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[1] (105, 876), script 2" + } + ], + "npcs": [ + {"name": "pokemon_breeder_f_0", "coord": [23, 14], "wander": {"min": [22, 14], "max": [24, 14]}}, + {"name": "collector_1", "coord": [12, 25]}, + {"name": "guitarist_3", "coord": [12, 5]} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json index f7e12b3b98..de9e05d987 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json @@ -1,6 +1,11 @@ { + "format": "pokesim-runtime-map/2", "name": "VerityLakefront", - "source": {"decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0004.bin; zone_event narc_0319", "revision": "default branch", "date": "2026-10-31"}, + "source": { + "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0004.bin; zone_event narc_0319", + "revision": "default branch", + "date": "2026-10-31" + }, "tiles": [ "....############################", "....############################", @@ -41,7 +46,23 @@ "lake_entrance": [17, 12] }, "coord_events": [ - {"name": "lake_entrance", "x": 16, "y": 12, "width": 2, "length": 1, "var": "VAR_VERITY_LAKEFRONT_STATE", "value": 0, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[0] (80, 844), script 3"}, - {"name": "coord_event_1", "x": 16, "y": 12, "width": 2, "length": 1, "var": "VAR_VERITY_LAKEFRONT_STATE", "value": 3, "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[1] (80, 844), script 4"} + { + "name": "lake_entrance", + "coord": [16, 12], + "width": 2, + "length": 1, + "var": "VAR_VERITY_LAKEFRONT_STATE", + "value": 0, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[0] (80, 844), script 3" + }, + { + "name": "coord_event_1", + "coord": [16, 12], + "width": 2, + "length": 1, + "var": "VAR_VERITY_LAKEFRONT_STATE", + "value": 3, + "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[1] (80, 844), script 4" + } ] } From 40cc6a75a5b1cd1673008110872666785b302555 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 14:14:52 -0800 Subject: [PATCH 58/74] BDSP nav: fix C4456 local declaration shadowing in static lambdas --- .../Data/PokemonBDSP_AutoStory_RouteRecords.cpp | 4 ++-- .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 12 ++++++------ .../Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 16 ++++++++-------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp index 2522d854c3..8c79df9f26 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -162,8 +162,8 @@ const std::vector& all(){ static const std::vector records = []{ std::vector all; for (auto part : {checkpoint_0001_records, checkpoints_0002_0003_records, segment01_records_to_oreburgh, segment01_records_from_jubilife}){ - const std::vector records = part(); - all.insert(all.end(), records.begin(), records.end()); + const std::vector part_records = part(); + all.insert(all.end(), part_records.begin(), part_records.end()); } return all; }(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp index 9d7d7311ce..6c546e89e7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -29,12 +29,12 @@ const char* const MAP_VERITY_LAKEFRONT = "Verity Lakefront"; // cell. const StoryWorld& segment00_maps(){ static const StoryWorld maps = []{ - StoryWorld maps; - maps.add(MAP_TWINLEAF_TOWN, story_map("TwinleafTown"), {96, 864}); - maps.add(MAP_ROUTE_201, story_map("Route201"), {96, 839}); - maps.add(MAP_VERITY_LAKEFRONT, story_map("VerityLakefront"), {64, 832}); - maps.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {160, 832}); - return maps; + StoryWorld world; + world.add(MAP_TWINLEAF_TOWN, story_map("TwinleafTown"), {96, 864}); + world.add(MAP_ROUTE_201, story_map("Route201"), {96, 839}); + world.add(MAP_VERITY_LAKEFRONT, story_map("VerityLakefront"), {64, 832}); + world.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {160, 832}); + return world; }(); return maps; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp index 7934c88438..4e21902d76 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -75,11 +75,11 @@ bool in_region(const std::string& map, const std::string& region, const TilePos& // Route 202's road comes down off its row 31 onto Sandgem's row 0. const StoryWorld& story_maps(){ static const StoryWorld maps = []{ - StoryWorld maps; - maps.add(MAP_ROUTE_201, story_map("Route201"), {0, 0}); - maps.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {64, -7}); - maps.add(MAP_ROUTE_202, story_map("Route202"), {63, -39}); - return maps; + StoryWorld world; + world.add(MAP_ROUTE_201, story_map("Route201"), {0, 0}); + world.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {64, -7}); + world.add(MAP_ROUTE_202, story_map("Route202"), {63, -39}); + return world; }(); return maps; } @@ -110,11 +110,11 @@ const int JUBILIFE_EAST_BOTTOM = 25; const StoryWorld& jubilife_east_maps(){ static const StoryWorld maps = []{ const MapData& city = story_map("JubilifeCity"); - StoryWorld maps; - maps.add(MAP_JUBILIFE_CITY, crop( + StoryWorld world; + world.add(MAP_JUBILIFE_CITY, crop( city, JUBILIFE_EAST_CORNER, city.tiles.width - JUBILIFE_EAST_CORNER.x, JUBILIFE_EAST_BOTTOM - JUBILIFE_EAST_CORNER.y + 1 ), {0, 0}); - return maps; + return world; }(); return maps; } From d2b89565b1c268c356a2d8abfab4b1308c900116 Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:17:17 -0800 Subject: [PATCH 59/74] BDSP: consume pinned Simulation map resources and pickup identities (#249) * Navigation: stage shared v1/v2 runtime map decoder * Navigation: enable compact maps through the existing parse_map API * Navigation: keep JSON diagnostic paths alive for GCC * Navigation tests: match shared FileIO Windows compiler policy * Canonicalize embedded map dependencies to prevent duplicate Ninja outputs * Allow native map parity fixtures from pinned v2 publishers * BDSP: build reconciled maps from pinned Simulation resources Keep bdsp_map_json as the native API, using validated Packages resources instead of source JSON. Retire duplicate authoring and forward the decomp CLI to Simulation. Pin the enriched candidate from Simulation #65, with resource preparation intentionally blocked until that revision is approved on publishing main. Native schema/legacy tests and 150 complete candidate decoder comparisons pass; full app builds follow publication. * Clarify repinning an unpublished resource candidate after squash * Runtime maps: expand optional pickup names and default quantity * Pin compact pickup defaults and inherit the shared reader update * Adopt the approved publishing squash and pickup-aware validator * Document Packages setup before preparing map resources --- .github/workflows/bdsp-map-resources.yml | 14 + .../workflows/cpp-ci-serial-programs-base.yml | 10 + .github/workflows/runtime-map-reader.yml | 29 + .gitignore | 12 +- SerialPrograms/CMakeLists.txt | 13 +- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../Pokemon/Navigation/Pokemon_MapData.cpp | 4 +- .../Pokemon/Navigation/Pokemon_MapData.h | 3 +- .../Pokemon/Navigation/Pokemon_RuntimeMap.cpp | 229 ++++++ .../Pokemon/Navigation/Pokemon_RuntimeMap.h | 22 + .../Navigation/Pokemon_RuntimeMap_Tests.cpp | 196 +++++ .../Navigation/Pokemon_RuntimeMap_Tests.h | 17 + .../Programs/AutoStory/Maps/FloaromaTown.json | 72 -- .../Programs/AutoStory/Maps/JubilifeCity.json | 191 ----- .../Programs/AutoStory/Maps/LakeVerity.json | 48 -- .../Programs/AutoStory/Maps/OreburghCity.json | 116 --- .../Programs/AutoStory/Maps/OreburghGate.json | 59 -- .../Programs/AutoStory/Maps/OreburghGym.json | 55 -- .../Programs/AutoStory/Maps/OreburghMine.json | 63 -- .../AutoStory/Maps/OreburghMineB1F.json | 50 -- .../AutoStory/Maps/PlayerHouse1F.json | 57 -- .../AutoStory/Maps/PlayerHouse2F.json | 65 -- .../Programs/AutoStory/Maps/RavagedPath.json | 92 --- .../Programs/AutoStory/Maps/RivalHouse1F.json | 33 - .../Programs/AutoStory/Maps/RivalHouse2F.json | 30 - .../Programs/AutoStory/Maps/Route201.json | 89 --- .../Programs/AutoStory/Maps/Route202.json | 159 ----- .../Programs/AutoStory/Maps/Route203.json | 82 --- .../AutoStory/Maps/Route204North.json | 90 --- .../AutoStory/Maps/Route204South.json | 63 -- .../Programs/AutoStory/Maps/RowansLab.json | 41 -- .../Programs/AutoStory/Maps/SandgemTown.json | 71 -- .../Programs/AutoStory/Maps/TwinleafTown.json | 75 -- .../AutoStory/Maps/VerityLakefront.json | 68 -- SerialPrograms/cmake/EmbedTextFiles.cmake | 5 +- SerialPrograms/cmake/SourceFiles.cmake | 4 + devtools/maps/README.md | 6 + devtools/maps/RESOURCE_MAPS.md | 91 +++ devtools/maps/__main__.py | 8 +- devtools/maps/bdsp_maps.py | 671 ------------------ devtools/maps/decomp.py | 593 ---------------- devtools/maps/map-resources.lock.json | 11 + devtools/maps/tests/test_decomp.py | 263 ------- devtools/runtime-map-tests/CMakeLists.txt | 65 ++ devtools/runtime-map-tests/README.md | 55 ++ devtools/runtime-map-tests/legacy_tests.cpp | 37 + devtools/runtime-map-tests/prepare_parity.py | 55 ++ 47 files changed, 878 insertions(+), 3206 deletions(-) create mode 100644 .github/workflows/bdsp-map-resources.yml create mode 100644 .github/workflows/runtime-map-reader.yml create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json create mode 100644 devtools/maps/RESOURCE_MAPS.md delete mode 100644 devtools/maps/bdsp_maps.py delete mode 100644 devtools/maps/decomp.py create mode 100644 devtools/maps/map-resources.lock.json delete mode 100644 devtools/maps/tests/test_decomp.py create mode 100644 devtools/runtime-map-tests/CMakeLists.txt create mode 100644 devtools/runtime-map-tests/README.md create mode 100644 devtools/runtime-map-tests/legacy_tests.cpp create mode 100644 devtools/runtime-map-tests/prepare_parity.py diff --git a/.github/workflows/bdsp-map-resources.yml b/.github/workflows/bdsp-map-resources.yml new file mode 100644 index 0000000000..644eecd648 --- /dev/null +++ b/.github/workflows/bdsp-map-resources.yml @@ -0,0 +1,14 @@ +name: BDSP map resources +on: + pull_request: + workflow_dispatch: +jobs: + integrity: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Prepare and check the approved BDSP resource pin + uses: dayfine/PokemonSimulation/integrations/arduino-source/verify-map-packs@4de7742a764d27293b4525d6ad2a6fc8a95f3e3a + with: + layout: resources + operation: prepare diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 58f1a9d890..a87f526da4 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -88,6 +88,14 @@ jobs: ref: 'master' path: 'Arduino-Source/Packages' + - name: Prepare pinned BDSP map resources + id: map-resources + uses: dayfine/PokemonSimulation/integrations/arduino-source/verify-map-packs@4de7742a764d27293b4525d6ad2a6fc8a95f3e3a + with: + layout: resources + operation: prepare + consumer-directory: Arduino-Source + - name: Install Qt uses: jurplel/install-qt-action@v4 with: @@ -204,6 +212,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/.github/workflows/runtime-map-reader.yml b/.github/workflows/runtime-map-reader.yml new file mode 100644 index 0000000000..027383c60b --- /dev/null +++ b/.github/workflows/runtime-map-reader.yml @@ -0,0 +1,29 @@ +name: Runtime map reader +on: + pull_request: + workflow_dispatch: +jobs: + native-schema: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - uses: actions/checkout@v7 + with: + repository: dayfine/PokemonSimulation + ref: 4de7742a764d27293b4525d6ad2a6fc8a95f3e3a + path: publisher + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - run: python devtools/runtime-map-tests/prepare_parity.py --publisher publisher --publisher-revision 4de7742a764d27293b4525d6ad2a6fc8a95f3e3a --out runtime-map-pairs.json + - run: cmake -S devtools/runtime-map-tests -B build-runtime-maps -DCMAKE_BUILD_TYPE=Debug + - run: cmake --build build-runtime-maps --config Debug -j4 + - run: ctest --test-dir build-runtime-maps -C Debug --output-on-failure + - if: runner.os != 'Windows' + run: ./build-runtime-maps/RuntimeMapTests runtime-map-pairs.json + - if: runner.os == 'Windows' + run: ./build-runtime-maps/Debug/RuntimeMapTests.exe runtime-map-pairs.json diff --git a/.gitignore b/.gitignore index ef6f409ae9..ab64316491 100644 --- a/.gitignore +++ b/.gitignore @@ -77,7 +77,11 @@ build_*/ .cache/* Packages/* - -# Local agent/linter environments. -.venv-code-health/ -__pycache__/ + +# Local agent/linter environments. +.venv-code-health/ +__pycache__/ + +# Prepared, pinned PokemonSimulation maps are external build inputs. +Packages/Resources/Pokemon/Maps/ +.pokesim-map-source/ diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index ad0ff7ae70..69bc4aca92 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -197,7 +197,18 @@ 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) -pa_embed_text_files(SerialProgramsLib Source/PokemonBDSP/Programs/AutoStory/Maps +# Prepared data is validated by the shared publisher tooling. No source-map +# fallback or network download is performed during configuration. +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 "Prepare devtools/maps/map-resources.lock.json and set POKESIM_TOOLS_SOURCE/POKESIM_SOURCE_CACHE; see devtools/maps/RESOURCE_MAPS.md.") +endif() +include("${POKESIM_TOOLS_SOURCE}/integrations/arduino-source/resource-maps.cmake") +get_filename_component(POKESIM_CONSUMER "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE) +pa_pokesim_map_directory(BDSP_MAP_DIRECTORY bdsp "${POKESIM_CONSUMER}" "${POKESIM_SOURCE_CACHE}") +file(RELATIVE_PATH BDSP_MAP_RESOURCES "${CMAKE_CURRENT_SOURCE_DIR}" "${BDSP_MAP_DIRECTORY}") +pa_embed_text_files(SerialProgramsLib "${BDSP_MAP_RESOURCES}" PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_map_json) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index e262f24f95..624be9b35e 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -33,6 +33,7 @@ #include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" #include "Pokemon/Navigation/Pokemon_Navigation_Tests.h" +#include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "PokemonBDSP/PokemonBDSP_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" @@ -73,6 +74,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); + Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); Pokemon::add_tests_StoryEvents(ret); Pokemon::add_tests_StorySegments(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp index 64a4a2a5a9..651228319e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -11,6 +11,7 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_RuntimeMap.h" #include "Pokemon_MapData.h" namespace PokemonAutomation{ @@ -523,7 +524,8 @@ void check_places(const MapData& map, const std::string& where){ MapData parse_map(const JsonValue& json, const std::string& source_name){ - const JsonObject& root = as_object(json, source_name); + const JsonValue normalized = normalize_runtime_map(json, source_name); + const JsonObject& root = as_object(normalized, source_name); const std::string where = source_name + ": "; MapData map; map.name = read_string(root, "name", where); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h index fc4ecada53..3a68ecdeb2 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -207,7 +207,8 @@ struct MapData{ std::vector patches; }; -// Reads a map from its parsed JSON. `source_name` names it in errors. +// Reads legacy/unmarked v1 or compact pokesim-runtime-map/2 JSON. +// Both games use this entry point; `source_name` names it in errors. // Throws ParseException, naming the source and the JSON path (e.g. // "Maps/TestTown.json: warps[2].x is missing."), when a field is missing, // doesn't fit the schema, or places something outside the tiles. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp new file mode 100644 index 0000000000..1258409505 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp @@ -0,0 +1,229 @@ +/* Versioned Runtime Map Decoder + * + * From: https://github.com/PokemonAutomation/ + */ +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_Grid.h" +#include "Pokemon_RuntimeMap.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + +enum class WireFormat{ LEGACY, COMPACT }; + +const JsonObject& object_at(const JsonValue& value, const std::string& where){ + const JsonObject* object = value.to_object(); + if (!object){ + throw ParseException(where + " is not a JSON object."); + } + return *object; +} + +const JsonArray& array_at(const JsonValue& value, const std::string& where){ + const JsonArray* array = value.to_array(); + if (!array){ + throw ParseException(where + " must be an array."); + } + return *array; +} + +JsonObject copy_without(const JsonObject& object, const std::set& omit){ + JsonObject result; + for (const auto& [key, value] : object){ + if (!omit.contains(key)){ + result[key] = value.clone(); + } + } + return result; +} + +int coordinate(const JsonValue* value, const std::string& where){ + if (!value){ + throw ParseException(where + " is missing."); + } + if (!value->is_integer()){ + throw ParseException(where + " is not an integer."); + } + const int64_t number = value->to_integer_default(); + if (number < std::numeric_limits::min() || number > std::numeric_limits::max()){ + throw ParseException(where + " does not fit a native coordinate."); + } + return (int)number; +} + +TilePos pair_at(const JsonObject& object, const std::array& keys, WireFormat format, const std::string& where){ + if (format == WireFormat::LEGACY){ + if (object.get_value(keys[2])){ + throw ParseException(where + keys[2] + " is not a v1 coordinate field."); + } + return {coordinate(object.get_value(keys[0]), where + keys[0]), coordinate(object.get_value(keys[1]), where + keys[1])}; + } + const JsonValue* value = object.get_value(keys[2]); + if (object.get_value(keys[0]) || object.get_value(keys[1]) || !value){ + throw ParseException(where + keys[2] + " requires only the v2 coordinate pair."); + } + const std::string pair_path = where + keys[2]; + const JsonArray& pair = array_at(*value, pair_path); + if (pair.size() != 2){ + throw ParseException(where + keys[2] + " requires exactly two integers."); + } + return {coordinate(&pair[0], where + keys[2] + "[0]"), coordinate(&pair[1], where + keys[2] + "[1]")}; +} + +JsonValue normalize_wander(const JsonValue& value, WireFormat format, const std::string& where){ + const JsonObject& source = object_at(value, where); + const TilePos low = pair_at(source, {"x0", "y0", "min"}, format, where); + const TilePos high = pair_at(source, {"x1", "y1", "max"}, format, where); + if (format == WireFormat::COMPACT && (low.x > high.x || low.y > high.y)){ + throw ParseException(where + "must have inclusive min <= max bounds."); + } + JsonObject result = copy_without(source, {"x0", "y0", "x1", "y1", "min", "max"}); + result["x0"] = low.x; + result["y0"] = low.y; + result["x1"] = high.x; + result["y1"] = high.y; + return result; +} + +JsonObject normalize_record(const JsonValue& value, WireFormat format, const std::string& where){ + const JsonObject& source = object_at(value, where); + const TilePos pos = pair_at(source, {"x", "y", "coord"}, format, where); + JsonObject result = copy_without(source, {"x", "y", "coord"}); + result["x"] = pos.x; + result["y"] = pos.y; + return result; +} + +// Expand compact pickup defaults without changing authored names or counts. +JsonObject normalize_pickup(JsonObject record, std::string_view where){ + const std::string* item = record.get_string("item"); + if (!item || item->empty()){ + throw ParseException(std::format("{}item must be a nonempty string.", where)); + } + if (const JsonValue* event = record.get_value("source_event")){ + const int index = coordinate(event, std::format("{}source_event", where)); + if (index < 0){ + throw ParseException(std::format("{}source_event must be nonnegative.", where)); + } + if (!record.get_value("name")){ + record["name"] = std::format("item_{}", index); + } + }else if (!record.get_value("name")){ + throw ParseException(std::format("{}unnamed pickup requires source_event.", where)); + } + if (const JsonValue* quantity = record.get_value("quantity")){ + if (!quantity->is_integer() || quantity->to_integer_default() <= 0){ + throw ParseException(std::format("{}quantity must be a positive integer.", where)); + } + }else{ + record["quantity"] = 1; + } + return record; +} + +void append_objects(JsonArray& output, const JsonArray& input, WireFormat format, const std::string& group, const std::string& where){ + for (size_t i = 0; i < input.size(); i++){ + const std::string path = where + group + "[" + std::to_string(i) + "]."; + JsonObject record = normalize_record(input[i], format, path); + if (format == WireFormat::COMPACT){ + if (record.get_value("kind")){ + throw ParseException(path + "kind is redundant in v2 typed arrays."); + } + record["kind"] = group == "npcs" ? "npc" : group == "signs" ? "sign" : "item"; + } + if (group == "interactables"){ + const JsonObject* interaction = record.get_object("interaction"); + const std::string* action = interaction ? interaction->get_string("kind") : nullptr; + if (!action || action->empty() || record.get_value("item") || record.get_value("quantity")){ + throw ParseException(path + "requires an interaction without an item reward."); + } + }else if (group == "items" && record.get_value("interaction")){ + throw ParseException(path + "interactions belong in interactables."); + } + if (group == "items" && (record.get_value("item") || record.get_value("quantity"))){ + record = normalize_pickup(std::move(record), path); + } + if (const JsonValue* wander = record.get_value("wander")){ + record["wander"] = normalize_wander(*wander, format, path + "wander."); + } + output.push_back(std::move(record)); + } +} + +WireFormat read_format(const JsonObject& root, const std::string& where){ + const JsonValue* field = root.get_value("format"); + if (!field){ + return WireFormat::LEGACY; + } + const std::string* format = field->to_string(); + if (format && *format == "pokesim-runtime-map/1"){ + return WireFormat::LEGACY; + } + if (format && *format == "pokesim-runtime-map/2"){ + return WireFormat::COMPACT; + } + throw ParseException(where + "format is unsupported."); +} + +void normalize_objects(JsonObject& output, const JsonObject& root, WireFormat format, const std::string& where){ + JsonArray objects; + const std::array groups{"npcs", "items", "signs", "interactables"}; + if (format == WireFormat::LEGACY){ + for (const std::string& group : groups){ + if (root.get_value(group)){ + throw ParseException(where + group + " is not a v1 object section."); + } + } + if (const JsonValue* value = root.get_value("objects")){ + append_objects(objects, array_at(*value, where + "objects"), format, "objects", where); + output["objects"] = std::move(objects); + } + return; + } + if (root.get_value("objects")){ + throw ParseException(where + "objects cannot be combined with v2 typed arrays."); + } + bool present = false; + for (const std::string& group : groups){ + if (const JsonValue* value = root.get_value(group)){ + present = true; + append_objects(objects, array_at(*value, where + group), format, group, where); + } + } + if (present){ + output["objects"] = std::move(objects); + } +} + +} // namespace + +JsonValue normalize_runtime_map(const JsonValue& json, std::string_view source_name){ + const std::string where = std::string(source_name) + ": "; + const JsonObject& root = object_at(json, where); + const WireFormat format = read_format(root, where); + JsonObject output = copy_without(root, {"format", "objects", "npcs", "items", "signs", "interactables", "warps", "patches", "coord_events"}); + normalize_objects(output, root, format, where); + for (const std::string section : {"warps", "patches", "coord_events"}){ + if (const JsonValue* field = root.get_value(section)){ + const std::string section_path = where + section; + const JsonArray& input = array_at(*field, section_path); + JsonArray records; + for (size_t i = 0; i < input.size(); i++){ + records.push_back(normalize_record(input[i], format, where + section + "[" + std::to_string(i) + "].")); + } + output[section] = std::move(records); + } + } + return output; +} + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.h new file mode 100644 index 0000000000..ab1b078f7d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.h @@ -0,0 +1,22 @@ +/* Versioned Runtime Map Decoder + * + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_RuntimeMap_H +#define PokemonAutomation_RuntimeMap_H + +#include +#include "Common/Cpp/Json/JsonValue.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +// Decode v1/v2 runtime wire data to legacy JSON without modifying the input. +// Preserve extension metadata; reject mixed encodings, malformed pairs and unknown formats. +// Group order is NPC, item, sign, interactable; order within each group is retained. +// Identified v2 pickups default quantity to 1; absent names use item_. +JsonValue normalize_runtime_map(const JsonValue& json, std::string_view source_name); + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp new file mode 100644 index 0000000000..a018a719cd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -0,0 +1,196 @@ +/* Versioned Runtime Map Tests + * + * From: https://github.com/PokemonAutomation/ + */ +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_MapData.h" +#include "Pokemon_RuntimeMap.h" +#ifndef PA_RUNTIME_MAP_STANDALONE +#include "Pokemon_RuntimeMap_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + +struct RuntimeMapInput{ + std::string_view name; + std::string_view fields; +}; + +struct RuntimeMapExpectation{ + std::string_view error = {}; + std::string_view normalized_fields = {}; +}; + +struct RuntimeMapCase{ + RuntimeMapInput input; + RuntimeMapExpectation expectation; +}; + +const char* const GOLDEN_V2 = R"( + "format":"pokesim-runtime-map/2", + "world":{"name":"Sinnoh","x":0,"y":0}, + "extension":{"zero":0,"false":false}, + "npcs":[ + {"name":"npc","coord":[0,0],"facing":"east","trainer":{"sight":1},"wander":{"min":[0,0],"max":[1,1]}}, + {"name":"npc","coord":[1,0],"hide_flag":"hidden"} + ], + "items":[{"name":"pickup","coord":[0,1],"item":"potion","quantity":1}], + "signs":[{"name":"sign","coord":[1,1]}], + "interactables":[{"name":"ball","coord":[1,0],"interaction":{"kind":"starter_choice","species":"squirtle"}}], + "warps":[{"coord":[1,1],"enter":"walk_north","to_map":"House","to_point":"exit"}], + "patches":[{"coord":[0,1],"glyph":"#","measured_by":"synthetic"}], + "coord_events":[{"coord":[0,0],"width":1,"length":2,"var":0}] +)"; + +const char* const GOLDEN_V1 = R"( + "world":{"name":"Sinnoh","x":0,"y":0}, + "extension":{"zero":0,"false":false}, + "objects":[ + {"name":"npc","kind":"npc","x":0,"y":0,"facing":"east","trainer":{"sight":1},"wander":{"x0":0,"y0":0,"x1":1,"y1":1}}, + {"name":"npc","kind":"npc","x":1,"y":0,"hide_flag":"hidden"}, + {"name":"pickup","kind":"item","x":0,"y":1,"item":"potion","quantity":1}, + {"name":"sign","kind":"sign","x":1,"y":1}, + {"name":"ball","kind":"item","x":1,"y":0,"interaction":{"kind":"starter_choice","species":"squirtle"}} + ], + "warps":[{"x":1,"y":1,"enter":"walk_north","to_map":"House","to_point":"exit"}], + "patches":[{"x":0,"y":1,"glyph":"#","measured_by":"synthetic"}], + "coord_events":[{"x":0,"y":0,"width":1,"length":2,"var":0}] +)"; + +const RuntimeMapCase RUNTIME_MAP_CASES[] = { + {.input = {.name = "pickup derived name and default quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"source_event":3,"item":"potion"}])"}, .expectation = {.normalized_fields = R"("objects":[{"x":0,"y":1,"kind":"item","name":"item_3","source_event":3,"item":"potion","quantity":1}])"}}, + {.input = {.name = "pickup explicit name and multiple quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"name":"gift_cache","coord":[0,1],"source_event":3,"item":"potion","quantity":4}])"}, .expectation = {.normalized_fields = R"("objects":[{"x":0,"y":1,"kind":"item","name":"gift_cache","source_event":3,"item":"potion","quantity":4}])"}}, + {.input = {.name = "pickup named quantity default", .fields = R"("format":"pokesim-runtime-map/2","items":[{"name":"pickup","coord":[0,1],"item":"potion"}])"}, .expectation = {.normalized_fields = R"("objects":[{"x":0,"y":1,"kind":"item","name":"pickup","item":"potion","quantity":1}])"}}, + {.input = {.name = "pickup missing event", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"item":"potion"}])"}, .expectation = {.error = "source_event"}}, + {.input = {.name = "pickup negative event", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"item":"potion","source_event":-1}])"}, .expectation = {.error = "source_event"}}, + {.input = {.name = "pickup boolean event", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"item":"potion","source_event":true}])"}, .expectation = {.error = "source_event"}}, + {.input = {.name = "pickup overflow event", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"item":"potion","source_event":2147483648}])"}, .expectation = {.error = "source_event"}}, + {.input = {.name = "pickup zero quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"name":"p","item":"potion","quantity":0}])"}, .expectation = {.error = "quantity"}}, + {.input = {.name = "pickup negative quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"name":"p","item":"potion","quantity":-1}])"}, .expectation = {.error = "quantity"}}, + {.input = {.name = "pickup boolean quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"name":"p","item":"potion","quantity":true}])"}, .expectation = {.error = "quantity"}}, + {.input = {.name = "pickup null quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"name":"p","item":"potion","quantity":null}])"}, .expectation = {.error = "quantity"}}, + {.input = {.name = "pickup float quantity", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"name":"p","item":"potion","quantity":1.5}])"}, .expectation = {.error = "quantity"}}, + {.input = {.name = "pickup empty item", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,1],"name":"p","item":""}])"}, .expectation = {.error = "item"}}, + + {.input = {.name = "complete normalized-value parity", .fields = GOLDEN_V2}, .expectation = {.normalized_fields = GOLDEN_V1}}, + {.input = {.name = "implicit v1", .fields = R"("objects":[{"name":"npc","kind":"npc","x":0,"y":0}])"}, .expectation = {}}, + {.input = {.name = "explicit v1", .fields = R"("format":"pokesim-runtime-map/1")"}, .expectation = {}}, + {.input = {.name = "v2 empty map", .fields = R"("format":"pokesim-runtime-map/2")"}, .expectation = {}}, + {.input = {.name = "v2 coordinates and inclusive wander", .fields = R"("format":"pokesim-runtime-map/2","npcs":[{"name":"npc","coord":[0,0],"wander":{"min":[0,0],"max":[1,1]}}])"}, .expectation = {}}, + {.input = {.name = "unsupported version", .fields = R"("format":"pokesim-runtime-map/99")"}, .expectation = {.error = "format"}}, + {.input = {.name = "nonstring version", .fields = R"("format":2)"}, .expectation = {.error = "format"}}, + {.input = {.name = "v1 typed section", .fields = R"("npcs":[])"}, .expectation = {.error = "npcs"}}, + {.input = {.name = "v2 legacy section", .fields = R"("format":"pokesim-runtime-map/2","objects":[])"}, .expectation = {.error = "objects"}}, + {.input = {.name = "mixed v2 position", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[0,0],"x":0}])"}, .expectation = {.error = "warps[0].coord"}}, + {.input = {.name = "mixed v1 position", .fields = R"("warps":[{"x":0,"y":0,"coord":[0,0]}])"}, .expectation = {.error = "warps[0].coord"}}, + {.input = {.name = "missing v2 position", .fields = R"("format":"pokesim-runtime-map/2","warps":[{}])"}, .expectation = {.error = "warps[0].coord"}}, + {.input = {.name = "short position", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[0]}])"}, .expectation = {.error = "warps[0].coord"}}, + {.input = {.name = "long position", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[0,0,0]}])"}, .expectation = {.error = "warps[0].coord"}}, + {.input = {.name = "floating coordinate", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[0.5,0]}])"}, .expectation = {.error = "coord[0]"}}, + {.input = {.name = "boolean coordinate", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[false,0]}])"}, .expectation = {.error = "coord[0]"}}, + {.input = {.name = "overflow coordinate", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[2147483648,0]}])"}, .expectation = {.error = "coord[0]"}}, + {.input = {.name = "outside map", .fields = R"("format":"pokesim-runtime-map/2","warps":[{"coord":[3,0]}])"}, .expectation = {.error = "outside"}}, + {.input = {.name = "mixed wander", .fields = R"("format":"pokesim-runtime-map/2","npcs":[{"name":"npc","coord":[0,0],"wander":{"min":[0,0],"max":[1,1],"x0":0}}])"}, .expectation = {.error = "wander.min"}}, + {.input = {.name = "reversed wander", .fields = R"("format":"pokesim-runtime-map/2","npcs":[{"name":"npc","coord":[0,0],"wander":{"min":[1,1],"max":[0,0]}}])"}, .expectation = {.error = "min <= max"}}, + {.input = {.name = "redundant kind", .fields = R"("format":"pokesim-runtime-map/2","signs":[{"name":"sign","coord":[0,0],"kind":"sign"}])"}, .expectation = {.error = "kind"}}, + {.input = {.name = "starter interaction", .fields = R"("format":"pokesim-runtime-map/2","interactables":[{"name":"ball","coord":[0,0],"interaction":{"kind":"starter_choice","species":"squirtle"}}])"}, .expectation = {}}, + {.input = {.name = "interaction has item", .fields = R"("format":"pokesim-runtime-map/2","interactables":[{"coord":[0,0],"interaction":{"kind":"starter_choice"},"item":"potion"}])"}, .expectation = {.error = "item reward"}}, + {.input = {.name = "interaction missing kind", .fields = R"("format":"pokesim-runtime-map/2","interactables":[{"coord":[0,0],"interaction":{}}])"}, .expectation = {.error = "interaction"}}, + {.input = {.name = "item has interaction", .fields = R"("format":"pokesim-runtime-map/2","items":[{"coord":[0,0],"interaction":{"kind":"starter_choice"}}])"}, .expectation = {.error = "interactables"}}, + {.input = {.name = "bad coordinate event", .fields = R"("format":"pokesim-runtime-map/2","coord_events":[{"coord":[0,true]}])"}, .expectation = {.error = "coord_events[0].coord[1]"}}, +}; + +std::string map_document(std::string_view fields){ + return R"({"name":"ContractMap","source":{"decomp_file":"synthetic","revision":"fixture","date":"2026-11-06"},"tiles":["..",".."],)" + std::string(fields) + "}"; +} + +// This is also used by the standalone pin-based 75-map parity check. +std::string check_pair(const JsonValue& input, const JsonValue& expected){ + const JsonValue normalized = normalize_runtime_map(input, "Maps/parity.json"); + if (!(normalized == expected)){ + return "Full normalized JSON differs (including extension metadata/order)."; + } + const MapData map = parse_map(input, "Maps/parity.json"); + const MapData legacy = parse_map(expected, "Maps/parity-v1.json"); + if (map.objects.size() != legacy.objects.size() || map.warps.size() != legacy.warps.size()){ + return "Native parsed object/warp counts differ."; + } + return {}; +} + +std::string check_runtime_case(const RuntimeMapCase& test){ + try{ + const JsonValue input = parse_json(map_document(test.input.fields)); + if (!test.expectation.normalized_fields.empty()){ + return check_pair(input, parse_json(map_document(test.expectation.normalized_fields))); + } + parse_map(input, "Maps/contract.json"); + }catch (const ParseException& error){ + const std::string message = error.message(); + if (!test.expectation.error.empty() && message.find(test.expectation.error) != std::string::npos && message.find("Maps/contract.json") != std::string::npos){ + return {}; + } + return "Unexpected parse error: " + message; + } + return test.expectation.error.empty() ? "" : "Expected rejection containing " + std::string(test.expectation.error); +} + +#ifndef PA_RUNTIME_MAP_STANDALONE +class RuntimeMapTest : public UnitTest{ +public: + explicit RuntimeMapTest(const RuntimeMapCase& test) + : UnitTest("Navigation/RuntimeMap/" + std::string(test.input.name)), m_test(test){} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_runtime_case(m_test); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + const RuntimeMapCase& m_test; +}; +#endif + +} // namespace + +#ifndef PA_RUNTIME_MAP_STANDALONE +void add_tests_RuntimeMap(UnitTestDatabase& database){ + for (const RuntimeMapCase& test : RUNTIME_MAP_CASES){ + database.add(test); + } +} +#endif + +} // namespace Pokemon +} // namespace PokemonAutomation + +#ifdef PA_RUNTIME_MAP_STANDALONE +// Optional argument: a parity pack of {input, expectation} records from a pinned publisher. +int main(int argc, char* argv[]){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::RUNTIME_MAP_CASES){ + const std::string error = PokemonAutomation::Pokemon::check_runtime_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << std::endl; + failed += !error.empty(); + } + if (argc == 2){ + const auto pack = PokemonAutomation::load_json_file(argv[1]); + for (const auto& record : pack.to_array_throw()){ + const auto& object = record.to_object_throw(); + const std::string error = PokemonAutomation::Pokemon::check_pair(object.get_value_throw("input"), object.get_value_throw("expectation")); + failed += !error.empty(); + if (!error.empty()){ + std::cerr << error << std::endl; + } + } + std::cout << "Checked " << pack.to_array_throw().size() << " complete map records." << std::endl; + }else if (argc != 1){ + return 2; + } + return failed; +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h new file mode 100644 index 0000000000..42f2cda081 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h @@ -0,0 +1,17 @@ +/* Versioned Runtime Map Tests + * + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_RuntimeMap_Tests_H +#define PokemonAutomation_RuntimeMap_Tests_H +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +// Register wire-schema compatibility/rejection and full normalized-value checks. +void add_tests_RuntimeMap(UnitTestDatabase& database); + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json deleted file mode 100644 index 5ec01e577b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/FloaromaTown.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "FloaromaTown", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0032.bin; zone_event narc_0404", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "######........................##", - "##..##........................##", - "..............................##", - "..............................##", - "..............................##", - "..............................##", - "..............................##", - "..................#####.......##", - "..................#####.......##", - "..................#####.......##", - "..................#####.......##", - "..........####...S##.##.......##", - "..........####................##", - "..........####................##", - "..........#D##................##", - ".......................####..S##", - ".......................####...##", - ".......................#D##...##", - "..............................##", - ".............S..................", - "................................", - "................................", - "................................", - "..............#####....####...##", - "..............#####....####...##", - "..............#####....####...##", - "..............##D##....#D##...##", - "..............................##", - "..............................##", - "..............................##", - "########.#...###################", - "########.#...###################" - ], - "points": { - "route_204_arrival": [11, 29], - "old_woman": [3, 25], - "old_man": [2, 25], - "pokemon_center_door": [16, 26] - }, - "coord_events": [ - { - "name": "coord_event_0", - "coord": [10, 29], - "width": 3, - "length": 1, - "var": "VAR_UNK_0x4072", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0404.bin coord_events[0] (170, 669), script 2" - } - ], - "npcs": [ - {"name": "pokemon_breeder_f_0", "coord": [19, 21]}, - {"name": "lass_1", "coord": [10, 5], "wander": {"min": [9, 5], "max": [11, 5]}}, - {"name": "school_kid_m_2", "coord": [16, 16], "wander": {"min": [15, 15], "max": [17, 17]}}, - {"name": "cyrus_3", "coord": [11, 26]}, - {"name": "lass_4", "coord": [23, 11], "facing": "west"}, - {"name": "grunt_m_7", "coord": [2, 1], "facing": "east"}, - {"name": "grunt_m_8", "coord": [3, 1], "facing": "west"}, - {"name": "camper_12", "coord": [6, 10]}, - {"name": "old_woman", "coord": [3, 25]}, - {"name": "old_man", "coord": [2, 25]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json deleted file mode 100644 index 3ba40ce415..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json +++ /dev/null @@ -1,191 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "JubilifeCity", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0015.bin, files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0017.bin, files/fielddata/land_data/land_data_release/narc_0018.bin; zone_event narc_0002", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "##########################################..............########", - "##########################################..............########", - "############################################.....###############", - "############################################......##############", - "############################################......##############", - "############################################......##############", - "############################################......##############", - "#############################################....###############", - "############################....#########.......S.##############", - "############################....#########.........##############", - "#########..#########..######....#########.........##############", - "#########..#########..######....#########.........##############", - "#########..#########..######....#########.........##############", - "#########..#########..######....#########.........##############", - "#########..#########..######....#########.........##############", - "#########..##D###D##..######....####D####.........##############", - "#########.............######...............#.....#######....####", - "#########.............######......................######....####", - "..#######.............######......................######....####", - "..###########S......########...........S.........S##D###....####", - "..#.S.#.......................#..........................#.S####", - "................................................................", - "D...............................................................", - "D...............................................................", - "................................................................", - "..#...#.......................#..........................#..####", - "..############.............####......####...................####", - "..############.............####......####................#######", - "##############.################...##.####..#.....######..#######", - "##############.################...##.####.........#####..#######", - "##############.################...................#D############", - "################################.........................#######", - "################################.........................##D####", - "################################.........................#######", - "################################.........................#######", - "###############............#####.........................#######", - "###############............#####......#####..............#######", - "###############..#########.#####.##########.......######.#######", - "###############..#########.#####.##########.......######.#######", - "###############..#########.#####.###########.....#######.#######", - "##################################..S.##D##.......##D###########", - "###############..#########.#####.........................#######", - "##############...####D####..###..........................#######", - "##############...........................................#######", - "##############.....S.....................................#######", - "##############...........................................#######", - "##############.............#########.....................#######", - "###############............#########.#####...............#######", - "###############............#########.#####...............#######", - "###############.####..####.###############...............#######", - "###############.####..####.###############...............#######", - "###############.####..####.###############...........###########", - "############D##.####..####.############D##...........###########", - "##########.................#########.......#.....#...########.##", - "##########.................#########.................########.##", - "##########............#..#.#########......S..........########.##", - "##########............#..#.#########.................########.##", - "##########.................#########.................########.##", - "###########################################.......##############", - "###########################################.......##############", - "########################################.##.......##############", - "########################################.####...################", - "########################################..........##############", - "########################################..........##############" - ], - "points": { - "trainers_school_door": [40, 40], - "pokemon_center_door": [52, 40], - "tv_station_door": [36, 15], - "poketch_president": [46, 35], - "clown_mart": [55, 33], - "clown_tv_station": [36, 16], - "clown_poketch_company": [15, 18], - "up_the_steps.1": [46, 58], - "up_the_steps.2": [47, 58], - "up_the_steps.3": [46, 59], - "up_the_steps.4": [47, 59], - "up_the_steps.5": [46, 60], - "up_the_steps.6": [47, 60], - "east_entrance.1": [61, 21], - "east_entrance.2": [62, 21], - "east_entrance.3": [63, 21], - "east_entrance.4": [61, 22], - "east_entrance.5": [62, 22], - "east_entrance.6": [63, 22], - "east_entrance.7": [61, 23], - "east_entrance.8": [62, 23], - "east_entrance.9": [63, 23], - "east_entrance.10": [61, 24], - "east_entrance.11": [62, 24], - "east_entrance.12": [63, 24], - "north_road.1": [44, 16], - "north_road.2": [45, 16], - "north_road.3": [46, 16], - "north_road.4": [47, 16], - "north_road.5": [48, 16], - "north_road.6": [44, 17], - "north_road.7": [45, 17], - "north_road.8": [46, 17], - "north_road.9": [47, 17], - "north_road.10": [48, 17], - "north_road.11": [44, 18], - "north_road.12": [45, 18], - "north_road.13": [46, 18], - "north_road.14": [47, 18], - "north_road.15": [48, 18], - "north_road.16": [44, 19], - "north_road.17": [45, 19], - "north_road.18": [46, 19], - "north_road.19": [47, 19], - "north_road.20": [48, 19], - "north_road.21": [44, 20], - "north_road.22": [45, 20], - "north_road.23": [46, 20], - "north_road.24": [47, 20], - "north_road.25": [48, 20] - }, - "coord_events": [ - { - "name": "dawn_at_the_steps", - "coord": [45, 60], - "width": 4, - "length": 1, - "var": "VAR_JUBILIFE_CITY_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[0] (173, 796), script 2" - }, - { - "name": "coord_event_1", - "coord": [45, 7], - "width": 3, - "length": 1, - "var": "VAR_JUBILIFE_CITY_STATE", - "value": 3, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[1] (173, 743), script 4" - }, - { - "name": "coord_event_2", - "coord": [60, 21], - "width": 1, - "length": 4, - "var": "VAR_JUBILIFE_CITY_STATE", - "value": 1, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[2] (188, 757), script 3" - }, - { - "name": "coord_event_3", - "coord": [27, 43], - "width": 1, - "length": 3, - "var": "VAR_GTS_ACCESS_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[3] (155, 779), script 19" - }, - { - "name": "poketch_president", - "coord": [44, 40], - "width": 5, - "length": 1, - "var": "VAR_POKETCH_CAMPAIGN_STATE", - "value": 1, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0002.bin coord_events[4] (172, 776), script 17" - } - ], - "npcs": [ - {"name": "ace_trainer_f_0", "coord": [22, 20], "wander": {"min": [21, 20], "max": [23, 20]}}, - {"name": "ace_trainer_m_1", "coord": [46, 21], "wander": {"min": [45, 21], "max": [47, 21]}}, - {"name": "school_kid_m_2", "coord": [17, 55]}, - {"name": "twin_3", "coord": [33, 18], "wander": {"min": [32, 17], "max": [34, 19]}}, - {"name": "expert_m_4", "coord": [44, 44]}, - {"name": "school_kid_m_5", "coord": [51, 34], "wander": {"min": [51, 33], "max": [51, 35]}}, - {"name": "pokefan_m_6", "coord": [41, 30], "wander": {"min": [40, 29], "max": [42, 31]}}, - {"name": "ace_trainer_m_22", "coord": [36, 25]}, - {"name": "poketch_president", "coord": [46, 35]}, - {"name": "clown_mart", "coord": [55, 33]}, - {"name": "clown_poketch_company", "coord": [15, 18]}, - {"name": "cashier_m_27", "coord": [26, 42]}, - {"name": "clown_tv_station", "coord": [36, 16]}, - {"name": "kid_with_nds_29", "coord": [52, 46]}, - {"name": "kid_with_nds_30", "coord": [54, 46]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json deleted file mode 100644 index db9fba355e..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/LakeVerity.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "LakeVerity", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0512.bin; zone_event narc_0298", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "wwwwwwwwwwwwwwww################", - "wwwwwwwwwwwwwwww################", - "wwwwwwwwwwwwwwww################", - "wwwwwwwwwwwwwwww################", - "......wwwwwwwwww##....##########", - "......wwwwwwwwww##....##########", - ".......wwwwwwwww##......########", - ".......wwwwwwwww##......########", - ".......wwwwwww####~.....########", - ".......wwwwwww####~~....########", - "wwwwwwwwwwww####~~~~....########", - "wwwwwwwwwwww####.~~~....########", - "wwwwwwwwww####.~~~~~..##########", - "wwwwwwwwww####.~~~~...##########", - "wwwwwwww####...~~~..############", - "wwwwwwww####........############", - "##########..........############", - "##########..........############", - "############......##############", - "############......##############", - "############......##############", - "############......##############", - "##############..################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################" - ], - "npcs": [ - {"name": "rowan", "coord": [16, 11], "facing": "north"}, - {"name": "counterpart", "coord": [17, 11], "facing": "north"}, - {"name": "starly_3", "coord": [16, 19], "facing": "north"} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json deleted file mode 100644 index 523e5ac370..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghCity.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "OreburghCity", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0022.bin, files/fielddata/land_data/land_data_release/narc_0023.bin, files/fielddata/land_data/land_data_release/narc_0024.bin, files/fielddata/land_data/land_data_release/narc_0175.bin; zone_event narc_0044", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "#########################################......#################", - "#########################################...S..#################", - "#########################################......#################", - "#########################################......#################", - "#########################################...####################", - "#########################################...####################", - "#########################################....###################", - "############.#####.######.#.############.....###################", - "###########..#####..#####...############.....###################", - "#########....#####..#####...############.....###################", - "##.....########D######D######D##########.....###################", - "##..S..###..........................####........#.#...##########", - "##..................................####.....S........##########", - "#D..................................####..............##########", - "##..................................####..............####.#####", - "##..................................####..............####.#####", - "##.....###.............#######......#D##..............####.#####", - "##.....##.......####...#######...............#####....####.#####", - "#########.......####.#.#######..............######......#.######", - "#########.......####...#######..............######.....#########", - "#########.......#D####S###D###...............##D##.....#########", - "#########........................................#.....#########", - "#########........................................#.....#########", - "#########........................................#....##########", - "#########........................................#....##########", - "#########........................................#....##########", - "##########.#.#..########.........................#....##########", - "########################.######.############.....#....##########", - "########################.######.###........#.....#....##D#######", - "########################.######.###.#..#...#.....#.........#####", - "############################################.....###############", - "############################################.....###############", - "############################################.....###############", - "############################################.....###############", - "############################################.....###############", - "############################################.....###############", - "############################################.....##D############", - "###################################.########.....#...........###", - "###################################.....####.....#...........###", - "###################################.....####.....#...........###", - "###################################....#####.....#...........###", - "#####################################..#.........#...........###", - "#####################################..#..#.#....#....#.#....###", - "#####################################..#..#.#....#....#.#....###", - "###################################....#.....................###", - "###################################....#.....................###", - "###################################....#.....................###", - "###################################....#.....................###", - "###################################....#.....................###", - "###################################..###..#.#................###", - "###################################..###..#.#...#.#########.####", - "###################################..###........#.#########.####", - "###################################....#..........#####.....####", - "###################################...............#####.....####", - "#####################################.............##.........###", - "#####################################..####.#.....###.....######", - "#####################################..####.#S....###.....######", - "###########################################.......####.......###", - "############################################.....#####.......###", - "############################################DDDDD#####.....#####", - "######################################################..#..#####", - "################################################################", - "################################################################", - "################################################################" - ], - "points": { - "pokemon_center_door": [47, 20], - "pokemon_center_doorstep": [46, 21], - "gym_door": [26, 20], - "gym_doorstep": [26, 21], - "gate_mouth": [1, 13] - }, - "coord_events": [ - { - "name": "coord_event_0", - "coord": [10, 12], - "width": 1, - "length": 4, - "var": "VAR_OREBURGH_CITY_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[0] (266, 748), script 3" - }, - { - "name": "coord_event_1", - "coord": [6, 12], - "width": 1, - "length": 4, - "var": "VAR_OREBURGH_CITY_STATE", - "value": 2, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0044.bin coord_events[1] (262, 748), script 4" - } - ], - "npcs": [ - {"name": "hiker_0", "coord": [47, 26], "wander": {"min": [46, 25], "max": [48, 27]}}, - {"name": "school_kid_f_1", "coord": [32, 18], "wander": {"min": [32, 16], "max": [32, 20]}}, - {"name": "pokefan_f_2", "coord": [45, 38], "wander": {"min": [45, 37], "max": [45, 39]}}, - {"name": "youngster_4", "coord": [10, 16], "facing": "north"}, - {"name": "worker_15", "coord": [11, 25]}, - {"name": "worker_16", "coord": [56, 57], "wander": {"min": [55, 54], "max": [57, 60]}}, - {"name": "camper_17", "coord": [36, 19], "wander": {"min": [33, 19], "max": [39, 19]}}, - {"name": "worker_18", "coord": [37, 39], "wander": {"min": [36, 38], "max": [38, 40]}}, - {"name": "worker_19", "coord": [50, 41], "wander": {"min": [50, 38], "max": [50, 44]}}, - {"name": "guitarist_20", "coord": [23, 13], "wander": {"min": [22, 10], "max": [24, 16]}}, - {"name": "battle_girl_21", "coord": [36, 23], "wander": {"min": [36, 21], "max": [36, 25]}}, - {"name": "machop_22", "coord": [55, 56], "wander": {"min": [53, 54], "max": [57, 58]}} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json deleted file mode 100644 index d0d6ba3ad5..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGate.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "OreburghGate", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0418.bin; zone_event narc_0250", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "################################", - "################################", - "################################", - "################################", - "############..#......###########", - "###########..........###########", - "###########........#.###########", - "###########..###################", - "###########..###################", - "###########..###################", - "###########.####################", - "############.###################", - "###########.####################", - "###########..###################", - "###########..###################", - "###########..###################", - "###########..###################", - "###########..###################", - "############.###################", - "###########..###################", - "#####...##...##########...#.####", - "####....##...##########.....####", - "###D........................D###", - "####...#....................####", - "###########..............#.#####", - "############.......#############", - "###########..#.#...#############", - "################################", - "################################", - "################################", - "################################", - "################################" - ], - "coord_events": [ - { - "name": "coord_event_0", - "coord": [7, 22], - "width": 1, - "length": 1, - "var": "VAR_OREBURGH_GATE_1F_HIKER_STATE", - "value": 1, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0250.bin coord_events[0] (7, 22), script 3" - } - ], - "npcs": [ - {"name": "picnicker_0", "coord": [24, 21], "facing": "south"}, - {"name": "camper_1", "coord": [17, 25], "facing": "north"}, - {"name": "hiker_10", "coord": [7, 20], "facing": "south"} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json deleted file mode 100644 index f9298e4aca..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghGym.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "OreburghGym", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0228.bin; zone_event narc_0046", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "################################", - "################################", - "################################", - "#..........#####################", - "#..........#####################", - "#..........#####################", - "#..##.##...#####################", - "#..........#####################", - "#..##.##...#####################", - "#..........#####################", - "#..........#####################", - "###.....#.######################", - "#..........#####################", - "#####.##...#####################", - "#####.##...#####################", - "#..........#####################", - "#..........#####################", - "#..........#####################", - "#..........#####################", - "##.#....########################", - "##.#....########################", - "#..........#####################", - "#..#...#...#####################", - "#..S...S...#####################", - "#....D.....#####################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################" - ], - "points": { - "entrance": [5, 23], - "roark": [5, 3], - "trainer_first_tier": [4, 18], - "trainer_second_tier": [7, 11] - }, - "npcs": [ - {"name": "roark_0", "coord": [5, 3], "facing": "south"}, - {"name": "gym_guide_1", "coord": [6, 23], "facing": "south"}, - {"name": "youngster_2", "coord": [4, 18], "facing": "east"}, - {"name": "youngster_3", "coord": [7, 11], "facing": "west"} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json deleted file mode 100644 index 362506d13c..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMine.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "OreburghMine", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0314.bin; zone_event narc_0197", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "################################", - "###############D################", - "#############.....##############", - "#############.....##############", - "#############.....##############", - "#############.....##############", - "#############.....##############", - "#############...################", - "#############...################", - "#############.....##############", - "#############..#..##############", - "###############...##############", - "#############...################", - "#############.....##############", - "###############...##############", - "########...####..............###", - "######.....##.................##", - "##.#..........................##", - "##....####################....##", - "##vvv##..................#....##", - "##....#..................#....##", - "##.##.#..................#....##", - "##..###..................###..##", - "##..###..................###..##", - "##....#..................#....##", - "##.##.#..................#....##", - "####..####################....##", - "####..####################....##", - "####.............#.#........####", - "######......................####", - "################################", - "################################" - ], - "points": { - "roark": [18, 28], - "corridor_exit_start": [14, 10], - "corridor_top.1": [14, 2], - "corridor_top.2": [15, 2], - "corridor_top.3": [16, 2] - }, - "npcs": [ - {"name": "roark", "coord": [18, 28], "facing": "east"}, - {"name": "worker_5", "coord": [8, 28], "facing": "north"}, - {"name": "worker_6", "coord": [26, 20], "facing": "west"}, - {"name": "worker_7", "coord": [21, 15], "facing": "north"}, - {"name": "machop_8", "coord": [12, 28], "wander": {"min": [11, 28], "max": [13, 28]}}, - {"name": "machop_9", "coord": [20, 15]}, - {"name": "machop_10", "coord": [27, 15], "facing": "north"} - ], - "items": [ - {"name": "item_3", "coord": [4, 28]}, - {"name": "item_4", "coord": [26, 24]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json deleted file mode 100644 index 8b3ed98419..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/OreburghMineB1F.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "OreburghMineB1F", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0313.bin; zone_event narc_0196", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "################################", - "###########DDD##################", - "######...##...##.###############", - "######...##...##.###############", - "####.................###########", - "####.................###########", - "####.................###########", - "####.................###########", - "####.................###########", - "####.................###########", - "######.............#############", - "######.............#############", - "######.............#############", - "######.............#############", - "########.........###############", - "########.........###############", - "########.........###############", - "########.........###############", - "##########.....#################", - "##########.....#################", - "##########.....#################", - "##########.DDD.#################", - "############D###################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################" - ], - "npcs": [ - {"name": "worker_0", "coord": [7, 4]}, - {"name": "twin_2", "coord": [6, 3]} - ], - "items": [ - {"name": "item_1", "coord": [19, 4]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json deleted file mode 100644 index f50a0f7ecb..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "PlayerHouse1F", - "source": { - "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_186.bin; events_twinleaf_town_player_house_1f.json; decomp only, not checked on the console", - "revision": "c6689696d5fb", - "date": "2026-11-01" - }, - "tiles": [ - "#############", - "#############", - "#############", - "#SS..S####..#", - "#.....####..#", - "#SSS..SS....#", - "#...........#", - "#...........#", - "#..##.......#", - "##.##......##", - "##....D....##", - "#############" - ], - "points": { - "stairs": [10, 3], - "mom": [7, 8], - "door": [6, 10] - }, - "warps": [ - {"coord": [6, 10], "to_map": "TwinleafTown", "to_point": "player_house_door"} - ], - "coord_events": [ - { - "name": "moms_warning", - "coord": [6, 10], - "width": 1, - "length": 1, - "var": "VAR_PLAYER_HOUSE_STATE", - "value": 1, - "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_1f.json coord_events[0] (6, 10), script 5" - }, - { - "name": "moms_call", - "coord": [6, 10], - "width": 1, - "length": 1, - "var": "CONSOLE_MOMS_CALL", - "value": 0, - "source": "console r45, r46 (2026-11-01): after her heal Mom calls us back as we step onto the mat (6, 10); no coord event in the decomp" - } - ], - "patches": [ - {"coord": [4, 8], "glyph": ".", "measured_by": "r32, 2026-11-01"} - ], - "npcs": [ - {"name": "mom_0", "coord": [7, 8], "facing": "north"} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json deleted file mode 100644 index 366de55b12..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse2F.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "PlayerHouse2F", - "source": { - "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_187.bin; events_twinleaf_town_player_house_2f.json; decomp only, not checked on the console", - "revision": "c6689696d5fb", - "date": "2026-11-01" - }, - "tiles": [ - "############", - "############", - "############", - "#######S####", - "#S#SSS...###", - "#........###", - "#..........#", - "#..........#", - "#........#.#", - "##.........#", - "##.......#.#", - "############" - ], - "points": { - "stairs": [8, 4], - "start": [4, 6] - }, - "coord_events": [ - { - "name": "coord_event_0", - "coord": [4, 5], - "width": 1, - "length": 1, - "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", - "value": 0, - "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[0] (4, 5), script 7" - }, - { - "name": "coord_event_1", - "coord": [3, 6], - "width": 1, - "length": 1, - "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", - "value": 0, - "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[1] (3, 6), script 8" - }, - { - "name": "coord_event_2", - "coord": [5, 6], - "width": 1, - "length": 1, - "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", - "value": 0, - "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[2] (5, 6), script 9" - }, - { - "name": "coord_event_3", - "coord": [4, 7], - "width": 1, - "length": 1, - "var": "VAR_PLAYER_HOUSE_RIVAL_STATE", - "value": 0, - "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_2f.json coord_events[3] (4, 7), script 10" - } - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json deleted file mode 100644 index 5fbeb4969b..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RavagedPath.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "RavagedPath", - "source": { - "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_435.bin, res/field/maps/data/map_data_436.bin; events_ravaged_path.json", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "................................", - "................................", - "........................########", - "........................########", - "........................##....##", - "############............##....##", - "############............##....##", - "####...#####............##www.##", - "##...#...############...##www###", - "##..####.############...##www###", - "##..####.#######...#######www###", - "##..####......##...#######www###", - "##.#.###########...##www##www###", - "###.##########.....##wwwwwwwww##", - "###..######.#########wwwwwwwww##", - "###..#####..#########wwwwwwwww##", - "####.#####vv#########www########", - "##...#####..#########www########", - "##..######..#########www###.....", - "##..######..#########www###.....", - "###.######..######wwwwwww##.....", - "##..######..######wwwwwww##.....", - "##.#.#####..######wwwwwww##.....", - "####.#####vv######www######.....", - "####.#......######www######.....", - "####........######www##.........", - "####....wwwwwwwwwwwww##.........", - "..##....wwwwwwwwwwwww##.........", - "..##....wwwwwwwwwwwww##.........", - "..#######www###########.........", - "..#######www###########.........", - "....#####www####................", - "....#####www####................", - "....##wwwwww####................", - "....##wwwwww####................", - "....##wwwwww####................", - "....##.wwww#.###................", - "....##.#....#.##................", - "....##..#.#...#########.........", - "....##....#..##########.........", - "....##.#.#.......#...###########", - "....###.....######...###########", - "....##############....#.......##", - "....##############....#.......##", - "..............####.....#......##", - "..............####...#######D###", - "..............####...###########", - "..............####...####.......", - "..............####...####.......", - "..............####...####.......", - "..............####...####.......", - "..............#####D#####.......", - "..............###########.......", - "..............###########......." - ], - "points": { - "entrance": [19, 50], - "east_end": [29, 44], - "above_exit": [28, 44], - "rocks.1": [11, 36], - "rocks.2": [7, 37], - "rocks.3": [12, 37], - "rocks.4": [8, 38], - "rocks.5": [10, 38], - "rocks.6": [10, 39], - "rocks.7": [13, 39], - "rocks.8": [7, 40], - "rocks.9": [9, 40], - "rocks.10": [17, 40], - "rocks.11": [12, 41], - "rocks.12": [22, 42], - "rocks.13": [22, 43], - "rocks.14": [23, 44], - "before_rocks.1": [21, 42], - "before_rocks.2": [21, 43] - }, - "items": [ - {"name": "item_27", "coord": [7, 38]}, - {"name": "item_28", "coord": [17, 11]}, - {"name": "item_29", "coord": [28, 5]}, - {"name": "item_30", "coord": [22, 44]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json deleted file mode 100644 index 82a2a042e4..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse1F.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "RivalHouse1F", - "source": { - "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_184.bin; events_twinleaf_town_rival_house_1f.json; decomp only, not checked on the console", - "revision": "c6689696d5fb", - "date": "2026-11-01" - }, - "tiles": [ - "#############", - "#############", - "#############", - "#..#####..###", - "#..####.....#", - "#....##..####", - "#...........#", - "#...........#", - "#.......##..#", - "##......##.##", - "##....D....##", - "#############" - ], - "points": { - "door": [6, 10], - "stairs": [2, 3] - }, - "warps": [ - {"coord": [6, 10], "to_map": "TwinleafTown", "to_point": "rival_house_door"} - ], - "npcs": [ - {"name": "pokefan_f_0", "coord": [4, 6]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json deleted file mode 100644 index 3da7eb8d6a..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RivalHouse2F.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "RivalHouse2F", - "source": { - "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_185.bin; events_twinleaf_town_rival_house_2f.json; decomp only, not checked on the console", - "revision": "c6689696d5fb", - "date": "2026-11-01" - }, - "tiles": [ - "############", - "############", - "############", - "############", - "###...S##S##", - "###........#", - "#..........#", - "#..........#", - "#.#........#", - "#.........##", - "#.#.......##", - "############" - ], - "points": { - "stairs": [3, 4], - "barry_talk": [8, 5] - }, - "npcs": [ - {"name": "barry", "coord": [9, 5], "facing": "north"} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json deleted file mode 100644 index 5b190bc277..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route201.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "Route201", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0005.bin, files/fielddata/land_data/land_data_release/narc_0006.bin; zone_event narc_0327", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "################################################################", - "################################################################", - "################################################################", - "##########################################~~~~~~~~~~~...........", - "##########################################~~~~~~~~~~~..S........", - "##########################################~~~~~~~~~~~...........", - "##########################################~~~~~~~~~~~...........", - "....####..........######..##....##..####..~~~~~~~~~##...........", - "....####..........######..##....##..####..~~~~~~~~~##...........", - "##........####............................~~~~~~~~~##vvvvv######", - "##........####............................~~~~~~~~~##.....######", - "..........................................~~~~~~~~~##.....######", - "vvvv####vvvvvvvvvvvvvvvvvvvvvvvv........S.~~~~~~~~~##.....######", - "....####............~~~~~~~~~~............................######", - "....................~~~~~~~~~~............................######", - "....................~~~~~~~~~~............................######", - "....................~~~~~~~~~~............................######", - "########.....S......##########............................######", - "########............##########............~~~~~~~~~~~~~~~~######", - "##############....############################~~~~~~~~~~~~######", - "##############....############################~~~~~~~~~~~~######", - "##############....##############################################", - "##############....##############################################", - "##############....##############################################", - "##############....##############################################" - ], - "points": { - "border_sign": [55, 4], - "potion_giver": [43, 3], - "potion_giver_talk_from": [44, 3], - "route_201_arrival": [15, 24], - "barry_warning": [15, 18], - "route_201_return": [0, 14], - "rowan_stop": [5, 14], - "route_201_east_end": [63, 5] - }, - "coord_events": [ - { - "name": "barry_warning", - "coord": [14, 18], - "width": 6, - "length": 1, - "var": "VAR_FOLLOWER_RIVAL_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[0] (110, 857), script 2" - }, - { - "name": "rowan_stop", - "coord": [5, 14], - "width": 1, - "length": 3, - "var": "VAR_FOLLOWER_RIVAL_STATE", - "value": 2, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[1] (101, 853), script 5" - }, - { - "name": "coord_event_2", - "coord": [14, 19], - "width": 6, - "length": 1, - "var": "VAR_FOLLOWER_RIVAL_STATE", - "value": 1, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0327.bin coord_events[2] (110, 858), script 3" - } - ], - "patches": [ - {"coord": [8, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"coord": [9, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"coord": [10, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"coord": [11, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"coord": [12, 18], "glyph": "#", "measured_by": "r16, 2026-10-31"}, - {"coord": [13, 18], "glyph": "S", "measured_by": "r16, 2026-10-31"}, - {"coord": [13, 17], "glyph": ".", "measured_by": "r16, 2026-10-31"} - ], - "npcs": [ - {"name": "pokemon_breeder_m_0", "coord": [27, 15], "wander": {"min": [26, 14], "max": [28, 16]}}, - {"name": "school_kid_m_9", "coord": [57, 8], "facing": "west"}, - {"name": "lass_11", "coord": [46, 16], "wander": {"min": [44, 16], "max": [48, 16]}} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json deleted file mode 100644 index 896620ce5c..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json +++ /dev/null @@ -1,159 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "Route202", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0014.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0328", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "###########........#################", - "###########........#################", - "###########........#################", - "###########........#################", - "###~~~~~~........S..~~~~~......#####", - "###~~~~~~...........~~~~~......#####", - "###.~~~~~...........~~~~~......#####", - "###~~~~~~...........~~~~~......#####", - "###~~~~~~...........~~~~~......#####", - "###~~~~~~.....########.........#####", - "#########vvvvv########vvvvvv...~~###", - "#########.....########~~~~~~~~~~~###", - "#######.......########~~~~~~~~~~~###", - "#######...........####~~~~~~~~~~~###", - "###...............####~~~~~~~~~~~###", - "###...............####~~~~~~~~~~~###", - "###............S..####~~~~~~~~~~~###", - "###...............####~~~~~~~~~~~###", - "###...............####..~~~~~~~~~###", - "###~~~~##...............~~~~~~~~~###", - "###~~~~##.................~~~~~~~###", - "###~~~~##....................~~~~###", - "###~~~~##......................#####", - "###~~~~##vvvvv########vvvvvvvvv#####", - "###~~~~##.....########.........#####", - "###~~~~~~......~~~~~~...S......#####", - "###~~~~~~......~~~~~~..........#####", - "###~~~~~~......~~~~~~..........#####", - "###~~~~~~......~~~~~~..........#####", - "###~~~~~~......~~~~~~..........#####", - "#####################..........#####", - "#####################..........#####" - ], - "points": { - "catch_spot": [19, 27], - "save_spot": [30, 24], - "trainer_tristan": [7, 13], - "trainer_natalie": [22, 18], - "trainer_logan": [26, 4], - "exit_jubilife": [15, 0], - "jubilife_exit.1": [11, 0], - "jubilife_exit.2": [12, 0], - "jubilife_exit.3": [13, 0], - "jubilife_exit.4": [14, 0], - "jubilife_exit.5": [15, 0], - "jubilife_exit.6": [16, 0], - "jubilife_exit.7": [17, 0], - "jubilife_exit.8": [18, 0], - "jubilife_exit.9": [11, 1], - "jubilife_exit.10": [12, 1], - "jubilife_exit.11": [13, 1], - "jubilife_exit.12": [14, 1], - "jubilife_exit.13": [15, 1], - "jubilife_exit.14": [16, 1], - "jubilife_exit.15": [17, 1], - "jubilife_exit.16": [18, 1], - "jubilife_exit.17": [11, 2], - "jubilife_exit.18": [12, 2], - "jubilife_exit.19": [13, 2], - "jubilife_exit.20": [14, 2], - "jubilife_exit.21": [15, 2], - "jubilife_exit.22": [16, 2], - "jubilife_exit.23": [17, 2], - "jubilife_exit.24": [18, 2], - "jubilife_exit.25": [11, 3], - "jubilife_exit.26": [12, 3], - "jubilife_exit.27": [13, 3], - "jubilife_exit.28": [14, 3], - "jubilife_exit.29": [15, 3], - "jubilife_exit.30": [16, 3], - "jubilife_exit.31": [17, 3], - "jubilife_exit.32": [18, 3], - "catch_save_area.1": [15, 25], - "catch_save_area.2": [16, 25], - "catch_save_area.3": [17, 25], - "catch_save_area.4": [18, 25], - "catch_save_area.5": [19, 25], - "catch_save_area.6": [20, 25], - "catch_save_area.7": [21, 25], - "catch_save_area.8": [15, 26], - "catch_save_area.9": [16, 26], - "catch_save_area.10": [17, 26], - "catch_save_area.11": [18, 26], - "catch_save_area.12": [19, 26], - "catch_save_area.13": [20, 26], - "catch_save_area.14": [21, 26], - "catch_save_area.15": [15, 27], - "catch_save_area.16": [16, 27], - "catch_save_area.17": [17, 27], - "catch_save_area.18": [18, 27], - "catch_save_area.19": [19, 27], - "catch_save_area.20": [20, 27], - "catch_save_area.21": [21, 27], - "catch_save_area.22": [21, 28], - "catch_save_area.23": [21, 29], - "after_training_area.1": [18, 25], - "after_training_area.2": [19, 25], - "after_training_area.3": [20, 25], - "after_training_area.4": [18, 26], - "after_training_area.5": [19, 26], - "after_training_area.6": [20, 26], - "after_training_area.7": [18, 27], - "after_training_area.8": [19, 27], - "after_training_area.9": [20, 27], - "catch_grass.1": [18, 25], - "catch_grass.2": [19, 25], - "catch_grass.3": [20, 25], - "catch_grass.4": [18, 26], - "catch_grass.5": [19, 26], - "catch_grass.6": [20, 26], - "catch_grass.7": [18, 27], - "catch_grass.8": [19, 27], - "catch_grass.9": [20, 27] - }, - "coord_events": [ - { - "name": "catch_tutorial", - "coord": [21, 25], - "width": 1, - "length": 5, - "var": "VAR_ROUTE_202_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0328.bin coord_events[0] (180, 825), script 6" - } - ], - "patches": [ - {"coord": [15, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [16, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [17, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [18, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [19, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [20, 28], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [15, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [16, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [17, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [18, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [19, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [20, 29], "glyph": "#", "measured_by": "r253, 2026-11-01"}, - {"coord": [21, 30], "glyph": "#", "measured_by": "r254, 2026-11-01"} - ], - "npcs": [ - {"name": "youngster_0", "coord": [7, 13], "facing": "south"}, - {"name": "lass_1", "coord": [22, 18], "facing": "south"}, - {"name": "youngster_2", "coord": [26, 4], "facing": "south"}, - {"name": "youngster_7", "coord": [10, 8], "wander": {"min": [9, 8], "max": [11, 8]}} - ], - "items": [ - {"name": "item_8", "coord": [3, 6]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json deleted file mode 100644 index 8a66bb297f..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route203.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "Route203", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0016.bin, files/fielddata/land_data/land_data_release/narc_0019.bin, files/fielddata/land_data/land_data_release/narc_0020.bin; zone_event narc_0329", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "#############################################################", - "#############################################################", - "#############################################################", - "#############################################################", - "#####..............###########..~~~~#########################", - "#####..............###########...~~~..~~~~~~~~~~~~~~#########", - "#####..................#######........~~~~~~~~~~~~~.....#####", - "#####..................#######wwwwww##~~~~~~~~~~~....S..#####", - "#####~~~~##...####.....#......wwwwww##~~~~~~~~~~~.......#####", - "#####~~~~##...####.....#......wwwwww##~~~~~~~~~~~.......D####", - "#####~~~~##...####.....#..S...wwwwww##~~~~~~~~~~~.......#####", - "#####~~~~##...####.....#......wwwwww##~~~~~~~~~~~.......#####", - "#####~~~~##...####.....#....~~~~~~~~##~~~~~~~~~S...~~~..#####", - "#####~~~~##...####vvvvv#...~~...~.~~##~~~~~~~~~....~~~..#####", - "#####~~................#....######~~##.....~~....##~~~..#####", - "#####..................#....######~~##vvvvvvvvvvv##~~~..#####", - "#####....S.............#....~~~..~~~.............~~~~~..#####", - "...........................~~~~...~~.............~~~~~..#####", - "...........................~~.....~~.............~~~~~..#####", - "..........................~~~~.....~##..........~~~~~~..#####", - "..........................~~~~~.~~~~#########################", - "#############################################################", - "#############################################################", - "#############################################################" - ], - "points": { - "gate_exit.1": [55, 9], - "gate_exit.2": [54, 9], - "gate_exit.3": [55, 8], - "gate_exit.4": [55, 10], - "west_line.1": [24, 18], - "west_line.2": [25, 18], - "west_line.3": [26, 18], - "west_line.4": [27, 18], - "west_line.5": [28, 18], - "west_line.6": [29, 18], - "west_line.7": [30, 18], - "west_line.8": [31, 18], - "west_line.9": [32, 18], - "west_line.10": [33, 18], - "west_line.11": [34, 18], - "west_line.12": [35, 18], - "west_line.13": [36, 18], - "west_line.14": [37, 18], - "west_line.15": [38, 18], - "west_line.16": [39, 18], - "west_line.17": [40, 18], - "west_line.18": [41, 18], - "west_line.19": [42, 18] - }, - "coord_events": [ - { - "name": "coord_event_0", - "coord": [5, 17], - "width": 1, - "length": 4, - "var": "VAR_ROUTE_203_RIVAL_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0329.bin coord_events[0] (196, 757), script 6" - } - ], - "npcs": [ - {"name": "youngster_1", "coord": [13, 10], "facing": "west"}, - {"name": "lass_2", "coord": [43, 17], "facing": "west"}, - {"name": "youngster_3", "coord": [31, 16], "facing": "south"}, - {"name": "lass_4", "coord": [49, 8], "facing": "south"}, - {"name": "lass_12", "coord": [15, 17], "wander": {"min": [14, 17], "max": [16, 17]}} - ], - "items": [ - {"name": "item_10", "coord": [31, 5]}, - {"name": "item_11", "coord": [20, 10]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json deleted file mode 100644 index e98b687858..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204North.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "Route204North", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0031.bin; zone_event narc_0331", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "########.#...###################", - "########.#...###################", - "####.....#...########.##########", - "##########...#......#.##########", - "#####....#...#......#...........", - "#####....#~~~#......#...######..", - "#####....#~~~###################", - "##########~~~.........##########", - "##........~~~~~.......##########", - "##..######.~~~~..S....##########", - "##..#....#.~~~........##########", - "##..#....#.~~.........##########", - "##########..............########", - "##########..............########", - "##########...####~~~~~~~########", - "##########vvv####~~~~~~~########", - "##########...######~~~~~########", - "##########...######~~~~~########", - "##########...######~~~~~########", - "##########...######~.~~~########", - "##########............~~########", - "##########............##########", - "##########............##########", - "##########...##.......##########", - "##########...##.......##########", - "##########...###################", - "##########...#######.###########", - "##########............##########", - "##########............##########", - "##########............##########", - "##########............##########", - "##########...###################" - ], - "points": { - "cave_exit": [20, 26], - "floaroma_waypoints.1": [20, 27], - "floaroma_waypoints.2": [11, 27], - "floaroma_waypoints.3": [11, 22], - "floaroma_waypoints.4": [19, 22], - "floaroma_waypoints.5": [19, 12], - "floaroma_waypoints.6": [11, 12], - "floaroma_waypoints.7": [11, 5], - "floaroma_path.1": [10, 0], - "floaroma_path.2": [11, 0], - "floaroma_path.3": [12, 0], - "floaroma_path.4": [10, 1], - "floaroma_path.5": [11, 1], - "floaroma_path.6": [12, 1], - "floaroma_path.7": [10, 2], - "floaroma_path.8": [11, 2], - "floaroma_path.9": [12, 2], - "floaroma_path.10": [10, 3], - "floaroma_path.11": [11, 3], - "floaroma_path.12": [12, 3], - "floaroma_path.13": [10, 4], - "floaroma_path.14": [11, 4], - "floaroma_path.15": [12, 4], - "floaroma_path.16": [10, 5], - "floaroma_path.17": [11, 5], - "floaroma_path.18": [12, 5], - "trainer_twin_left": [15, 7], - "trainer_twin_right": [16, 7], - "trainer_taylor": [17, 20], - "trainer_brandon": [20, 12] - }, - "patches": [ - {"coord": [12, 6], "glyph": "#", "measured_by": "r248a, 2026-10-31"} - ], - "npcs": [ - {"name": "bug_catcher_brandon", "coord": [20, 12]}, - {"name": "pokemon_breeder_f_1", "coord": [17, 20]}, - {"name": "twin_2", "coord": [15, 7], "facing": "south"}, - {"name": "twin_3", "coord": [16, 7], "facing": "south"}, - {"name": "youngster_4", "coord": [15, 28], "wander": {"min": [14, 28], "max": [16, 28]}}, - {"name": "ace_trainer_f_10", "coord": [31, 4], "facing": "west"} - ], - "items": [ - {"name": "item_9", "coord": [2, 10]}, - {"name": "item_11", "coord": [20, 23]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json deleted file mode 100644 index ed745aa65e..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route204South.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "Route204South", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0021.bin; zone_event narc_0330", - "revision": "default branch", - "date": "2026-11-01" - }, - "tiles": [ - "################################", - "###########D###.################", - "########..S.....################", - "########........################", - "########........################", - "##########...~##################", - "##########...~##################", - "##########..~~##################", - "##########..~~###wwwwwwwww######", - "####~~~~~~~~~~###wwwwwwwww######", - "####~~~~~~~~~~###wwwwwwwww######", - "####~~~~~~~~~~###wwwwwwwww######", - "####~~~~~~~~~~###wwwwwwwww....##", - "####~~~~~~~~~~###wwwwwwwww....##", - "####~~~~~~~~~~#..wwwww##########", - "##~~~~~~~~~~~~#..wwwww##########", - "##~~~~~~~~~~~~#..wwwww##########", - "##~~~~~~~~~~~~S.################", - "##~~~~~.........#.##############", - "##~~~~~.........#.##############", - "##~~~~~.........#.##############", - "##.#########....#.##############", - "##wwwwwwwww#....#......~########", - "##wwwwwwwww#....#wwwww~~########", - "##wwwwwwwww#....#wwwww~~########", - "##wwwwwwwww#....#wwwww~~########", - "##wwwwwwwww#....#wwwww~~########", - "##wwwwwwwww#....#wwwww~~########", - "##..######.#....#..~~~~~########", - "##..######.#....#...~~~~########", - "##########.#....#.......########", - "############....######..########" - ], - "points": { - "below_door": [11, 2], - "jubilife_entry.1": [14, 31], - "jubilife_entry.2": [14, 30], - "jubilife_entry.3": [14, 29], - "trainer_samantha": [11, 8], - "trainer_sarah": [12, 21], - "trainer_tyler": [7, 18] - }, - "npcs": [ - {"name": "lass_0", "coord": [12, 21]}, - {"name": "lass_1", "coord": [11, 8], "facing": "south"}, - {"name": "youngster_2", "coord": [7, 18]}, - {"name": "youngster_3", "coord": [13, 2], "wander": {"min": [12, 2], "max": [14, 2]}} - ], - "items": [ - {"name": "item_7", "coord": [2, 28]}, - {"name": "item_8", "coord": [29, 12]}, - {"name": "item_9", "coord": [17, 18]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json deleted file mode 100644 index 0ba5cde636..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/RowansLab.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "RowansLab", - "source": { - "decomp_file": "pret/pokeplatinum: res/field/maps/data/map_data_222.bin; events_sandgem_town_pokemon_research_lab.json; decomp only, not checked on the console", - "revision": "c6689696d5fb", - "date": "2026-11-01" - }, - "tiles": [ - "######################", - "######################", - "###SSSS####S####.###S#", - "#........#...##......#", - "#.###................#", - "#...................##", - "#.............#....###", - "###........###########", - "###........###########", - "###........###########", - "#............#########", - "##..........##########", - "##..........##########", - "###........###########", - "###........###########", - "###....D...###########", - "######################", - "######################" - ], - "points": { - "door": [7, 15], - "rowan_talk": [7, 6] - }, - "warps": [ - {"coord": [7, 15], "to_map": "SandgemTown", "to_point": "lab_door"} - ], - "npcs": [ - {"name": "rowan", "coord": [7, 5], "facing": "south"}, - {"name": "scientist_m_1", "coord": [3, 12], "wander": {"min": [1, 12], "max": [5, 12]}}, - {"name": "scientist_f_2", "coord": [10, 12]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json deleted file mode 100644 index 9c3f88a9d9..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "SandgemTown", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0007.bin, files/fielddata/land_data/land_data_release/narc_0173.bin; zone_event narc_0396", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "########################......####", - "########################......####", - "####################..........####", - "####################..........####", - "####################..........####", - "####################..........####", - "####################......########", - "####################......########", - "####################......########", - "####################......########", - "########D##....##D##S....S#D######", - ".....S........................####", - "..............................####", - "..............................####", - "..............................####", - "..............................####", - "######........................####", - "######........................####", - "######.........#####..........####", - "##########.....#####..........####", - "##########.....#####..........####", - "##########.....#####..........####", - "#######D##....S#D###..S.......####", - "######........................####", - "######........................####", - "######........................####", - "######....................########", - "####################......########", - "####################......########", - "####################......########", - "####################......########", - "####################......########" - ], - "points": { - "route_202_entry_stop": [29, 5], - "lab_door": [8, 10], - "pokemon_center_door": [17, 10], - "pokemon_center_sign": [20, 10], - "poke_mart_door": [27, 10], - "front_row_east_end": [29, 11], - "below_sign_gap.1": [21, 11], - "below_sign_gap.2": [22, 11], - "below_sign_gap.3": [23, 11], - "below_sign_gap.4": [24, 11], - "sandgem_arrival": [0, 12], - "dawn_stop": [4, 12] - }, - "coord_events": [ - { - "name": "dawn_walks_us_to_the_lab", - "coord": [4, 10], - "width": 1, - "length": 6, - "var": "VAR_SANDGEM_TOWN_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0396.bin coord_events[0] (164, 842), script 2" - } - ], - "npcs": [ - {"name": "youngster_0", "coord": [27, 23], "wander": {"min": [26, 22], "max": [28, 24]}} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json deleted file mode 100644 index d8fa00a75c..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/TwinleafTown.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "TwinleafTown", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0000.bin; zone_event narc_0389", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "############........############", - "#######....#........#....#######", - "#######....#........#....#######", - "############........############", - "######....................######", - "######....................######", - "######....................######", - "######..#####.............######", - "######..#####......####...######", - "######..#####......####...######", - "######..######.....####...######", - "######..#D###S.....#D##...######", - "######....................######", - "######....................######", - "######..........S.........######", - "######....................######", - "######....................######", - "######.............#####..######", - "######...####......#####..######", - "######...####......#####..######", - "######...####.....######..######", - "######...#D##.....S#D###..######", - "######....................######", - "######....................######", - "######....................######", - "######....................######", - "######....................######", - "######......wwwwwwww......######", - "############wwwwwwww############", - "############wwwwwwww############", - "############wwwwwwww############", - "############wwwwwwww############" - ], - "points": { - "house_doorstep": [20, 22], - "barry_doorstep": [9, 12], - "twinleaf_north_exit": [15, 0], - "player_house_door": [20, 21], - "rival_house_door": [9, 11] - }, - "coord_events": [ - { - "name": "coord_event_0", - "coord": [12, 3], - "width": 8, - "length": 1, - "var": "VAR_TWINLEAF_TOWN_GUITARIST_TRIGGER_STATE", - "value": 1, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[0] (108, 867), script 4" - }, - { - "name": "barry_doorstep", - "coord": [9, 12], - "width": 1, - "length": 1, - "var": "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0389.bin coord_events[1] (105, 876), script 2" - } - ], - "npcs": [ - {"name": "pokemon_breeder_f_0", "coord": [23, 14], "wander": {"min": [22, 14], "max": [24, 14]}}, - {"name": "collector_1", "coord": [12, 25]}, - {"name": "guitarist_3", "coord": [12, 5]} - ] -} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json deleted file mode 100644 index de9e05d987..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/VerityLakefront.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "format": "pokesim-runtime-map/2", - "name": "VerityLakefront", - "source": { - "decomp_file": "pret/pokediamond: files/fielddata/land_data/land_data_release/narc_0004.bin; zone_event narc_0319", - "revision": "default branch", - "date": "2026-10-31" - }, - "tiles": [ - "....############################", - "....############################", - "....############################", - "....############################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################..##############", - "################..##############", - "################..##############", - "##############.S....<...........", - "##############......<.....####..", - "##############......<.....####..", - "##############......<...........", - "##############......<...........", - "##############......#vvvvv##vvvv", - "################..........##....", - "################................", - "##################..............", - "##################..............", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################", - "################################" - ], - "points": { - "lakefront_arrival": [31, 23], - "below_lake_entrance": [17, 14], - "lake_entrance": [17, 12] - }, - "coord_events": [ - { - "name": "lake_entrance", - "coord": [16, 12], - "width": 2, - "length": 1, - "var": "VAR_VERITY_LAKEFRONT_STATE", - "value": 0, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[0] (80, 844), script 3" - }, - { - "name": "coord_event_1", - "coord": [16, 12], - "width": 2, - "length": 1, - "var": "VAR_VERITY_LAKEFRONT_STATE", - "value": 3, - "source": "pret/pokediamond files/fielddata/eventdata/zone_event_release/narc_0319.bin coord_events[1] (80, 844), script 4" - } - ] -} diff --git a/SerialPrograms/cmake/EmbedTextFiles.cmake b/SerialPrograms/cmake/EmbedTextFiles.cmake index 3bf5f4ae91..943c6f25ab 100644 --- a/SerialPrograms/cmake/EmbedTextFiles.cmake +++ b/SerialPrograms/cmake/EmbedTextFiles.cmake @@ -17,7 +17,10 @@ # at run time, so no literal exceeds MSVC's limit of 16380 bytes. function(pa_embed_text_files TARGET FOLDER HEADER NAMESPACE FUNCTION) - file(GLOB FILES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${FOLDER}/*.json") + # Canonicalize once so resource verification and embedding watch the same + # paths. Mixed absolute/../ aliases can produce duplicate Ninja outputs. + file(REAL_PATH "${FOLDER}" MAP_DIRECTORY BASE_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}") + file(GLOB FILES CONFIGURE_DEPENDS "${MAP_DIRECTORY}/*.json") if(NOT FILES) message(FATAL_ERROR "pa_embed_text_files(): no .json files in ${FOLDER}.") endif() diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 54765460e5..f44aad54c2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1470,6 +1470,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_MapData.cpp Source/Pokemon/Navigation/Pokemon_MapData.h Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp + Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp + Source/Pokemon/Navigation/Pokemon_RuntimeMap.h + Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp + Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h Source/Pokemon/Navigation/Pokemon_RouteLog.cpp Source/Pokemon/Navigation/Pokemon_RouteLog.h diff --git a/devtools/maps/README.md b/devtools/maps/README.md index a3c713c0dc..37f94d3416 100644 --- a/devtools/maps/README.md +++ b/devtools/maps/README.md @@ -1,5 +1,11 @@ # Map tools for AutoStory routes +BDSP maps are now pinned external build resources. See +[RESOURCE_MAPS.md](RESOURCE_MAPS.md) for preparation, publishing prerequisites +and native validation. The Sinnoh decomp CLI below forwards to the shared +PokemonSimulation parser; set `PYTHONPATH=/path/to/pokesim/src`. Author map +corrections and run decoder/builder tests there. Image fetch/overlay remain local. + Offline helpers that give a route planner its tile grid (standard library only, Python 3.8+): a decoder for the Pokemon Platinum and Diamond decompilations, an overlay that draws a grid and a run's routes over the map diff --git a/devtools/maps/RESOURCE_MAPS.md b/devtools/maps/RESOURCE_MAPS.md new file mode 100644 index 0000000000..874a94d618 --- /dev/null +++ b/devtools/maps/RESOURCE_MAPS.md @@ -0,0 +1,91 @@ +# BDSP map resources + +BDSP's existing `bdsp_map_json()` API embeds the 22 maps from prepared +`Packages/Resources/Pokemon/Maps/bdsp`. The shared nav-core reader handles their +compact v2 format. Source-map copies and the duplicate BDSP builder/Sinnoh parser +are removed; Python authoring and its tests live in PokemonSimulation. Native +map/route/story tests remain here. No controller behavior changes in this handoff. + +## Publishing prerequisite and pins + +[PokemonSimulation #65](https://github.com/dayfine/PokemonSimulation/pull/65) +merged by squash as `4de7742a764d27293b4525d6ad2a6fc8a95f3e3a`. The checked-in resource lock and +CI tools now use that approved revision. The squash preserves the reviewed +candidate's manifest/license and all 22 map bytes. Normal resource preparation +verifies the published ancestry, manifest hash and exports before configuration. + +Before enrichment, all 22 maps matched #226 at +`fc56a720b9c0b1f4d945dbef382d61b0a6382b97` byte-for-byte. The publishing change +adds resolved Diamond/Platinum-baseline identities, quantities, collection flags +and provenance to 15 pickups, with no geometry, point, NPC, trigger or warp edits. +Pickup names and quantity 1 are omitted on the wire: `source_event: 3` +restores internal label `item_3`; `item: escape_rope` identifies the reward. +Explicit custom names and quantities above one remain supported. +These are explicitly remake baselines, not verified BDSP item data. Reading a +map never grants an item or proves that a controller action collected it. + +The shared v2 normalizer preserves all JSON extensions. The existing native +`MapData` model consumes its known navigation fields (including collection +flags); typed battle/inventory consumers for reward metadata remain future work. + +## Prepare and build + +On a fresh Arduino checkout, clone Packages before preparing the map subdirectory. +Skip this command when the checkout already has its Packages repository: + +```sh +git clone --depth 1 --branch master https://github.com/PokemonAutomation/Packages.git /path/to/Arduino-Source/Packages +``` + +Use the same approved tool revision pinned in CI. Preparation reads the separate +data revision from the resource lock; tools and data pins are independent. + +```sh +git clone https://github.com/dayfine/PokemonSimulation.git /path/to/pokesim +git -C /path/to/pokesim checkout 4de7742a764d27293b4525d6ad2a6fc8a95f3e3a +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 +cmake --build /path/to/build -j4 +``` + +Prepared resources include license/provenance and are ignored by Git. CMake +checks their exact inventory, hashes and publishing ancestry before embedding. +Missing, modified, extra or unapproved files fail; configuration never fetches +maps or falls back to an old authored directory. + +To deliberately advance the approved BDSP data pin after publication: + +```sh +PYTHONPATH=/path/to/pokesim/src python3 -m pokesim.maps.consumer_sync update \ + --layout resources --source /path/to/pokesim --consumer /path/to/Arduino-Source \ + --game bdsp --revision FULL_APPROVED_PUBLISHING_SHA +``` + +Update validates the existing lock and files before changing either; it preserves +independent game pins. Commit the resource lock, not the generated Packages files. +Do not rewrite the resource pin merely to make a locally edited map pass. + +## Offline tools and tests + +The existing decomp CLI forwards to the publisher parser. Fetch and overlay +commands still work without the Python package. For decompilation, supply the +approved tools on PYTHONPATH: + +```sh +PYTHONPATH=/path/to/pokesim/src python3 -m devtools.maps decomp ROUTE_204_NORTH --text +python3 -m unittest devtools.maps.tests.test_overlay +cmake -S devtools/runtime-map-tests -B build/runtime-map-tests +cmake --build build/runtime-map-tests -j4 +ctest --test-dir build/runtime-map-tests --output-on-failure +python3 devtools/runtime-map-tests/prepare_parity.py --publisher /path/to/candidate \ + --publisher-revision 4de7742a764d27293b4525d6ad2a6fc8a95f3e3a --out /tmp/bdsp-map-pairs.json +build/runtime-map-tests/RuntimeMapTests /tmp/bdsp-map-pairs.json +``` + +Parity fixtures require a clean checkout of the exact supplied candidate SHA. +They can test an unmerged candidate; that does not approve it as a resource pin. +The native schema workflow compares 150 complete records on three platforms. +Full application build/story validation is a separate gate after publication. +This fork resource setup is not an upstream Packages submission. diff --git a/devtools/maps/__main__.py b/devtools/maps/__main__.py index 57656e2a62..5a89522c7f 100644 --- a/devtools/maps/__main__.py +++ b/devtools/maps/__main__.py @@ -10,7 +10,7 @@ import sys from pathlib import Path -from . import decomp, fetch, grid_source, route_log, svg +from . import fetch, grid_source, route_log, svg CACHE = Path.home() / '.cache' / 'maps' @@ -26,7 +26,7 @@ def main(argv=None): sub = parser.add_subparsers(dest='command', required=True) dec = sub.add_parser('decomp', help="decode a map's tile grid and objects from the pret decompilation") dec.add_argument('map', help='the map header name, e.g. ROUTE_204_NORTH or RAVAGED_PATH') - dec.add_argument('--repo', default=decomp.Platinum.REPO, choices=[decomp.Platinum.REPO, decomp.Diamond.REPO], + dec.add_argument('--repo', default="pret/pokeplatinum", choices=["pret/pokeplatinum", "pret/pokediamond"], help='which decompilation to read (default: pret/pokeplatinum)') dec.add_argument('--rect', nargs=4, type=int, metavar=('X0', 'Z0', 'W', 'H'), help="world rectangle to decode; default: the map's own cell(s)") @@ -53,6 +53,10 @@ def main(argv=None): args = parser.parse_args(argv) if args.command == 'decomp': + try: + from pokesim.maps import dppt_map_decomp_parser as decomp + except ModuleNotFoundError: + parser.error('Set PYTHONPATH to the pinned PokemonSimulation src directory; see devtools/maps/RESOURCE_MAPS.md.') game = decomp.game_for(args.repo, args.cache / 'decomp', args.local) decoded = decomp.decode(game, args.map, tuple(args.rect) if args.rect else None) print(decomp.render_text(decoded) if args.text else decomp.render_cpp(decoded)) diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py deleted file mode 100644 index 6454bb3b47..0000000000 --- a/devtools/maps/bdsp_maps.py +++ /dev/null @@ -1,671 +0,0 @@ -"""Writes BDSP AutoStory's maps as JSON, from the Pokemon Diamond decompilation. - -TODO: move the maps to PokemonAutomation/Packages (Resources/PokemonBDSP/Maps) when ready. - -Usage: - python3 devtools/maps/bdsp_maps.py # rewrite every map in OUT - python3 devtools/maps/bdsp_maps.py Route202 # rewrite one - python3 devtools/maps/bdsp_maps.py --check # regenerate, fail on any difference - -Each map is a rectangle of the decompilation's world grid (MAPS below), -decoded tile for tile by devtools/maps/decomp.py from the files cached in -~/.cache/maps/decomp (`python3 -m devtools.maps decomp` fetches missing ones -with `gh api`; this script never fetches, it names the file it lacks). BDSP -keeps Diamond/Pearl's layout, so Diamond is read unless a map says otherwise. -The tables below add what the decompilation doesn't say or BDSP changed: - -- POINTS: named tiles the story walks from and to. A region (a set of - tiles, in order where the order matters) is written as numbered points, - `.1`, `.2`, ...: the shared schema (Pokemon_MapData.h) - has single-tile points only. -- OBJECTS: which of the events file's objects BDSP shows. People hidden by - a story flag are left out, and people who stand still or wander are kept, - unless an entry here says otherwise (`show`, `hide`, `still`, `at`), or - adds someone the console found that Diamond doesn't have. -- WARP_DOORS: warp tiles written 'D' so that no plan steps onto them; the - other warp tiles are written '.', since the story arrives on them. -- WARPS: doors that lead to a point of another map in OUT. -- PATCHES: tiles measured on the console that differ from Diamond's, with - the run that measured them. The map's tiles stay the decompilation's; the - loader applies the patches. -- COORD_EVENTS: names for the events file's coord events (the scene - triggers), and triggers found on the console that the decompilation - doesn't have, with the run that found them. - -The legend is the schema's: '#' wall, '.' open, '~' tall grass, 'w' water, -'^' 'v' '<' '>' ledges hopped the arrow's way, 'D' a door or cave mouth -(walked into) or a warp tile in WARP_DOORS, 'S' a sign or mailbox (read by -facing it; a sign script on a wall too). Items on the ground are objects of -kind "item"; rocks, cut trees, berry soil and steam vents are '#'. - -Rules: terrain from the decomp, people and BDSP's edits from the console; -a route is coded only over tiles a human or a probe has walked; a map change -re-runs every checkpoint that walks it. Bulbapedia's DP images (12 px rows -for 16 px columns, cliffs painted tall) are for drawing routes over, not for -terrain. - -Each map lists its events file's coord events under "coord_events" (the -shared schema, Pokemon_MapData.h, leaves the key to the game; BDSP AutoStory's -Data/PokemonBDSP_AutoStory_CoordEvents.h reads it): `width` columns and -`length` rows from local (x, y), armed while the story variable `var` holds -`value`, and a `source` that names the file, the event's index, its world -tile and its script. Boxes are clipped to the map's rectangle. -""" -import argparse -import json -import os -import sys -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parents[2])) -from devtools.maps import decomp # noqa: E402 - -OUT = 'SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps' -CACHE = Path.home() / '.cache' / 'maps' / 'decomp' -# When the cache was filled from the decompilations' default branches. -READ = '2026-10-31' - -LEDGES = {'north': '^', 'south': 'v', 'west': '<', 'east': '>'} -SIGN_GFX = ('MAILBOX',) -OBSTACLE_GFX = ('CUT_TREE', 'ROCK_SMASH', 'STRENGTH_BOULDER', 'BERRY_SOIL', 'VENT') -FACING = {'LOOK_NORTH': 'north', 'LOOK_SOUTH': 'south', 'LOOK_WEST': 'west', 'LOOK_EAST': 'east'} - - -# Decoded from pokeplatinum at this revision, not yet checked on the console. -INTERIOR = {'repo': decomp.Platinum.REPO, 'revision': 'c6689696d5fb', 'read': '2026-11-01', 'unverified': True} - -# Each map: its header constant, the world rectangle (x0, z0, width, -# height), and the decompilation when not Diamond. Local (x, y) = world -# (x - x0, z - z0). A map that joins another on the world grid keeps its -# rectangle's world corner, so story code can place them side by side. -MAPS = { - # Cells (3..4, 26) from z 839: the image-traced grid's columns and the - # game's rows. Console: the border sign read from (54, 4) facing east, - # row 3 open east of the grass, row 5 to Sandgem without a stop, the - # Potion lady on row 3 (2026-10-28 to 30, CFR "walk"). - 'Route201': {'header': 'ROUTE_201', 'rect': (96, 839, 64, 25)}, - # Cell (5, 25) from x 159. Console: under the south ledge at (22, 24), - # the save spot (30, 24) against the east trees, Natalie's challenge at - # (22, 22), column 30 north to row 4 (r75), the catch spot's walls. - 'Route202': {'header': 'ROUTE_202', 'rect': (159, 800, 36, 32)}, - # Cells (5..6, 23) from x 191: column 0 is Jubilife's east edge. - # Console (r227 hand pass, 2026-10-31): the Gate's warp at column 55, - # the ledge on row 15, the girl at (43, 17), row 18 straight west to - # Jubilife (35 taps). Diamond has four sand rows under the ledge where - # the console counted three (the first tap may only have turned). - 'Route203': {'header': 'ROUTE_203', 'rect': (191, 740, 61, 24)}, - # Cell (5, 21). Console: row 27 open under the cliff, the stairs, - # Taylor's sight at column 17 (human walk, 2026-10-31). Suspects: - # column 23 rows 12..19 blocked (r242a); three open rows under the cave, - # not four (r241a, r243a). - 'Route204North': {'header': 'ROUTE_204_NORTH', 'rect': (160, 672, 32, 32)}, - # Cell (5, 22). Console: north up column 14 stops at the signpost - # (14, 17); column 13 is grass to the cliff (13, 2); Sarah walked up and - # fought on row 21 (r233a, r234a). 01.08 passed once (r235a). - 'Route204South': {'header': 'ROUTE_204_SOUTH', 'rect': (160, 704, 32, 32), 'read': '2026-11-01'}, - # Cell (5, 26). Console (2026-10-29/30): the three doors, five signs, - # the doors' front row, the Lab's sign, the stop above the Mart (29, 5). - 'SandgemTown': {'header': 'SANDGEM', 'rect': (160, 832, 34, 32)}, - # Cells (4..5, 23..24). Console (2026-10-30/31): the lamps (43, 53) and - # (49, 53), north from (52, 53) to the Center's door, the School's door - # from the Center's doorstep, the east street to Route 203 (r230a), the - # north street, and the 00.05 people on their events-file tiles. - 'JubilifeCity': {'header': 'JUBLIFE', 'rect': (128, 736, 64, 64)}, - # Cells (8..9, 23..24); Platinum's map_data_022/023/175/024 are the - # same terrain. Console (r204 to r215): 20 D-pad taps from the - # Center's doorstep (46, 21) to below the Gym's door. - 'OreburghCity': {'header': 'OREBURGH', 'rect': (256, 736, 64, 64)}, - # The only cell of matrix 003; Platinum identical. - 'OreburghGate': {'header': 'OREBURGH_GATE_1F', 'rect': (0, 0, 32, 32)}, - # The only cell of matrix 113. 01.04 walks north up column 5. - 'OreburghGym': {'header': 'OREBURGH_GYM', 'rect': (0, 0, 32, 32)}, - # B2F, the coal room: matrix 006. Console (2026-10-28, r99): the - # corridor's rocks zigzag a row at a time, the room's second row passes - # under the worker, Roark a row above the bottom between two rocks; the - # walk north into the hall went up column 14 (the warp is column 15: a - # stick hold drifts, or BDSP's stairs are wider). - 'OreburghMine': {'header': 'OREBURGH_MINE_B2F', 'rect': (0, 0, 32, 32)}, - # Platinum's matrix 051 (Diamond's matrix is not in the cache), rows - # 0..53. Console (2026-10-31, r235b and D-pad probes): in from the south - # door onto (19, 50), up the stairs (18..20, 45..47) to the wall at row - # 39, the corridor three wide to row 41 and open east on rows 42..44, - # the rocks (22, 42), (22, 43), (23, 44) and the Potion (22, 44). Rows - # 0..29 were a hand trace from the DP image before; nothing walks there. - 'RavagedPath': {'header': 'RAVAGED_PATH', 'rect': (0, 0, 32, 54), 'repo': decomp.Platinum.REPO}, - # Cell (5, 20); the cell above carries the same header but is cut off - # from the town. Console: the old couple (2026-10-31 walk, r251a). - 'FloaromaTown': {'header': 'FLOAROMA', 'rect': (160, 640, 32, 32)}, - # Cell (3, 27). The player's house is the south-east one, door - # (20, 21); Barry's the north-west one, door (9, 11) (the interiors say - # so; Diamond's map constants name them the other way round). - 'TwinleafTown': {'header': 'TWINLEAF', 'rect': (96, 864, 32, 32)}, - # Cell (2, 26), of the four the header covers (the others are trees - # and water). The ledges on column 20 (rows 14..18) are hopped west. - 'VerityLakefront': {'header': 'VERITY_LAKEFRONT', 'rect': (64, 832, 32, 32)}, - # Cell (1, 1) of the lake's matrix 101: the shore where the starter - # scene plays. Only this cell is reached on foot. - 'LakeVerity': {'header': 'LAKE_VERITY', 'rect': (32, 32, 32, 32)}, - # 00.01 to 00.03's interiors, from pokeplatinum (c6689696d5fb), each - # the only cell of its own matrix: decomp only, not yet checked on the - # console. Mom's warning on the way out is a coord event on the - # player's door tile (6, 10). - 'PlayerHouse1F': {'header': 'TWINLEAF_TOWN_PLAYER_HOUSE_1F', 'rect': (0, 0, 13, 12), **INTERIOR}, - 'PlayerHouse2F': {'header': 'TWINLEAF_TOWN_PLAYER_HOUSE_2F', 'rect': (0, 0, 12, 12), **INTERIOR}, - 'RivalHouse1F': {'header': 'TWINLEAF_TOWN_RIVAL_HOUSE_1F', 'rect': (0, 0, 13, 12), **INTERIOR}, - 'RivalHouse2F': {'header': 'TWINLEAF_TOWN_RIVAL_HOUSE_2F', 'rect': (0, 0, 12, 12), **INTERIOR}, - 'RowansLab': {'header': 'SANDGEM_TOWN_POKEMON_RESEARCH_LAB', 'rect': (0, 0, 22, 18), **INTERIOR}, -} - - -def box(x0, y0, x1, y1): - """Every tile of a box, both corners inclusive, row by row.""" - return [(x, y) for y in range(y0, y1 + 1) for x in range(x0, x1 + 1)] - - -# Named tiles; a list is a region, written as numbered points. -POINTS = { - 'Route201': { - # The arrow sign to Sandgem. Console (CFR "walk"): east along row 4 - # stops at its west side and A reads it. - 'border_sign': (55, 4), - # The Poke Mart lady (10 Potions): Diamond spawns her at (44, 3), the - # console had her at (43, 3) and walking west along row 3 stopped at - # (44, 3), facing her (99715d5d6, f823453e9; r135a missed her on row 4). - 'potion_giver': (43, 3), - 'potion_giver_talk_from': (44, 3), - # Segment 00's lines (Segment00Lines). - 'route_201_arrival': (15, 24), - 'barry_warning': (15, 18), - 'route_201_return': (0, 14), - 'rowan_stop': (5, 14), - 'route_201_east_end': (63, 5), - }, - 'Route202': { - # 00.03's save after the catch: the catch patch's bottom row. The - # sign (24, 25) is 5 right and 2 up; south are trees (r253). - 'catch_spot': (19, 27), - # 00.04's save before the trainers, under the south ledge against - # the east trees (r113a..r117a). - 'save_spot': (30, 24), - 'trainer_tristan': (7, 13), - 'trainer_natalie': (22, 18), - 'trainer_logan': (26, 4), - # The middle of the gap to Jubilife, below its 3-wide neck. - 'exit_jubilife': (15, 0), - # The open rows at the top: north from any of them is Jubilife. - 'jubilife_exit': box(11, 0, 18, 3), - # Where 00.04b's save after the catch may stand: the patch and the - # lawn column east of it, down to the pocket where r252 saved. - 'catch_save_area': box(15, 25, 21, 27) + [(21, 28), (21, 29)], - # Where training may leave us (the catch spot's column and one either - # side, between the tree rows), and its grass: all of it. - 'after_training_area': box(18, 25, 20, 27), - 'catch_grass': box(18, 25, 20, 27), - }, - 'Route203': { - # The warp tile the Gate puts us on, and its open neighbours. - 'gate_exit': [(55, 9), (54, 9), (55, 8), (55, 10)], - # Row 18 between the cliffs: it runs straight west into Jubilife. - 'west_line': box(24, 18, 42, 18), - }, - 'Route204North': { - 'cave_exit': (20, 26), - # The line a human walked on 2026-10-31: out of the cave, west under - # the cliff, up the stairs, east (Taylor), north up column 19, west - # below the flower beds, north between them on column 11 ((12, 6) - # is blocked on the console). - 'floaroma_waypoints': [(20, 27), (11, 27), (11, 22), (19, 22), (19, 12), (11, 12), (11, 5)], - # The path north into Floaroma: walking north from here leaves. - 'floaroma_path': box(10, 0, 12, 5), - 'trainer_twin_left': (15, 7), - 'trainer_twin_right': (16, 7), - 'trainer_taylor': (17, 20), - 'trainer_brandon': (20, 12), - }, - 'Route204South': { - 'below_door': (11, 2), - # Where the walk north from Jubilife may stop, up to two tiles past - # the border (400 ms holds between looks). - 'jubilife_entry': [(14, 31), (14, 30), (14, 29)], - 'trainer_samantha': (11, 8), - 'trainer_sarah': (12, 21), - 'trainer_tyler': (7, 18), - }, - 'SandgemTown': { - # The walk south from Route 202 down the road's east side stops here, - # above the Mart where the road narrows (console, 2026-10-29/30). - 'route_202_entry_stop': (29, 5), - 'lab_door': (8, 10), - 'pokemon_center_door': (17, 10), - # Walking north from row 14 in its column stops below it. - 'pokemon_center_sign': (20, 10), - 'poke_mart_door': (27, 10), - # East along the doors' front row stops here, at the trees (CFR - # "walk", 2026-10-30): a known tile to plan north from. - 'front_row_east_end': (29, 11), - # The front row below the gap between the Center's and the Mart's - # signs: the only way north from that row that passes no door. - 'below_sign_gap': box(21, 11, 24, 11), - 'sandgem_arrival': (0, 12), - 'dawn_stop': (4, 12), - }, - 'JubilifeCity': { - # A doorway (warp tile) stepped onto from (40, 41). - 'trainers_school_door': (40, 40), - # Walked into from (52, 41); eleven taps west from its doorstep put - # us under the School's door (2026-10-30). - 'pokemon_center_door': (52, 40), - 'tv_station_door': (36, 15), - # Talked to from the east (also works from the south). - 'poketch_president': (46, 35), - # His spawn tile; Diamond has him wander a tile either side, the - # console had him a tile east of it. - 'clown_mart': (55, 33), - 'clown_tv_station': (36, 16), - # Talked to from the south; west along row 18 stops beside him. - 'clown_poketch_company': (15, 18), - # A tile west of 00.05's save below the steps, then north: on - # column 46 or 47 a few rows up (CFR "walk", 2026-10-30). - 'up_the_steps': box(46, 58, 47, 60), - # Where Route 203's road enters, rows 21..24 at the east edge. - 'east_entrance': box(61, 21, 63, 24), - # The north road where it leaves the plaza: north from here goes - # up the road to Route 204 and Rowan's scene. - 'north_road': box(44, 16, 48, 20), - }, - 'OreburghCity': { - 'pokemon_center_door': (47, 20), - # The taps say x 46, a column west of the door. - 'pokemon_center_doorstep': (46, 21), - 'gym_door': (26, 20), - 'gym_doorstep': (26, 21), - 'gate_mouth': (1, 13), - }, - 'OreburghGym': { - # Coming in puts us here; the door is below. - 'entrance': (5, 23), - 'roark': (5, 3), - 'trainer_first_tier': (4, 18), - 'trainer_second_tier': (7, 11), - }, - 'OreburghMine': { - 'roark': (18, 28), - 'corridor_exit_start': (14, 10), - # The first open row below the warp tile, where the walk in from - # the hall leaves us. - 'corridor_top': box(14, 2, 16, 2), - }, - 'RavagedPath': { - 'entrance': (19, 50), - 'east_end': (29, 44), - 'above_exit': (28, 44), - # Rock Smash rocks, open once smashed. - 'rocks': [(11, 36), (7, 37), (12, 37), (8, 38), (10, 38), (10, 39), (13, 39), - (7, 40), (9, 40), (17, 40), (12, 41), (22, 42), (22, 43), (23, 44)], - # West of the two rocks on rows 42 and 43. - 'before_rocks': [(21, 42), (21, 43)], - }, - 'FloaromaTown': { - 'route_204_arrival': (11, 29), - 'old_woman': (3, 25), - 'old_man': (2, 25), - 'pokemon_center_door': (16, 26), - }, - 'TwinleafTown': { - 'house_doorstep': (20, 22), - # Barry's scene fires here, below his door. - 'barry_doorstep': (9, 12), - 'twinleaf_north_exit': (15, 0), - 'player_house_door': (20, 21), - 'rival_house_door': (9, 11), - }, - 'VerityLakefront': { - 'lakefront_arrival': (31, 23), - 'below_lake_entrance': (17, 14), - # The lake's scene fires here; it is assumed to leave us here too. - 'lake_entrance': (17, 12), - }, - 'PlayerHouse1F': {'stairs': (10, 3), 'mom': (7, 8), 'door': (6, 10)}, - # A new game starts on (4, 6); the TV is the signs at (3, 4) and (4, 4). - 'PlayerHouse2F': {'stairs': (8, 4), 'start': (4, 6)}, - 'RivalHouse1F': {'door': (6, 10), 'stairs': (2, 3)}, - # Barry stands at (9, 5) facing his PC; he is talked to from the west. - 'RivalHouse2F': {'stairs': (3, 4), 'barry_talk': (8, 5)}, - # Rowan is talked to from below, facing north. - 'RowansLab': {'door': (7, 15), 'rowan_talk': (7, 6)}, -} - - -# Overrides by events-file object index. `show`: a person hidden by a -# story flag who is there when the story walks the map. `hide`: someone -# BDSP doesn't have, or the story never meets. `still`: a wanderer who -# stood still on the console. `at`: where the console found them. `add`: -# people Diamond doesn't have, from the console. -OBJECTS = { - 'Route201': { - # The Potion lady stands a tile off her spawn on the console, and - # her talk is walked to, not planned (POINTS). - 1: {'hide': 'her talk is walked to, not planned'}, - }, - 'Route203': { - # Stands still in Diamond, wanders near the Gate in BDSP (console). - 0: {'hide': 'wanders in BDSP'}, - }, - 'Route204North': { - # Bug Catcher Brandon paces in Diamond from (22, 13); he stopped us - # on row 12 (r246a), and the DP map draws him at (20, 12). - 0: {'at': (20, 12), 'still': 'r246a', 'name': 'bug_catcher_brandon'}, - }, - 'SandgemTown': { - # Stand still in Diamond, wander on the console. - 1: {'hide': 'wanders in BDSP'}, - 2: {'hide': 'wanders in BDSP'}, - }, - 'JubilifeCity': { - # 00.05's story people, hidden before and after it. - 24: {'show': '00.05', 'name': 'poketch_president'}, - 28: {'show': '00.05', 'name': 'clown_tv_station'}, - # Wander in Diamond; stood still on the console (00.05, three runs). - 25: {'show': '00.05', 'still': '00.05, three runs', 'name': 'clown_mart'}, - 26: {'show': '00.05', 'still': '00.05, three runs', 'name': 'clown_poketch_company'}, - }, - 'FloaromaTown': { - # Grunts at the Meadow until the Valley Windworks is cleared, and - # the man with Cyrus's sprite (whether he is there is for the console). - 7: {'show': 'until the Valley Windworks'}, - 8: {'show': 'until the Valley Windworks'}, - 3: {'show': 'not yet checked on the console'}, - 'add': [ - # Not in Diamond's data. Walking north from (3, 29) stopped 3 - # tiles up at the old woman (r251a). - {'name': 'old_woman', 'x': 3, 'y': 25, 'measured_by': 'r251a, 2026-10-31'}, - {'name': 'old_man', 'x': 2, 'y': 25, 'measured_by': 'r251a, 2026-10-31'}, - ], - }, - 'OreburghMine': { - # Hidden once his scene here is over; the story walks to him. - 0: {'show': '01.03', 'name': 'roark'}, - }, - 'RivalHouse2F': { - # Barry in his room, until he leaves for the lake. - 0: {'show': '00.01', 'name': 'barry'}, - }, - 'RowansLab': { - # Rowan at his desk when the story walks in. - 0: {'show': '00.03', 'name': 'rowan'}, - }, - 'LakeVerity': { - # The starter scene's actors, where the walk in ends. - 0: {'show': 'the starter scene', 'name': 'rowan'}, - 1: {'show': 'the starter scene', 'name': 'counterpart'}, - 3: {'show': 'the starter scene'}, - }, -} - - -WARP_DOORS = { - # The Ravaged Path's door: its warp tile is the mouth. - 'Route204South': [(11, 1)], - # The Route 218 gate, and the doorways of the School and the Global - # Terminal: entered, never stood on by a route. - 'JubilifeCity': [(0, 22), (0, 23), (40, 40), (21, 42)], - # The way up to the entrance hall: stepping on it leaves the room. - 'OreburghMine': [(15, 1)], -} - - -# Stepping onto (x, y) puts the player at a point of another map. -WARPS = { - 'PlayerHouse1F': [(6, 10, 'TwinleafTown', 'player_house_door')], - 'RivalHouse1F': [(6, 10, 'TwinleafTown', 'rival_house_door')], - 'RowansLab': [(7, 15, 'SandgemTown', 'lab_door')], -} - - -PATCHES = { - 'Route202': ( - # BDSP has trees where Diamond's catch patch has its two bottom rows: - # west along row 29 stopped at column 21, beside them. - [(x, y, '#', 'r253, 2026-11-01') for y in (28, 29) for x in range(15, 21)] - # South from the pocket (21, 29), where the catch's save loads, - # was blocked at once. - + [(21, 30, '#', 'r254, 2026-11-01')] - ), - 'PlayerHouse1F': [ - # Open on the console, a wall in the data: west along row 8 stops - # at x 4 (r32). - (4, 8, '.', 'r32, 2026-11-01'), - ], - 'Route201': ( - # Row 18 west of the exit path is trees on the console, open in the - # decomp, and the 201 sign stands at (13, 18), not (13, 17) (r16, - # walked by hand). - [(x, 18, '#', 'r16, 2026-10-31') for x in range(8, 13)] - + [(13, 18, 'S', 'r16, 2026-10-31'), (13, 17, '.', 'r16, 2026-10-31')] - ), - 'Route204North': [ - # Grass in the data, blocked on the console twice. - (12, 6, '#', 'r248a, 2026-10-31'), - ], -} - - -# Coord events by events-file index: their names (the default is -# coord_event_), and under 'add' the triggers the console found that -# the decompilation doesn't have. -COORD_EVENTS = { - # Barry stops us on row 18 (POINTS barry_warning); Rowan on column 5 - # (POINTS rowan_stop). - 'Route201': {0: 'barry_warning', 1: 'rowan_stop'}, - 'Route202': {0: 'catch_tutorial'}, - 'SandgemTown': {0: 'dawn_walks_us_to_the_lab'}, - 'JubilifeCity': {0: 'dawn_at_the_steps', 4: 'poketch_president'}, - 'TwinleafTown': {1: 'barry_doorstep'}, - 'VerityLakefront': {0: 'lake_entrance'}, - 'PlayerHouse1F': { - 0: 'moms_warning', - 'add': [ - {'name': 'moms_call', 'x': 6, 'y': 9, 'width': 1, 'length': 1, 'var': 'CONSOLE_MOMS_CALL', 'value': 0, - 'measured_by': 'console r45, r46 (2026-11-01): after her heal Mom calls us back as we step above' - ' the door; no coord event in the decomp'}, - ], - }, -} - - -def no_fetch(repo, path): - raise SystemExit(f'{repo}/{path} is not in {CACHE}. Fetch it with `python3 -m devtools.maps decomp ...` first.') - - -def glyph(attr): - behaviour = attr & 0xff - if behaviour in decomp.JUMP: - return LEDGES[decomp.JUMP[behaviour]] - if behaviour in decomp.JUMP_TWICE: - return LEDGES[decomp.JUMP_TWICE[behaviour]] - if behaviour == decomp.DOOR or behaviour in decomp.CAVE_MOUTHS: - return 'D' - if behaviour in decomp.WARP_TILES or behaviour in decomp.WARP_STAIRS: - return 'W' - if behaviour in decomp.WATER: - return 'w' - if attr & decomp.BLOCKED: - return '#' - if behaviour in decomp.TALL_GRASS: - return '~' - return '.' - - -def wander_box(obj, x, y, width, height): - return {'x0': max(0, x - obj.range_x), 'y0': max(0, y - obj.range_z), - 'x1': min(width - 1, x + obj.range_x), 'y1': min(height - 1, y + obj.range_z)} - - -def place_objects(name, events, rect, rows): - """Writes signs and obstacles into `rows`; returns the objects.""" - x0, z0, width, height = rect - overrides = OBJECTS.get(name, {}) - objects = [] - for index, obj in enumerate(events.objects): - x, y = obj.x - x0, obj.z - z0 - if not (0 <= x < width and 0 <= y < height): - continue - override = overrides.get(index, {}) - if obj.gfx in OBSTACLE_GFX: - rows[y][x] = '#' - continue - if obj.gfx == decomp.ITEM: - objects.append({'name': f'item_{index}', 'kind': 'item', 'x': x, 'y': y}) - continue - if obj.hidden and 'show' not in override or 'hide' in override: - continue - if 'SIGN' in obj.gfx or obj.gfx in SIGN_GFX: - rows[y][x] = 'S' - continue - x, y = override.get('at', (x, y)) - entry = {'name': override.get('name', f'{obj.gfx.lower()}_{index}'), 'kind': 'npc', 'x': x, 'y': y} - if obj.movement in FACING: - entry['facing'] = FACING[obj.movement] - if obj.movement.startswith(('WANDER', 'WALK')) and 'still' not in override: - entry['wander'] = wander_box(obj, x, y, width, height) - objects.append(entry) - for added in overrides.get('add', []): - objects.append({'name': added['name'], 'kind': 'npc', 'x': added['x'], 'y': added['y']}) - return objects - - -def coord_events(name, repo, game, events_id, rect): - """The map's coord events: the events file's, clipped to `rect`, then COORD_EVENTS' additions.""" - x0, z0, width, height = rect - names = COORD_EVENTS.get(name, {}) - out = [] - for index, event in enumerate(game.events(events_id).coord_events): - left, top = max(event.x, x0), max(event.z, z0) - right, bottom = min(event.x + event.width, x0 + width), min(event.z + event.length, z0 + height) - if left >= right or top >= bottom: - continue - out.append({ - 'name': names.get(index, f'coord_event_{index}'), - 'x': left - x0, 'y': top - z0, 'width': right - left, 'length': bottom - top, - 'var': event.var, 'value': event.value, - 'source': f'{repo} {game.events_path(events_id)} coord_events[{index}] ({event.x}, {event.z}),' - f' script {event.script}', - }) - for added in names.get('add', []): - fields = {k: v for k, v in added.items() if k != 'measured_by'} - out.append({**fields, 'source': added['measured_by']}) - return out - - -def decode_map(name): - spec = MAPS[name] - repo = spec.get('repo', decomp.Diamond.REPO) - game = decomp.game_for(repo, CACHE, None, no_fetch) - header = game.header(spec['header']) - matrix = game.matrix(header.matrix_id) - world = decomp.World(game, matrix) - x0, z0, width, height = spec['rect'] - rows = [] - for y in range(height): - row = [] - for x in range(width): - attr = world.attr(x0 + x, z0 + y) - if attr is None: - raise SystemExit(f'{name}: ({x}, {y}) is outside matrix {header.matrix_id}.') - row.append(glyph(attr)) - rows.append(row) - events = game.events(header.events_id) - for sign in events.signs: - x, y = sign.x - x0, sign.z - z0 - if 0 <= x < width and 0 <= y < height and rows[y][x] == '#': - rows[y][x] = 'S' - objects = place_objects(name, events, spec['rect'], rows) - doors = set(WARP_DOORS.get(name, [])) - for y, row in enumerate(rows): - for x, tile in enumerate(row): - if tile == 'W': - row[x] = 'D' if (x, y) in doors else '.' - # Every cell the rectangle touches, also when it does not start on a cell's edge. - C = decomp.CELL - lands = sorted({world.land_id(C * col, C * row) for row in range(z0 // C, (z0 + height - 1) // C + 1) - for col in range(x0 // C, (x0 + width - 1) // C + 1)} - {None}) - unverified = '; decomp only, not checked on the console' if spec.get('unverified') else '' - source = { - 'decomp_file': f'{repo}: ' + ', '.join(game.land_path(land) for land in lands) - + f'; {game.events_name(header.events_id)}{unverified}', - 'revision': spec.get('revision', 'default branch'), - 'date': spec.get('read', READ), - } - triggers = coord_events(name, repo, game, header.events_id, spec['rect']) - return [''.join(row) for row in rows], objects, source, triggers - - -def points_of(name): - points = {} - for point, value in POINTS.get(name, {}).items(): - if isinstance(value, list): - for i, pos in enumerate(value, 1): - points[f'{point}.{i}'] = pos - else: - points[point] = value - return points - - -def map_text(name): - """The map's JSON: one line per row, point, object and patch.""" - tiles, objects, source, triggers = decode_map(name) - lines = ['{', f' "name": {json.dumps(name)},', f' "source": {json.dumps(source)},', ' "tiles": ['] - lines += [f' {json.dumps(row)},' for row in tiles] - lines[-1] = lines[-1].rstrip(',') - lines.append(' ]') - - def section(key, items): - if not items: - return - lines[-1] += ',' - lines.append(f' "{key}": ' + ('{' if key == 'points' else '[')) - lines.extend(f' {item},' for item in items) - lines[-1] = lines[-1].rstrip(',') - lines.append(' ' + ('}' if key == 'points' else ']')) - - section('points', [f'{json.dumps(p)}: [{x}, {y}]' for p, (x, y) in points_of(name).items()]) - section('warps', [json.dumps({'x': x, 'y': y, 'to_map': m, 'to_point': p}) for x, y, m, p in WARPS.get(name, [])]) - section('objects', [json.dumps(o) for o in objects]) - section('coord_events', [json.dumps(e) for e in triggers]) - section('patches', [json.dumps({'x': x, 'y': y, 'glyph': g, 'measured_by': m}) - for x, y, g, m in PATCHES.get(name, [])]) - lines.append('}') - return '\n'.join(lines) + '\n' - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) - parser.add_argument('--out', default=OUT, help='folder of the .json files') - parser.add_argument('--check', action='store_true', help='check the files in --out instead of writing them') - parser.add_argument('maps', nargs='*', help='default: every map in MAPS') - args = parser.parse_args() - names = args.maps or sorted(MAPS) - for name in names: - if name not in MAPS: - parser.error(f'{name}: not in MAPS') - texts = {name: map_text(name) for name in names} - if args.check: - differ = [n for n, text in texts.items() - if not os.path.exists(os.path.join(args.out, n + '.json')) - or open(os.path.join(args.out, n + '.json'), newline='').read() != text] - if not args.maps: - extra = sorted(f[:-5] for f in os.listdir(args.out) if f.endswith('.json') and f[:-5] not in MAPS) - differ += [f'{n} (not in MAPS)' for n in extra] - if differ: - sys.exit(f'Differ from the generator: {", ".join(differ)}. Regenerate them without --check.') - print(f'{len(texts)} maps in {args.out} match the generator.') - return - os.makedirs(args.out, exist_ok=True) - for name, text in texts.items(): - with open(os.path.join(args.out, name + '.json'), 'w', newline='') as file: - file.write(text) - print(f'Wrote {len(texts)} maps to {args.out}.') - - -if __name__ == '__main__': - main() diff --git a/devtools/maps/decomp.py b/devtools/maps/decomp.py deleted file mode 100644 index 881fa19347..0000000000 --- a/devtools/maps/decomp.py +++ /dev/null @@ -1,593 +0,0 @@ -"""Decodes a map's tile grid from the Pokemon Platinum or Diamond decompilation. - -The pret decompilations hold each 32 x 32 map cell's collision as a land data -file: a 16-byte header of four u32 sizes (attributes, movement models, map -models, height data), then 1024 little-endian u16 tile attributes, row-major, -index z * 32 + x. Bit 0x8000 blocks the tile; the low byte is its behaviour -(tall grass, water, ledges, doors, warps). Cells sit in a matrix: the -overworld's is 30 x 30 (matrix 000), caves have their own; world -x = 32 * column + lx, z = 32 * row + lz, and the events files place objects -in these world coordinates. - -pokeplatinum keeps matrices and events as JSON and its map headers in -include/data/map_headers.h. pokediamond keeps them as binary NARC entries -(the layout pokeplatinum's tools/jsoncnv packs) with the header table in -arm9/src/map_header.c, and gives sprites, movement types, trainer types and -story variables by number; pokeplatinum's generated/*.txt tables name them. -An events file lists bg events, object events, warps and coord events (the -scene triggers: stepping onto one of a box of tiles while a story variable -holds a value starts a script), in that order. BDSP keeps -Diamond/Pearl's layout; Platinum's few changes show up on the console. -""" -import datetime -import json -import re -import struct -import subprocess -import textwrap -from dataclasses import dataclass, field -from pathlib import Path - -CELL = 32 -# Tile attribute bits and behaviours (include/constants/field/map_tile_behaviors.h). -BLOCKED = 0x8000 -TALL_GRASS = {0x02, 0x03} -WATER = {0x10, 0x13, 0x15} # river, waterfall, sea -JUMP = {0x38: 'east', 0x39: 'west', 0x3a: 'north', 0x3b: 'south'} -JUMP_TWICE = {0x5a: 'north', 0x5b: 'south', 0x5c: 'west', 0x5d: 'east'} -WARP_STAIRS = {0x5e, 0x5f} -CAVE_MOUTHS = {0x62, 0x63, 0x64, 0x65} # blocked, walked into -DOOR = 0x69 -WARP_TILES = {0x6c, 0x6d, 0x6e, 0x6f} # walkable, stood on -# Objects that stand on the ground and block it. -OBSTACLES = {'CUT_TREE', 'ROCK_SMASH', 'STRENGTH_BOULDER'} -ITEM = 'POKEBALL' -# bg events: 0 facing, 1 wall sign, 2 hidden item (generated/bg_event_types.txt). -BG_SIGNS = {0, 1} - - -def tile_char(attr): - """Our legend for one tile attribute: (char, note or None).""" - behaviour = attr & 0xff - if behaviour in JUMP or behaviour in JUMP_TWICE: - twice = behaviour in JUMP_TWICE - side = JUMP_TWICE[behaviour] if twice else JUMP[behaviour] - if side == 'south': - return 'v', 'double ledge' if twice else None - return '#', f'ledge jumped {side}{" twice" if twice else ""}, shown as a wall' - if behaviour == DOOR or behaviour in CAVE_MOUTHS: - return 'D', None - if behaviour in WARP_TILES or behaviour in WARP_STAIRS: - return 'W', None - if behaviour in WATER: - return '#', 'water' - if attr & BLOCKED: - return '#', None - if behaviour in TALL_GRASS: - return '"', None - return '.', None - - -def decode_land_data(data): - """The 1024 tile attributes of a land data file (map_data_NNN.bin / narc_NNNN.bin).""" - sizes = struct.unpack('<4I', data[:16]) - if sizes[0] != 2 * CELL * CELL: - raise ValueError(f'land data: attribute block is {sizes[0]} bytes, expected {2 * CELL * CELL}') - return list(struct.unpack(f'<{CELL * CELL}H', data[16:16 + sizes[0]])) - - -def gh_fetch(repo, path): - """One file of a GitHub repository, raw; binary works.""" - result = subprocess.run( - ['gh', 'api', f'repos/{repo}/contents/{path}', '-H', 'Accept: application/vnd.github.raw'], - check=True, stdout=subprocess.PIPE) - return result.stdout - - -class Source: - """Files of one decompilation: a local checkout, or fetched once into the cache.""" - - def __init__(self, repo, cache, local=None, fetch=gh_fetch): - self.repo = repo - self.cache = Path(cache) - self.local = Path(local) if local else None - self.fetch = fetch - - def read(self, path): - if self.local: - return (self.local / path).read_bytes() - cached = self.cache / self.repo / path - if not cached.exists(): - data = self.fetch(self.repo, path) - cached.parent.mkdir(parents=True, exist_ok=True) - cached.write_bytes(data) - return cached.read_bytes() - - def text(self, path): - return self.read(path).decode('utf-8', errors='replace') - - -@dataclass -class MapHeader: - name: str - matrix_id: int - events_id: object # Platinum: events archive name; Diamond: NARC index - - -@dataclass -class Matrix: - matrix_id: int - width: int - height: int - maps: list # land data id per cell, row-major, None for MAP_NONE - headers: list = None # map header name per cell, or None when the matrix has none - - def cells_of(self, header_name): - """(row, col) of every cell carrying this header; all cells when the matrix has no headers.""" - cells = [(i // self.width, i % self.width) for i in range(self.width * self.height) - if self.maps[i] is not None and (self.headers is None or self.headers[i] == header_name)] - return cells - - -@dataclass -class ObjectEvent: - name: str - gfx: str - movement: str - trainer: bool - sight: int - range_x: int - range_z: int - x: int - z: int - hidden: str = '' - - -@dataclass -class Warp: - x: int - z: int - dest: str - - -@dataclass -class Sign: - x: int - z: int - - -@dataclass -class CoordEvent: - """A scene trigger: `width` x `length` tiles from (x, z), armed while `var` holds `value`.""" - script: int - x: int - z: int - width: int - length: int - var: str - value: int - - -@dataclass -class Events: - objects: list = field(default_factory=list) - warps: list = field(default_factory=list) - signs: list = field(default_factory=list) - coord_events: list = field(default_factory=list) - - -def strip_prefix(name, prefix): - return name[len(prefix):] if name.startswith(prefix) else name - - -class Platinum: - """pret/pokeplatinum: JSON matrices and events, map headers in include/data/map_headers.h.""" - REPO = 'pret/pokeplatinum' - GAME = 'Pokemon Platinum' - HEADER = re.compile(r'\[MAP_HEADER_(\w+)\]\s*=\s*\{(.*?)\}', re.S) - - def __init__(self, source): - self.source = source - self._headers = None - - def header(self, name): - if self._headers is None: - text = self.source.text('include/data/map_headers.h') - self._headers = {m.group(1): m.group(2) for m in self.HEADER.finditer(text)} - body = self._headers.get(name) - if body is None: - raise KeyError(f'{name}: no MAP_HEADER_{name} in include/data/map_headers.h') - matrix = re.search(r'\.mapMatrixID\s*=\s*map_matrix_(\d+)', body) - events = re.search(r'\.eventsArchiveID\s*=\s*(\w+)', body) - return MapHeader(name, int(matrix.group(1)), events.group(1)) - - def matrix(self, matrix_id): - data = json.loads(self.source.text(f'res/field/matrices/map_matrix_{matrix_id:03d}.json')) - maps = [None if m == 'MAP_NONE' else int(m[len('MAP_'):]) for row in data['maps'] for m in row] - headers = [strip_prefix(h, 'MAP_HEADER_') for row in data['headers'] for h in row] or None - return Matrix(matrix_id, len(data['maps'][0]), len(data['maps']), maps, headers) - - def land_name(self, land_id): - return f'map_data_{land_id:03d}' - - def land_path(self, land_id): - return f'res/field/maps/data/{self.land_name(land_id)}.bin' - - def land_data(self, land_id): - return decode_land_data(self.source.read(self.land_path(land_id))) - - def events_name(self, events_id): - return f'{events_id}.json' - - def events_path(self, events_id): - return f'res/field/events/{events_id}.json' - - def events(self, events_id): - data = json.loads(self.source.text(self.events_path(events_id))) - events = Events() - for o in data.get('object_events', []): - trainer = o['trainer_type'] != 'TRAINER_TYPE_NONE' - events.objects.append(ObjectEvent( - name=title(strip_prefix(o['id'], 'LOCALID_')), - gfx=strip_prefix(o['graphics_id'], 'OBJ_EVENT_GFX_'), - movement=strip_prefix(o['movement_type'], 'MOVEMENT_TYPE_'), - trainer=trainer, - sight=(o.get('data') or [0])[0] if trainer else 0, - range_x=o.get('movement_range_x', 0), range_z=o.get('movement_range_z', 0), - x=o['x'], z=o['z'], - hidden='' if str(o.get('hidden_flag', '0')) == '0' else str(o['hidden_flag']))) - for w in data.get('warp_events', []): - events.warps.append(Warp(w['x'], w['z'], strip_prefix(w['dest_header_id'], 'MAP_HEADER_'))) - for b in data.get('bg_events', []): - if b['type'] in BG_SIGNS: - events.signs.append(Sign(b['x'], b['z'])) - for c in data.get('coord_events', []): - events.coord_events.append(CoordEvent( - c['script'], c['x'], c['z'], c['width'], c['length'], c['var'], c['value'])) - return events - - -class Diamond: - """pret/pokediamond: binary matrices and events, the header table in arm9/src/map_header.c. - - Sprites, movement types and trainer types are numbers there; `names` is a - Source for pret/pokeplatinum, whose generated/*.txt tables list them in - order (checked on Route 204 North: the same twelve objects come out). - Story variables are numbered from 0x4000 in both games; Platinum's - generated/vars_flags.txt (a C enum) names them (checked: the coord events - that pokeplatinum also has on Route 202, Sandgem, Jubilife and the - player's house come out with Platinum's variable names). A number that - table does not name stays a number. - """ - REPO = 'pret/pokediamond' - GAME = 'Pokemon Diamond' - HEADER_LINE = re.compile(r'\{([^{}]*)\}\s*,?\s*//\s*(MAP_\w+)') - DEFINE = re.compile(r'#define\s+(MAP_\w+)\s+(\d+)') - - def __init__(self, source, names): - self.source = source - self.names = names - self._headers = None - self._map_ids = None - self._tables = {} - - def header(self, name): - if self._headers is None: - text = self.source.text('arm9/src/map_header.c') - self._headers = {m.group(2): m.group(1) for m in self.HEADER_LINE.finditer(text)} - body = self._headers.get(f'MAP_{name}') - if body is None: - raise KeyError(f'{name}: no MAP_{name} row in arm9/src/map_header.c') - matrix = re.search(r'NARC_map_matrix_narc_(\d+)_bin', body) - events = re.search(r'NARC_zone_event_release_narc_(\d+)_bin', body) - return MapHeader(name, int(matrix.group(1)), int(events.group(1))) - - def map_name(self, map_id): - """MAP_ constant name (without the prefix) for a numeric map header id.""" - if self._map_ids is None: - text = self.source.text('include/constants/maps.h') - self._map_ids = {int(m.group(2)): m.group(1) for m in self.DEFINE.finditer(text)} - return strip_prefix(self._map_ids.get(map_id, f'MAP_{map_id}'), 'MAP_') - - def table(self, name): - if name not in self._tables: - self._tables[name] = self.names.text(f'generated/{name}.txt').split() - return self._tables[name] - - def named(self, table, prefix, value): - entries = self.table(table) - return strip_prefix(entries[value], prefix) if value < len(entries) else str(value) - - def var_name(self, number): - if 'vars' not in self._tables: - values = enum_values(self.names.text('generated/vars_flags.txt').splitlines()) - names = {} - for name, value in values.items(): - if name.startswith('VAR_'): - names.setdefault(value, name) - self._tables['vars'] = names - return self._tables['vars'].get(number, str(number)) - - def matrix(self, matrix_id): - data = self.source.read(f'files/fielddata/mapmatrix/map_matrix/narc_{matrix_id:04d}.bin') - width, height, has_headers, has_altitudes, name_len = struct.unpack_from('<5B', data, 0) - offset = 5 + name_len - count = width * height - headers = None - if has_headers: - headers = [self.map_name(h) for h in struct.unpack_from(f'<{count}H', data, offset)] - offset += 2 * count - if has_altitudes: - offset += count - maps = [None if m == 0xffff else m for m in struct.unpack_from(f'<{count}H', data, offset)] - return Matrix(matrix_id, width, height, maps, headers) - - def land_name(self, land_id): - return f'land_data narc_{land_id:04d}' - - def land_path(self, land_id): - return f'files/fielddata/land_data/land_data_release/narc_{land_id:04d}.bin' - - def land_data(self, land_id): - return decode_land_data(self.source.read(self.land_path(land_id))) - - def events_name(self, events_id): - return f'zone_event narc_{events_id:04d}' - - def events_path(self, events_id): - return f'files/fielddata/eventdata/zone_event_release/narc_{events_id:04d}.bin' - - def events(self, events_id): - data = self.source.read(self.events_path(events_id)) - events = Events() - offset = 0 - (count,) = struct.unpack_from('